Repository navigation
Test suite cleanup: port older tests to datasette.client, parametrize duplicates - #3075
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3075 +/- ##
=====================================
Coverage 0.00% 0.00%
=====================================
Files 80 79 -1
Lines 14046 13981 -65
=====================================
+ Misses 14046 13981 -65 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
33 commits is too many. I'm having Claude reduce that down to 7. |
make_ds() is the datasette.client equivalent of make_app_client(): the same default settings, config, metadata and plugins, but the fixtures database is in memory and nothing is written to disk. Tests call it and then make requests with ds.client. The ds_client fixture is now built on it. Also adds session-scoped fixtures built the same way - ds_client_with_trace, ds_client_with_cors, ds_client_shorter_time_limit, ds_client_base_url_prefix, ds_client_two_attached_databases and ds_client_no_files - and get_unprefixed(), for tests that need to request a path without datasette.client adding the base_url prefix. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
These tests used the synchronous TestClient, mostly through make_app_client(), to get an instance with different settings, config, metadata, templates or extra tables. They now use make_ds() or a ds_client fixture, so they run against in-memory databases. Files: test_tracer.py, test_custom_pages.py, test_facets.py, test_csrf_middleware.py, test_auth.py, test_stored_queries.py, test_plugins.py, test_table_api.py, test_config_dir.py. - csrftoken_from= was the reason some of these stayed on TestClient, and it has been a no-op since CSRF tokens were removed - TestClient.post() sent raw bodies with a form content type by default, so two stored query tests now set that header explicitly - The stored query test for immutable databases still writes a file, but uses its ds.client - test_cli_create_token stays synchronous because the CLI command starts its own event loop - Tests no longer need restore_working_directory, which was only there because make_app_client() changes the working directory Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Most tests in these files move to make_ds() or a ds_client fixture. The ones that need a real file - immutable databases, /fixtures.db downloads, inspect data, a filename containing a dot, --crossdb - keep their on-disk fixtures and make requests through ds.client on them. Files: test_csv.py, test_crossdb.py, test_permissions.py, test_html.py, test_table_html.py, test_api.py, test_setting_aliases.py. The base_url tests request both prefixed and unprefixed paths, so they use get_unprefixed(). Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Eight Database tests only needed a Datasette instance to construct Database objects against, but used the session-scoped app_client and left databases attached to it. They now use the function-scoped bare_ds fixture. make_app_client() used to chdir into a temporary directory that was deleted when the context manager exited. The two inspect CLI tests relied on that to find fixtures.db by a relative path, which only worked if app_client was the most recent client created. They now write their own fixtures.db and chdir with monkeypatch. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Eight app_client_* session fixtures have been replaced by in-memory ds_client_* fixtures or by make_ds() calls, and restore_working_directory is not needed now that make_app_client() leaves the working directory alone. conftest.py moved nine tests to the front of the run so they ran "before any asyncio code kicks in". Two of those names no longer match any test, the inspect tests no longer depend on which client was created last, and the suite passes without the reordering both serially and under pytest-xdist. The three telemetry tests that start subprocesses are still moved to the front, for the reason given in the comment. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The time limit is 20ms, so sleep(0.1) exceeds it as reliably as sleep(0.5) did and saves most of a second. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Groups of tests that differed only in their inputs and expected values are now single parametrized tests: - test_column_types.py: nine insert, update and upsert validation tests - test_utils_sql_analysis.py: six analyze_sql_tables() table operation tests - test_custom_pages.py: three status and text tests, three redirect tests - test_csrf_middleware.py: three Origin scheme and port tests - test_plugins.py: three render_cell pks tests - test_table_api.py: three _shape=array and _shape=object tests, two infinity tests - test_api.py: two row JSON tests - test_csv.py: the CSV and TSV download tests - test_table_html.py: test_metadata_sort and test_metadata_sort_desc - test_multipart.py: three bad content type tests - test_error_shape.py: the invalid _shape pair and the invalid _size pair Other look-alike tests in test_error_shape.py are left separate, because they are grouped by which error path they document. The test_hook_top_* tests are also left alone: every plugin hook needs its own test_hook_<name> test. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
c823b2e to
f78d15a
Compare
|
I think I really do need to line-by-line review this one, don't want to risk losing tests over it. |
| # A unique memory_name avoids collisions between Datasette instances in | ||
| # the same process - the database is still served as /fixtures | ||
| db = ds.add_database( | ||
| Database(ds, memory_name=f"fixtures_{secrets.token_hex(8)}"), name="fixtures" | ||
| ) |
There was a problem hiding this comment.
Cute trick - every instance gets /fixtures but it's actually a named memory database called fixtures_RAND under the hood.
asyncio_mode = auto runs every async def test as an asyncio test, so the 1,362 @pytest.mark.asyncio lines in tests/ are no longer needed. Also removes the "import pytest" lines this left unused. The same 3,320 tests pass before and after, serially and with -n auto. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
I noted to Claude that this change adds more lines than it removes (+1,835 -1,728) and it suggested using pytest-asyncio auto mode:
Sure enough, +1,692 -2,969 after 6a4fcd7 |
| yield TestClient(ds) | ||
| yield ds.client | ||
| finally: | ||
| ds.close() |
There was a problem hiding this comment.
This feels a bit redundant now. Let's inline these instead (it's only used in three places).
Its two tests now create Datasette([]) themselves. The Datasette pytest plugin closes instances created inside a test, so the fixture's try/finally added nothing. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| "/fixtures/-/query.json?sql=select+sleep(0.1)", | ||
| ) | ||
| assert 400 == response.status | ||
| assert 400 == response.status_code |
There was a problem hiding this comment.
The older tests use
assert 400 == response.status_codeor similar in a bunch of places, but actually I later realized thatassert response.status_code == 400is better. Use tree sitter or a similar tool to find and fix all of those instances.
There was a problem hiding this comment.
S="/private/tmp/claude-501/-Users-simon-Dropbox-dev-datasette--claude-worktrees-test-suite-refactor-audit-3a910b/c1cf27b7-bd00-4409-84f8-7894559af749/scratchpad"; cat > $S/yoda.py <<'EOF'
"""Swap `assert <literal> == <expr>` to `assert <expr> == <literal>` using ast for locations."""
import ast, sys, pathlib, collections
def is_literal(n):
if isinstance(n, ast.Constant): return True
if isinstance(n, ast.UnaryOp) and isinstance(n.op, ast.USub): return is_literal(n.operand)
if isinstance(n, (ast.List, ast.Tuple, ast.Set)): return all(is_literal(e) for e in n.elts)
if isinstance(n, ast.Dict): return all(k is not None and is_literal(k) and is_literal(v) for k, v in zip(n.keys, n.values))
return False
def kind(n):
if isinstance(n, ast.Constant): return type(n.value).__name__
return type(n).__name__
def offsets(src):
# byte offsets per line (ast col offsets are utf8 bytes)
lines = src.encode().split(b"\n"); out=[0]
for l in lines: out.append(out[-1]+len(l)+1)
return out
def find(tree):
for node in ast.walk(tree):
if not isinstance(node, ast.Assert): continue
t = node.test
if isinstance(t, ast.Compare) and len(t.ops)==1 and isinstance(t.ops[0], (ast.Eq, ast.NotEq)):
l, r = t.left, t.comparators[0]
if is_literal(l) and not is_literal(r):
yield node, l, r
fix = "--fix" in sys.argv
counts = collections.Counter(); total=0
for p in sorted(pathlib.Path("tests").rglob("*.py")):
src = p.read_text(); b = src.encode(); tree = ast.parse(src); off = offsets(src)
edits=[]
for node, l, r in find(tree):
counts[kind(l)] += 1; total += 1
ls, le = off[l.lineno-1]+l.col_offset, off[l.end_lineno-1]+l.end_col_offset
rs, re_ = off[r.lineno-1]+r.col_offset, off[r.end_lineno-1]+r.end_col_offset
edits.append((ls, le, rs, re_))
if not fix and "-v" in sys.argv: print(f"{p}:{node.lineno}: {ast.get_source_segment(src,node)[:90]!r}")
if fix and edits:
for ls, le, rs, re_ in sorted(edits, reverse=True):
# keep any parentheses/whitespace between the operands as-is
b = b[:ls] + b[rs:re_] + b[le:rs] + b[ls:le] + b[re_:]
p.write_text(b.decode())
print(total, dict(counts))
EOF
uv run python $S/yoda.py; uv run python $S/yoda.py -v | awk -F: '{print $1}' | sort | uniq -c | sort -rn | head -40Output:
222 {'str': 82, 'int': 71, 'List': 51, 'Dict': 17, 'bytes': 1}
31 tests/test_plugins.py
25 tests/test_html.py
18 tests/test_stored_queries.py
17 tests/test_table_html.py
17 tests/test_table_api.py
14 tests/test_utils.py
14 tests/test_facets.py
12 tests/test_internals_response.py
11 tests/test_config_dir.py
10 tests/test_internals_request.py
10 tests/test_api.py
9 tests/utils.py
6 tests/test_publish_cloudrun.py
6 tests/test_cli.py
6 tests/test_auth.py
5 tests/test_internals_database.py
3 tests/test_publish_heroku.py
3 tests/test_permissions.py
2 tests/test_package.py
2 tests/test_internals_datasette.py
1 tests/test_cli_serve_get.py
1 222 {'str'
285 assertions were written as "assert 400 == response.status_code", with the expected value on the left. They now read "assert response.status_code == 400". Found and rewritten with a script using Python's ast module: any assert comparing with == or != where the left side is a literal, a list or dict of literals, or a name starting with "expected", and the right side is not. The script checked that each file's syntax tree is unchanged apart from the swapped operands. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
I had Claude compare the speed of the test suite on main to the test suite on this branch:
|
| assert form["username"] == "john_doe" | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_multiple_text_fields(self): |
There was a problem hiding this comment.
class-based tests are rare in this test suite.
There was a problem hiding this comment.
I spotted class TestMultipartBasic is the tests - that's rare, we don't use class based test collections in many places. Audit and lest everywhere that does that.
There was a problem hiding this comment.
Results of the audit showed they were all in this module:
| Class | Line | Tests |
|---|---|---|
| TestFormUrlEncoded | 219 | 4 |
| TestMultipartBasic | 290 | 4 |
| TestMultipartWithFiles | 405 | 5 |
| TestMultipartCleanup | 570 | 2 |
| TestMultipartEdgeCases | 627 | 3 |
| TestSecurityLimits | 709 | 3 |
| TestMultipartStrictnessAndLimits | 786 | 10 |
| TestFormDataLenSemantics | 1034 | 1 |
There was a problem hiding this comment.
It really likes using the ast module:
uv run pytest tests/test_multipart.py -q --collect-only 2>&1 | grep "::" | sed -E 's/::Test[A-Za-z]+::/::/' | sort > /tmp/x 2>/dev/null; S="/private/tmp/claude-501/-Users-simon-Dropbox-dev-datasette--claude-worktrees-test-suite-refactor-audit-3a910b/c1cf27b7-bd00-4409-84f8-7894559af749/scratchpad"; mv /tmp/x $S/before.txt; uv run python - <<'EOF'
import ast, pathlib, re
p = pathlib.Path("tests/test_multipart.py"); src = p.read_text(); lines = src.split("\n")
tree = ast.parse(src)
classes = [n for n in tree.body if isinstance(n, ast.ClassDef) and n.name.startswith("Test")]
for c in reversed(classes):
doc = ast.get_docstring(c); first = c.body[0]
assert isinstance(first, ast.Expr) and first.lineno == first.end_lineno == c.lineno + 1
body = lines[c.lineno + 1 : c.end_lineno]
out = []
for l in body:
assert l == "" or l.startswith(" "), l
l = l[4:]
l = re.sub(r"^((?:async )?def test_\w+\()self(?:, )?", r"\1", l)
out.append(l)
while out and out[0] == "": out.pop(0)
lines[c.lineno - 1 : c.end_lineno] = ["# " + doc.rstrip("."), "", ""] + out
p.write_text("\n".join(lines))
EOF
uv run black tests/test_multipart.py -q; uv run ruff check . | tail -1; grep -n "self" tests/test_multipart.py | head; uv run pytest tests/test_multipart.py -q --collect-only 2>&1 | grep "::" | sort | diff - $S/before.txt && echo same-test-ids; sed -n 215,232p tests/test_multipart.py; git diff --shortstat; git diff -w --shortstatAll checks passed!
112: def blocking_feed(self, chunk):
113: original_feed(self, chunk)
same-test-ids
return receive
# Test request.form() with application/x-www-form-urlencoded data
async def test_basic_form_fields():
"""Basic URL-encoded form should be parseable via request.form()."""
body = b"username=john&password=secret"
scope = {
"type": "http",
"method": "POST",
"headers": [
(b"content-type", b"application/x-www-form-urlencoded"),
],
}
request = Request(scope, make_receive(body))
1 file changed, 851 insertions(+), 827 deletions(-)
1 file changed, 72 insertions(+), 48 deletions(-)
The eight Test* classes there were the only class-based test collections in the suite. None of their 32 methods used self, so they are now module-level functions like every other test. Each class docstring is kept as a comment heading its group of tests. The collected test names are unchanged apart from the class prefix. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| async def update_query(client, name, **kwargs): | ||
| await client.ds.update_query("data", name, **kwargs) |
When a query failed part way through, such as json_type() hitting malformed JSON during facet suggestion, the exception's traceback kept the cursor alive until the garbage collector ran. On Python 3.11 an open cursor stops SQLite from really closing the connection, so a named in-memory database could outlive Datasette.close(). This showed up as test_recent_item_marker in tests/test_homepage.py failing on 3.11 with "table authors already exists": the fixture recreates an in-memory database called "books" for every test. Database.execute() now closes the cursor before re-raising. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
update_query() in test_stored_queries.py only filled in the "data" argument to ds.update_query(), and _count_threads() in test_fd_leak.py was threading.active_count() under another name. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| # The traceback keeps this frame, and so the cursor, | ||
| # alive until the garbage collector runs. An open | ||
| # cursor stops SQLite from really closing the | ||
| # connection, so release it now. | ||
| if cursor is not None: | ||
| cursor.close() |
There was a problem hiding this comment.
One of the CI runs helped discover the area after a surprise failure on Python 3.11.
Claude explanation:
This is a real bug in Datasette, not in the tests, so the fix is in
datasette/database.py. It was already latent onmain; the PR only changed timing enough to expose it.
- Cause: when a read query fails part way through, the exception's traceback keeps the cursor alive until the garbage collector runs. On Python 3.11 an open cursor stops SQLite from really closing the connection, so a named in-memory database outlives
Datasette.close().- Why that test: the table page's facet suggestion runs
json_type()on a text column and fails with "malformed JSON". Thedsfixture intests/test_homepage.pythen recreates an in-memory database calledbooks, and the old one is still there.- Fix:
Database.execute()now closes the cursor before re-raising.- Regression test:
test_close_releases_memory_database_after_failed_queryintests/test_internals_database.pyturns the garbage collector off to make the leak deterministic. It fails on 3.11 without the fix and passes with it.The full suite passes on 3.11 and 3.15 locally (3,321 tests). I reproduced the original failure by running
tests/test_homepage.pyon 3.11 with the garbage collector disabled; that now passes too. CI has not re-run yet.
| ) as client: | ||
| yield client | ||
| # Immutable databases need a file on disk | ||
| yield client.ds.client |
There was a problem hiding this comment.
Why
yield client.ds.clientand not justyield client?
There was a problem hiding this comment.
Claude replied:
Because
clientthere is the old syncTestClientthatmake_app_client()returns, and the tests need the asyncdatasette.clientinstead.client.dsis the Datasette instance behind theTestClient, and.clienton that is itsDatasetteClient.It appears in two fixtures, tests/test_permissions.py:562 and tests/test_stored_queries.py:89. Both need a real database file on disk (one tests downloading
/fixtures.db, the other needs an immutable database), so they still go throughmake_app_client(), which is the only helper that writes one. Yielding plainclientwould hand the tests the syncTestClient, and theirawait client.get(...)calls would fail.It does read oddly, and the same
.ds.clienthop shows up 17 times across the tests for the same reason. The cleaner fix would be an async helper that writes the fixtures file and returns aDatasette, so these fixtures never touchTestClientat all. I haven't done that; say if you want it.
make_app_client() wrapped its Datasette instance in the old sync TestClient, so async tests had to reach back through it with client.ds.client. It is now make_ds_on_disk() and yields the Datasette instance itself, and the app_client* fixtures built on it are renamed to ds_on_disk*: - app_client -> ds_on_disk - app_client_with_dot -> ds_on_disk_with_dot - app_client_with_cors -> ds_on_disk_with_cors - app_client_immutable_and_inspect_file -> ds_on_disk_immutable_and_inspect_file - app_client_two_attached_databases_one_immutable -> ds_on_disk_two_databases_one_immutable - app_client_two_attached_databases_crossdb_enabled -> ds_on_disk_two_databases_crossdb test_cli_create_token still makes one sync request, since the CLI command it runs starts its own event loop. It builds a TestClient itself. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
I think it's time to remove the Fixed that here: |
datasette.utils.testing held TestClient and TestResponse, the sync test client that pre-dated datasette.client. It was never documented. "datasette serve --get" was its last use outside the tests. It now makes its request with datasette.client, still asking for the path exactly as given without the base_url prefix. The two tests that still used TestClient call datasette.client through asyncio.run() instead, since each runs code that starts its own event loop. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
TestClient was the only thing using it, for async_to_sync(). The test suite passes in a fresh environment without asgiref installed. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
| async def test_in_memory_databases_forbid_writes(app_client): | ||
| ds = app_client.ds | ||
| async def test_in_memory_databases_forbid_writes(bare_ds): | ||
| ds = bare_ds |
Three tests in test_internals_database.py started with "ds = bare_ds" and then used ds. They now use bare_ds throughout. Refs #3074 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
I eyeball reviewed all 89 files! Ready to merge. |
Refs #1048, #1342, #1479, #1553, #1611, #1627, #1630, #1671, #1674, #1822, #1841, #1873, #1914, #1919, #1973, #2045, #2073, #2145, #2253, #2356, #2419, #2713, #2805, #2807, #2810, #2826, #2942, #2967, #3070, #3074, #3075, #3078, #3079, #3081, #3082, #3083, #3084, #3085, #3087, #3088, #3089, #3090, #3091, #3092, #3093, #3097, #3098, #3099, #3100, #3101, #3102, #3103, #3104, #3105, #3106, #3107, #3108, #3109, #3111, #3112, #3113, #3115
Closes:
datasette.client, parametrize duplicates #3074Claude Fable 5.2 Medium
Moves the older
TestClient-based tests over todatasette.client, removes some shared state between tests, and combines near-identical tests withpytest.mark.parametrize. Each file is ported in its own commit.The suite passes serially and under
-n auto. This does not make the suite faster: the serial run takes the same time asmain.New helpers in
tests/fixtures.pymake_ds(): thedatasette.clientequivalent ofmake_app_client(). Same default settings, config, metadata and plugins, but the fixtures database is in memory and nothing is written to disk. Theds_clientfixture is now built on it.ds_client_with_trace,ds_client_with_cors,ds_client_shorter_time_limit,ds_client_base_url_prefix,ds_client_two_attached_databases,ds_client_no_files: session fixtures replacing theapp_client_*ones.get_unprefixed():datasette.clientadds thebase_urlprefix to paths, but the base URL tests need to request both prefixed and unprefixed paths.Ported to
datasette.clienttest_tracer.py,test_custom_pages.py,test_facets.py,test_csrf_middleware.py,test_auth.py,test_csv.py,test_crossdb.py,test_stored_queries.py,test_permissions.py,test_plugins.py,test_html.py,test_table_html.py,test_table_api.py,test_api.py,test_config_dir.py,test_setting_aliases.pyTests that need a real database file (immutable databases, downloads, inspect data, dotted filenames,
--crossdb) still write one, but make their requests throughds.client.Still on
TestClient: two uses intest_cli.py, andtest_cli_create_tokenstays synchronous, because the CLI commands start their own event loop.Shared state between tests
Databasetests no longer attach databases to the session-wideapp_client.make_app_client()no longer changes the working directory. The two inspect CLI tests relied on that to findfixtures.db, and now write their own.app_client_*fixtures andrestore_working_directoryare removed.conftest.pyno longer moves nine CLI tests to the front of the run. The three telemetry subprocess tests are still moved.Parametrized
analyze_sql_tablestable operations: 6 into 1render_cellpks: 3 into 1_shapearray/object: 3 into 1, and the two infinity teststest_error_shape.pyLeft alone from the issue
test_hook_top_*stay separate:test_plugin_hooks_have_testsrequires atest_hook_<name>test for every plugin hook.test_error_shape.py, which are grouped by the error path they document.test_expand_labels/test_expand_label,test_install/test_uninstall,test_autocomplete.pyand the pair intest_restriction_sql.py.Not fixed here
Reversing the test order shows order dependence inside
test_internals_database.py,test_permissions.py(the cascade tests) andtest_telemetry_testing_kit.py. The same failures exist onmain.🤖 Generated with Claude Code