Skip to content

Test suite cleanup: port older tests to datasette.client, parametrize duplicates - #3075

Merged
simonw merged 17 commits into
mainfrom
test-suite-cleanup
Nov 16, 2026
Merged

simonw merged 17 commits into
mainfrom
test-suite-cleanup

Conversation

@simonw

@simonw simonw commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Closes:

Claude Fable 5.2 Medium

Moves the older TestClient-based tests over to datasette.client, removes some shared state between tests, and combines near-identical tests with pytest.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 as main.

New helpers in tests/fixtures.py

  • make_ds(): the datasette.client equivalent of make_app_client(). Same default settings, config, metadata and plugins, but the fixtures database is in memory and nothing is written to disk. The ds_client fixture 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 the app_client_* ones.
  • get_unprefixed(): datasette.client adds the base_url prefix to paths, but the base URL tests need to request both prefixed and unprefixed paths.

Ported to datasette.client

test_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.py

Tests that need a real database file (immutable databases, downloads, inspect data, dotted filenames, --crossdb) still write one, but make their requests through ds.client.

Still on TestClient: two uses in test_cli.py, and test_cli_create_token stays synchronous, because the CLI commands start their own event loop.

Shared state between tests

  • Eight Database tests no longer attach databases to the session-wide app_client.
  • make_app_client() no longer changes the working directory. The two inspect CLI tests relied on that to find fixtures.db, and now write their own.
  • Seven unused app_client_* fixtures and restore_working_directory are removed.
  • conftest.py no longer moves nine CLI tests to the front of the run. The three telemetry subprocess tests are still moved.

Parametrized

  • Column type validation: 9 tests into 1
  • analyze_sql_tables table operations: 6 into 1
  • Custom pages: 3 status/text tests and 3 redirect tests
  • Origin scheme and port checks: 3 into 1
  • render_cell pks: 3 into 1
  • Table _shape array/object: 3 into 1, and the two infinity tests
  • CSV and TSV download, metadata sort, two row JSON tests, multipart bad content types
  • Two adjacent pairs in test_error_shape.py

Left alone from the issue

  • test_hook_top_* stay separate: test_plugin_hooks_have_tests requires a test_hook_<name> test for every plugin hook.
  • Other look-alikes in test_error_shape.py, which are grouped by the error path they document.
  • The 5-test CSV group, test_expand_labels / test_expand_label, test_install / test_uninstall, test_autocomplete.py and the pair in test_restriction_sql.py.

Not fixed here

Reversing the test order shows order dependence inside test_internals_database.py, test_permissions.py (the cascade tests) and test_telemetry_testing_kit.py. The same failures exist on main.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 0.00%. Comparing base (6ce5c28) to head (45997ae).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
datasette/cli.py 0.00% 4 Missing ⚠️
datasette/database.py 0.00% 3 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@simonw

simonw commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

33 commits is too many. I'm having Claude reduce that down to 7.

simonw and others added 7 commits November 15, 2026 15:36
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>
@simonw
simonw force-pushed the test-suite-cleanup branch from c823b2e to f78d15a Compare November 15, 2026 23:39
@simonw

simonw commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

I think I really do need to line-by-line review this one, don't want to risk losing tests over it.

Comment thread tests/fixtures.py
Comment on lines +225 to +229
# 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"
)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@simonw

simonw commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner Author

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:

[tool.pytest.ini_options]
asyncio_mode = "auto"

In auto mode pytest-asyncio automatically adds the asyncio marker to all asynchronous test functions. It will also take ownership of all async fixtures, regardless of whether they are decorated with @pytest.fixture or @pytest_asyncio.fixture.

Sure enough, +1,692 -2,969 after 6a4fcd7

Comment thread tests/fixtures.py Outdated
yield TestClient(ds)
yield ds.client
finally:
ds.close()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Comment thread tests/test_api.py Outdated
"/fixtures/-/query.json?sql=select+sleep(0.1)",
)
assert 400 == response.status
assert 400 == response.status_code

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The older tests use assert 400 == response.status_code or similar in a bunch of places, but actually I later realized that assert response.status_code == 400 is better. Use tree sitter or a similar tool to find and fix all of those instances.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 -40

Output:

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'

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@simonw

simonw commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

I had Claude compare the speed of the test suite on main to the test suite on this branch:

Parallel runs are done (main and the branch both land around 14s); now timing the serial runs, which take about 90 seconds each.

The branch is about 3.5 seconds faster than main when run serially and indistinguishable from it under -n auto.

All runs were in the same checkout, alternating between origin/main (166d2a3) and the branch head (44a23fa), with 3,320 tests passing every time.

Mode main Branch
Serial, 2 runs each 66.2s, 65.6s 62.3s, 62.2s
-n auto, 4 runs each 14.7s, 14.4s, 14.6s, 13.6s 14.0s, 14.7s, 13.8s, 14.5s
  • Serial: the gap is about 5% and was consistent across both pairs. The machine was much quieter than last time, when serial runs of the same code varied by 40 seconds.
  • Parallel: the averages are 14.3s for main and 14.2s for the branch, well inside run-to-run variation.

origin/main has moved on by a few commits since the branch was cut, so the branch is now behind it. That does not affect the comparison (same test count on both), but the PR will need a rebase or merge before it lands.

Comment thread tests/test_multipart.py Outdated
assert form["username"] == "john_doe"

@pytest.mark.asyncio
async def test_multiple_text_fields(self):

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class-based tests are rare in this test suite.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Flatten them.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 --shortstat
All 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>
Comment thread tests/test_stored_queries.py Outdated
Comment on lines +17 to +18
async def update_query(client, name, **kwargs):
await client.ds.update_query("data", name, **kwargs)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pointless.

simonw and others added 2 commits November 15, 2026 19:39
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>
Comment thread datasette/database.py
Comment on lines +761 to +766
# 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()

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 on main; 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". The ds fixture in tests/test_homepage.py then recreates an in-memory database called books, 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_query in tests/test_internals_database.py turns 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.py on 3.11 with the garbage collector disabled; that now passes too. CI has not re-run yet.

Comment thread tests/test_stored_queries.py Outdated
) as client:
yield client
# Immutable databases need a file on disk
yield client.ds.client

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why yield client.ds.client and not just yield client ?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude replied:

Because client there is the old sync TestClient that make_app_client() returns, and the tests need the async datasette.client instead. client.ds is the Datasette instance behind the TestClient, and .client on that is its DatasetteClient.

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 through make_app_client(), which is the only helper that writes one. Yielding plain client would hand the tests the sync TestClient, and their await client.get(...) calls would fail.

It does read oddly, and the same .ds.client hop 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 a Datasette, so these fixtures never touch TestClient at all. I haven't done that; say if you want it.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do that cleaner fix

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>
@simonw

simonw commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner Author

I think it's time to remove the TestClient mechanism entirely. I scanned my checkouts and the only plugin to use it was datasette-scan.

Fixed that here:

simonw added a commit to simonw/datasette-scan that referenced this pull request Nov 16, 2026
simonw and others added 2 commits November 15, 2026 19:52
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>
Comment thread tests/test_internals_database.py Outdated
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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not keen on this.

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>
@simonw

simonw commented Nov 16, 2026

Copy link
Copy Markdown
Owner Author

I eyeball reviewed all 89 files! Ready to merge.

@simonw
simonw merged commit 51badf9 into main Nov 16, 2026
15 checks passed
@simonw
simonw deleted the test-suite-cleanup branch November 16, 2026 04:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant