diff --git a/.dagger/modules/dagger-pytest-otel/dagger-module.toml b/.dagger/modules/dagger-pytest-otel/dagger-module.toml index 178aa85..98c0883 100644 --- a/.dagger/modules/dagger-pytest-otel/dagger-module.toml +++ b/.dagger/modules/dagger-pytest-otel/dagger-module.toml @@ -1,5 +1,5 @@ name = "dagger-pytest-otel" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/.dagger/modules/e2e/dagger-module.toml b/.dagger/modules/e2e/dagger-module.toml index 61c2aa2..d84143b 100644 --- a/.dagger/modules/e2e/dagger-module.toml +++ b/.dagger/modules/e2e/dagger-module.toml @@ -1,5 +1,5 @@ name = "e2e" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 2ec565e..805a59b 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -52,18 +52,18 @@ type E2e { } """ - Assert that a batch failure names every failing project and no passing one. + Assert that a collection failure names every failing project and no passing one. """ let assertReports(failure: String!, failing: [String!]!, passing: [String!]!): Void { let unreported = failing.reject { path => failure.contains("- " + path + ":") } assert( unreported.isEmpty, - "the batch did not report every failing project (" + unreported.join(", ") + "): " + failure, + "the collection did not report every failing project (" + unreported.join(", ") + "): " + failure, ) let reported = passing.filter { path => failure.contains("- " + path + ":") } assert( reported.isEmpty, - "the batch reported a passing project (" + reported.join(", ") + "): " + failure, + "the collection reported a passing project (" + reported.join(", ") + "): " + failure, ) } @@ -485,7 +485,7 @@ type E2e { let ruffRangeOldFixture: String! = "testdata/project-ruff-range-old" """ - Fixtures that are broken on purpose, left out so the batch checks + Fixtures that are broken on purpose, left out so the collection runs describe a healthy workspace. """ let healthy: [String!]! = [ @@ -515,7 +515,7 @@ type E2e { project with no Python source of its own. """ mypyCheck(ws: Workspace!): Void @check { - run(mypy(scope: healthy).projects(ws).batch.typeCheck(ws)) + mypy(scope: healthy).projects(ws).typeCheck(ws) let failure = mypyFailure(ws, typeFailFixture) assert( @@ -523,23 +523,19 @@ type E2e { "mypy did not fail on a type error: " + failure, ) - # A batch that quietly selected nothing would pass the call above, so + # A collection run that quietly selected nothing would pass the call above, so # point it at the project that fails and require the failure to surface. - let batch = failureOf( - mypy(scope: [typeFailFixture]).projects(ws).batch.typeCheck(ws), - ) + let collected = { mypy(scope: [typeFailFixture]).projects(ws).typeCheck(ws); "passed" } rescue { err: Error => err.message } assert( - batch.contains("exit code"), - "the batch type check did not run the failing project it selected: " + batch, + collected.contains("exit code"), + "the collection type check did not run the failing project it selected: " + collected, ) # A deselected project is not checked even though it is broken, by its own - # check or by the batch. + # check or by the collection. let deselected = mypy(scope: ["**", "!" + typeFailFixture]) run(deselected.project(ws, typeFailFixture).typeCheck(ws)) - run( - deselected.projects(ws).subset(keys: [typeFailFixture]).batch.typeCheck(ws), - ) + deselected.projects(ws).subset(keys: [typeFailFixture]).typeCheck(ws) # No Python source of its own, so nothing to check. run(mypy.project(ws, deepFixture).typeCheck(ws)) @@ -590,7 +586,7 @@ type E2e { ty reaches the same verdicts as mypy on the same fixtures. """ tyCheck(ws: Workspace!): Void @check { - run(ty(scope: healthy).projects(ws).batch.typeCheck(ws)) + ty(scope: healthy).projects(ws).typeCheck(ws) let failure = tyFailure(ws, typeFailFixture) assert( @@ -630,7 +626,7 @@ type E2e { """ mypy's and ty's projects form collections keyed by project root: a project - with no Python source of its own is not a key, a subset batch runs only its + with no Python source of its own is not a key, a subset runs only its own projects, and every failing project is reported. """ typeCheckCollectionCheck(ws: Workspace!): Void @check { @@ -646,18 +642,12 @@ type E2e { assert(mypy.project(ws, deepFixture).hasSources(ws) == false, "a project with no Python source reported some") let subset = [passFixture, typeFailFixture, nestedChildFixture] - let mypyFailures = failureOf( - mypy.projects(ws).subset(keys: subset).batch.typeCheck(ws), - ) - let tyFailures = failureOf( - ty.projects(ws).subset(keys: subset).batch.typeCheck(ws), - ) + let mypyFailures = { mypy.projects(ws).subset(keys: subset).typeCheck(ws); "passed" } rescue { err: Error => err.message } + let tyFailures = { ty.projects(ws).subset(keys: subset).typeCheck(ws); "passed" } rescue { err: Error => err.message } assertReports(mypyFailures, [typeFailFixture, nestedChildFixture], [passFixture]) assertReports(tyFailures, [typeFailFixture, nestedChildFixture], [passFixture]) - run( - mypy.projects(ws).subset(keys: [passFixture, nestedFixture]).batch.typeCheck(ws), - ) + mypy.projects(ws).subset(keys: [passFixture, nestedFixture]).typeCheck(ws) null } @@ -685,10 +675,10 @@ type E2e { "the refreshed uv.lock did not pick up the new requires-python", ) - let driftedAll = uv(lock: [lockDriftFixture]).projects(ws).batch.lock(ws) + let driftedAll = uv(lock: [lockDriftFixture]).projects(ws).lock(ws) assert( driftedAll.modifiedPaths.contains(lockDriftFixture + "/uv.lock"), - "the batch lock did not re-lock the drifted project it selected: " + "the collection lock did not re-lock the drifted project it selected: " + (driftedAll.modifiedPaths + driftedAll.addedPaths).join(", "), ) @@ -713,16 +703,16 @@ type E2e { "a deselected project was locked anyway", ) - let all = uv(lock: ["**", "!" + lockDriftFixture]).projects(ws).batch.lock(ws) + let all = uv(lock: ["**", "!" + lockDriftFixture]).projects(ws).lock(ws) assert( all.addedPaths.isEmpty and all.modifiedPaths.isEmpty and all.removedPaths.isEmpty, - "the batch lock rewrote up-to-date lockfiles: " + "the collection lock rewrote up-to-date lockfiles: " + (all.addedPaths + all.modifiedPaths + all.removedPaths).join(", "), ) # The CLI applies a changeset at the caller's cwd, so it is rooted there. let fromProject = ws.withWorkdir(lockDriftFixture) - let local = uv.projects(fromProject).batch.lock(fromProject) + let local = uv.projects(fromProject).lock(fromProject) assert( local.modifiedPaths == ["uv.lock"], "a changeset from inside the project was not rooted at the cwd: " + changedPaths(local), @@ -736,7 +726,7 @@ type E2e { uv.projects(insideOtel).keys == [otelSource], "uv keys from inside a project: " + uv.projects(insideOtel).keys.join(", "), ) - let otelLock = uv.projects(insideOtel).batch.lock(insideOtel) + let otelLock = uv.projects(insideOtel).lock(insideOtel) assert(isEmpty(otelLock), "locking from inside a project reached above the cwd: " + changedPaths(otelLock)) null } @@ -770,13 +760,13 @@ type E2e { args.contains("uv audit failed (uv audit --locked --no-such-flag"), "uv audit did not take its args, or did not name the step: " + args, ) - run(uv(audit: ["**", "!" + lockDriftFixture]).projects(ws).batch.audit(ws)) + uv(audit: ["**", "!" + lockDriftFixture]).projects(ws).audit(ws) null } """ uv's projects form a collection keyed by the roots of the projects that have - a uv.lock: a subset batch locks and audits only its own projects, and a + a uv.lock: a subset locks and audits only its own projects, and a project deselected for one verb is still a key for the other. """ uvCollectionCheck(ws: Workspace!): Void @check { @@ -787,13 +777,13 @@ type E2e { assert(keys.contains(passFixture) == false, "a project without a uv.lock is a uv key") let pair = uv.projects(ws).subset(keys: [lockDriftFixture, regenerateFixture]) - let locked = pair.batch.lock(ws) + let locked = pair.lock(ws) assert( locked.modifiedPaths == [lockDriftFixture + "/uv.lock"] and locked.addedPaths.isEmpty, - "the batch lock did not return exactly the drifted lockfile: " + changedPaths(locked), + "the collection lock did not return exactly the drifted lockfile: " + changedPaths(locked), ) assert( - isEmpty(uv.projects(ws).subset(keys: [regenerateFixture]).batch.lock(ws)), + isEmpty(uv.projects(ws).subset(keys: [regenerateFixture]).lock(ws)), "a subset without the drifted project locked it anyway", ) @@ -809,17 +799,15 @@ type E2e { "includeSkipped false dropped a project that is still audited", ) assert( - isEmpty(split.projects(ws).subset(keys: [lockDriftFixture]).batch.lock(ws)), - "a deselected project was locked by the batch", - ) - run( - uv.projects(ws).subset(keys: [regenerateFixture, pinnedFixture]).batch.audit(ws), + isEmpty(split.projects(ws).subset(keys: [lockDriftFixture]).lock(ws)), + "a deselected project was locked by the collection", ) + uv.projects(ws).subset(keys: [regenerateFixture, pinnedFixture]).audit(ws) - let dist = uv.projects(ws).subset(keys: [regenerateFixture]).batch.build(ws).glob("**/*.whl") + let dist = uv.projects(ws).subset(keys: [regenerateFixture]).build(ws).glob("**/*.whl") assert( dist.length == 1 and dist.all { file => file.hasPrefix(regenerateFixture + "/") }, - "the batch build did not place the wheel under its project root: " + dist.join(", "), + "the collection build did not place the wheel under its project root: " + dist.join(", "), ) null } @@ -1115,7 +1103,7 @@ type E2e { deselected project alone. """ ruffCheck(ws: Workspace!): Void @check { - run(ruff(scope: ruffHealthy).projects(ws).batch.lint(ws)) + ruff(scope: ruffHealthy).projects(ws).lint(ws) let failure = failureOf(ruff.project(ws, lintFailFixture).lint(ws)) assert( @@ -1123,16 +1111,14 @@ type E2e { "ruff did not fail on a lint violation: " + failure, ) - let batch = failureOf( - ruff(scope: [lintFailFixture]).projects(ws).batch.lint(ws), - ) + let collected = { ruff(scope: [lintFailFixture]).projects(ws).lint(ws); "passed" } rescue { err: Error => err.message } assert( - batch.contains("exit code"), - "the batch lint did not run the failing project it selected: " + batch, + collected.contains("exit code"), + "the collection lint did not run the failing project it selected: " + collected, ) # A deselected project is still a key, but neither its own lint nor the - # batch runs it. + # collection runs it. let deselected = ruff(scope: ["**", "!" + lintFailFixture]) run(deselected.project(ws, lintFailFixture).lint(ws)) assert(deselected.project(ws, lintFailFixture).skip, "a deselected project was not skipped") @@ -1144,9 +1130,7 @@ type E2e { deselected.projects(ws, includeSkipped: false).keys.contains(lintFailFixture) == false, "includeSkipped false kept a deselected project", ) - run( - deselected.projects(ws).subset(keys: [lintFailFixture, passFixture]).batch.lint(ws), - ) + deselected.projects(ws).subset(keys: [lintFailFixture, passFixture]).lint(ws) assert( ruff.version.contains("ruff"), @@ -1159,7 +1143,7 @@ type E2e { Every tool's keys follow the cwd: from a project root, that project and the projects below it; from inside a project, exactly the enclosing project; from outside any project, the projects below. From inside a project, the - batches run that project with no selection at all. + collection helpers run that project with no selection at all. """ cwdSelectionCheck(ws: Workspace!): Void @check { let atRoot = ws.withWorkdir(nestedFixture) @@ -1223,20 +1207,17 @@ type E2e { ) assertKeys("uv at an unlocked root", uv.projects(atRoot).keys, []) - # With no selection, the batches run the enclosing project, and a failure + # With no selection, the collection helpers run the enclosing project, and a failure # there is its own. let insidePass = ws.withWorkdir(passFixture + "/tests") - run(ruff.projects(insidePass).batch.lint(insidePass)) - run(mypy.projects(insidePass).batch.typeCheck(insidePass)) - pytest.projects(insidePass).batch.test(insidePass) - run( - pytest.projects(insidePass).get(key: passFixture).tests(insidePass).batch.test(insidePass), - ) - assertReports( - failureOf(mypy.projects(insideChild).batch.typeCheck(insideChild)), - [nestedChildFixture], - [nestedFixture], - ) + ruff.projects(insidePass).lint(insidePass) + mypy.projects(insidePass).typeCheck(insidePass) + pytest.projects(insidePass).test(insidePass) + pytest.projects(insidePass).get(key: passFixture).tests(insidePass).test(insidePass) + let insideFailure = { mypy.projects(insideChild).typeCheck(insideChild); "passed" } rescue { + err: Error => err.message + } + assertReports(insideFailure, [nestedChildFixture], [nestedFixture]) null } @@ -1246,8 +1227,8 @@ type E2e { """ ruff's projects form a collection keyed by project root: get and subset stay - within the keys, a subset - batch runs only its own projects, and every failing project is reported. + within the keys, a subset runs only its own projects, and every failing + project is reported. """ ruffCollectionCheck(ws: Workspace!): Void @check { let projects = ruff.projects(ws) @@ -1293,23 +1274,21 @@ type E2e { let none = projects.subset(keys: []) assert(none.keys.isEmpty, "empty subset kept keys: " + none.keys.join(", ")) - run(none.batch.lint(ws)) - assert(isEmpty(none.batch.format(ws)), "an empty subset formatted something") + none.lint(ws) + assert(isEmpty(none.format(ws)), "an empty subset formatted something") # The failing projects are keys, but a subset without them passes. - run(projects.subset(keys: [passFixture, nestedFixture]).batch.lint(ws)) + projects.subset(keys: [passFixture, nestedFixture]).lint(ws) # Every failing project is reported, and a passing one is not. - let both = failureOf( - projects.subset(keys: [passFixture, lintFailFixture, ruffTomlFixture]).batch.lint(ws), - ) + let both = { projects.subset(keys: [passFixture, lintFailFixture, ruffTomlFixture]).lint(ws); "passed" } rescue { err: Error => err.message } assertReports(both, [lintFailFixture, ruffTomlFixture], [passFixture]) null } """ - ruff formats what needs formatting and leaves the rest alone, and the batch - returns one changeset over the selected projects. + ruff formats what needs formatting and leaves the rest alone, and the + collection's `format` returns one changeset over the selected projects. """ ruffFormatCheck(ws: Workspace!): Void @check { let changed = ruff.project(ws, unformattedFixture).format(ws) @@ -1321,11 +1300,11 @@ type E2e { let clean = ruff.project(ws, passFixture).format(ws) assert(isEmpty(clean), "ruff format rewrote an already-formatted project: " + changedPaths(clean)) - let batch = ruff.projects(ws).subset(keys: [passFixture, unformattedFixture]).batch.format(ws) + let collected = ruff.projects(ws).subset(keys: [passFixture, unformattedFixture]).format(ws) assert( - sameFiles(batch.modifiedPaths, [unformattedFixture + "/sub/narrow.py", unformattedFixture + "/wide.py"]) - and batch.addedPaths.isEmpty, - "the batch format did not return exactly the unformatted files: " + changedPaths(batch), + sameFiles(collected.modifiedPaths, [unformattedFixture + "/sub/narrow.py", unformattedFixture + "/wide.py"]) + and collected.addedPaths.isEmpty, + "the collection format did not return exactly the unformatted files: " + changedPaths(collected), ) let skipped = ruff(scope: ["!" + unformattedFixture]).project(ws, unformattedFixture).format(ws) @@ -1333,7 +1312,7 @@ type E2e { # The CLI applies a changeset at the caller's cwd, so it is rooted there. let fromProject = ws.withWorkdir(unformattedFixture) - let local = ruff.projects(fromProject).batch.format(fromProject) + let local = ruff.projects(fromProject).format(fromProject) assert( sameFiles(local.modifiedPaths, ["sub/narrow.py", "wide.py"]), "a changeset from the project root was not rooted at the cwd: " + changedPaths(local), @@ -1351,7 +1330,7 @@ type E2e { let fromSub = ws.withWorkdir(unformattedFixture + "/sub") let sub = ruff.projects(fromSub) assert(sub.keys == [unformattedFixture], "keys from inside a project: " + sub.keys.join(", ")) - let below = sub.batch.format(fromSub) + let below = sub.format(fromSub) assert( below.modifiedPaths == ["narrow.py"] and below.addedPaths.isEmpty, "a changeset from inside the project did not hold just the part below the cwd: " @@ -1377,10 +1356,10 @@ type E2e { isEmpty(ruff.project(ws, passFixture).fix(ws)), "ruff fix changed a clean project", ) - let batch = ruff.projects(ws).subset(keys: [passFixture, lintFailFixture]).batch.fix(ws) + let collected = ruff.projects(ws).subset(keys: [passFixture, lintFailFixture]).fix(ws) assert( - batch.modifiedPaths == [lintFailFixture + "/unused.py"], - "the batch fix did not return exactly the fixed file: " + changedPaths(batch), + collected.modifiedPaths == [lintFailFixture + "/unused.py"], + "the collection fix did not return exactly the fixed file: " + changedPaths(collected), ) null } @@ -1393,7 +1372,7 @@ type E2e { having no tests yet used to fail the whole check. """ pytestCheck(ws: Workspace!): Void @check { - pytest(scope: pytestHealthy).projects(ws).batch.test(ws) + pytest(scope: pytestHealthy).projects(ws).test(ws) let failure = { pytest.project(ws, testFailFixture).test(ws) @@ -1412,7 +1391,7 @@ type E2e { ) # The fix: no test files means skipped, not exit 5. pytest.project(ws, noTestsFixture2).test(ws) - run(pytest.project(ws, noTestsFixture2).tests(ws).batch.test(ws)) + pytest.project(ws, noTestsFixture2).tests(ws).test(ws) assert( pytest.hasTests(ws, passFixture), @@ -1437,7 +1416,7 @@ type E2e { deselected.test(ws) assert(deselected.skip, "a deselected project was not skipped") assert(deselected.tests(ws).keys.isEmpty, "a deselected project offered test files") - run(deselected.tests(ws).batch.test(ws)) + deselected.tests(ws).test(ws) null } @@ -1468,9 +1447,9 @@ type E2e { assert(keys.contains(deepFixture) == false, "a project without test files is a key") assert(projects.get(key: passFixture).path == passFixture, "get did not return the project at its key") - projects.subset(keys: [passFixture, nestedFixture, skipFixture]).batch.test(ws) + projects.subset(keys: [passFixture, nestedFixture, skipFixture]).test(ws) let failures = { - projects.subset(keys: [passFixture, testFailFixture, nestedChildFixture]).batch.test(ws) + projects.subset(keys: [passFixture, testFailFixture, nestedChildFixture]).test(ws) "passed" } rescue { err: Error => err.message @@ -1506,19 +1485,430 @@ type E2e { } assert(unknown == "rejected", "subset accepted an unknown test file") - # One test file runs on its own, and fails only when it is the broken one. - run(tests.get(key: passing).test(ws)) - let one = failureOf(tests.get(key: broken).test(ws)) - assert(one.contains("exit code"), "the broken test file passed on its own: " + one) - - # The whole collection runs the whole project, which fails; filtered to its - # passing file, the same project passes, so only the selection ran. - let whole = failureOf(tests.batch.test(ws)) - assert(whole.contains("exit code"), "the project's whole test run passed: " + whole) - run(tests.subset(keys: [passing]).batch.test(ws)) - let filtered = failureOf(tests.subset(keys: [broken]).batch.test(ws)) - assert(filtered.contains("exit code"), "the broken test file passed in a subset: " + filtered) - run(tests.subset(keys: []).batch.test(ws)) + # Each file's top-level tests are a collection keyed by name, in byte order. + assert( + tests.get(key: broken).tests.keys == ["test_broken"], + "test discovery found: " + tests.get(key: broken).tests.keys.join(", "), + ) + let skipping = pytest.project(ws, skipFixture).tests(ws).get(key: "tests/test_skipping.py").tests.keys + assert( + skipping == ["test_called_skip", "test_marked_skip", "test_runs"], + "test discovery found: " + skipping.join(", "), + ) + + # A test check reads its own result from the shared run of the collection + # it is given: the broken test fails, and the passing one passes beside it. + let passingTest = tests.get(key: passing).tests.get(key: "test_passing") + let brokenTest = tests.get(key: broken).tests.get(key: "test_broken") + run(passingTest.test(ws, selection: tests)) + let one = failureOf(brokenTest.test(ws, selection: tests)) + assert(one.contains("test_broken failed"), "the broken test passed: " + one) + run(passingTest.test(ws, selection: tests.subset(keys: [passing]))) + let excluded = failureOf(brokenTest.test(ws, selection: tests.subset(keys: [passing]))) + assert( + excluded.contains("outside the test selection"), + "a test outside its selection did not say so: " + excluded, + ) + + # The collection helper runs the selection once and reports every failing + # test; filtered to its passing file, the same project passes. + let whole = { tests.test(ws); "passed" } rescue { err: Error => err.message } + assert( + whole.contains(testFailFixture + "/tests/test_broken.py::test_broken: test_broken failed") + and whole.contains("test_passing") == false, + "the project's test run did not report exactly the broken test: " + whole, + ) + tests.subset(keys: [passing]).test(ws) + let filtered = { tests.subset(keys: [broken]).test(ws); "passed" } rescue { err: Error => err.message } + assert(filtered.contains("test_broken failed"), "the broken test file passed in a subset: " + filtered) + tests.subset(keys: []).test(ws) + null + } + + # Only the unindented CHECKS header counts. Nested TESTS summaries can + # report correct pytest results even when Dagger attributes the checks + # incorrectly. + let checkSummaryMatches(output: String!, passed: Int!, failed: Int!): Boolean! { + let headers = output.split("\n").filter { line => + line.hasPrefix("CHECKS ") or line.hasPrefix("== CHECKS ==") + } + let expected = (if (failed > 0) { ["✘", `${failed}`, "failed"] } else { [] }) + + (if (passed > 0) { ["✔", `${passed}`, "passed"] } else { [] }) + headers.length == 1 and headers[0]!.trimPrefix("== ").trimPrefix("CHECKS").trimPrefix(" ==") + .trimSpace.split(" ").filter { word => word != "" } == expected + } + + """ + The check totals the selection checks read are the CLI's own, not the + nested test summaries. + """ + selectedSummaryCheck: Void @check { + let wrong = "CHECKS ✘ 8 failed\n TESTS\n ✘ 1 failed\n ✔ 7 passed\n" + assert(checkSummaryMatches(wrong, 7, 1) == false, "nested test counts hid failed checks") + assert(checkSummaryMatches(wrong, 0, 8), "zero passing checks were not recognized") + assert(checkSummaryMatches("CHECKS ✔ 18 passed\n", 8, 0) == false, "accepted a partial count") + assert(checkSummaryMatches("CHECKS ✘ 1 failed ✔ 7 passed\n", 7, 1), "mixed counts were not recognized") + assert(checkSummaryMatches("== CHECKS == ✔ 8 passed\n", 8, 0), "agent report was not recognized") + assert(checkSummaryMatches(" CHECKS ✔ 8 passed\n", 8, 0) == false, "accepted a nested header") + null + } + + """ + The engine's own CLI, run over a fixture workspace whose dagger.toml is + `config`, with this repository's library and `modules` mounted at /source. + """ + let cli(ws: Workspace!, fixture: Directory!, modules: [String!]!, config: String!, args: [String!]!): Container! { + container + .from("alpine:3.24.1") + # The CLI's workspace is this container, and discovery searches it with + # the ripgrep found here. + .withExec(["apk", "add", "--no-cache", "ripgrep"]) + .withEnvVariable("NO_COLOR", "1") + .withDirectory( + "/source", + ws.directory( + "/", + include: ["dagger.toml", "dagger.lock", "pyproject/**"] + modules.map { module => module + "/**" }, + exclude: lib.exclude, + ), + ) + # The modules' dependency on ../pyproject resolves within the repository + # a .git marks. + .withNewFile("/source/.git/HEAD", "ref: refs/heads/main\n") + .withDirectory("/work", fixture) + .withNewFile("/work/.git/HEAD", "ref: refs/heads/main\n") + .withNewFile("/work/dagger.toml", config) + .withWorkdir("/work") + .withExec(["/dev/.dagger/dagger", "--progress=report"] + args, expect: ANY, daggerInDaggerNewSession: true) + } + + # The dagger.toml lines that install `module` from /source with `settings`. + let moduleConfig(module: String!, settings: String!): String! { + "[modules." + module + "]\nsource = \"/source/" + module + "\"\n\n[modules." + module + ".settings]\n" + settings + "\n" + } + + """ + Run `dagger check` with the engine's own CLI over a fixture workspace that + installs one module from this repository, pytest by default, and assert the + check totals and messages; return the output. + + Direct Dang calls do not apply the engine's filtered collection view, so + only the CLI shows what a selection really runs and how each test check is + attributed. + """ + let selectedCheck( + ws: Workspace!, + fixture: Directory!, + args: [String!]!, + passed: Int!, + failed: Int! = 0, + messages: [String!]! = [], + module: String! = "pytest", + # A nested engine for the tests would only slow this down. + settings: String! = "nesting = false\n", + ): String! { + let result = cli(ws, fixture, [module], moduleConfig(module, settings), ["check", "--generated=false"] + args) + let output = result.stdout + result.stderr + assert((result.exitCode == 0) == (failed == 0), "unexpected check exit status:\n" + output) + assert(checkSummaryMatches(output, passed, failed), "unexpected Dagger check totals:\n" + output) + messages.map { message => + assert(output.contains(message), "missing " + message + ":\n" + output) + } + output + } + + let selectionPyproject(name: String!): String! { + "[project]\nname = \"" + name + "\"\nversion = \"0\"\nrequires-python = \">=3.10\"\n" + } + + let selectionTests: String! = "def test_foo():\n pass\n\n\ndef test_bar():\n pass\n\n\ndef test_other():\n raise AssertionError(\"excluded test ran\")\n" + + """ + Two projects of three test files, each with test_foo, test_bar and a + test_other that fails if it runs. The third file fails to import, so it + fails the run if it is collected at all. + """ + let selectionFixture: Directory! { + ["p1", "p2"].reduce(directory) { fixture, project => + fixture + .withNewFile(project + "/pyproject.toml", selectionPyproject(project)) + .withNewFile(project + "/tests/test_a.py", selectionTests) + .withNewFile(project + "/tests/test_b.py", selectionTests) + .withNewFile(project + "/tests/test_unused.py", "raise ImportError(\"excluded file ran\")\n\n\n" + selectionTests) + } + } + + let selectionArgs: [String!]! { + ["p1", "p2"].map { project => "--pytest-project=" + project } + + ["tests/test_a.py", "tests/test_b.py"].map { file => "--pytest-test-file=" + file } + + ["test_foo", "test_bar"].map { name => "--pytest-test=" + name } + } + + """ + A selection over two projects, two files and two tests runs exactly those + eight checks, and nothing it leaves out runs. + """ + selectedTestsCheck(ws: Workspace!): Void @check { + selectedCheck(ws, selectionFixture, selectionArgs, passed: 8) + null + } + + """ + With only files selected, each file runs as a whole, so a failing test in + it fails its own check and no other. + """ + selectedFileCheck(ws: Workspace!): Void @check { + selectedCheck( + ws, + selectionFixture, + ["--pytest-project=p1", "--pytest-test-file=tests/test_a.py"], + passed: 2, + failed: 1, + # The report may show the failing test's span rather than the check's + # own error when it has one, so assert what both show. + messages: ["excluded test ran"], + ) + null + } + + """ + A failing selected test fails only its own check. + """ + selectedFailureCheck(ws: Workspace!): Void @check { + let fixture = selectionFixture.withNewFile( + "p1/tests/test_a.py", + "def test_foo():\n raise AssertionError(\"selected failure\")\n\n\ndef test_bar():\n pass\n", + ) + selectedCheck(ws, fixture, selectionArgs, passed: 7, failed: 1, messages: ["selected failure"]) + null + } + + """ + A file that fails to import fails every selected test in it, and only + those: the other files of the project still run. + """ + selectedImportFailureCheck(ws: Workspace!): Void @check { + let fixture = selectionFixture.withNewFile("p2/tests/test_a.py", "import no_such_module\n\n\n" + selectionTests) + selectedCheck( + ws, + fixture, + selectionArgs, + passed: 6, + failed: 2, + messages: ["tests/test_a.py failed outside a selected test check", "no_such_module"], + ) + null + } + + # One project of two passing tests, run as a whole. + let reportingFixture: Directory! { + directory + .withNewFile("r/pyproject.toml", selectionPyproject("r")) + .withNewFile("r/tests/test_ok.py", "def test_ok():\n pass\n") + .withNewFile("r/tests/test_visible.py", "def test_visible():\n pass\n") + } + + # A test pytest collects but discovery misses: it is not declared at the + # top level of its file. + let hiddenFailure: String! = "\n\nif True:\n\n def test_hidden():\n raise AssertionError(\"undiscovered failure\")\n" + + """ + A failure in a file with no test checks fails every check of the project + run: it belongs to none of them, and passing them all would hide it. + """ + selectedOutsideFailureCheck(ws: Workspace!): Void @check { + selectedCheck( + ws, + reportingFixture.withNewFile("r/tests/test_hidden.py", hiddenFailure), + ["--pytest-project=r"], + passed: 0, + failed: 2, + messages: ["undiscovered failure"], + ) + null + } + + """ + A failing test discovery missed, in a file it found, fails that file's + checks and no other. + """ + selectedUndiscoveredFailureCheck(ws: Workspace!): Void @check { + selectedCheck( + ws, + reportingFixture.withNewFile("r/tests/test_visible.py", "def test_visible():\n pass\n" + hiddenFailure), + ["--pytest-project=r"], + passed: 1, + failed: 1, + messages: ["pytest-test-file=tests/test_visible.py&pytest-test=test_visible", "undiscovered failure"], + ) + null + } + + """ + A selected test pytest never runs fails rather than passing with nothing + behind it: a test class with __init__ is declared like a test, but pytest + does not collect it. + """ + selectedNeverRanCheck(ws: Workspace!): Void @check { + selectedCheck( + ws, + reportingFixture.withNewFile( + "r/tests/test_visible.py", + "def test_visible():\n pass\n\n\nclass TestHelper:\n def __init__(self):\n pass\n\n def test_x(self):\n pass\n", + ), + ["--pytest-project=r"], + passed: 2, + failed: 1, + messages: ["TestHelper did not run: pytest passed tests/test_visible.py without it"], + ) + null + } + + """ + For ruff, as for mypy, ty and uv, a project is a check of its own: each + selected project runs its own command and fails on its own, a project left + out is not run, and no collection-level check runs them a second time. + """ + selectedProjectsCheck(ws: Workspace!): Void @check { + let fixture = directory + .withNewFile("a/pyproject.toml", selectionPyproject("a")) + .withNewFile("a/clean.py", "VALUE = 1\n") + .withNewFile("b/pyproject.toml", selectionPyproject("b")) + .withNewFile("b/unused.py", "import os\n") + .withNewFile("c/pyproject.toml", selectionPyproject("c")) + .withNewFile("c/unused.py", "import sys\n") + selectedCheck( + ws, + fixture, + ["--ruff-project=a", "--ruff-project=b"], + passed: 1, + failed: 1, + messages: ["check=lint&ruff-project=b", "ruff check failed (ruff check, exit code 1)", "F401"], + module: "ruff", + settings: "", + ) + null + } + + """ + Every test check of a project reads the one pytest run of that project: + each test fails with a token its session drew at random, and every failure + in a project carries the same token, while the two projects' differ. + """ + selectedOneRunCheck(ws: Workspace!): Void @check { + let fixture = ["p1", "p2"].reduce(directory) { fixture, project => + let failing = "def test_foo(token):\n raise AssertionError(\"RUN-TOKEN " + project + " \" + token)\n\n\n" + + "def test_bar(token):\n raise AssertionError(\"RUN-TOKEN " + project + " \" + token)\n" + fixture + .withNewFile(project + "/pyproject.toml", selectionPyproject(project)) + .withNewFile( + project + "/tests/conftest.py", + "import os\n\nimport pytest\n\n\n@pytest.fixture(scope=\"session\")\ndef token():\n return os.urandom(8).hex()\n", + ) + .withNewFile(project + "/tests/test_a.py", failing) + .withNewFile(project + "/tests/test_b.py", failing) + } + let output = selectedCheck(ws, fixture, selectionArgs, passed: 0, failed: 8) + let p1 = output.matchAll(`RUN-TOKEN p1 ([0-9a-f]{16})`).map { m => m.captures[0] ?? "" } + let p2 = output.matchAll(`RUN-TOKEN p2 ([0-9a-f]{16})`).map { m => m.captures[0] ?? "" } + assert(p1.length >= 4 and p2.length >= 4, "not every failing check showed its run's token:\n" + output) + assert(p1.uniq.length == 1, "project p1 ran pytest more than once: " + p1.uniq.join(", ")) + assert(p2.uniq.length == 1, "project p2 ran pytest more than once: " + p2.uniq.join(", ")) + assert(p1.uniq != p2.uniq, "two projects shared one pytest run") + null + } + + """ + Under pytest-xdist, workers collect for themselves, and the selection still + holds there: excluded tests and files do not run. + """ + selectedXdistCheck(ws: Workspace!): Void @check { + let fixture = ["p1", "p2"].reduce(selectionFixture) { fixture, project => + fixture.withNewFile( + project + "/pyproject.toml", + selectionPyproject(project) + "dependencies = [\"pytest-xdist==3.8.0\"]\n", + ) + } + # The selected tests fail unless an xdist worker runs them, so a setting + # that did not reach pytest cannot pass for one that did. + let inWorker = "import os\n\n\ndef test_foo():\n assert os.environ.get(\"PYTEST_XDIST_WORKER\")\n\n\n" + + "def test_bar():\n assert os.environ.get(\"PYTEST_XDIST_WORKER\")\n\n\n" + + "def test_other():\n raise AssertionError(\"excluded test ran\")\n" + let workers = ["p1", "p2"].reduce(fixture) { files, project => + files.withNewFile(project + "/tests/test_a.py", inWorker).withNewFile(project + "/tests/test_b.py", inWorker) + } + selectedCheck(ws, workers, selectionArgs, passed: 8, settings: "nesting = false\nargs = [\"-v\", \"-n\", \"2\"]\n") + null + } + + """ + An environment that cannot be built fails every selected test of its + project, and no other project's. + """ + selectedEnvironmentFailureCheck(ws: Workspace!): Void @check { + let fixture = selectionFixture.withNewFile( + "p2/pyproject.toml", + selectionPyproject("p2") + "dependencies = [\"dagger-e2e-no-such-package==0.0.0\"]\n", + ) + selectedCheck(ws, fixture, selectionArgs, passed: 4, failed: 4, messages: ["environment failed"]) + null + } + + """ + For mypy, as for ty and pytest, an environment that cannot be built fails + its own project's check and no other. + """ + selectedTypeCheckProjectsCheck(ws: Workspace!): Void @check { + let fixture = directory + .withNewFile("a/pyproject.toml", selectionPyproject("a")) + .withNewFile("a/main.py", "VALUE: int = 1\n") + .withNewFile("b/pyproject.toml", selectionPyproject("b") + "dependencies = [\"dagger-e2e-no-such-package==0.0.0\"]\n") + .withNewFile("b/main.py", "VALUE: int = 1\n") + .withNewFile("c/pyproject.toml", selectionPyproject("c")) + .withNewFile("c/main.py", "VALUE: int = \"not an int\"\n") + selectedCheck( + ws, + fixture, + ["--mypy-project=a", "--mypy-project=b"], + passed: 1, + failed: 1, + messages: ["check=type-check&mypy-project=b", "environment failed"], + module: "mypy", + settings: "", + ) + null + } + + """ + Listing runs no tool and builds no environment: with every module's base + an image that has no Python, uv or ruff, so any tool step would fail, a + dependency that does not exist, a lockfile and a config that are garbage, + and a test file that cannot import, every module still lists its checks. + (A setting's image is resolved when the module loads, so the base must + exist.) + """ + listingCheck(ws: Workspace!): Void @check { + let broken = "\"alpine:3.24.1\"" + let modules = ["pytest", "ruff", "mypy", "ty", "uv"] + let config = modules.map { module => + moduleConfig(module, if (module == "ruff") { "container = " + broken } else { "base = " + broken }) + }.join("\n") + let fixture = directory + .withNewFile("app/pyproject.toml", selectionPyproject("app") + "dependencies = [\"dagger-e2e-no-such-package==0.0.0\"]\n") + .withNewFile("app/uv.lock", "this is not a lockfile\n") + .withNewFile("app/ruff.toml", "this is not toml\n") + .withNewFile("app/main.py", "import no_such_module\n") + .withNewFile("app/tests/test_app.py", "import no_such_module\n\n\ndef test_listed():\n pass\n") + let result = cli(ws, fixture, modules, config, ["check", "-l", "--all", "-f", "cli"]) + let output = result.stdout + result.stderr + assert(result.exitCode == 0, "listing failed:\n" + output) + [ + "--pytest-project=app --pytest-test-file=tests/test_app.py --pytest-test=test_listed", + "--ruff-project=app", + "--mypy-project=app", + "--ty-project=app", + "--uv-project=app", + ].map { row => assert(output.contains(row), "listing missed " + row + ":\n" + output) } null } } diff --git a/AGENTS.md b/AGENTS.md index 1c58fff..527c4d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,14 +5,24 @@ One repository, one module per directory: - `pyproject/` — the shared library. It never gets `@check` functions. - `ruff/`, `pytest/`, `uv/`, `mypy/`, `ty/` — tool modules, each with its own checks. `ruff/` never runs through uv; it is a standalone binary. Each one's - `projects` is a Dagger collection keyed by project root: checks live on the - item type, and the collection's batch functions run them over a selection. + `projects` is a Dagger collection keyed by project root, and checks live on + item types only: collection-level functions are plain helpers, never checks + or generators. There is no `.batch` namespace. pytest's leaves are + top-level tests (project > test file > test); every test check of a project + takes the engine-filtered `tests` collection as its `selection` and shares + one pytest command, whose report `pytest/helpers/pytest-report` indexes into + one result per check. Keep that command byte-identical for every check of a + project: build it only from the sorted selection, never from the check's + own name. - `.dagger/modules/e2e` — one end-to-end suite covering every module. - `testdata/` — fixture projects shared by the suite. Several fail on purpose. The design this implements is `hack/designs/python-modules-design.html`. -To run the tests: `dagger check -m .dagger/modules/e2e`. Collections need -engine v1.0.0-beta.15 or later; until it is released, use a dev engine. +To run the tests: `dagger check --e-2-e`. The modules need engine +v1.0.0-beta.22 or later, for selected collection arguments on checks. Direct +Dang calls do not apply the engine's filtered collection view, so selection +and per-test attribution are tested through the CLI, by the suite's +`selected-*` checks. When changing a module, always make sure the tests are up to date. diff --git a/README.md b/README.md index 61d9080..82354fe 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,10 @@ github.com/dagger/python ## Requirements -Every module requires Dagger v1.0.0-beta.15 or later. +Every module requires Dagger v1.0.0-beta.22 or later, for selected collection +arguments on checks: each pytest test check receives its project's filtered +test file collection and passes it to one shared run (see [One run per +project](#one-run-per-project)). ## Install @@ -46,9 +49,10 @@ library; see "Relationship to the standalone modules" below. Each tool module's `projects` is a Dagger collection keyed by project root, so it adds a dimension — `ruff-project`, `pytest-project`, `mypy-project`, -`ty-project`, `uv-project` — that checks and generators select on. pytest adds a -second one under it, `pytest-test-file`, keyed by test file. For a repository -with projects `app` and `libs/core`: +`ty-project`, `uv-project` — that checks and generators select on. pytest adds +two more under it: `pytest-test-file`, keyed by test file, and under that +`pytest-test`, keyed by top-level test. For a repository with projects `app` +and `libs/core`: ```console $ dagger list ruff-projects -a @@ -56,13 +60,14 @@ $ dagger list pytest-test-files --pytest-project=app -a $ dagger check --ruff --check lint --ruff-project=app $ dagger check --check type-check # mypy and ty together $ dagger check --pytest --pytest-project=app --pytest-test-file=tests/test_api.py +$ dagger check --pytest --pytest-project=app --pytest-test=test_login $ dagger generate --ruff --ruff-project=app # ruff format $ dagger check -l --all --ruff -f=cli # one line per project, as flags ``` `dagger check --help` lists the flags in effect: `--ruff-project`, -`--pytest-project`, `--pytest-test-file`, `--mypy-project`, `--ty-project` and -`--uv-project` select keys (`--ruff-projects`, `--pytest-tests` and so on select +`--pytest-project`, `--pytest-test-file`, `--pytest-test`, `--mypy-project`, +`--ty-project` and `--uv-project` select keys (`--ruff-projects`, `--pytest-tests` and so on select a whole dimension); `--ruff`, `--pytest`, `--mypy`, `--ty` and `--uv` select a module; and `--check ` selects a check by name across modules: `lint`, `test`, `type-check`, `audit`, or `stale` for the generators' staleness checks. @@ -118,13 +123,24 @@ project holding it, so a nested project's files are never its parent's. From inside a project, one more `findRoots` finds that project's nested projects. pytest's test files are `test_*.py` and `*_test.py` files holding a line that -declares a test pytest collects by default: `def test…`, `async def test…` or -`class Test…`. A helper module named like a test file is not listed, since -running it alone collects nothing. What a search cannot see is not listed -either: a test built at runtime, or one found through a project's own -`python_files`, `python_classes`, `python_functions` or `testpaths`. The -whole-project run still collects those, because it runs pytest the way the -project configures it. +declares, at the top level, a test pytest collects by default: `def test…`, +`async def test…` or `class Test…`. Each such declaration is one test, and the +same search that finds the files names them. A helper module named like a test +file is not listed, since running it alone collects nothing. What a search +cannot see is not listed either: a test built at runtime, one declared inside +an `if`, or one found through a project's own `python_files`, +`python_classes`, `python_functions` or `testpaths`. The whole-project run +still collects those, because it runs pytest the way the project configures +it, and fails every check of the project if one of them fails. Files under a +directory pytest's default `norecursedirs` skips — `build`, `dist`, `venv`, +`node_modules`, `*.egg`, a dot-directory — are not listed, as a +whole-project run collects none of them. Where discovery and pytest still +disagree, the test that pytest never runs fails, saying so. + +Listing runs no tool and builds no environment: no `uv sync`, no pytest +collection, no container at all. A project whose dependencies cannot be +installed, or whose test files cannot import, still lists its checks; the +run reports the failure, on those checks. On a tree with 40 projects and 16,000 files in their virtualenvs, discovery for `dagger check -l --all` with all five modules installed takes 4–8 seconds, @@ -188,11 +204,66 @@ mypy type check failed: Found 1 error in 1 file (checked 4 source files) ``` -### Batches - -Every check runs once per selected set of keys, through the collection's batch -function, rather than once per project. A batch runs the projects in parallel -and, when some fail, names every failing project: +### One run per project + +The project is the unit that owns a tool's configuration, environment and +container, so no two projects ever share a command, and nothing inside one +project runs its tool twice. + +For ruff, mypy, ty and uv the project is also the check: `lint`, +`type-check`, `audit` and the `format` and `lock` generators each run one +command over the project. Those tools take files as arguments, but a project's +check is not the sum of per-file checks — mypy and ty check a whole program, +and a file list on the command line overrides the files the project's own +config names — and their machine output lists only diagnostics, so a file that +passed and a file the tool never read look the same. A per-file check could +not tell them apart, so there is none. + +pytest goes one level further, as `go test` does in `dagger/go`. Each selected +top-level test — a module-level `test…` function, with all its parameters, or +a `Test…` class, with all its tests — has its own check. Every test check of a +project receives the same engine-filtered `tests` collection and calls the same +helper, which runs one pytest command and returns a shared report. The engine +deduplicates the identical container operations, so a project's selected +tests cost one pytest run, however many checks they are: + +- With nothing selected out at any level, pytest runs the project as it + collects it, honouring its own `testpaths` and `python_files`. +- With test files selected out, it runs the selected files. +- With tests selected out too, it runs the selected files, and a bundled + plugin deselects every top-level test outside the selection, as `go test + -run` leaves tests out. + +The command is built from the sorted selection, so every check builds the +same bytes. The bundled plugin is loaded by name, so pytest-xdist workers +(`-n` in `args`) load it too and apply the same selection where they collect. It runs with `--continue-on-collection-errors` and never raises; +the bundled runner writes every report pytest makes as a JSON line, and an +indexer reads that report once and writes one bounded result per check. Each +check reads its own: failure messages keep the last 32 KiB of each diagnostic +stream, and no result exceeds 96 KiB, however large the run. + +A failed test fails its own check, with the output of every parameter or +method that failed. A test file that fails to import, skips at module level +aside, fails every selected test in it, and so does a failing test discovery +did not list in a file it did. A failure in a file with no selected test, or a +non-zero exit with no failure to show for it, fails every check sharing the +command: it belongs to none of them, and passing them would hide it. A +selected test pytest never runs while its file passes fails, saying it did not +run, rather than passing with nothing behind it — a test class with an +`__init__` is the usual case. A test the project's own `-m`, `-k` or `addopts` +deselects passes, and so does a test `-x` or `--maxfail` never reached after +a reported failure. Otherwise passing tests pass. + +Logs and test spans belong to the check that started the shared command; +the other checks share its result. A whole-project run also runs the +project's tests that are no check, so their failures fail every check of the +project. + +The collection-level functions — `projects(...).lint`, `type-check`, `audit`, +`format`, `lock`, `build` and `test`, and pytest's `tests(...).test` — are +plain functions rather than checks or generators, so `dagger check` and +`dagger generate` never run the same work twice. They run every selected +project and, when some fail, name every failing project: ``` ruff lint failed: @@ -200,6 +271,15 @@ ruff lint failed: - testdata/project-ruff-toml: exit code: 2 ``` +There is no `.batch` namespace. Where a caller wrote +`run(projects(ws).batch.lint(ws))`, it now writes `projects(ws).lint(ws)`: the +helper returns `Void` and raises on failure, so it is not wrapped as a +`Check`. The same holds for `typeCheck`, `audit` and pytest's `test`; +`batch.format`, `batch.fix`, `batch.lock` and `batch.build` become `format`, +`fix`, `lock` and `build`. A pytest test file has no `test` of its own any +more: run one with `tests(ws).subset(keys: [file]).test(ws)`, or one test +through its check, as below. + Generators return one changeset over the selected projects, rooted at the cwd, where `dagger generate` applies it. From inside a project, that changeset holds only the part of the project below the cwd, since a changeset applied there @@ -219,17 +299,24 @@ let run(check: Check!): Void { null } -run(ruff.projects(ws).batch.lint(ws)) # every project -run(ruff.projects(ws).subset(keys: ["app", "libs/core"]).batch.lint(ws)) -run(ruff.projects(ws).get(key: "app").lint(ws)) # one project -let changes = ruff.projects(ws).batch.format(ws) # a Changeset +ruff.projects(ws).lint(ws) # plain: raises on failure +ruff.projects(ws).subset(keys: ["app", "libs/core"]).lint(ws) +run(ruff.projects(ws).get(key: "app").lint(ws)) # one project's check +let changes = ruff.projects(ws).format(ws) # a Changeset run(mypy.project(ws, "app/src").typeCheck(ws)) # by any path inside -pytest.projects(ws).batch.test(ws) # plain: raises on failure -run(pytest.project(ws, "app").tests(ws).subset(keys: ["tests/test_api.py"]).batch.test(ws)) +pytest.projects(ws).test(ws) # each project as a whole + +let files = pytest.project(ws, "app").tests(ws) +files.subset(keys: ["tests/test_api.py"]).test(ws) # one run, every failure +run(files.get(key: "tests/test_api.py").tests.get(key: "test_login").test(ws, selection: files)) ``` `projects(ws).keys` lists the keys, `get(key:)` builds one item, and -`subset(keys:)` narrows the batch. `dagger call` cannot step into a collection +`subset(keys:)` narrows a collection. A test check called directly takes the +collection to run as its `selection`; the shared run covers all of it, and the +check reads only its own result. A direct call has no engine selection, so +the run lists the files and tests explicitly rather than running the project +as pytest collects it. `dagger call` cannot step into a collection yet; use `dagger check`, `dagger list`, `dagger -c`, or a module. ## Scoping @@ -287,8 +374,9 @@ Pass `includeSkipped: false` to `projects` to leave such projects out. On a project: `lint` (a `@check`, `ruff check`), `format` (a `@generate`, `ruff format`), `fix` (`ruff check --fix --exit-zero`, returns a changeset), -`version`, `pinned-version` and `skip`. The collection's batch `lint`, `format` and `fix` run once over the -selected projects. +`version`, `pinned-version` and `skip`. The collection's `lint`, `format` and +`fix` are plain functions over the selected projects, each with its own +command. `format` is a generator, so `dagger generate` applies it and `dagger check` fails when a project is not formatted, as ruff's `stale` check. `fix` is not a @@ -334,26 +422,29 @@ mount. | `base` | none | Base image with Python and uv, instead of the default one. | On a project: `tests`, `test`, `has-tests`, `version`, `skip`. `tests` is a -collection of the project's test files, keyed by project-relative path, and its -`test` is the check: +collection of the project's test files, keyed by project-relative path; each +file's `tests` is a collection of its top-level tests, keyed by name; and a +test's `test` is the check: ```console $ dagger check --pytest --pytest-project=sdk # whole project $ dagger check --pytest --pytest-project=sdk --pytest-test-file=tests/test_api.py +$ dagger check --pytest --pytest-test=test_login --pytest-test-file=tests/test_api.py ``` -With every test file of a project selected, the batch runs `pytest` over the -whole project, as pytest collects it; with some filtered out, it runs `pytest` -over the selected files only. One run happens per project either way. +A test name in two files selects both; `--pytest-test-file` narrows that. One +pytest run happens per project, whatever is selected: see [One run per +project](#one-run-per-project). -Test files are found as described in [How projects are -found](#how-projects-are-found): by name and by a test declaration, without -running pytest. +Tests are found as described in [How projects are +found](#how-projects-are-found): by file name and by a top-level test +declaration, without running pytest. -`test` on a project and on `projects` are plain functions rather than checks, -so that `dagger check` does not run the same tests twice. The `projects` batch -`test` runs every selected project even after one fails, then lists each -failing project by path. +`test` on a project, on `projects` and on `tests` are plain functions rather +than checks, so that `dagger check` does not run the same tests twice. The +`projects` one runs every selected project as a whole, even after one fails, +then lists each failing project by path; the `tests` one runs the selected +files in one shared run and lists each failing test. A project with no test files is not a key, and its `test` does nothing: bare pytest exits 5 on an empty collection, so running it there would fail a project @@ -394,9 +485,9 @@ the module its address names instead of looking for it inside this module. On a project: `audit` (a `@check`, `uv audit`), `lock` (a `@generate`, `uv lock`), `build` (`uv build`, returns `dist` with the wheel and sdist), -`has-lockfile`, `skip-lock` and `skip-audit`. The collection's batch `audit`, -`lock` and `build` run once over the selected projects; the batch `build` -places each `dist` under its project root. +`has-lockfile`, `skip-lock` and `skip-audit`. The collection's `audit`, `lock` +and `build` are plain functions over the selected projects; its `build` places +each `dist` under its project root. `audit` runs `uv audit --locked` over the lockfile. To leave dependency groups out, pass uv's own flags: `["--no-dev"]` for the `dev` group, @@ -458,6 +549,7 @@ with a check for the same tool would run that tool twice. | `roots` | Their roots, workspace-root-relative, in byte order. | | `roots-owning` | The roots owning a file that matches a glob and a pattern. | | `owned-files` | Those files, workspace-root-relative, from the same one search. | +| `owned-matches` | The matching lines in those files, from the same one search. | | `roots-with` | The roots holding a named file, such as `uv.lock`. | | `project` | The project containing a workspace path. | | `at` | The project rooted at a path, with no lookup. | @@ -478,6 +570,7 @@ On a project: | `sync-flags` | `--locked` when the project has a `uv.lock`. | | `uv-run` | The start of a `uv run` command for a tool in `env`. | | `step` | Run a command, failing with its name, command, exit code and output. | +| `attempt` | Run a command whatever its exit code, its output redirected to files, for a tool whose report several checks share. | | `absorbed` | uv workspace members and path sources below this project that belong to it. | | `version-from-vcs` | Whether the project's version comes from version control. | | `sets-key` | Whether a config file sets a key in a section. | @@ -488,6 +581,8 @@ On a project: | `search-files` | Files below this root matching a glob and a pattern (one search). | | `has-own-files` | Whether files matching a glob are this project's, not a child's. | | `own-files` | Those files, project-relative, unique and in byte order. | +| `search-matches` | The matching lines below this root (one search). | +| `own-matches` | Those lines in this project's own files, project-relative paths. | | `cwd-path` | Where this project's changes land in a changeset rooted at the cwd. | | `cwd-subpath` | The part of this project such a changeset can hold. | | `tool-version` | The version of a tool this project pins, or null. | @@ -553,10 +648,22 @@ Two differences are worth knowing before you switch: ## Development ```sh -dagger check -m .dagger/modules/e2e +dagger check --e-2-e ``` -The suite requires Dagger v1.0.0-beta.15 or later, as the modules do. +The suite requires Dagger v1.0.0-beta.22 or later, as the modules do. + +Direct Dang calls do not apply the engine's filtered collection view, so the +`selected-*` checks run `dagger check` itself, with the engine's own CLI, over +small fixture workspaces that install `pytest` from this repository, and +assert the check totals and messages: several projects and files, excluded +tests that must not run (also under pytest-xdist), a failing test, a file that +fails to import, an environment that cannot be built, failures outside any +selected test, a selected test pytest never runs, and per-project checks for +ruff and mypy. `selected-one-run-check` asserts that every test check of a +project reads one pytest run, and `listing-check` that listing runs no tool: +it lists all five modules over a project whose dependencies, lockfile, +config and imports are all broken, with base images that hold no tool. `testdata/` holds the fixture projects the suite runs against. Several of them fail on purpose — a failing test, a type error, a stale lockfile — and the diff --git a/mypy/dagger-module.toml b/mypy/dagger-module.toml index 6defaf3..ab5913f 100644 --- a/mypy/dagger-module.toml +++ b/mypy/dagger-module.toml @@ -1,5 +1,5 @@ name = "mypy" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/mypy/main.dang b/mypy/main.dang index 432c6bb..13b9242 100644 --- a/mypy/main.dang +++ b/mypy/main.dang @@ -141,9 +141,12 @@ type MypyProjects @collection { } """ - Type check the selected projects with mypy. + Type check the selected projects with mypy, each with its own command. + + A plain function rather than a check, so that `dagger check` does not run + the same work twice: each project's own `typeCheck` is its check. """ - typeCheck(ws: Workspace!): Void @check { + typeCheck(ws: Workspace!): Void { # A selection over a list evaluates its elements concurrently, so every # project is checked in parallel and every failure is reported. let failures = paths.map { p => project(p) }.{{path, failure: typeCheckFailure(ws)}} diff --git a/pyproject/dagger-module.toml b/pyproject/dagger-module.toml index 58e34d9..9756554 100644 --- a/pyproject/dagger-module.toml +++ b/pyproject/dagger-module.toml @@ -1,5 +1,5 @@ name = "pyproject" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/pyproject/main.dang b/pyproject/main.dang index bcf8798..f998060 100644 --- a/pyproject/main.dang +++ b/pyproject/main.dang @@ -249,6 +249,21 @@ type Pyproject { ) } + """ + The lines matching `pattern` in the files, among those the projects in + `roots` own, that match the ripgrep `globs`. One search covers every + project, as for `ownedFiles`, so this runs no container. Paths are + workspace-root-relative; the order is the search's own, so a caller that + needs one sorts. + """ + ownedMatches(ws: Workspace!, globs: [String!]!, pattern: String!): [PythonMatch!]! { + let candidates = roots(ws) + let all = ownershipRoots(ws, candidates) + at(searchBase(ws, candidates)).searchMatches(ws, globs, pattern).filter { found => + candidates.contains(ownerOf(all, parentPath(found.path))) + } + } + """ The directory one search has to cover: the enclosing project when the cwd is inside one, since its files outside the cwd are its own too, else the cwd. @@ -723,6 +738,40 @@ type PythonProject { .uniq } + """ + The lines matching `pattern` in the files at or below this project root that + match the ripgrep `globs`, from one search with `exclude` pruned. Nested + projects' files included; paths are workspace-root-relative. + """ + searchMatches(ws: Workspace!, globs: [String!]!, pattern: String!): [PythonMatch!]! { + ws + .search(paths: ["/" + subpath("")], globs: globs + searchExcludes, pattern: pattern) + .{{filePath, matchedLines}} + .map { found => + PythonMatch( + path: found.filePath.trimPrefix("/").trimPrefix("./"), + line: found.matchedLines.trimSuffix("\n").trimSuffix("\r"), + ) + } + } + + """ + The lines matching `pattern` in the files matching the ripgrep `globs` that + belong to this project rather than to a project nested inside it, with + project-relative paths. The order is the search's own. + """ + ownMatches(ws: Workspace!, globs: [String!]!, pattern: String!): [PythonMatch!]! { + let nested = nestedProjects(ws) + searchMatches(ws, globs, pattern) + .map { found => + PythonMatch( + path: if (path == ".") { found.path } else { found.path.trimPrefix(path + "/") }, + line: found.line, + ) + } + .reject { found => nested.any { dir => found.path.hasPrefix(dir + "/") } } + } + """ `exclude` as ripgrep globs. A "dir/**" pattern also names the directory itself, so ripgrep skips it instead of walking every file inside. @@ -968,6 +1017,49 @@ type PythonProject { what: String!, nesting: Boolean! = false, ): Container! { + let done = nestable(ctr, nesting).withExec(args, expect: ReturnType.ANY, daggerInDaggerNewSession: nesting) + let code = done.exitCode + if (code == 0) { + done + } else { + let tail = (done.stdout + "\n" + done.stderr) + .split("\n") + .reject { line => line.trimSpace == "" } + .takeLast(12) + .map { line => " " + line } + .join("\n") + let detail = if (tail == "") { "" } else { ":\n" + tail } + raise what + " failed (" + args.join(" ") + ", exit code " + toString(code) + ")" + detail + } + } + + """ + Run one step whatever its exit code, with its stdout and stderr redirected + to the named files, for a caller that reads a machine report and the exit + code rather than having the step raise. + + A tool whose results are shared between several checks runs here: a raise + would fail every one of them with the same message, while the report can + say which of them actually failed. + """ + attempt( + ctr: Container!, + args: [String!]!, + stdout: String!, + stderr: String!, + nesting: Boolean! = false, + ): Container! { + nestable(ctr, nesting).withExec( + args, + expect: ReturnType.ANY, + redirectStdout: stdout, + redirectStderr: stderr, + daggerInDaggerNewSession: nesting, + ) + } + + # A container ready to run a step that may talk to a nested Dagger engine. + let nestable(ctr: Container!, nesting: Boolean!): Container! { # A nested session finds its workspace root by walking up to a .git # directory, and the container mirrors the workspace under /ws, so without # a marker there the session gets an empty workspace and every @@ -982,27 +1074,13 @@ type PythonProject { # one at /dev/.dagger/dagger; name it, because the SDK otherwise downloads # the release its own client was generated against, over the network and # against an engine of whatever version the user is on. - let nested = if (nesting) { + if (nesting) { ctr .withDirectory(mountRoot + "/.git", directory) .withEnvVariable("_EXPERIMENTAL_DAGGER_CLI_BIN", "/dev/.dagger/dagger") } else { ctr } - let done = nested.withExec(args, expect: ReturnType.ANY, daggerInDaggerNewSession: nesting) - let code = done.exitCode - if (code == 0) { - done - } else { - let tail = (done.stdout + "\n" + done.stderr) - .split("\n") - .reject { line => line.trimSpace == "" } - .takeLast(12) - .map { line => " " + line } - .join("\n") - let detail = if (tail == "") { "" } else { ":\n" + tail } - raise what + " failed (" + args.join(" ") + ", exit code " + toString(code) + ")" + detail - } } """ @@ -1226,3 +1304,19 @@ type PythonProject { } } } + +""" +A line one workspace search matched. +""" +type PythonMatch { + """ + The file that holds the line: workspace-root-relative, or project-relative + from a project's own search. + """ + path: String! + + """ + The matched line, without its line ending. + """ + line: String! +} diff --git a/pytest/dagger-module.toml b/pytest/dagger-module.toml index 57ffb32..a944657 100644 --- a/pytest/dagger-module.toml +++ b/pytest/dagger-module.toml @@ -1,5 +1,5 @@ name = "pytest" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/pytest/helpers/pytest-report/dagger_pytest_index.py b/pytest/helpers/pytest-report/dagger_pytest_index.py new file mode 100644 index 0000000..46b4afa --- /dev/null +++ b/pytest/helpers/pytest-report/dagger_pytest_index.py @@ -0,0 +1,235 @@ +"""Read one shared pytest report and write a bounded result for each test check. + + python -I dagger_pytest_index.py --report FILE --stdout FILE --stderr FILE \ + --selection FILE --exit-code N --output DIR + +The selection is a JSON list of {"path", "names"}: the test files of one +project, relative to its root, and the top-level tests of each that are +checks. The report is the JSON lines dagger_pytest_report.py wrote. + +Every check gets a file at DIR//, ranks counted in byte +order, so a file or test name never becomes a path. An empty file is a pass; +anything else is the check's failure message, at most 96 KiB however large the +report is. +""" + +import argparse +import json +import os +import sys + +DIAGNOSTIC_LIMIT = 32 << 10 + + +class Tail: + """The last DIAGNOSTIC_LIMIT characters written, whatever was written.""" + + def __init__(self): + self.data = "" + self.truncated = False + + def add(self, text): + if not text: + return + self.data += text if text.endswith("\n") else text + "\n" + if len(self.data) > DIAGNOSTIC_LIMIT: + self.data = self.data[-DIAGNOSTIC_LIMIT:] + self.truncated = True + + def __str__(self): + if self.truncated: + return "[earlier output omitted; showing diagnostic tail]\n" + self.data + return self.data + + +class Test: + def __init__(self): + self.observed = False + self.failed = False + self.started = set() + self.finished = set() + self.log = Tail() + + +class File: + def __init__(self, names): + self.tests = {name: Test() for name in names} + self.failed = False # failed outside every selected test + self.skipped = False + self.log = Tail() + + +def failure_text(event): + text = event.get("longrepr") or "" + for title, body in event.get("sections") or []: + text += "\n" + "-" * 8 + " " + title + " " + "-" * 8 + "\n" + body + return event["nodeid"] + " " + event.get("when", "collection") + " failed\n" + text + + +def summarize(events, selections, exit_code, stdout, stderr): + files = {} + for s in selections: + if not s["path"] or s["path"] in files: + raise ValueError("invalid or duplicate selected file %r" % s["path"]) + if len(set(s["names"])) != len(s["names"]) or not all(s["names"]): + raise ValueError("invalid or duplicate selected test in %s" % s["path"]) + files[s["path"]] = File(s["names"]) + + outside = [] + outside_log = Tail() + any_failure = False + stopped = False + for e in events: + kind = e.get("type") + if kind == "finish": + stopped = bool(e.get("stopped")) + continue + f = files.get(e.get("path")) + t = f.tests.get(e.get("name")) if f is not None else None + if kind == "deselected": + # Left out by the project's own -k, -m or addopts. + if t is not None: + t.observed = True + continue + failed = e.get("outcome") == "failed" + any_failure = any_failure or failed + if kind == "collect": + if t is not None: + # A test class that failed to collect. + t.observed = True + if failed: + t.failed = True + t.log.add(failure_text(e)) + elif f is not None and e.get("name") is None: + if failed: + f.failed = True + f.log.add(failure_text(e)) + else: + f.skipped = True + elif failed: + outside.append(e.get("nodeid") or "") + outside_log.add(failure_text(e)) + continue + if t is None: + if failed: + if f is not None: + # A test the discovery missed, in a file it found. + f.failed = True + f.log.add(failure_text(e)) + else: + outside.append(e["nodeid"]) + outside_log.add(failure_text(e)) + continue + t.observed = True + if e.get("when") == "setup": + t.started.add(e["nodeid"]) + if e.get("when") == "teardown" or (e.get("when") == "setup" and e.get("outcome") != "passed"): + t.finished.add(e["nodeid"]) + if failed: + t.failed = True + t.log.add(failure_text(e)) + + tails = str(stdout) + str(stderr) + global_failure = "" + if outside: + global_failure = ( + "failures outside the selected test checks: " + ", ".join(sorted(set(outside))) + "\n" + + str(outside_log) + tails + ) + elif exit_code != 0 and not any_failure: + global_failure = "shared pytest command failed (pytest exit %d)\n%s" % (exit_code, tails) + + results = {} + for s in selections: + f = files[s["path"]] + for name in s["names"]: + t = f.tests[name] + failure = global_failure + if not failure: + if t.failed: + failure = name + " failed\n" + str(t.log) + elif f.failed: + failure = "%s failed outside a selected test check (pytest exit %d)\n%s" % ( + s["path"], exit_code, str(f.log)) + elif t.observed and t.started - t.finished: + failure = "%s did not finish (pytest exit %d)\n%s" % (name, exit_code, tails) + elif t.observed or f.skipped: + pass + elif exit_code == 0: + # pytest left the test out: discovery read a declaration that + # pytest does not collect, such as a test class with __init__. + failure = "%s did not run: pytest passed %s without it\n%s" % (name, s["path"], str(stdout)) + elif stopped and any_failure: + # -x or --maxfail stopped the session at a reported failure, + # so later tests have no result. That failure is not theirs. + pass + else: + failure = "no result for %s (pytest exit %d)\n%s" % (name, exit_code, tails) + if len(failure) > 3 * DIAGNOSTIC_LIMIT: + failure = failure[: 3 * DIAGNOSTIC_LIMIT] + "\n[remaining diagnostics omitted]\n" + results[(s["path"], name)] = failure + return results + + +def read_events(path): + events = [] + with open(path, encoding="utf-8", errors="replace") as f: + for line in f: + line = line.strip() + if line: + try: + events.append(json.loads(line)) + except ValueError: + # A report cut short by a crash ends in a partial line. + pass + return events + + +def read_tail(path, header): + tail = Tail() + try: + with open(path, encoding="utf-8", errors="replace") as f: + while True: + chunk = f.read(1 << 16) + if not chunk: + break + tail.add(chunk) + except FileNotFoundError: + pass + if not tail.data: + return "" + tail.data = header + "\n" + tail.data + return tail + + +def main(): + parser = argparse.ArgumentParser() + for flag in ("--report", "--stdout", "--stderr", "--selection", "--output"): + parser.add_argument(flag, required=True) + parser.add_argument("--exit-code", type=int, required=True) + args = parser.parse_args() + with open(args.selection, encoding="utf-8") as f: + selections = json.load(f) + results = summarize( + read_events(args.report), + selections, + args.exit_code, + read_tail(args.stdout, "-------- pytest output --------"), + read_tail(args.stderr, "-------- pytest stderr --------"), + ) + # The same byte-order ranks PytestResults.assertPassed counts. + key = lambda text: text.encode("utf-8") + for file_rank, s in enumerate(sorted(selections, key=lambda s: key(s["path"]))): + for test_rank, name in enumerate(sorted(s["names"], key=key)): + out = os.path.join(args.output, str(file_rank), str(test_rank)) + os.makedirs(os.path.dirname(out), exist_ok=True) + with open(out, "w", encoding="utf-8") as f: + f.write(results[(s["path"], name)]) + + +if __name__ == "__main__": + try: + main() + except Exception as err: # noqa: BLE001 - one line, not a traceback + print("pytest report indexer: %s" % err, file=sys.stderr) + sys.exit(1) diff --git a/pytest/helpers/pytest-report/dagger_pytest_report.py b/pytest/helpers/pytest-report/dagger_pytest_report.py new file mode 100644 index 0000000..5c8f22c --- /dev/null +++ b/pytest/helpers/pytest-report/dagger_pytest_report.py @@ -0,0 +1,170 @@ +"""Run pytest once for many Dagger test checks, recording every outcome. + + python dagger_pytest_report.py --report FILE [--selection FILE] -- PYTEST_ARGS + +Each test check is a top-level test of a file: a module-level test function +or a test class. Every report pytest makes is written to FILE as a JSON line +naming the file, relative to the directory pytest runs in, and the top-level +test it belongs to, so the indexer can give each check its own result. + +With --selection, a JSON list of {"path", "names"}, only those top-level tests +of those files run; the others are deselected, as `go test -run` leaves them +out. + +The runner loads this same file as a plugin by name, with `-p`, and hands it +the report and selection through the environment, so pytest-xdist workers, +which are separate processes that collect for themselves, load it and apply +the selection too. Workers only filter and record what they deselect; the +controller records the reports, which xdist forwards to it. + +Only the standard library and pytest are imported: this runs in the project's +own environment. +""" + +import json +import os +import sys + +import pytest + +REPORT = "DAGGER_PYTEST_REPORT" +SELECTION = "DAGGER_PYTEST_SELECTION" + +_state = {} + + +def _write(record): + # Every process appends one line per write, so the controller and xdist + # workers never cut into each other's records. + with open(_state["report"], "a", encoding="utf-8") as out: + out.write(json.dumps(record) + "\n") + + +def _locate(nodeid): + """The file, relative to the cwd, and top-level test of a node id.""" + parts = nodeid.split("::") + path = os.path.relpath(os.path.join(_state["rootdir"], parts[0]), _state["cwd"]) + path = path.replace(os.sep, "/") + # A parametrized function's id is name[params]; the check is the name. + name = parts[1].split("[", 1)[0] if len(parts) > 1 else None + return path, name + + +def _worker(config): + return hasattr(config, "workerinput") + + +@pytest.hookimpl(tryfirst=True) +def pytest_configure(config): + report = os.environ.get(REPORT) + if not report: + return + selection = None + if os.environ.get(SELECTION): + with open(os.environ[SELECTION], encoding="utf-8") as f: + selection = {s["path"]: set(s["names"]) for s in json.load(f)} + root = getattr(config, "rootpath", None) or config.rootdir + _state.update( + report=report, + selection=selection, + cwd=str(config.invocation_params.dir) if hasattr(config, "invocation_params") else os.getcwd(), + rootdir=str(root), + worker=_worker(config), + dropped=set(), + ) + + +@pytest.hookimpl(trylast=True) +def pytest_collection_modifyitems(session, config, items): + if not _state or _state["selection"] is None: + return + keep, drop = [], [] + for item in items: + path, name = _locate(item.nodeid) + (keep if name in _state["selection"].get(path, ()) else drop).append(item) + if drop: + _state["dropped"].update(item.nodeid for item in drop) + config.hook.pytest_deselected(items=drop) + items[:] = keep + + +def pytest_deselected(items): + # Deselected by the project's own -k, -m or addopts rather than by the + # selection: reported, so a check whose tests all are is not taken for one + # that never ran. Under xdist only workers collect, so they write these. + if not _state: + return + for item in items: + if item.nodeid not in _state["dropped"]: + path, name = _locate(item.nodeid) + _write({"type": "deselected", "nodeid": item.nodeid, "path": path, "name": name}) + + +def pytest_collectreport(report): + # A file that fails to import, or skips itself at module level. xdist + # forwards workers' collection reports to the controller. + if not _state or _state["worker"]: + return + if report.failed or report.skipped: + path, name = _locate(report.nodeid) if report.nodeid else ("", None) + _write({ + "type": "collect", + "nodeid": report.nodeid, + "path": path, + "name": name, + "outcome": report.outcome, + "longrepr": report.longreprtext, + }) + + +def pytest_runtest_logreport(report): + if not _state or _state["worker"]: + return + path, name = _locate(report.nodeid) + record = { + "type": "test", + "nodeid": report.nodeid, + "path": path, + "name": name, + "when": report.when, + "outcome": report.outcome, + } + if report.failed: + record["longrepr"] = report.longreprtext + record["sections"] = [[title, text] for title, text in report.sections] + _write(record) + + +def pytest_sessionfinish(session, exitstatus): + if not _state or _state["worker"]: + return + _write({ + "type": "finish", + "exitstatus": int(exitstatus), + # -x and --maxfail stop the session after a failure. + "stopped": bool(session.shouldfail or session.shouldstop), + }) + + +def main(argv): + env = {} + while argv and argv[0] != "--": + flag, value, argv = argv[0], argv[1], argv[2:] + if flag == "--report": + env[REPORT] = value + elif flag == "--selection": + env[SELECTION] = value + else: + sys.exit("unknown flag " + flag) + if REPORT not in env: + sys.exit("--report is required") + os.environ.update(env) + # Workers import the plugin by name, so it must be on their path; keep + # whatever path the base already sets. + here = os.path.dirname(os.path.abspath(__file__)) + os.environ["PYTHONPATH"] = os.pathsep.join(p for p in [here, os.environ.get("PYTHONPATH", "")] if p) + return int(pytest.main(["-p", "dagger_pytest_report"] + argv[1:])) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/pytest/main.dang b/pytest/main.dang index 6bc0abc..f57a7a1 100644 --- a/pytest/main.dang +++ b/pytest/main.dang @@ -31,11 +31,46 @@ type Pytest { let testGlobs: [String!]! = ["test_*.py", "*_test.py"] """ - A line that declares a test pytest collects by default: a function whose - name starts with "test", or a class whose name starts with "Test". A file - matching `testGlobs` without one is a helper, and holds no tests to run. + A line that declares a top-level test pytest collects by default: a + module-level function whose name starts with "test", or a class whose name + starts with "Test". Each one is a test check. A file matching `testGlobs` + without one is a helper, and holds no tests to run. """ - let testLine: String! = `^\s*((async\s+)?def\s+test|class\s+Test)` + let testLine: String! = `^((async\s+)?def\s+test|class\s+Test)` + + """ + The test a `testLine` match declares, as its first capture. + """ + let testName: Regexp! = `^(?:(?:async\s+)?def|class)\s+([^\s(:]+)` + + """ + The bundled pytest runner that records every outcome as a JSON line, and the + indexer that reads that report into one result per test check. + """ + let reportHelpers: Directory! { + currentModule.source.directory("helpers/pytest-report") + } + + """ + A pinned interpreter for the indexer, the same for every project whatever + its base, so its step is shared by every test check of a project. + """ + let indexerBase: Container! { + container.from("python:3.14-slim@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d").withoutEntrypoint + } + + """ + Whether pytest's default recursion collects a project-relative test file: + no directory on its way matches the default `norecursedirs` ("*.egg", ".*", + "_darcs", "build", "CVS", "dist", "node_modules", "venv", "{arch}"). A file + there is listed by no check, as a whole-project run collects none of it. + """ + let collected(file: String!): Boolean! { + file.split("/").dropLast(1).any { dir => + dir.hasPrefix(".") or dir.hasSuffix(".egg") + or ["_darcs", "build", "CVS", "dist", "node_modules", "venv", "{arch}"].contains(dir) + } == false + } """ Python version used for the default base image. Null when a custom base is set. @@ -144,23 +179,66 @@ type Pytest { fault is having no tests yet. """ projects(ws: Workspace!, includeSkipped: Boolean! = true): PytestProjects! { - # One search finds every project's test files, and each project's own are + # One search finds every project's tests, and each project's own are # handed to it from here rather than searched for again. - let files = lib.ownedFiles(ws, testGlobs, pattern: testLine) - let dirs = files.map { file => file.split("/").dropLast(1).join("/") }.uniq + let tests = testNodes(lib.ownedMatches(ws, testGlobs, testLine).{{path, line}}) let roots = lib.roots(ws) PytestProjects( paths: roots - .filter { root => owns(roots, root, dirs) } + .filter { root => + let prefix = if (root == ".") { "" } else { root + "/" } + ownPaths(roots, root, tests).any { test => collected(test.trimPrefix(prefix)) } + } .map { root => pytestProject(root, null) }.{{path, skip}} .filter { project => includeSkipped or project.skip == false } .map { project => project.path }, - testFiles: files, + tests: tests, roots: roots, tool: self, ) } + """ + The top-level tests that `testLine` matches, each as its file path, a tab and + its name, unique and in byte order. A tab sorts below every character of a + path, so a file's tests are adjacent and files come in byte order. + """ + let testNodes(matches: [{{path: String!, line: String!}}!]!): [String!]! { + sorted( + matches.map { found => + found.path + "\t" + found.line.matchAll(testName).map { m => m.captures[0] ?? "" }.join("") + }.reject { node => node.hasSuffix("\t") }, + ).uniq + } + + # Strings in byte order, as Go's sort.Strings orders them. The test command + # every check of a project shares is built from these, so the same selection + # must always give the same bytes. Dang has no list sort. + let sorted(items: [String!]!): [String!]! { + if (items.length < 2) { + items + } else { + let half = items.length / 2 + mergeSorted(sorted(items.takeFirst(half)), sorted(items.dropFirst(half))) + } + } + + let mergeSorted(a: [String!]!, b: [String!]!): [String!]! { + let i = 0 + let j = 0 + (a + b).map { unused => + if (j == b.length or (i < a.length and a[i]! <= b[j]!)) { + let item = a[i]! + i += 1 + item + } else { + let item = b[j]! + j += 1 + item + } + } + } + """ The pytest project containing a workspace path. """ @@ -180,10 +258,6 @@ type Pytest { .reject { path => deeper.any { other => path == other or path.hasPrefix(other + "/") } } } - let owns(roots: [String!]!, root: String!, dirs: [String!]!): Boolean! { - ownPaths(roots, root, dirs).isEmpty == false - } - let pytestProject(root: String!, discovered: [String!]): PytestProject! { PytestProject(path: root, discovered: discovered, tool: self) } @@ -204,6 +278,7 @@ type Pytest { } } + # Keep all Dang types in one source file until Dagger can convert Workspace # arguments for installed multi-file Dang modules. See dagger/dagger#13476. @@ -216,9 +291,9 @@ type PytestProjects @collection { """ paths: [String!]! @keys - # Every key's test files, workspace-root-relative, from the one search that - # found the keys. - let testFiles: [String!]! + # Every key's tests, as workspace-root-relative file, tab, name, from the one + # search that found the keys. + let tests: [String!]! # Every discovered project root, keys or not, which decides whose each test # file is. @@ -230,11 +305,14 @@ type PytestProjects @collection { The pytest project rooted at path. """ project(path: String!): PytestProject! @get { - tool.pytestProject(path, tool.ownPaths(roots, path, testFiles)) + tool.pytestProject(path, tool.ownPaths(roots, path, tests)) } """ - Run the tests of the selected projects. + Run the tests of the selected projects, each as a whole. + + A plain function rather than a check, so that `dagger check` does not run + the same tests twice: each project's tests are its checks. """ test(ws: Workspace!): Void { # A selection over a list evaluates its elements concurrently, so every @@ -259,8 +337,8 @@ type PytestProject { """ path: String! - # This project's test files, workspace-root-relative, when the collection - # that built it already found them; null to search for them. + # This project's tests, as workspace-root-relative file, tab, name, when the + # collection that built it already found them; null to search for them. let discovered: [String!] let tool: Pytest! @@ -289,35 +367,53 @@ type PytestProject { } """ - Test files in this project, keyed by project-relative path. Empty when the - project is outside the configured scope. + Test files in this project, keyed by project-relative path, each with its + top-level tests. Empty when the project is outside the configured scope. """ tests(ws: Workspace!): PytestTestFiles! { - PytestTestFiles(files: testFiles(ws), project: self) - } - - # Test files are found by searching for pytest's default file name patterns - # and a test declaration, so listing them runs no container. A project that - # changes python_files, python_functions or testpaths in its pytest config is - # still listed by the defaults; the whole-project run honours its config. - let testFiles(ws: Workspace!): [String!]! { let empty: [String!]! = [] - if (skip) { empty } else { ownTests(ws) } + let nodes = if (skip) { empty } else { ownTests(ws) } + let files = nodes.map { node => node.split("\t")[0]! }.uniq + # Nodes are in byte order with a file's tests adjacent, so each file takes + # the next run of them. + let next = 0 + let entries = files.map { file => + let names = nodes.dropFirst(next).takeWhile { node => node.hasPrefix(file + "\t") } + next += names.length + PytestTestFileSelection( + path: file, + tests: PytestTests( + names: names.map { node => node.trimPrefix(file + "\t") }, + file: file, + project: self, + ), + ) + } + PytestTestFiles(files: files, entries: entries, project: self) } + # Tests are found by searching for pytest's default file name patterns and + # top-level test declarations, so listing them runs no container. A project + # that changes python_files, python_functions or testpaths in its pytest + # config is still listed by the defaults; the whole-project run honours its + # config. Project-relative file, tab, name, in byte order. let ownTests(ws: Workspace!): [String!]! { let empty: [String!]! = [] - if (discovered == null) { - tool.lib.at(path).ownFiles(ws, tool.testGlobs, pattern: tool.testLine) + let nodes = if (discovered == null) { + tool.testNodes(tool.lib.at(path).ownMatches(ws, tool.testGlobs, tool.testLine).{{path, line}}) } else { - (discovered ?? empty).map { file => - if (path == ".") { file } else { file.trimPrefix(path + "/") } - } + discovered ?? empty + } + let relative = if (path == "." or discovered == null) { nodes } else { + nodes.map { node => node.trimPrefix(path + "/") } } + relative.filter { node => tool.collected(node) } } """ - Run this project's tests. + Run this project's tests as a whole, as pytest collects them. + + A plain function rather than a check: each test is its own check. """ test(ws: Workspace!): Void { let failure = testFailure(ws) @@ -335,7 +431,7 @@ type PytestProject { if (skip or hasTests(ws) == false) { null } else { - { testExec(ws, []).sync; null } rescue { + { testExec(ws).sync; null } rescue { err: Error => err.message.replace(old: "evaluating receiver: ", new: "").replace( old: "reduce function: ", new: "", @@ -344,42 +440,99 @@ type PytestProject { } } - """ - Run the tests in the named project-relative files, naming this project when - they fail. - """ - let runFiles(ws: Workspace!, files: [String!]!): Void { - testExec(ws, files).sync rescue { - err: Error => raise "pytest failed:\n- " + path + ": " + err - .message - .replace(old: "evaluating receiver: ", new: "") - .replace(old: "reduce function: ", new: "") - } - null - } - - """ - Container that has run pytest in this project: over the named project-relative - files, or over the whole project when none are named. - """ - let testExec(ws: Workspace!, files: [String!]!): Container! { - let project = tool.lib.at(path) - + # The packages pytest runs with, resolved into the environment. + let packages(ws: Workspace!): [String!]! { # dagger-pytest-otel is mounted and named by path rather than fetched from # PyPI, so a module version always runs the plugin source it ships with. uv # resolves it with pytest against the project's dependencies while the # environment is built, before any source is mounted. let plugin = if (tool.tracing) { ["/opt/dagger_pytest_otel"] } else { [] } - let packages = ["pytest==" + version(ws)] + plugin - let ignoreNested = project.nestedProjects(ws).map { nested => "--ignore=" + nested } + ["pytest==" + version(ws)] + plugin + } + let env(ws: Workspace!): Container! { + tool.lib.at(path).env(ws, with: packages(ws), mount: tool.pytestOtel, mountPath: "/opt/dagger_pytest_otel") + } + + let ignoreNested(ws: Workspace!): [String!]! { + tool.lib.at(path).nestedProjects(ws).map { nested => "--ignore=" + nested } + } + + """ + Container that has run pytest over the whole project, failing with the + command, its exit code and the end of its output. + """ + let testExec(ws: Workspace!): Container! { + let project = tool.lib.at(path) project.step( - project.env(ws, with: packages, mount: tool.pytestOtel, mountPath: "/opt/dagger_pytest_otel"), - project.uvRun(packages) + ["pytest"] + tool.args + ignoreNested + files, + env(ws), + project.uvRun(packages(ws)) + ["pytest"] + tool.args + ignoreNested(ws), "pytest", nesting: tool.nesting, ) } + + """ + Run the tests a selected collection of this project's test files holds, in + one pytest command, and index its report into one result per test. + + Every test check of the project calls this with the same engine-filtered + collection, so the command below is the same bytes in each and runs once. + Nothing here depends on which check is asking. + """ + let runTests(ws: Workspace!, files: PytestTestFiles!): PytestResults! { + let discovered = files + .entries + .filter { entry => files.files.contains(entry.path) } + .map { entry => + PytestSelection(path: entry.path, names: entry.tests.names, narrowed: entry.tests.narrowed) + } + let selected = discovered.filter { s => s.names.length > 0 } + if (selected.length == 0) { raise "no tests selected in pytest project " + path } + let empty: [String!]! = [] + let narrowed = discovered.any { s => s.narrowed } + # With nothing selected out at any level, pytest runs the project as it + # collects it, honouring its own testpaths and python_files. Otherwise it + # runs the selected files, and when tests were selected out too, only the + # selected tests of each. Without a delta, a direct call, the explicit + # selection is the safe choice. + let whole = files.narrowed == false and narrowed == false + let targets = if (whole) { empty } else { tool.sorted(selected.map { s => s.path }) } + let selection = JSON.encode(selected.map { s => {{path: s.path, names: s.names}} }) + let filter = if (narrowed) { ["--selection", "/dagger-pytest/selection.json"] } else { empty } + let project = tool.lib.at(path) + let executed = project.attempt( + env(ws) + .withDirectory("/opt/dagger-pytest-report", tool.reportHelpers, include: ["dagger_pytest_report.py"]) + .withNewFile("/dagger-pytest/selection.json", selection) + # Created ahead, writable by any user, so a base that runs as another + # user can write it and a run that never starts still leaves one. + .withNewFile("/dagger-pytest/report.jsonl", "", permissions: 438), + project.uvRun(packages(ws)) + + ["python", "/opt/dagger-pytest-report/dagger_pytest_report.py", "--report", "/dagger-pytest/report.jsonl"] + + filter + # A file that fails to import fails its own tests, not every other + # file's: pytest stops at a collection error otherwise. + + ["--", "--continue-on-collection-errors"] + + tool.args + ignoreNested(ws) + targets, + "/dagger-pytest/stdout.log", + "/dagger-pytest/stderr.log", + nesting: tool.nesting, + ) + let indexed = tool.indexerBase + .withDirectory("/opt/dagger-pytest-report", tool.reportHelpers, include: ["dagger_pytest_index.py"]) + .withDirectory("/in", executed.directory("/dagger-pytest")) + .withExec([ + "python", "-I", "/opt/dagger-pytest-report/dagger_pytest_index.py", + "--report", "/in/report.jsonl", + "--stdout", "/in/stdout.log", + "--stderr", "/in/stderr.log", + "--selection", "/in/selection.json", + "--exit-code", `${executed.exitCode}`, + "--output", "/out", + ]) + PytestResults(results: indexed.directory("/out"), selections: selected, project: path) + } } """ @@ -394,7 +547,18 @@ type PytestTestFiles @collection { """ Test files selected in or out since the collection was discovered. """ - delta: CollectionDelta + delta: CollectionDelta @delta + + """ + Whether the active selection removed test files from this collection. + """ + narrowed: Boolean! { delta == null or delta!.removedKeys.length > 0 } + + """ + Stored test collections for the files. Lists are data, not artifact paths. + The engine filters these collections when passing a selected file set. + """ + entries: [PytestTestFileSelection!]! let project: PytestProject! @@ -402,30 +566,33 @@ type PytestTestFiles @collection { The test file at this project-relative path. """ file(path: String!): PytestTestFile! @get { - PytestTestFile(path: path, project: project) + PytestTestFile( + path: path, + tests: entries.filter { entry => entry.path == path }[0]!.tests, + ) } """ - Run the selected test files in this project. + Run the selected tests in the selected files, in one pytest command. + + A plain function rather than a check: each test is its own check. """ - test(ws: Workspace!): Void @check { - # With nothing selected out, run the project's tests as a whole, as pytest - # collects them, rather than listing every file. Without a delta, the file - # list is the safe choice. - let whole = if (delta == null) { - false - } else { - delta.addedKeys.length == 0 and delta.removedKeys.length == 0 - } - if (whole) { - project.test(ws) - } else if (files.length > 0) { - project.runFiles(ws, files) + test(ws: Workspace!): Void { + if (files.length > 0) { + project.runTests(ws, self).assertAllPassed } null } } +""" +A test file and its tests, as the file collection stores them. +""" +type PytestTestFileSelection { + path: String! + tests: PytestTests! +} + """ A pytest test file. """ @@ -435,12 +602,112 @@ type PytestTestFile { """ path: String! + """ + Top-level tests in this file, keyed by name. + """ + tests: PytestTests! +} + +""" +Top-level tests in a test file, keyed by name: module-level test functions +and test classes. +""" +type PytestTests @collection { + """ + Test function and test class names. + """ + names: [String!]! @keys + + """ + Tests selected in or out since the collection was discovered. + """ + delta: CollectionDelta @delta + + """ + Whether the active selection removed tests from this collection. + """ + narrowed: Boolean! { delta == null or delta!.removedKeys.length > 0 } + + let file: String! + + let project: PytestProject! + + """ + The top-level test with this name. + """ + named(name: String!): PytestTest! @get { + PytestTest(name: name, file: file, project: project) + } +} + +""" +A top-level pytest test: a module-level test function, with all its +parameters, or a test class, with all its tests. +""" +type PytestTest { + """ + Test function or class name. + """ + name: String! + + """ + The test file, relative to the project root. + """ + file: String! + let project: PytestProject! """ - Run this test file. + Run this test. """ - test(ws: Workspace!): Void @check { - project.runFiles(ws, [path]) + test(ws: Workspace!, selection: PytestTestFiles!): Void @check { + project.runTests(ws, selection).assertPassed(file, name) } } + +# The shared indexer keeps each result small, whatever the report's size. +type PytestResults { + let results: Directory! + let selections: [PytestSelection!]! + let project: String! + + let label(file: String!, name: String!): String! { + (if (project == ".") { "" } else { project + "/" }) + file + "::" + name + } + + let failure(file: String!, name: String!): String! { + let selected = selections.filter { s => s.path == file } + if (selected.length == 0) { raise "pytest test file is outside the test selection: " + label(file, name) } + if (selected[0]!.names.contains(name) == false) { raise "pytest test is outside the selection: " + label(file, name) } + # Numeric ranks, in the byte order the indexer sorts in, keep file and + # test names out of paths. + let fileIndex = selections.filter { s => s.path < file }.length + let testIndex = selected[0]!.names.filter { test => test < name }.length + results.file(`${fileIndex}` + "/" + `${testIndex}`).contents + } + + let assertPassed(file: String!, name: String!): Void { + let text = failure(file, name) + if (text != "") { raise "pytest " + label(file, name) + ": " + text } + null + } + + let assertAllPassed: Void { + let empty: [String!]! = [] + let failures = selections.reduce(empty) { all, s => + all + s.names.map { name => + let text = failure(s.path, name) + if (text == "") { "" } else { "- " + label(s.path, name) + ": " + text } + }.filter { line => line != "" } + } + if (failures.length > 0) { raise "pytest failed:\n" + failures.join("\n") } + null + } +} + +# The helper's immutable copy of a file's filtered collection keys. +type PytestSelection { + let path: String! + let names: [String!]! + let narrowed: Boolean! +} diff --git a/ruff/dagger-module.toml b/ruff/dagger-module.toml index edad8fd..b848cd5 100644 --- a/ruff/dagger-module.toml +++ b/ruff/dagger-module.toml @@ -1,5 +1,5 @@ name = "ruff" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/ruff/main.dang b/ruff/main.dang index e5f3e55..a96feac 100644 --- a/ruff/main.dang +++ b/ruff/main.dang @@ -217,9 +217,12 @@ type RuffProjects @collection { } """ - Lint the selected projects with ruff. + Lint the selected projects with ruff, each with its own command. + + A plain function rather than a check, so that `dagger check` does not run + the same work twice: each project's own `lint` is its check. """ - lint(ws: Workspace!): Void @check { + lint(ws: Workspace!): Void { # A selection over a list evaluates its elements concurrently, so every # project is linted in parallel and every failure is reported. let failures = paths.map { p => project(p) }.{{path, failure: lintFailure(ws)}} @@ -233,9 +236,12 @@ type RuffProjects @collection { } """ - Format the selected projects with ruff. + Format the selected projects with ruff, as one changeset. + + A plain function rather than a generator: each project's own `format` is + its generator. """ - format(ws: Workspace!): Changeset! @generate { + format(ws: Workspace!): Changeset! { let roots = paths.map { p => project(p) }.filter { p => p.skip == false }.map { p => p.path } tool.changes(ws, roots, ["format"]) rescue { err: Error => raise tool.clean(err.message) diff --git a/ty/dagger-module.toml b/ty/dagger-module.toml index 6b1130b..23765cf 100644 --- a/ty/dagger-module.toml +++ b/ty/dagger-module.toml @@ -1,5 +1,5 @@ name = "ty" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/ty/main.dang b/ty/main.dang index ec4f326..865549e 100644 --- a/ty/main.dang +++ b/ty/main.dang @@ -143,9 +143,12 @@ type TyProjects @collection { } """ - Type check the selected projects with ty. + Type check the selected projects with ty, each with its own command. + + A plain function rather than a check, so that `dagger check` does not run + the same work twice: each project's own `typeCheck` is its check. """ - typeCheck(ws: Workspace!): Void @check { + typeCheck(ws: Workspace!): Void { # A selection over a list evaluates its elements concurrently, so every # project is checked in parallel and every failure is reported. let failures = paths.map { p => project(p) }.{{path, failure: typeCheckFailure(ws)}} diff --git a/uv/dagger-module.toml b/uv/dagger-module.toml index a05e0b6..239e16e 100644 --- a/uv/dagger-module.toml +++ b/uv/dagger-module.toml @@ -1,5 +1,5 @@ name = "uv" -engineVersion = "v1.0.0-beta.15" +engineVersion = "v1.0.0-beta.22" [runtime] source = "dang" diff --git a/uv/main.dang b/uv/main.dang index ece5d7f..5c9ca55 100644 --- a/uv/main.dang +++ b/uv/main.dang @@ -175,9 +175,13 @@ type UvProjects @collection { } """ - Audit the selected projects' dependencies for known vulnerabilities. + Audit the selected projects' dependencies for known vulnerabilities, each + with its own command. + + A plain function rather than a check, so that `dagger check` does not run + the same work twice: each project's own `audit` is its check. """ - audit(ws: Workspace!): Void @check { + audit(ws: Workspace!): Void { # A selection over a list evaluates its elements concurrently, so every # project is audited in parallel and every failure is reported. let failures = paths.map { p => project(p) }.{{path, failure: auditFailure(ws)}} @@ -191,9 +195,12 @@ type UvProjects @collection { } """ - Refresh the selected projects' uv.lock. + Refresh the selected projects' uv.lock, as one changeset. + + A plain function rather than a generator: each project's own `lock` is its + generator. """ - lock(ws: Workspace!): Changeset! @generate { + lock(ws: Workspace!): Changeset! { let roots = paths.map { p => project(p) }.{{path, skipLock, locked: hasLockfile(ws)}} .filter { p => p.skipLock == false and p.locked } .map { p => p.path }