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
52 changes: 35 additions & 17 deletions .github/workflows/scripts/pytest-selected.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
durations file, each shard gets whole selected files, balanced by the
per-file test counts in `selected-tests.counts.json`, and a file too big for
one shard gets several shards, which split it by test.
- Full runs filtered with `-m`/`-k`: every shard collects everything and keeps
its hash share, unless PYTEST_SELECTED_FILTERED_PLAN=1. Then they get the
full-run plan too: every file is still assigned to a shard, and pytest
applies the filter to the files it collects. A shard whose files have no
selected tests passes.
"""

from __future__ import annotations
Expand Down Expand Up @@ -164,16 +169,22 @@ def file_weights(files: list[str]) -> dict[str, float]:
return estimate_file_seconds(files, DURATIONS_FILE)


def is_filtered(args: list[str]) -> bool:
"""Whether `-m`/`-k` filter the tests after collection."""
every_arg = [*args, *shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))]
return any(arg.startswith(("-m", "-k")) and not arg.startswith("--") for arg in every_arg)


def per_file_plan_applies(args: list[str], files: list[str]) -> bool:
"""Whether planning by file gives each shard the tests pytest would run.

`-m`/`-k` filter after the plan, so most shards could end up with no
selected tests (e.g. `-m snuba_ci` in Snuba's CI). The sentry plugin
matches the planned paths relative to the rootdir, which
pytest_shard_plugin checks is the working directory.
selected tests (e.g. `-m snuba_ci` in Snuba's CI). Callers that accept
that set PYTEST_SELECTED_FILTERED_PLAN=1. The sentry plugin matches the
planned paths relative to the rootdir, which pytest_shard_plugin checks
is the working directory.
"""
every_arg = [*args, *shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))]
if any(arg.startswith(("-m", "-k")) and not arg.startswith("--") for arg in every_arg):
if is_filtered(args) and os.environ.get("PYTEST_SELECTED_FILTERED_PLAN") != "1":
return False
return not any(os.path.isabs(f) or f.startswith(os.pardir + os.sep) for f in files)

Expand All @@ -195,8 +206,9 @@ def run_full_shard(args: list[str], total: int, group: int) -> int:
# As before per-file sharding: every shard collects everything and the
# sentry plugin keeps its hash share of the items.
print(
"pytest-selected: -m/-k or paths outside the working directory, so "
"every shard collects everything and keeps its hash share",
"pytest-selected: -m/-k without PYTEST_SELECTED_FILTERED_PLAN=1, or "
"paths outside the working directory, so every shard collects "
"everything and keeps its hash share",
file=sys.stderr,
)
return int(pytest.main(args))
Expand All @@ -205,15 +217,21 @@ def run_full_shard(args: list[str], total: int, group: int) -> int:
return int(pytest.main(args))
artifacts = Path(".artifacts")
artifacts.mkdir(exist_ok=True)
return run_planned_shard(
args, plan, group, len(files), artifacts / f"full-tests.shard-{group}.txt"
)
shard_file = artifacts / f"full-tests.shard-{group}.txt"
# A filter can select none of this shard's files.
return run_planned_shard(args, plan, group, len(files), shard_file, is_filtered(args))


def run_planned_shard(
args: list[str], plan: list[Shard], group: int, file_count: int, shard_file: Path
args: list[str],
plan: list[Shard],
group: int,
file_count: int,
shard_file: Path,
empty_ok: bool,
) -> int:
"""Run this shard of a plan_full_shards plan."""
"""Run this shard of a plan_full_shards plan. With empty_ok, a shard that
collects no tests passes."""
shard = plan[group]
print(
f"pytest-selected: shard {group + 1}/{len(plan)} runs {len(shard.files)} of "
Expand All @@ -237,7 +255,10 @@ def run_planned_shard(
filter(None, [os.environ.get("PYTEST_PLUGINS"), "pytest_shard_plugin"])
)
start_assert_rewrite_prewarm(shard_file)
return int(pytest.main(args))
exit_code = pytest.main(args)
if empty_ok and exit_code == pytest.ExitCode.NO_TESTS_COLLECTED:
return 0
return int(exit_code)


def main(args: list[str]) -> int:
Expand All @@ -257,11 +278,8 @@ def main(args: list[str]) -> int:
plan = plan_full_shards(file_weights(selected), total, SELECTED_PIECES_PER_SHARD)
if plan is not None:
shard_file = Path(selected_file).with_suffix(f".shard-{group}.txt")
exit_code = run_planned_shard(args, plan, group, len(selected), shard_file)
# Durations are estimates, so a shard can end up with no tests.
if exit_code == pytest.ExitCode.NO_TESTS_COLLECTED:
return 0
return exit_code
return run_planned_shard(args, plan, group, len(selected), shard_file, True)

counts_file = Path(selected_file).with_suffix(".counts.json")
counts = json.loads(counts_file.read_text()) if counts_file.is_file() else {}
Expand Down
67 changes: 66 additions & 1 deletion .github/workflows/scripts/test_pytest_selected.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,8 @@ def run_full_main(
total: int,
group: int,
addopts: str = "",
extra_env: dict[str, str] | None = None,
exit_code: pytest.ExitCode = pytest.ExitCode.OK,
) -> tuple[int, list[tuple[object, ...]]]:
write_files(tmp_path, files)
durations_file = tmp_path / "durations.json"
Expand All @@ -271,13 +273,15 @@ def run_full_main(
def fake_main(args: list[str]) -> pytest.ExitCode:
env = ("SELECTED_TESTS_FILE", "TOTAL_TEST_GROUPS", "TEST_GROUP", "PYTEST_SHARD_PARTS")
calls.append((args, *(os.environ.get(k) for k in env)))
return pytest.ExitCode.OK
return exit_code

env = {
"SELECTED_TESTS_FILE": "",
"TOTAL_TEST_GROUPS": str(total),
"TEST_GROUP": str(group),
"PYTEST_ADDOPTS": addopts,
"PYTEST_SELECTED_FILTERED_PLAN": "",
**(extra_env or {}),
}
with (
contextlib.chdir(tmp_path),
Expand Down Expand Up @@ -336,6 +340,51 @@ def test_filtered_run_falls_back_to_hash_sharding(self, tmp_path: Path) -> None:
)
assert calls == [(["tests", "-q"], "", "16", "12", None)]

def test_opted_in_filtered_run_runs_only_this_shards_files(self, tmp_path: Path) -> None:
durations = {"seconds_per_test": 1.0, "files": {}}
with pieces_per_shard(1):
exit_code, calls = run_full_main(
tmp_path,
["tests/test_a.py", "tests/test_b.py"],
durations,
2,
1,
"-k 'not __In' -m snuba_ci",
{"PYTEST_SELECTED_FILTERED_PLAN": "1"},
)
shard_file = ".artifacts/full-tests.shard-1.txt"
assert exit_code == 0
assert calls == [
(["tests", "-q"], shard_file, "1", "0", ".artifacts/full-tests.shard-1.json")
]
assert (tmp_path / shard_file).read_text() == "tests/test_b.py\n"

def test_opted_in_filtered_shard_with_no_selected_tests_passes(self, tmp_path: Path) -> None:
durations = {"seconds_per_test": 1.0, "files": {}}
exit_code, _ = run_full_main(
tmp_path,
["tests/test_a.py", "tests/test_b.py"],
durations,
2,
0,
"-m snuba_ci",
{"PYTEST_SELECTED_FILTERED_PLAN": "1"},
pytest.ExitCode.NO_TESTS_COLLECTED,
)
assert exit_code == 0

def test_unfiltered_shard_with_no_tests_still_fails(self, tmp_path: Path) -> None:
durations = {"seconds_per_test": 1.0, "files": {}}
exit_code, _ = run_full_main(
tmp_path,
["tests/test_a.py", "tests/test_b.py"],
durations,
2,
0,
exit_code=pytest.ExitCode.NO_TESTS_COLLECTED,
)
assert exit_code == pytest.ExitCode.NO_TESTS_COLLECTED


@pytest.mark.parametrize(
("args", "addopts", "files", "applies"),
Expand All @@ -355,3 +404,19 @@ def test_per_file_plan_applies(
) -> None:
with mock.patch.dict(os.environ, {"PYTEST_ADDOPTS": addopts}):
assert _mod.per_file_plan_applies(args, files) is applies


@pytest.mark.parametrize(
("args", "addopts", "files", "applies"),
[
(["tests", "-m", "snuba_ci"], "", ["tests/a.py"], True),
(["tests"], "-k 'not __In' -m 'snuba_ci or snuba'", ["tests/a.py"], True),
(["/abs/tests", "-m", "snuba_ci"], "", ["/abs/tests/a.py"], False),
],
)
def test_per_file_plan_applies_to_opted_in_filtered_runs(
args: list[str], addopts: str, files: list[str], applies: bool
) -> None:
env = {"PYTEST_ADDOPTS": addopts, "PYTEST_SELECTED_FILTERED_PLAN": "1"}
with mock.patch.dict(os.environ, env):
assert _mod.per_file_plan_applies(args, files) is applies
33 changes: 30 additions & 3 deletions tests/sentry/testutils/pytest/test_sentry.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ def test_marked(n):

def test_unmarked():
pass

@pytest.mark.snuba_ci
class Base:
def test_inherited(self):
pass

class TestChild(Base):
def test_own(self):
pass
"""
)

Expand Down Expand Up @@ -72,11 +81,25 @@ def _collect(project: Path, command: list[str], env: dict[str, str]) -> Counter[
return Counter(line for line in proc.stdout.splitlines() if "::" in line)


def test_filtered_run_spreads_selected_tests_over_every_shard(tmp_path: Path) -> None:
@pytest.mark.parametrize(
"plan_env",
[
# Every shard collects everything and keeps its hash share.
{},
# Every shard collects only its planned files, and test_marked0.py is
# heavy enough to be split across shards.
{"PYTEST_SELECTED_FILTERED_PLAN": "1"},
],
)
def test_filtered_run_spreads_selected_tests_over_every_shard(
tmp_path: Path, plan_env: dict[str, str]
) -> None:
files = {
"conftest.py": "from sentry.testutils.pytest.sentry import pytest_collection_modifyitems, pytest_ignore_collect # noqa: F401\n",
"pytest.ini": "[pytest]\nmarkers =\n snuba_ci\n",
"durations.json": json.dumps({"seconds_per_test": 0.1, "files": {}}),
"durations.json": json.dumps(
{"seconds_per_test": 0.1, "files": {"tests/test_marked0.py": 10.0}}
),
**{f"tests/test_marked{i}.py": MARKED for i in range(2)},
**{f"tests/test_plain{i}.py": "def test_p():\n pass\n" for i in range(12)},
}
Expand All @@ -94,9 +117,13 @@ def test_filtered_run_spreads_selected_tests_over_every_shard(tmp_path: Path) ->
"TOTAL_TEST_GROUPS": str(SHARDS),
"TEST_GROUP": str(group),
"TEST_GROUP_STRATEGY": "roundrobin",
**plan_env,
},
)
assert len(unsharded) == 20
planned = (tmp_path / ".artifacts" / f"full-tests.shard-{group}.txt").is_file()
assert planned == bool(plan_env)
# 10 parametrized and 2 inherited marked tests in each of 2 files.
assert len(unsharded) == 24
assert sharded == unsharded


Expand Down
Loading