Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions release-files.json
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@
"tests/repo/layout.test.ts",
"tests/repo/lockfile-free-dependencies.test.ts",
"tests/repo/lockfiles.test.ts",
"tests/repo/python-addopts-plugins.test.ts",
"tests/repo/mocharc-config-fallback.test.ts",
"tests/repo/orphan-tool-config.test.ts",
"tests/repo/removed-files.test.ts",
Expand Down
31 changes: 27 additions & 4 deletions src/repo/adapters/python.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import { contribution, type AdapterContext, type AdapterContribution, type Repos
* and, for a file in a directory without `__init__.py`, that directory (pytest's default `prepend`
* import mode puts it on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
* which run on import. Tests follow pytest's `python_files` and `testpaths`; each test also depends on
* every `conftest.py` from its directory up to the root, which pytest loads before it.
* every `conftest.py` from its directory up to the root, which pytest loads before it, and on every
* plugin module that `addopts` loads with `-p`.
*
* Full validation instead, as global blockers: no Python interpreter, a file that does not parse, an
* `importlib.import_module` / `__import__` / `pytest_plugins` entry whose name is computed, a first-party
Expand Down Expand Up @@ -83,6 +84,8 @@ export interface PytestSettings {
pythonFiles: string[];
testpaths: string[];
pythonpath: string[];
/** Plugin modules `addopts` loads with `-p`; every test depends on them. */
plugins?: string[];
/** A key that is present but could not be read; its file makes the analysis fall back. */
unreadable?: string;
}
Expand All @@ -94,10 +97,15 @@ function splitList(value: string): string[] {
/** pytest's own configuration, from the first file pytest would use. Only the keys selection depends on. */
export function readPytestSettings(read: (path: string) => string | undefined): PytestSettings {
const settings: PytestSettings = { pythonFiles: ["test_*.py", "*_test.py"], testpaths: [], pythonpath: [] };
const keys = ["python_files", "testpaths", "pythonpath"] as const;
const keys = ["python_files", "testpaths", "pythonpath", "addopts"] as const;
const apply = (key: (typeof keys)[number], values: string[]) => {
if (key === "python_files") settings.pythonFiles = values;
else settings[key] = values;
else if (key === "addopts") {
// `-p name` and `-pname` import a plugin module before collection; `-p no:name` disables one.
const plugins = values.flatMap((value, index) => value === "-p" ? [values[index + 1] ?? ""] : value.startsWith("-p") && !value.startsWith("--") ? [value.slice(2)] : [])
.filter((name) => !name.startsWith("no:"));
if (plugins.length) settings.plugins = plugins;
} else settings[key] = values;
};
for (const [file, header] of [["pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const) {
const text = read(file);
Expand All @@ -108,7 +116,12 @@ export function readPytestSettings(read: (path: string) => string | undefined):
for (const key of keys) {
if (file === "pyproject.toml") {
const match = new RegExp(`^${key}\\s*=\\s*(\\[[\\s\\S]*?\\]|"[^"]*"|'[^']*')`, "m").exec(body);
if (match) apply(key, splitList(match[1]!.replace(/^\[|\]$/g, "")));
// A multi-line string would otherwise match as an empty one. Its contents are read as one string;
// a basic string's line-ending backslash only joins lines. An unterminated one cannot be read.
const multiline = new RegExp(`^${key}\\s*=\\s*("""|'{3})([\\s\\S]*?)\\1`, "m").exec(body);
if (multiline) apply(key, splitList(multiline[1] === '"""' ? multiline[2]!.replace(/\\\r?\n/g, " ") : multiline[2]!));
else if (new RegExp(`^${key}\\s*=\\s*(?:"""|'{3})`, "m").test(body)) settings.unreadable = `${file} ${key}`;
else if (match) apply(key, splitList(match[1]!.replace(/^\[|\]$/g, "")));
else if (new RegExp(`^${key}\\s*=`, "m").test(body)) settings.unreadable = `${file} ${key}`;
} else {
// INI values continue on indented lines.
Expand Down Expand Up @@ -203,6 +216,16 @@ export function resolvePythonGraph(files: readonly string[], parsed: Record<stri
}
// pytest loads every conftest.py from the rootdir down to the test's directory first.
if (tests.has(file)) {
// Plugins named by `-p` in addopts are imported before any test is collected.
for (const plugin of settings.plugins ?? []) {
const parts = plugin.split(".");
const target = roots.map((root) => moduleFiles(root, parts)).find(Boolean);
if (target) add(target);
else if (!plugin || firstParty.has(parts[0]!)) {
const blocker = `Unresolved pytest plugin in addopts: -p ${plugin}`;
if (!blockers.includes(blocker)) blockers.push(blocker);
}
}
const segments = dir ? dir.split("/") : [];
for (let depth = 0; depth <= segments.length; depth += 1) {
const conftest = [...segments.slice(0, depth), "conftest.py"].join("/");
Expand Down
84 changes: 84 additions & 0 deletions tests/repo/python-addopts-plugins.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// SPDX-License-Identifier: MIT
import { strict as assert } from "node:assert";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, it } from "node:test";

import { pythonInterpreter, readPytestSettings, resolvePythonGraph, type PythonFileImports } from "../../src/repo/adapters/python.js";
import { computeAnalysis } from "../../src/git/git-diff.js";
import type { ChangedFile, GitDelta } from "../../src/git/types.js";
import { buildDependencyGraph } from "../../src/repo/graph.js";
import { ImpactAnalyzer } from "../../src/repo/impact.js";

// `addopts = -p myplugin` makes pytest import myplugin.py before collecting any test, so a change to it
// reaches every test even though no test imports it.
describe("pytest plugins loaded with -p in addopts", () => {
it("reads -p plugins from pytest.ini and pyproject.toml, and skips -p no:", () => {
const ini = readPytestSettings((path) => path === "pytest.ini" ? "[pytest]\naddopts = -p myplugin -ptools.fixtures -p no:cacheprovider --strict-markers\n" : undefined);
assert.deepEqual(ini.plugins, ["myplugin", "tools.fixtures"]);
const string = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = \"-p myplugin -q\"\n" : undefined);
assert.deepEqual(string.plugins, ["myplugin"]);
const list = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = [\"-p\", \"myplugin\"]\n" : undefined);
assert.deepEqual(list.plugins, ["myplugin"]);
const none = readPytestSettings((path) => path === "pytest.ini" ? "[pytest]\naddopts = -q --strict-markers\n" : undefined);
assert.equal(none.plugins, undefined);
});

it("reads a multi-line pyproject.toml string instead of an empty one, and falls back on an unterminated one", () => {
const basic = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = \"\"\"\n -p myplugin \\\n --strict-markers\n\"\"\"\ntestpaths = [\"tests\"]\n" : undefined);
assert.equal(basic.unreadable, undefined);
assert.deepEqual(basic.plugins, ["myplugin"]);
assert.deepEqual(basic.testpaths, ["tests"]);
const literal = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = '''\n -p tools.fixtures\n'''\n" : undefined);
assert.deepEqual(literal.plugins, ["tools.fixtures"]);
const plain = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = \"\"\"\n --strict-markers\n\"\"\"\n" : undefined);
assert.equal(plain.unreadable, undefined);
assert.equal(plain.plugins, undefined);
const unterminated = readPytestSettings((path) => path === "pyproject.toml" ? "[tool.pytest.ini_options]\naddopts = \"\"\"\n -p myplugin\n" : undefined);
assert.equal(unterminated.unreadable, "pyproject.toml addopts");
});

it("makes every test depend on a first-party plugin, and falls back when one cannot be resolved", () => {
const files = ["myplugin.py", "tests/test_a.py", "tests/test_b.py"];
const parsed: Record<string, PythonFileImports> = { "myplugin.py": { imports: [] }, "tests/test_a.py": { imports: [] }, "tests/test_b.py": { imports: [] } };
const tests = new Set(["tests/test_a.py", "tests/test_b.py"]);
const settings = { pythonFiles: ["test_*.py"], testpaths: [], pythonpath: [], plugins: ["myplugin", "pytest_cov"] };
const { edges, blockers } = resolvePythonGraph(files, parsed, settings, tests);
assert.deepEqual(blockers, []);
assert.deepEqual(edges, [{ from: "tests/test_a.py", to: "myplugin.py" }, { from: "tests/test_b.py", to: "myplugin.py" }]);
const missing = resolvePythonGraph(files, parsed, { ...settings, plugins: ["tests.gone"] }, tests);
assert.deepEqual(missing.blockers, ["Unresolved pytest plugin in addopts: -p tests.gone"]);
});
});

const interpreter = pythonInterpreter(process.cwd());

describe("pytest -p plugins end to end", { skip: interpreter ? false : "no Python 3 interpreter on PATH" }, () => {
it("selects the tests when only the plugin changes", async () => {
const root = mkdtempSync(join(tmpdir(), "diffci-python-plugin-"));
const files: Record<string, string> = {
"pyproject.toml": "[tool.pytest.ini_options]\naddopts = \"-p myplugin\"\n",
"myplugin.py": "import pytest\n\n@pytest.fixture\ndef answer():\n return 42\n",
"tests/test_a.py": "def test_a(answer):\n assert answer == 42\n",
};
for (const [path, content] of Object.entries(files)) {
mkdirSync(dirname(join(root, path)), { recursive: true });
writeFileSync(join(root, path), content);
}
try {
const graph = await buildDependencyGraph({ repoPath: root });
const changed: ChangedFile[] = [{ path: "myplugin.py", changeType: "modified" }];
const delta: GitDelta = {
baseSha: "base", headSha: "head", files: changed, directories: [],
summary: { total: 1, added: 0, modified: 1, deleted: 0, renamed: 0, copied: 0, unmerged: 0, unknown: 0 },
analysis: computeAnalysis(changed),
};
const result = new ImpactAnalyzer().analyze(delta, graph, graph.profile, { repositoryFiles: new Set(graph.graph.nodes.map((node) => node.path)) });
assert.equal(result.fallbackRequired, false, result.fallbackReasons.join("; "));
assert.deepEqual(result.affectedTests.map((test) => test.path), ["tests/test_a.py"]);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
Loading