From e3d2f1fff5db4f920f8752811739f1a0128ea6b9 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Mon, 20 Jan 2025 15:30:00 -0700 Subject: [PATCH 1/8] Initial implementation of test sharding for the pytest runner --- examples/pytest/BUILD.bazel | 15 ++++++ examples/pytest/sharding_test.py | 5 ++ py/private/py_pytest_main.bzl | 2 +- py/private/pytest.py.tmpl | 15 +++++- py/private/pytest_shard/BUILD.bazel | 7 +++ py/private/pytest_shard/LICENSE | 7 +++ py/private/pytest_shard/pytest_shard.py | 65 +++++++++++++++++++++++++ 7 files changed, 114 insertions(+), 2 deletions(-) create mode 100644 examples/pytest/sharding_test.py create mode 100644 py/private/pytest_shard/BUILD.bazel create mode 100644 py/private/pytest_shard/LICENSE create mode 100644 py/private/pytest_shard/pytest_shard.py diff --git a/examples/pytest/BUILD.bazel b/examples/pytest/BUILD.bazel index 25889c147..51e2068e9 100644 --- a/examples/pytest/BUILD.bazel +++ b/examples/pytest/BUILD.bazel @@ -40,3 +40,18 @@ py_test( "@pypi_pytest//:pkg", ], ) + +py_test( + name = "sharding_test", + srcs = [ + "__test__.py", + "sharding_test.py", + ], + imports = ["../.."], + main = "__test__.py", + package_collisions = "warning", + shard_count = 2, + deps = [ + "__test__", + ], +) diff --git a/examples/pytest/sharding_test.py b/examples/pytest/sharding_test.py new file mode 100644 index 000000000..a50ece51e --- /dev/null +++ b/examples/pytest/sharding_test.py @@ -0,0 +1,5 @@ +def test_shard_one(): + assert True + +def test_shard_two(): + assert True diff --git a/py/private/py_pytest_main.bzl b/py/private/py_pytest_main.bzl index 9237c8690..3e5aa59c5 100644 --- a/py/private/py_pytest_main.bzl +++ b/py/private/py_pytest_main.bzl @@ -88,6 +88,6 @@ def py_pytest_main(name, py_library = default_py_library, deps = [], data = [], srcs = [test_main], tags = tags, visibility = visibility, - deps = deps, + deps = deps + ["//py/private/pytest_shard"], data = data, ) diff --git a/py/private/pytest.py.tmpl b/py/private/pytest.py.tmpl index e8a4d6c27..fa60eb0e9 100644 --- a/py/private/pytest.py.tmpl +++ b/py/private/pytest.py.tmpl @@ -14,10 +14,13 @@ import sys import os +from pathlib import Path from typing import List import pytest +from aspect_rules_py.py.private.pytest_shard.pytest_shard import ShardPlugin + if __name__ == "__main__": # Change to the directory where we need to run the test or execute a no-op $$CHDIR$$ @@ -40,6 +43,16 @@ if __name__ == "__main__": if suite_name: args.extend(["-o", f"junit_suite_name={suite_name}"]) + test_shard_index = os.environ.get("TEST_SHARD_INDEX") + test_total_shards = os.environ.get("TEST_TOTAL_SHARDS") + test_shard_status_file = os.environ.get("TEST_SHARD_STATUS_FILE") + if all([test_shard_index, test_total_shards, test_shard_status_file]): + args.extend([ + f"--shard-id={test_shard_index}", + f"--num-shards={test_total_shards}", + ]) + Path(test_shard_status_file).touch() + test_filter = os.environ.get("TESTBRIDGE_TEST_ONLY") if test_filter is not None: args.append(f"-k={test_filter}") @@ -52,7 +65,7 @@ if __name__ == "__main__": if len(cli_args) > 0: args.extend(cli_args) - exit_code = pytest.main(args) + exit_code = pytest.main(args, plugins=[ShardPlugin()]) if exit_code != 0: print("Pytest exit code: " + str(exit_code), file=sys.stderr) diff --git a/py/private/pytest_shard/BUILD.bazel b/py/private/pytest_shard/BUILD.bazel new file mode 100644 index 000000000..5c6351445 --- /dev/null +++ b/py/private/pytest_shard/BUILD.bazel @@ -0,0 +1,7 @@ +load("@aspect_rules_py//py:defs.bzl", "py_library") + +py_library( + name = "pytest_shard", + srcs = [":pytest_shard.py"], + visibility = ["//visibility:public"], +) diff --git a/py/private/pytest_shard/LICENSE b/py/private/pytest_shard/LICENSE new file mode 100644 index 000000000..88a9bda1a --- /dev/null +++ b/py/private/pytest_shard/LICENSE @@ -0,0 +1,7 @@ +Copyright 2019 Adam Gleave + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/py/private/pytest_shard/pytest_shard.py b/py/private/pytest_shard/pytest_shard.py new file mode 100644 index 000000000..f464309e8 --- /dev/null +++ b/py/private/pytest_shard/pytest_shard.py @@ -0,0 +1,65 @@ +""" +This has been adapted from the original code at +https://github.com/AdamGleave/pytest-shard +The main difference is that the plugin has been converted to a class +so that it can be passed to pytest.main's plugins attribute, and the +shard selection was changed from a hash-based approach to a round-robin +approach for a more balanced distribution with smaller numbers of tests. +""" +from typing import Iterable, List, Sequence + +from _pytest import nodes # for type checking only + + +def positive_int(x) -> int: + x = int(x) + if x < 0: + raise ValueError(f"Argument {x} must be positive") + return x + + +def filter_items_by_shard( + items: Iterable[nodes.Node], shard_id: int, num_shards: int +) -> Sequence[nodes.Node]: + """Computes `items` that should be tested in `shard_id` out of `num_shards` total shards.""" + shards = [i % num_shards for i in range(len(items))] + + new_items = [] + for shard, item in zip(shards, items): + if shard == shard_id: + new_items.append(item) + return new_items + +class ShardPlugin: + @staticmethod + def pytest_addoption(parser): + """Add pytest-shard specific configuration parameters.""" + group = parser.getgroup("shard") + group.addoption( + "--shard-id", dest="shard_id", type=positive_int, default=0, help="Number of this shard." + ) + group.addoption( + "--num-shards", + dest="num_shards", + type=positive_int, + default=1, + help="Total number of shards.", + ) + + @staticmethod + def pytest_report_collectionfinish(config, items: Sequence[nodes.Node]) -> str: + """Log how many and, if verbose, which items are tested in this shard.""" + msg = f"Running {len(items)} items in this shard" + if config.option.verbose > 0 and config.getoption("num_shards") > 1: + msg += ": " + ", ".join([item.nodeid for item in items]) + return msg + + @staticmethod + def pytest_collection_modifyitems(config, items: List[nodes.Node]): + """Mutate the collection to consist of just items to be tested in this shard.""" + shard_id = config.getoption("shard_id") + shard_total = config.getoption("num_shards") + if shard_id >= shard_total: + raise ValueError("shard_num = f{shard_num} must be less than shard_total = f{shard_total}") + + items[:] = filter_items_by_shard(items, shard_id, shard_total) From b9ce9063c5a92952dabdc3201c790df4ea6d6be1 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Mon, 20 Jan 2025 15:33:43 -0700 Subject: [PATCH 2/8] change reference --- py/private/py_pytest_main.bzl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/py/private/py_pytest_main.bzl b/py/private/py_pytest_main.bzl index 3e5aa59c5..a8c4db70a 100644 --- a/py/private/py_pytest_main.bzl +++ b/py/private/py_pytest_main.bzl @@ -88,6 +88,6 @@ def py_pytest_main(name, py_library = default_py_library, deps = [], data = [], srcs = [test_main], tags = tags, visibility = visibility, - deps = deps + ["//py/private/pytest_shard"], + deps = deps + ["@aspect_rules_py//py/private/pytest_shard"], data = data, ) From 7194656fd32027461266a1d63d36415cde3815a5 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Mon, 20 Jan 2025 20:07:48 -0700 Subject: [PATCH 3/8] change imports --- py/private/pytest.py.tmpl | 2 +- py/private/pytest_shard/BUILD.bazel | 6 +++++- py/private/pytest_shard/__init__.py | 0 3 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 py/private/pytest_shard/__init__.py diff --git a/py/private/pytest.py.tmpl b/py/private/pytest.py.tmpl index fa60eb0e9..5bfd05069 100644 --- a/py/private/pytest.py.tmpl +++ b/py/private/pytest.py.tmpl @@ -19,7 +19,7 @@ from typing import List import pytest -from aspect_rules_py.py.private.pytest_shard.pytest_shard import ShardPlugin +from pytest_shard import ShardPlugin if __name__ == "__main__": # Change to the directory where we need to run the test or execute a no-op diff --git a/py/private/pytest_shard/BUILD.bazel b/py/private/pytest_shard/BUILD.bazel index 5c6351445..5bcf8994f 100644 --- a/py/private/pytest_shard/BUILD.bazel +++ b/py/private/pytest_shard/BUILD.bazel @@ -2,6 +2,10 @@ load("@aspect_rules_py//py:defs.bzl", "py_library") py_library( name = "pytest_shard", - srcs = [":pytest_shard.py"], + srcs = [ + "__init__.py", + ":pytest_shard.py", + ], + imports = ["."], visibility = ["//visibility:public"], ) diff --git a/py/private/pytest_shard/__init__.py b/py/private/pytest_shard/__init__.py new file mode 100644 index 000000000..e69de29bb From db4eeb59b38ca207260fbdcb0001aea950454fc8 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Mon, 20 Jan 2025 20:22:36 -0700 Subject: [PATCH 4/8] apply ruff formatting --- py/private/pytest_shard/pytest_shard.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/py/private/pytest_shard/pytest_shard.py b/py/private/pytest_shard/pytest_shard.py index f464309e8..bd7111416 100644 --- a/py/private/pytest_shard/pytest_shard.py +++ b/py/private/pytest_shard/pytest_shard.py @@ -6,6 +6,7 @@ shard selection was changed from a hash-based approach to a round-robin approach for a more balanced distribution with smaller numbers of tests. """ + from typing import Iterable, List, Sequence from _pytest import nodes # for type checking only @@ -30,13 +31,18 @@ def filter_items_by_shard( new_items.append(item) return new_items + class ShardPlugin: @staticmethod def pytest_addoption(parser): """Add pytest-shard specific configuration parameters.""" group = parser.getgroup("shard") group.addoption( - "--shard-id", dest="shard_id", type=positive_int, default=0, help="Number of this shard." + "--shard-id", + dest="shard_id", + type=positive_int, + default=0, + help="Number of this shard.", ) group.addoption( "--num-shards", @@ -60,6 +66,8 @@ def pytest_collection_modifyitems(config, items: List[nodes.Node]): shard_id = config.getoption("shard_id") shard_total = config.getoption("num_shards") if shard_id >= shard_total: - raise ValueError("shard_num = f{shard_num} must be less than shard_total = f{shard_total}") + raise ValueError( + "shard_num = f{shard_num} must be less than shard_total = f{shard_total}" + ) items[:] = filter_items_by_shard(items, shard_id, shard_total) From 77ce3d1da187027fdc08168b0a36a1715a207505 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Fri, 24 Jan 2025 10:11:05 -0700 Subject: [PATCH 5/8] code review --- py/private/py_pytest_main.bzl | 2 +- py/private/pytest.py.tmpl | 4 +++- py/private/pytest_shard/README.md | 9 +++++++++ py/private/pytest_shard/pytest_shard.py | 9 --------- 4 files changed, 13 insertions(+), 11 deletions(-) create mode 100644 py/private/pytest_shard/README.md diff --git a/py/private/py_pytest_main.bzl b/py/private/py_pytest_main.bzl index a8c4db70a..4ce6292a2 100644 --- a/py/private/py_pytest_main.bzl +++ b/py/private/py_pytest_main.bzl @@ -88,6 +88,6 @@ def py_pytest_main(name, py_library = default_py_library, deps = [], data = [], srcs = [test_main], tags = tags, visibility = visibility, - deps = deps + ["@aspect_rules_py//py/private/pytest_shard"], + deps = deps + [Label("//py/private/pytest_shard")], data = data, ) diff --git a/py/private/pytest.py.tmpl b/py/private/pytest.py.tmpl index 5bfd05069..befa31558 100644 --- a/py/private/pytest.py.tmpl +++ b/py/private/pytest.py.tmpl @@ -27,6 +27,7 @@ if __name__ == "__main__": os.environ["ENV"] = "testing" + plugins = [] args = [ "--verbose", "--ignore=external/", @@ -52,6 +53,7 @@ if __name__ == "__main__": f"--num-shards={test_total_shards}", ]) Path(test_shard_status_file).touch() + plugins.append(ShardPlugin()) test_filter = os.environ.get("TESTBRIDGE_TEST_ONLY") if test_filter is not None: @@ -65,7 +67,7 @@ if __name__ == "__main__": if len(cli_args) > 0: args.extend(cli_args) - exit_code = pytest.main(args, plugins=[ShardPlugin()]) + exit_code = pytest.main(args, plugins=plugins) if exit_code != 0: print("Pytest exit code: " + str(exit_code), file=sys.stderr) diff --git a/py/private/pytest_shard/README.md b/py/private/pytest_shard/README.md new file mode 100644 index 000000000..56bcce116 --- /dev/null +++ b/py/private/pytest_shard/README.md @@ -0,0 +1,9 @@ +# pytest-shard + +This is a fork of [pytest-shard](https://github.com/AdamGleave/pytest-shard) @ [4610a08](https://github.com/AdamGleave/pytest-shard/commit/64610a08dac6b0511b6d51cf895d0e1040d162ad) + +## Changes + +* The pytest hooks were moved into a class `ShardPlugin`, so that they can be loaded via `pytest.main` +* The sharding strategy was changed to a simple round-robin strategy + * The hash-bashed strategy was causing unbalanced or empty shards with small test sets \ No newline at end of file diff --git a/py/private/pytest_shard/pytest_shard.py b/py/private/pytest_shard/pytest_shard.py index bd7111416..d034400d0 100644 --- a/py/private/pytest_shard/pytest_shard.py +++ b/py/private/pytest_shard/pytest_shard.py @@ -1,12 +1,3 @@ -""" -This has been adapted from the original code at -https://github.com/AdamGleave/pytest-shard -The main difference is that the plugin has been converted to a class -so that it can be passed to pytest.main's plugins attribute, and the -shard selection was changed from a hash-based approach to a round-robin -approach for a more balanced distribution with smaller numbers of tests. -""" - from typing import Iterable, List, Sequence from _pytest import nodes # for type checking only From 5a17cb0bc4a8e67971609f03187f70499ac4e803 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Fri, 24 Jan 2025 10:14:41 -0700 Subject: [PATCH 6/8] also check total shards > 1 --- py/private/pytest.py.tmpl | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/py/private/pytest.py.tmpl b/py/private/pytest.py.tmpl index befa31558..ff0e89404 100644 --- a/py/private/pytest.py.tmpl +++ b/py/private/pytest.py.tmpl @@ -47,7 +47,10 @@ if __name__ == "__main__": test_shard_index = os.environ.get("TEST_SHARD_INDEX") test_total_shards = os.environ.get("TEST_TOTAL_SHARDS") test_shard_status_file = os.environ.get("TEST_SHARD_STATUS_FILE") - if all([test_shard_index, test_total_shards, test_shard_status_file]): + if ( + all([test_shard_index, test_total_shards, test_shard_status_file]) + and int(test_total_shards) > 1 + ): args.extend([ f"--shard-id={test_shard_index}", f"--num-shards={test_total_shards}", From b61b9e580e09d9ef741accf27512df4fb1a64e29 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Fri, 24 Jan 2025 10:20:18 -0700 Subject: [PATCH 7/8] format README --- py/private/pytest_shard/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/py/private/pytest_shard/README.md b/py/private/pytest_shard/README.md index 56bcce116..bf1c0770d 100644 --- a/py/private/pytest_shard/README.md +++ b/py/private/pytest_shard/README.md @@ -4,6 +4,6 @@ This is a fork of [pytest-shard](https://github.com/AdamGleave/pytest-shard) @ [ ## Changes -* The pytest hooks were moved into a class `ShardPlugin`, so that they can be loaded via `pytest.main` -* The sharding strategy was changed to a simple round-robin strategy - * The hash-bashed strategy was causing unbalanced or empty shards with small test sets \ No newline at end of file +- The pytest hooks were moved into a class `ShardPlugin`, so that they can be loaded via `pytest.main` +- The sharding strategy was changed to a simple round-robin strategy + - The hash-bashed strategy was causing unbalanced or empty shards with small test sets From 4e716cddf7c3d1f4fb8e721d553123efbf0d73c0 Mon Sep 17 00:00:00 2001 From: Vince Rose Date: Fri, 24 Jan 2025 10:45:32 -0700 Subject: [PATCH 8/8] add :__test__ as a dep in virtual_deps example --- examples/virtual_deps/BUILD.bazel | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/virtual_deps/BUILD.bazel b/examples/virtual_deps/BUILD.bazel index b71fd20cf..6e34e56f7 100644 --- a/examples/virtual_deps/BUILD.bazel +++ b/examples/virtual_deps/BUILD.bazel @@ -69,6 +69,7 @@ py_test( ), deps = [ requirement("pytest"), + "__test__", ":greet", ], )