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
15 changes: 15 additions & 0 deletions examples/pytest/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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__",
],
)
5 changes: 5 additions & 0 deletions examples/pytest/sharding_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
def test_shard_one():
assert True

def test_shard_two():
assert True
1 change: 1 addition & 0 deletions examples/virtual_deps/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ py_test(
),
deps = [
requirement("pytest"),
"__test__",
":greet",
],
)
2 changes: 1 addition & 1 deletion py/private/py_pytest_main.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
20 changes: 19 additions & 1 deletion py/private/pytest.py.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import sys
import os
from pathlib import Path
from typing import List

import pytest
Expand All @@ -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/",
Expand All @@ -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}")
Expand All @@ -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)
Expand Down
11 changes: 11 additions & 0 deletions py/private/pytest_shard/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -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"],
)
7 changes: 7 additions & 0 deletions py/private/pytest_shard/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2019 Adam Gleave
Comment thread
vinnybod marked this conversation as resolved.

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.
9 changes: 9 additions & 0 deletions py/private/pytest_shard/README.md
Original file line number Diff line number Diff line change
@@ -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
Empty file.
64 changes: 64 additions & 0 deletions py/private/pytest_shard/pytest_shard.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
from typing import Iterable, List, Sequence

from _pytest import nodes # for type checking only
Comment thread
alexeagle marked this conversation as resolved.


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:
Comment thread
vinnybod marked this conversation as resolved.
msg += ": " + ", ".join([item.nodeid for item in items])
return msg

@staticmethod
def pytest_collection_modifyitems(config, items: List[nodes.Node]):
Comment thread
alexeagle marked this conversation as resolved.
"""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)