feat(pytest_test): stop adding pytest-shard and pytest-randomly by default (#4529)

pytest_test added pytest-shard and pytest-randomly to the deps of every
test, so users had to add both to their requirements even when they did
not want a random test order. pytest-bazel 1.0 shards the tests itself
and seeds pytest-randomly only when it is installed, so neither plugin
is needed any more.

Stop adding them by default. The `pytest_shard` and `pytest_randomly`
args stay for compatibility: `pytest_shard` is deprecated and
`pytest_randomly` opts into a random test order. Use pytest-bazel 1.0.0
for the tests of rules_python.

Also add a "Testing with pytest" docs page on how to set up
pytest_test, with the main features of pytest-bazel and links to its
docs.

Fixes #4251

---------

Co-authored-by: Richard Levasseur <richardlev@gmail.com>
diff --git a/MODULE.bazel b/MODULE.bazel
index 51139cb..4b69b54 100644
--- a/MODULE.bazel
+++ b/MODULE.bazel
@@ -95,8 +95,6 @@
 )
 pip.dep(name = "pytest")
 pip.dep(name = "pytest-bazel")
-pip.dep(name = "pytest-randomly")
-pip.dep(name = "pytest-shard")
 use_repo(pip, "pypi", "rules_python_publish_deps")
 
 bazel_dep(
diff --git a/dev/pyproject.toml b/dev/pyproject.toml
index 0be689e..30410ba 100644
--- a/dev/pyproject.toml
+++ b/dev/pyproject.toml
@@ -19,8 +19,7 @@
     "macholib",
     "markupsafe",
     "pytest",
-    "pytest-bazel",
+    # >=1.0.0 for built-in test sharding and non-sandbox rootdir fixes.
+    "pytest-bazel>=1.0.0",
     "pytest-mock",
-    "pytest-randomly",
-    "pytest-shard",
 ]
diff --git a/dev/uv.lock b/dev/uv.lock
index 5b4db32..0fefcb0 100644
--- a/dev/uv.lock
+++ b/dev/uv.lock
@@ -627,13 +627,14 @@
 
 [[package]]
 name = "pytest-bazel"
-version = "0.1.6"
+version = "1.0.0"
 source = { registry = "https://pypi.org/simple" }
 dependencies = [
     { name = "pytest" },
+    { name = "tomli", marker = "python_full_version < '3.11'" },
 ]
 wheels = [
-    { url = "https://files.pythonhosted.org/packages/c2/90/4726a39728fb5a5f77a773c5e9d7bfd3a0120aa2029963a88fd06e2c5fb2/pytest_bazel-0.1.6-py3-none-any.whl", hash = "sha256:a29e80e1d67c3db801bdd4d0b6b742f2bfb48cd6841caa33401458e5c4e29c21", size = 10126, upload-time = "2025-10-31T08:41:17.165Z" },
+    { url = "https://files.pythonhosted.org/packages/95/30/8287af2d903b8e89be01f5319adf5f574363a83a3666077ec6667a283d8d/pytest_bazel-1.0.0-py3-none-any.whl", hash = "sha256:d60268fad51c707081463efa9e45b10d3012394acc6c83bcc7ae70900a98d2b7", size = 43475, upload-time = "2026-11-19T09:33:24.697Z" },
 ]
 
 [[package]]
@@ -649,30 +650,6 @@
 ]
 
 [[package]]
-name = "pytest-randomly"
-version = "5.0.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
-    { name = "pytest" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/01/3b/6a40e1b9d925651e601e056a97f60d8a1daeddeac03d5609be60cb4362ce/pytest_randomly-5.0.0.tar.gz", hash = "sha256:e9c575a5873ef168ddbe340ed9e97ce9edb4492ccc821e4b2ac6bb1f0ed515d2", size = 8542, upload-time = "2026-09-01T22:34:20.441Z" }
-wheels = [
-    { url = "https://files.pythonhosted.org/packages/10/b4/47e939285caad9a623d021512912ac08dc92a467ad075d179f43729d2934/pytest_randomly-5.0.0-py3-none-any.whl", hash = "sha256:8a0d4703115c0c25b38b6e129fc16b1947b9643ff26a41bc1d185d7e5a7689c1", size = 8920, upload-time = "2026-09-01T22:34:19.227Z" },
-]
-
-[[package]]
-name = "pytest-shard"
-version = "0.1.2"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
-    { name = "pytest" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/c6/ca/3efa6f3b84dab83220db45997e785be726684c2c2c4267bffb7d80101c7f/pytest-shard-0.1.2.tar.gz", hash = "sha256:b86a967fbfd1c8e50295095ccda031b7e890862ee06531d5142844f4c1d1cd67", size = 3579, upload-time = "2020-12-11T19:52:55.083Z" }
-wheels = [
-    { url = "https://files.pythonhosted.org/packages/65/7a/dbeb4c54e9fc3b59622f410091365f354a69cda1af10c3b83ac0ca6e6f4f/pytest_shard-0.1.2-py3-none-any.whl", hash = "sha256:407a1df385cebe1feb9b4d2e7eeee8b044f8a24f0919421233159a17c59be2b9", size = 4608, upload-time = "2020-12-11T19:52:54.226Z" },
-]
-
-[[package]]
 name = "pyyaml"
 version = "6.0.3"
 source = { registry = "https://pypi.org/simple" }
@@ -789,8 +766,6 @@
     { name = "pytest" },
     { name = "pytest-bazel" },
     { name = "pytest-mock" },
-    { name = "pytest-randomly" },
-    { name = "pytest-shard" },
     { name = "readthedocs-sphinx-ext" },
     { name = "sphinx", version = "8.1.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
     { name = "sphinx", version = "9.0.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" },
@@ -811,10 +786,8 @@
     { name = "pefile" },
     { name = "pyelftools" },
     { name = "pytest" },
-    { name = "pytest-bazel" },
+    { name = "pytest-bazel", specifier = ">=1.0.0" },
     { name = "pytest-mock" },
-    { name = "pytest-randomly" },
-    { name = "pytest-shard" },
     { name = "readthedocs-sphinx-ext" },
     { name = "sphinx" },
     { name = "sphinx-autodoc2" },
diff --git a/docs/index.md b/docs/index.md
index 0204f38..0b0f1b6 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -98,6 +98,7 @@
 pypi/index
 Toolchains <toolchains>
 coverage
+Testing with pytest <pytest>
 precompiling
 gazelle/docs/index
 REPL <repl>
diff --git a/docs/pytest.md b/docs/pytest.md
new file mode 100644
index 0000000..871dd06
--- /dev/null
+++ b/docs/pytest.md
@@ -0,0 +1,110 @@
+:::{default-domain} bzl
+:::
+
+# Testing with pytest
+
+{obj}`pytest_test` runs [pytest] tests with [pytest-bazel], a pytest runner
+that follows the Bazel [test encyclopedia]. It writes its own `main` that
+runs pytest on the `srcs`, so there is no `main` to maintain, and creates a
+test per Python version with `python_versions`.
+
+## Setup
+
+`pytest_test` depends on `@pypi//pytest` and `@pypi//pytest_bazel` by
+default. Add `pytest` and `pytest-bazel>=1.0` to the requirements that
+{obj}`pip.parse` reads for the {ref}`unified @pypi hub <unified-pypi-hub>`,
+or pass other targets with the `pytest` and `pytest_bazel` arguments.
+
+```starlark
+load("@rules_python//python:pytest_test.bzl", "pytest_test")
+
+pytest_test(
+    name = "lib_test",
+    srcs = ["lib_test.py"],
+    deps = [":lib"],
+)
+
+pytest_test(
+    name = "lib_all_test",
+    srcs = ["lib_test.py"],
+    # A `lib_all_py3.13_test` and a `lib_all_py3.14_test` in a test suite
+    # named `lib_all_test`.
+    python_versions = ["3.13", "3.14"],
+    deps = [":lib"],
+)
+```
+
+`pytest-randomly` is optional. Pass `pytest_randomly = "@pypi//pytest_randomly"`
+to run the tests in a random order, which `pytest-bazel` seeds from
+`--runs_per_test`, so that each run uses a different order that can be
+reproduced.
+
+To use `pytest-bazel` with a plain {obj}`py_test`, call it from the `main`:
+
+```python
+import pytest_bazel
+
+if __name__ == "__main__":
+    pytest_bazel.main()
+```
+
+## What pytest-bazel does
+
+The [pytest-bazel docs][pytest-bazel] show each feature with the output of
+an example. The main ones are:
+
+| Bazel | pytest-bazel | Docs |
+| --- | --- | --- |
+| `--test_filter` | Selects tests by their exact names, e.g. `TestClass.test_fn`, a path or a pytest node id, or several of them separated by commas. A filter with spaces is a `-k` expression. | [Test filter][test-filter] |
+| `shard_count` | Splits the tests into balanced shards, no `pytest-shard` needed. | [Sharding][sharding] |
+| `--runs_per_test`, `--test_env=TEST_RANDOM_SEED=...` | Seeds `pytest-randomly`, or `random.seed` without it. | [Runs per test][runs-per-test] |
+| `--test_runner_fail_fast` | Stops at the first failure. | [Fail fast][fail-fast] |
+| Test timeouts | Prints the stacks of all threads, and of the `pytest-xdist` workers, when Bazel stops the test. | [Timeout][timeout], [xdist][xdist] |
+| `bazel-testlogs` | Writes the JUnit XML with the output of failed tests, keeps the `tmp_path` of failed tests in `test.outputs` and writes the warnings to `test.warnings`. | [JUnit XML][junit-xml], [Keep failed tmp_path][keep-failed-tmp-path], [Warnings][warnings] |
+| `TEST_TMPDIR` | Points `TMPDIR` and pytest's `tmp_path` at it, so tests do not write outside the sandbox. | [Temporary directories][tmpdir] |
+| `bazel run` | Debug a test with `bazel run //pkg:test -- --pdb`, as `bazel test` gives tests no terminal. | [Debugging][debugging] |
+
+Paths in tracebacks and warnings are relative to the workspace root, so
+editors can open them, see [Editors][editors].
+
+## Configuration
+
+pytest reads its config file, e.g. `pytest.ini` or `pyproject.toml`, from the
+runfiles: add it to the `data` of the test. `pytest-bazel` also uses the
+config file in the Bazel package of the test or in its parents, see
+[Config from package][config-from-package].
+
+Pass pytest flags with `args` or `--test_arg`, e.g.
+`bazel test //pkg:test --test_arg=-vv`.
+
+The behaviours of `pytest-bazel` that changed in 1.0 can be turned off with
+an env var set to `0`, in the `env` of a test or for all tests with
+`--test_env`:
+
+```starlark
+pytest_test(
+    name = "lib_test",
+    srcs = ["lib_test.py"],
+    env = {"PYTEST_BAZEL_EXACT_TEST_FILTER": "0"},
+)
+```
+
+See the [flags][flags] for the list.
+
+[pytest]: https://docs.pytest.org/
+[pytest-bazel]: https://pytest-bazel.readthedocs.io/latest/
+[test encyclopedia]: https://bazel.build/reference/test-encyclopedia
+[test-filter]: https://pytest-bazel.readthedocs.io/latest/features/test-filter.html
+[sharding]: https://pytest-bazel.readthedocs.io/latest/features/sharding.html
+[runs-per-test]: https://pytest-bazel.readthedocs.io/latest/features/runs-per-test.html
+[fail-fast]: https://pytest-bazel.readthedocs.io/latest/features/fail-fast.html
+[timeout]: https://pytest-bazel.readthedocs.io/latest/features/timeout.html
+[xdist]: https://pytest-bazel.readthedocs.io/latest/features/xdist.html
+[junit-xml]: https://pytest-bazel.readthedocs.io/latest/features/junit-xml.html
+[keep-failed-tmp-path]: https://pytest-bazel.readthedocs.io/latest/features/keep-failed-tmp-path.html
+[warnings]: https://pytest-bazel.readthedocs.io/latest/features/warnings.html
+[tmpdir]: https://pytest-bazel.readthedocs.io/latest/features/tmpdir.html
+[debugging]: https://pytest-bazel.readthedocs.io/latest/features/debugging.html
+[editors]: https://pytest-bazel.readthedocs.io/latest/editors.html
+[config-from-package]: https://pytest-bazel.readthedocs.io/latest/features/config-from-package.html
+[flags]: https://github.com/aignas/pytest-bazel#flags
diff --git a/news/4529.changed.md b/news/4529.changed.md
new file mode 100644
index 0000000..768f47f
--- /dev/null
+++ b/news/4529.changed.md
@@ -0,0 +1,6 @@
+(rules) {obj}`pytest_test` uses `pytest-bazel` 1.0, which shards the tests
+itself, so `pytest-shard` and `pytest-randomly` are no longer added to the
+`deps` by default. `pytest_shard` is deprecated, and `pytest_randomly` is
+optional: set it to run the tests in a random order. `pytest-bazel` 1.0 also
+changes some defaults, e.g. `--test_filter` selects tests by their exact
+names, see its [changelog](https://github.com/aignas/pytest-bazel/blob/main/CHANGELOG.md).
diff --git a/python/private/pytest_test/BUILD.bazel b/python/private/pytest_test/BUILD.bazel
index b877cdd..a7e105b 100644
--- a/python/private/pytest_test/BUILD.bazel
+++ b/python/private/pytest_test/BUILD.bazel
@@ -35,15 +35,3 @@
     actual = "@pypi//pytest_bazel",
     visibility = NOT_ACTUALLY_PUBLIC,
 )
-
-alias(
-    name = "default_pytest_shard",
-    actual = "@pypi//pytest_shard",
-    visibility = NOT_ACTUALLY_PUBLIC,
-)
-
-alias(
-    name = "default_pytest_randomly",
-    actual = "@pypi//pytest_randomly",
-    visibility = NOT_ACTUALLY_PUBLIC,
-)
diff --git a/python/private/pytest_test/pytest_test.bzl b/python/private/pytest_test/pytest_test.bzl
index 5e66bfd..da6ab55 100644
--- a/python/private/pytest_test/pytest_test.bzl
+++ b/python/private/pytest_test/pytest_test.bzl
@@ -4,8 +4,6 @@
 
 _DEFAULT_PYTEST = Label("//python/private/pytest_test:default_pytest")
 _DEFAULT_PYTEST_BAZEL = Label("//python/private/pytest_test:default_pytest_bazel")
-_DEFAULT_PYTEST_SHARD = Label("//python/private/pytest_test:default_pytest_shard")
-_DEFAULT_PYTEST_RANDOMLY = Label("//python/private/pytest_test:default_pytest_randomly")
 
 def pytest_test(
         *,
@@ -19,35 +17,57 @@
         **kwargs):
     """Run pytest tests.
 
+    The tests are run with
+    [pytest-bazel](https://pytest-bazel.readthedocs.io/latest/), which makes
+    pytest follow the Bazel test encyclopedia, e.g. for `--test_filter`,
+    sharding, `--runs_per_test` and the test outputs. See {doc}`/pytest` for
+    setup and configuration.
+
     :::{versionadded} 2.5.0
     :::
 
+    :::{versionchanged} VERSION_NEXT_FEATURE
+    `pytest-randomly` and `pytest-shard` are no longer added by default, as
+    `pytest-bazel` 1.0 shards the tests itself.
+    :::
+
     Args:
         name: A unique name for this target.
         srcs: List of source files (test files). These are the files that
             pytest will run as tests.
         pytest: The pytest target to use. Defaults to `@pypi//pytest`.
-        pytest_bazel: The pytest-bazel target to use. Defaults to
-            `@pypi//pytest_bazel`.
-        pytest_shard: The pytest-shard target to use. Defaults to
-            `@pypi//pytest_shard`.
-        pytest_randomly: The pytest-randomly target to use. Defaults to
-            `@pypi//pytest_randomly`. Pass `@rules_python//python:none` or
-            another empty {obj}`py_library` target to disable it.
+        pytest_bazel: The pytest-bazel target to use (`pytest-bazel >= 1.0`).
+            Defaults to `@pypi//pytest_bazel`.
+        pytest_shard: Deprecated; `pytest-bazel >= 0.3.0` shards tests itself.
+            If set and `shard_count` is specified, the target is added to
+            `deps`.
+        pytest_randomly: An optional pytest-randomly target, e.g.
+            `@pypi//pytest_randomly`, to run the tests in a random order.
+            `pytest-bazel` seeds it from `TEST_RANDOM_SEED` or the
+            `--runs_per_test` run number. If set, the target is added to
+            `deps`.
         python_versions: List of Python versions to test against. If specified,
             a test is created for each version and grouped under a test_suite
             named `name`.
         **kwargs: Additional arguments passed to {obj}`py_test`. Note that
             `main` is not a supported argument.
     """
+    deps = kwargs.pop("deps", None) or []
+    if pytest == None:
+        pytest = _DEFAULT_PYTEST
+    if pytest_bazel == None:
+        pytest_bazel = _DEFAULT_PYTEST_BAZEL
+    extra_deps = [pytest, pytest_bazel]
+    if pytest_shard != None and kwargs.get("shard_count"):
+        extra_deps.append(pytest_shard)
+    if pytest_randomly != None and pytest_randomly not in extra_deps:
+        extra_deps.append(pytest_randomly)
+    kwargs["deps"] = deps + extra_deps
+
     if python_versions != None:
         _multi_pytest_test(
             name = name,
             srcs = srcs,
-            pytest = pytest,
-            pytest_bazel = pytest_bazel,
-            pytest_shard = pytest_shard,
-            pytest_randomly = pytest_randomly,
             python_versions = python_versions,
             **kwargs
         )
@@ -55,10 +75,6 @@
         _single_pytest_test(
             name = name,
             srcs = srcs,
-            pytest = pytest,
-            pytest_bazel = pytest_bazel,
-            pytest_shard = pytest_shard,
-            pytest_randomly = pytest_randomly,
             **kwargs
         )
 
@@ -66,10 +82,6 @@
         *,
         name,
         srcs,
-        pytest = None,
-        pytest_bazel = None,
-        pytest_shard = None,
-        pytest_randomly = None,
         python_versions,
         **kwargs):
     if "python_version" in kwargs:
@@ -86,10 +98,6 @@
         _single_pytest_test(
             name = test_name,
             srcs = srcs,
-            pytest = pytest,
-            pytest_bazel = pytest_bazel,
-            pytest_shard = pytest_shard,
-            pytest_randomly = pytest_randomly,
             python_version = python_version,
             **kwargs
         )
@@ -109,21 +117,7 @@
         *,
         name,
         srcs,
-        pytest = None,
-        pytest_bazel = None,
-        pytest_shard = None,
-        pytest_randomly = None,
         **kwargs):
-    deps = kwargs.pop("deps", None) or []
-    if pytest == None:
-        pytest = _DEFAULT_PYTEST
-    if pytest_bazel == None:
-        pytest_bazel = _DEFAULT_PYTEST_BAZEL
-    if pytest_shard == None:
-        pytest_shard = _DEFAULT_PYTEST_SHARD
-    if pytest_randomly == None:
-        pytest_randomly = _DEFAULT_PYTEST_RANDOMLY
-
     bootstrap_target = name + "_bootstrap"
     main_file = name + "_boot.py"
     _write_pytest_bootstrap(
@@ -133,20 +127,10 @@
         tags = ["manual"],
     )
 
-    extra_deps = [
-        pytest,
-        pytest_bazel,
-        pytest_randomly,
-    ]
-    if kwargs.get("shard_count"):
-        extra_deps.append(pytest_shard)
-
-    kwargs = dict(kwargs)
     py_test(
         name = name,
         main = main_file,
         srcs = [bootstrap_target] + srcs,
-        deps = deps + extra_deps,
         **kwargs
     )
 
diff --git a/python/pytest_test.bzl b/python/pytest_test.bzl
index 52facab..26d1634 100644
--- a/python/pytest_test.bzl
+++ b/python/pytest_test.bzl
@@ -1,16 +1,16 @@
-"""
-A public entrypoint for `pytest_test` rule.
+"""Public entrypoint for the {obj}`pytest_test` macro.
 
 Use this to create test targets using [pytest](https://pypi.org/project/pytest)
-instead of having to declare the main entrypoint for your {obj}`py_test` rules.
-
-In order to use this rule you'll have to have the following packages:
-* `pytest` and `pytest-bazel` - used to invoke pytest.
-* `pytest-randomly` - used to have consistent random number usage.
-* `pytest-shard` - optional, used only if tests need to be sharded.
+instead of declaring a `main` entrypoint for {obj}`py_test` rules. See
+{doc}`/pytest` for setup (`pytest` and `pytest-bazel >= 1.0`) and usage.
 
 :::{versionadded} 2.5.0
 :::
+
+:::{versionchanged} VERSION_NEXT_FEATURE
+`pytest-randomly` and `pytest-shard` are no longer required by default;
+sharding requires `pytest-bazel >= 0.3.0`.
+:::
 """
 
 load("//python/private/pytest_test:pytest_test.bzl", _pytest_test = "pytest_test")
diff --git a/tests/pytest_test/BUILD.bazel b/tests/pytest_test/BUILD.bazel
index 664566d..3a5beac 100644
--- a/tests/pytest_test/BUILD.bazel
+++ b/tests/pytest_test/BUILD.bazel
@@ -24,19 +24,26 @@
     shard_count = 2,
     target_compatible_with = SUPPORTS_BZLMOD,
     # Verify that pytest_test handles select() expressions in deps when
-    # appending default and sharding dependencies.
+    # appending default dependencies.
     deps = select({
         "//conditions:default": [],
     }),
 )
 
 pytest_test(
-    name = "pytest_no_randomly_test",
+    name = "pytest_optional_deps_test",
     srcs = [
         "basic_test.py",
     ],
+    # Verify explicit plugin target args work with select() in deps without
+    # duplicating labels when both use //python:none.
     pytest_randomly = "//python:none",
+    pytest_shard = "//python:none",
+    shard_count = 2,
     target_compatible_with = SUPPORTS_BZLMOD,
+    deps = select({
+        "//conditions:default": [],
+    }),
 )
 
 pytest_test(
diff --git a/tests/pytest_test/pytest_test_tests.bzl b/tests/pytest_test/pytest_test_tests.bzl
index 2d75b76..62d8da8 100644
--- a/tests/pytest_test/pytest_test_tests.bzl
+++ b/tests/pytest_test/pytest_test_tests.bzl
@@ -1,12 +1,96 @@
 """Tests for pytest_test."""
 
+load("@rules_testing//lib:analysis_test.bzl", "analysis_test")
 load("@rules_testing//lib:test_suite.bzl", "test_suite")
+load("@rules_testing//lib:util.bzl", "TestingAspectInfo", rt_util = "util")
+load("//python:py_library.bzl", "py_library")
+load("//python:pytest_test.bzl", "pytest_test")
 load(
     "//python/private/pytest_test:pytest_test.bzl",
     "get_version_test_name",
 )  # buildifier: disable=bzl-visibility
 
 _tests = []
+_basic_tests = []
+
+def _define_stub_deps(name):
+    stub_names = (
+        "pytest",
+        "pytest_bazel",
+        "pytest_shard",
+        "pytest_randomly",
+        "user_dep",
+    )
+    for suffix in stub_names:
+        rt_util.helper_target(
+            py_library,
+            name = name + "_" + suffix,
+        )
+
+def _test_default_deps(name):
+    _define_stub_deps(name)
+    rt_util.helper_target(
+        pytest_test,
+        name = name + "_subject",
+        srcs = ["basic_test.py"],
+        pytest = ":" + name + "_pytest",
+        pytest_bazel = ":" + name + "_pytest_bazel",
+        # Verify pytest_shard is ignored when shard_count is unset.
+        pytest_shard = ":" + name + "_pytest_shard",
+    )
+    analysis_test(
+        name = name,
+        impl = _test_default_deps_impl,
+        target = name + "_subject",
+    )
+
+def _test_default_deps_impl(env, target):
+    prefix = target.label.name[:-len("_subject")]
+    env.expect.that_collection(target[TestingAspectInfo].attrs.deps).transform(
+        desc = "target.label",
+        map_each = lambda t: t.label,
+    ).contains_exactly([
+        Label(":" + prefix + "_pytest"),
+        Label(":" + prefix + "_pytest_bazel"),
+    ])
+
+_tests.append(_test_default_deps)
+
+def _test_optional_deps_with_select(name):
+    _define_stub_deps(name)
+    rt_util.helper_target(
+        pytest_test,
+        name = name + "_subject",
+        srcs = ["basic_test.py"],
+        pytest = ":" + name + "_pytest",
+        pytest_bazel = ":" + name + "_pytest_bazel",
+        pytest_shard = ":" + name + "_pytest_shard",
+        pytest_randomly = ":" + name + "_pytest_randomly",
+        shard_count = 2,
+        deps = select({
+            "//conditions:default": [":" + name + "_user_dep"],
+        }),
+    )
+    analysis_test(
+        name = name,
+        impl = _test_optional_deps_with_select_impl,
+        target = name + "_subject",
+    )
+
+def _test_optional_deps_with_select_impl(env, target):
+    prefix = target.label.name[:-len("_subject")]
+    env.expect.that_collection(target[TestingAspectInfo].attrs.deps).transform(
+        desc = "target.label",
+        map_each = lambda t: t.label,
+    ).contains_exactly([
+        Label(":" + prefix + "_user_dep"),
+        Label(":" + prefix + "_pytest"),
+        Label(":" + prefix + "_pytest_bazel"),
+        Label(":" + prefix + "_pytest_shard"),
+        Label(":" + prefix + "_pytest_randomly"),
+    ])
+
+_tests.append(_test_optional_deps_with_select)
 
 def _test_get_version_test_name(env):
     want = {
@@ -26,7 +110,7 @@
     }
     env.expect.that_dict(actual).contains_exactly(want)
 
-_tests.append(_test_get_version_test_name)
+_basic_tests.append(_test_get_version_test_name)
 
 def pytest_test_test_suite(name):
     """Create the test suite.
@@ -34,4 +118,4 @@
     Args:
         name: The name of the test suite.
     """
-    test_suite(name = name, basic_tests = _tests)
+    test_suite(name = name, tests = _tests, basic_tests = _basic_tests)