From 45e502aace6cc1198cc5f9a04d61b4a1860a012b Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Fri, 17 Nov 2017 08:08:11 -0800 Subject: [PATCH] Added unit tests for inspect() foreign key detection Used them to fix a bug with it. Refs #85 --- datasette/utils.py | 2 +- tests/test_inspect.py | 76 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 tests/test_inspect.py diff --git a/datasette/utils.py b/datasette/utils.py index 94093d78..32721c94 100644 --- a/datasette/utils.py +++ b/datasette/utils.py @@ -215,7 +215,7 @@ def get_all_foreign_keys(conn): for table in tables: infos = conn.execute( 'PRAGMA foreign_key_list([{}])'.format(table) - ).fetchmany() + ).fetchall() for info in infos: if info is not None: id, seq, table_name, from_, to_, on_update, on_delete, match = info diff --git a/tests/test_inspect.py b/tests/test_inspect.py new file mode 100644 index 00000000..c138eaf9 --- /dev/null +++ b/tests/test_inspect.py @@ -0,0 +1,76 @@ +from datasette.app import Datasette +import os +import pytest +import sqlite3 +import tempfile + + +TABLES = ''' +CREATE TABLE "election_results" ( + "county" INTEGER, + "party" INTEGER, + "office" INTEGER, + "votes" INTEGER, + FOREIGN KEY (county) REFERENCES county(id), + FOREIGN KEY (party) REFERENCES party(id), + FOREIGN KEY (office) REFERENCES office(id) + ); + +CREATE TABLE "county" ( + "id" INTEGER PRIMARY KEY , + "name" TEXT +); + +CREATE TABLE "party" ( + "id" INTEGER PRIMARY KEY , + "name" TEXT +); + +CREATE TABLE "office" ( + "id" INTEGER PRIMARY KEY , + "name" TEXT +); +''' + + +@pytest.fixture(scope='module') +def ds_instance(): + with tempfile.TemporaryDirectory() as tmpdir: + filepath = os.path.join(tmpdir, 'test_tables.db') + conn = sqlite3.connect(filepath) + conn.executescript(TABLES) + yield Datasette([filepath]) + + +def test_inspect(ds_instance): + info = ds_instance.inspect() + tables = info['test_tables']['tables'] + for table_name in ('county', 'party', 'office'): + assert 0 == tables[table_name]['count'] + foreign_keys = tables[table_name]['foreign_keys'] + assert [] == foreign_keys['outgoing'] + assert [{ + 'column': 'id', + 'other_column': table_name, + 'other_table': 'election_results' + }] == foreign_keys['incoming'] + + election_results = tables['election_results'] + assert 0 == election_results['count'] + assert sorted([{ + 'column': 'county', + 'other_column': 'id', + 'other_table': 'county' + }, { + 'column': 'party', + 'other_column': 'id', + 'other_table': 'party' + }, { + 'column': 'office', + 'other_column': 'id', + 'other_table': 'office' + }], key=lambda d: d['column']) == sorted( + election_results['foreign_keys']['outgoing'], + key=lambda d: d['column'] + ) + assert [] == election_results['foreign_keys']['incoming']