diff --git a/examples/pytest/BUILD.bazel b/examples/pytest/BUILD.bazel index 085c3f54b..d423cacdd 100644 --- a/examples/pytest/BUILD.bazel +++ b/examples/pytest/BUILD.bazel @@ -58,3 +58,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/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", ], ) diff --git a/py/private/py_pytest_main.bzl b/py/private/py_pytest_main.bzl index 9237c8690..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, + deps = deps + [Label("//py/private/pytest_shard")], data = data, ) diff --git a/py/private/pytest.py.tmpl b/py/private/pytest.py.tmpl index cf15fd8fe..dd3acb056 100644 --- a/py/private/pytest.py.tmpl +++ b/py/private/pytest.py.tmpl @@ -14,6 +14,7 @@ import sys import os +from pathlib import Path from typing import List import pytest @@ -33,12 +34,15 @@ if "COVERAGE_MANIFEST" in os.environ: print("WARNING: python coverage setup failed. Do you need to include the 'coverage' library as a dependency of py_pytest_main?", e) pass +from pytest_shard import ShardPlugin + if __name__ == "__main__": # Change to the directory where we need to run the test or execute a no-op $$CHDIR$$ os.environ["ENV"] = "testing" + plugins = [] args = [ "--verbose", "--ignore=external/", @@ -55,6 +59,20 @@ 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]) + and int(test_total_shards) > 1 + ): + args.extend([ + f"--shard-id={test_shard_index}", + 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: args.append(f"-k={test_filter}") @@ -67,7 +85,7 @@ if __name__ == "__main__": if len(cli_args) > 0: args.extend(cli_args) - exit_code = pytest.main(args) + 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/BUILD.bazel b/py/private/pytest_shard/BUILD.bazel new file mode 100644 index 000000000..5bcf8994f --- /dev/null +++ b/py/private/pytest_shard/BUILD.bazel @@ -0,0 +1,11 @@ +load("@aspect_rules_py//py:defs.bzl", "py_library") + +py_library( + name = "pytest_shard", + srcs = [ + "__init__.py", + ":pytest_shard.py", + ], + imports = ["."], + 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/README.md b/py/private/pytest_shard/README.md new file mode 100644 index 000000000..bf1c0770d --- /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 diff --git a/py/private/pytest_shard/__init__.py b/py/private/pytest_shard/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/py/private/pytest_shard/pytest_shard.py b/py/private/pytest_shard/pytest_shard.py new file mode 100644 index 000000000..d034400d0 --- /dev/null +++ b/py/private/pytest_shard/pytest_shard.py @@ -0,0 +1,64 @@ +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)