diff --git a/docs/pypi/download.md b/docs/pypi/download.md index ad8b40e70d..121f254fb9 100644 --- a/docs/pypi/download.md +++ b/docs/pypi/download.md @@ -243,6 +243,35 @@ the `pyproject.toml` selects the optional dependencies of the project. The packages that are not part of the hub are ignored, so a single `pyproject.toml` can list tools that are missing from the lock file. +### Testonly Packages + +Set {attr}`pip.configure.testonly` to make the selected packages testonly, so +that they can only be used by tests and other testonly targets: + +```starlark +pip.configure( + hub_name = "pypi_hub", + dependency_groups = ["default"], +) +pip.configure( + hub_name = "pypi_hub", + dependency_groups = ["group:test"], + testonly = True, +) +``` + +A package that is also selected by a tag without `testonly` is not testonly. +The testonly packages are left out of the `all_requirements`, +`all_whl_requirements` and `all_data_requirements` lists in the hub's +`requirements.bzl` and are listed in `all_testonly_requirements` instead. In +the [Unified @pypi Hub](unified-pypi-hub), the targets of a package point to +the hub that is selected, so the package is testonly when it is testonly in +that hub. + +Only the targets of the hub are testonly. The other packages of the hub can +depend on the testonly packages, so a testonly package is still a transitive +dependency of the packages that need it, even if they are not testonly. + :::{versionadded} VERSION_NEXT_FEATURE ::: diff --git a/news/4428.added.md b/news/4428.added.md new file mode 100644 index 0000000000..179e302535 --- /dev/null +++ b/news/4428.added.md @@ -0,0 +1,3 @@ +(pypi) Added {attr}`pip.configure.testonly` to make the packages selected by +{obj}`pip.configure` testonly +([#3413](https://github.com/bazel-contrib/rules_python/issues/3413)). diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index e867cd9163..b940fe83cf 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -363,6 +363,7 @@ bzl_library( deps = [ ":labels", ":whl_library_deps_targets", + "//python:py_library", "//python/private:common_labels", "//python/private:text_util", "@bazel_skylib//lib:selects", diff --git a/python/private/pypi/config.bzl.tmpl b/python/private/pypi/config.bzl.tmpl index 1037153cac..b529e8a5e5 100644 --- a/python/private/pypi/config.bzl.tmpl +++ b/python/private/pypi/config.bzl.tmpl @@ -5,3 +5,5 @@ with your usecase. This may change in between rules_python versions without any """ packages = %%PACKAGES%% + +testonly_packages = %%TESTONLY_PACKAGES%% diff --git a/python/private/pypi/extension.bzl b/python/private/pypi/extension.bzl index 753e34e541..7ffa5d8c20 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -390,16 +390,30 @@ You cannot use both the additive_build_content and additive_build_content_file a # The `all_*requirements` only list the selected packages that are # available on all of the platforms, while all of the selected packages # stay public. - for hub_name, packages in configured_hubs.items(): - selected = {name: None for name in packages} + testonly_packages = {} + unified_testonly_packages = {} + for hub_name, info in configured_hubs.items(): + selected = {name: None for name in info.packages} exposed_packages[hub_name] = [ name for name in exposed_packages[hub_name] if name in selected ] + testonly_packages[hub_name] = info.testonly_packages + + # The unified hub only has aliases and `testonly` is enforced by the + # targets of the hubs that they point to, so a package is only marked as + # testonly there if it is testonly in all of the hubs that have it. + for hub_name, hub in hubs.items(): + info = configured_hubs.get(hub_name) + hub_testonly = {pkg: None for pkg in info.testonly_packages} if info else {} + for pkg in (info.packages if info else hub.packages): + unified_testonly_packages[pkg] = ( + unified_testonly_packages.get(pkg, True) and pkg in hub_testonly + ) return struct( - # dict[str, list[str]]: configured hubs and exposed packages. + # dict[str, struct]: configured hubs, see `hub_exposure`. configured_hubs = configured_hubs, config = config, declared_deps = declared_deps, @@ -409,7 +423,13 @@ You cannot use both the additive_build_content and additive_build_content_file a facts = simpleapi_cache.get_facts(), hub_group_map = hub_group_map, hub_whl_map = hub_whl_map, + testonly_packages = testonly_packages, unified_hub_requirements_bzl = config.unified_hub_requirements_bzl, + unified_testonly_packages = sorted([ + pkg + for pkg, testonly in unified_testonly_packages.items() + if testonly + ]), whl_libraries = whl_libraries, whl_mods = whl_mods, platform_config_settings = { @@ -434,10 +454,9 @@ def _create_unified_hub_repo(mods): for hub_name in hubs: # The hubs configured with `pip.configure` only expose some packages. - hub_packages = mods.configured_hubs.get( - hub_name, - mods.hub_whl_map[hub_name], - ) + hub_packages = mods.hub_whl_map[hub_name] + if hub_name in mods.configured_hubs: + hub_packages = mods.configured_hubs[hub_name].packages for pkg_name in hub_packages: norm_pkg = normalize_name(pkg_name) if norm_pkg not in packages: @@ -469,6 +488,7 @@ def _create_unified_hub_repo(mods): hubs = hubs, packages = packages, requirements_bzl = mods.unified_hub_requirements_bzl, + testonly_packages = mods.unified_testonly_packages, ) def _pip_impl(module_ctx): @@ -562,7 +582,10 @@ def _pip_impl(module_ctx): groups = mods.hub_group_map.get(hub_name), # The hubs configured with `pip.configure` hide the other packages. hide_unexposed_packages = hub_name in mods.configured_hubs, - public_packages = mods.configured_hubs.get(hub_name, []), + public_packages = ( + mods.configured_hubs[hub_name].packages if hub_name in mods.configured_hubs else [] + ), + testonly_packages = mods.testonly_packages.get(hub_name, []), ) _create_unified_hub_repo(mods) @@ -1178,6 +1201,24 @@ the same module and hub, then to the {attr}`pip.parse.pyproject_toml` of the hub, then to {attr}`pip.default.pyproject_toml` if the hub is defined by the root module. It is only needed when {attr}`dependency_groups` is set. +:::{versionadded} VERSION_NEXT_FEATURE +::: +""", + ), + "testonly": attr.bool( + default = False, + doc = """\ +Make the aliases of the selected packages testonly. A package that is also +selected by a `pip.configure` tag without `testonly` is not testonly. It can't +be used with `["*", "transitive"]`, which exposes all of the packages. + +The testonly packages are left out of the `all_requirements`, +`all_whl_requirements` and `all_data_requirements` lists in the hub's +`requirements.bzl` and listed in `all_testonly_requirements` instead. In the +[Unified @pypi Hub](unified-pypi-hub), the targets of a package point to the +hub that is selected, so the package is testonly when it is testonly in that +hub. + :::{versionadded} VERSION_NEXT_FEATURE ::: """, diff --git a/python/private/pypi/generate_whl_library_build_bazel.bzl b/python/private/pypi/generate_whl_library_build_bazel.bzl index bec45bb08f..be24a1463a 100644 --- a/python/private/pypi/generate_whl_library_build_bazel.bzl +++ b/python/private/pypi/generate_whl_library_build_bazel.bzl @@ -29,6 +29,7 @@ _RENDER = { "requires_dist": render.list, "srcs_exclude": render.list, "tags": render.list, + "testonly_deps": str, } # NOTE @aignas 2024-10-25: We have to keep this so that files in @@ -94,8 +95,9 @@ def generate_whl_library_build_bazel( # no deps, we can leave the extra loads out pass elif config_load: - loads.append("""load("{}", "{}")""".format(config_load, "packages")) + loads.append("""load("{}", "packages", "testonly_packages")""".format(config_load)) kwargs["include"] = "packages" + kwargs["testonly_deps"] = "testonly_packages" kwargs["requires_dist"] = requires_dist else: kwargs["requires_dist"] = requires_dist diff --git a/python/private/pypi/hub_exposure.bzl b/python/private/pypi/hub_exposure.bzl index 7393c28fbe..3098af040e 100644 --- a/python/private/pypi/hub_exposure.bzl +++ b/python/private/pypi/hub_exposure.bzl @@ -18,10 +18,17 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): _fail: {type}`callable` the failure function, mainly for testing. Returns: - {type}`dict[str, list[str]] | None` the configured hubs mapped to the - sorted packages that they expose. The hubs that are not configured or - that expose all of their packages are not included, so that they - behave the same. Returns `None` on failure. + {type}`dict[str, struct] | None` the configured hubs mapped to a + struct with: + * `packages`: {type}`list[str]` the sorted packages that the hub + exposes. + * `testonly_packages`: {type}`list[str]` the sorted packages whose + aliases are testonly. A package is testonly only if all of the + tags that select it are testonly. + + The hubs that are not configured or that expose all of their packages + are not included, so that they behave the same. Returns `None` on + failure. """ # The root module wins over the owner of the hub when both configure it. @@ -60,6 +67,9 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): last_pyproject[hub] = tag.pyproject_toml if not tag.dependency_groups: # The tag does not select any packages. + if tag.testonly: + _fail("pip.configure() for hub '{}' uses `testonly`, which needs the `dependency_groups` of the testonly packages".format(hub)) + return None continue pyproject = last_pyproject.get(hub) or info.pyproject @@ -80,6 +90,9 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): if selection == None: return None if selection.all: + if tag.testonly: + _fail("pip.configure() for hub '{}' cannot use `testonly` when exposing all of the packages with {}".format(hub, tag.dependency_groups)) + return None exposes_all[hub] = None # Multiple tags for the same hub are combined. @@ -88,10 +101,13 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): # The pyproject.toml may list packages that are not in the hub, # e.g. tools that are not locked. if name in info.packages: - exposed[name] = None + exposed[name] = exposed.get(name, True) and tag.testonly return { - hub: sorted(packages) + hub: struct( + packages = sorted(packages), + testonly_packages = sorted([name for name, testonly in packages.items() if testonly]), + ) for hub, packages in configured.items() if hub not in exposes_all } diff --git a/python/private/pypi/hub_repository.bzl b/python/private/pypi/hub_repository.bzl index c401168873..bf3a91b855 100644 --- a/python/private/pypi/hub_repository.bzl +++ b/python/private/pypi/hub_repository.bzl @@ -32,6 +32,7 @@ def _impl(rctx): else: bzl_packages = rctx.attr.packages or rctx.attr.whl_map.keys() exposed_packages = None + testonly_packages = rctx.attr.testonly_packages aliases = render_multiplatform_pkg_aliases( aliases = { key: _whl_config_settings_from_json(values) @@ -41,6 +42,7 @@ def _impl(rctx): extra_hub_aliases = rctx.attr.extra_hub_aliases, requirement_cycles = rctx.attr.groups, platform_config_settings = rctx.attr.platform_config_settings, + testonly_packages = testonly_packages, ) for path, contents in aliases.items(): rctx.file(path, contents) @@ -57,20 +59,31 @@ def _impl(rctx): rctx.attr._config_template, substitutions = { "%%PACKAGES%%": render.dict(rctx.attr.whl_map, value_repr = lambda x: "None"), + "%%TESTONLY_PACKAGES%%": render.list(sorted(testonly_packages)), }, ) + + # The testonly packages are only listed in `all_testonly_requirements`, + # which also leaves out the packages that are not available on all of the + # platforms. + all_packages = [p for p in bzl_packages if p not in testonly_packages] + all_testonly_packages = [p for p in bzl_packages if p in testonly_packages] rctx.template("requirements.bzl", rctx.attr._requirements_bzl_template, substitutions = { "%%ALL_DATA_REQUIREMENTS%%": render.list([ macro_tmpl.format(p, "data") - for p in bzl_packages + for p in all_packages ]), "%%ALL_REQUIREMENTS%%": render.list([ macro_tmpl.format(p, "pkg") - for p in bzl_packages + for p in all_packages + ]), + "%%ALL_TESTONLY_REQUIREMENTS%%": render.list([ + macro_tmpl.format(p, "pkg") + for p in all_testonly_packages ]), "%%ALL_WHL_REQUIREMENTS_BY_PACKAGE%%": render.dict({ p: macro_tmpl.format(p, "whl") - for p in bzl_packages + for p in all_packages }), "%%MACRO_TMPL%%": macro_tmpl, }) @@ -114,6 +127,10 @@ the platforms. mandatory = True, doc = "The apparent name of the repo. This is needed because in bzlmod, the name attribute becomes the canonical name.", ), + "testonly_packages": attr.string_list( + default = [], + doc = "The packages whose aliases should be testonly.", + ), "whl_map": attr.string_dict( mandatory = True, doc = """\ diff --git a/python/private/pypi/labels.bzl b/python/private/pypi/labels.bzl index c77167b593..3b6385e3eb 100644 --- a/python/private/pypi/labels.bzl +++ b/python/private/pypi/labels.bzl @@ -20,6 +20,10 @@ WHEEL_FILE_IMPL_LABEL = "_whl" WHEEL_FILE = "whl_file" PY_LIBRARY_PUBLIC_LABEL = "pkg" PY_LIBRARY_IMPL_LABEL = "_pkg" + +# The prefix of the hub targets that the `testonly` public targets wrap. The +# whl repositories depend on them, because they are not `testonly`. +TESTONLY_IMPL_PREFIX = "_testonly_" PY_SRCS_LABEL = "srcs" DATA_LABEL = "data" DIST_INFO_LABEL = "dist_info" diff --git a/python/private/pypi/pip_repository.bzl b/python/private/pypi/pip_repository.bzl index d02c62eae1..22946ecbd5 100644 --- a/python/private/pypi/pip_repository.bzl +++ b/python/private/pypi/pip_repository.bzl @@ -276,6 +276,7 @@ def _pip_repository_impl(rctx): pkg: None for pkg in bzl_packages }, value_repr = lambda x: "None"), + "%%TESTONLY_PACKAGES%%": "[]", }, ) config_repo_template = repr(rctx.attr.name) diff --git a/python/private/pypi/pkg_aliases.bzl b/python/private/pypi/pkg_aliases.bzl index 227e9bf10f..b70380469c 100644 --- a/python/private/pypi/pkg_aliases.bzl +++ b/python/private/pypi/pkg_aliases.bzl @@ -32,6 +32,7 @@ setting maps to and their precedence, refer to documentation on that page. """ load("@bazel_skylib//lib:selects.bzl", "selects") +load("//python:py_library.bzl", "py_library") load("//python/private:common_labels.bzl", "labels") load("//python/private:text_util.bzl", "render") load( @@ -42,6 +43,7 @@ load( "PY_LIBRARY_IMPL_LABEL", "PY_LIBRARY_PUBLIC_LABEL", "PY_SRCS_LABEL", + "TESTONLY_IMPL_PREFIX", "WHEEL_FILE", "WHEEL_FILE_IMPL_LABEL", "WHEEL_FILE_PUBLIC_LABEL", @@ -86,6 +88,7 @@ def pkg_aliases( extras = [], include = [], group_deps = [], + testonly = False, **kwargs): """Create aliases for an actual package. @@ -107,10 +110,14 @@ def pkg_aliases( dependencies when parsing the requires_dist. Comes from METADATA or a lock file. include: {type}`list[str]` The subset of packages to include. Comes from `//:config.bzl#packages` + testonly: {type}`bool` Whether the public targets should be testonly. + Bazel does not enforce `testonly` on aliases, so the main public + targets are testonly wrappers around the aliases. **kwargs: extra kwargs to pass to {bzl:obj}`get_config_settings`. """ _native = kwargs.pop("native", native) rules = kwargs.pop("rules", struct( + py_library = py_library, whl_library_deps_targets = whl_library_deps_targets, )) select = kwargs.pop("select", selects.with_or) @@ -118,6 +125,7 @@ def pkg_aliases( _native.alias( name = name, actual = ":" + PY_LIBRARY_PUBLIC_LABEL, + **({"testonly": True} if testonly else {}) ) if requires_dist: @@ -210,20 +218,80 @@ def pkg_aliases( elif target_name in (WHEEL_FILE, PY_SRCS_LABEL): kwargs["visibility"] = ["//visibility:private"] - _native.alias( + # The private targets are used by the non-testonly `//_groups` libraries. + _alias( + _native, + rules, name = target_name, actual = _actual, + testonly = testonly and not target_name.startswith("_"), **kwargs ) if group_name: - _native.alias( + _alias( + _native, + rules, name = PY_LIBRARY_PUBLIC_LABEL, actual = "//_groups:{}_pkg".format(group_name), + testonly = testonly, ) - _native.alias( + _alias( + _native, + rules, name = WHEEL_FILE_PUBLIC_LABEL, actual = "//_groups:{}_whl".format(group_name), + testonly = testonly, + ) + +# The public targets that are wrapped in testonly targets, because Bazel does +# not enforce `testonly` on aliases. +_TESTONLY_WRAPPED = [ + PY_LIBRARY_PUBLIC_LABEL, + WHEEL_FILE_PUBLIC_LABEL, + DATA_LABEL, + DIST_INFO_LABEL, + EXTRACTED_WHEEL_FILES, +] + +# The wrapped targets that the whl repositories depend on. +_TESTONLY_DEPS = [ + PY_LIBRARY_PUBLIC_LABEL, + WHEEL_FILE_PUBLIC_LABEL, +] + +def _alias(_native, rules, *, name, actual, testonly, **kwargs): + if not testonly: + _native.alias(name = name, actual = actual, **kwargs) + return + + if name not in _TESTONLY_WRAPPED: + # E.g. the extra aliases, which may point to executables. Best effort, + # because Bazel does not enforce `testonly` on aliases. + _native.alias(name = name, actual = actual, testonly = True, **kwargs) + return + + # The whl repositories are not `testonly`, so they depend on the wrapped + # targets of the `pkg` and `whl` instead. + impl = TESTONLY_IMPL_PREFIX + name + _native.alias( + name = impl, + actual = actual, + visibility = ["//visibility:public" if name in _TESTONLY_DEPS else "//visibility:private"], + ) + if name == PY_LIBRARY_PUBLIC_LABEL: + rules.py_library( + name = name, + deps = [":" + impl], + testonly = True, + **kwargs + ) + else: + _native.filegroup( + name = name, + srcs = [":" + impl], + testonly = True, + **kwargs ) def multiplatform_whl_aliases( diff --git a/python/private/pypi/render_pkg_aliases.bzl b/python/private/pypi/render_pkg_aliases.bzl index f03c33355e..edfdc59d39 100644 --- a/python/private/pypi/render_pkg_aliases.bzl +++ b/python/private/pypi/render_pkg_aliases.bzl @@ -94,6 +94,7 @@ def render_pkg_aliases( requirement_cycles = None, extra_hub_aliases = {}, exposed_packages = None, + testonly_packages = [], **kwargs): """Create alias declarations for each PyPI package. @@ -110,6 +111,7 @@ def render_pkg_aliases( exposed_packages: The packages that should be public. When set, the aliases of the other packages are only visible to the wheel repositories. + testonly_packages: The packages whose aliases should be testonly. **kwargs: Extra kwargs to pass to the rules. Returns: @@ -134,6 +136,11 @@ def render_pkg_aliases( for whl_name in group_whls } + testonly_packages = { + normalize_name(name): None + for name in testonly_packages + } + public = ["//visibility:public"] if exposed_packages != None: exposed_packages = { @@ -157,6 +164,7 @@ def render_pkg_aliases( extra_aliases = extra_hub_aliases.get(name, []), group_name = whl_group_mapping.get(name), visibility = visibility, + testonly = name in testonly_packages, **kwargs ).strip() diff --git a/python/private/pypi/requirements.bzl.tmpl.bzlmod b/python/private/pypi/requirements.bzl.tmpl.bzlmod index ba227aeb2d..7904ed5578 100644 --- a/python/private/pypi/requirements.bzl.tmpl.bzlmod +++ b/python/private/pypi/requirements.bzl.tmpl.bzlmod @@ -7,6 +7,8 @@ load("@rules_python//python:pip.bzl", "pip_utils") all_requirements = %%ALL_REQUIREMENTS%% +all_testonly_requirements = %%ALL_TESTONLY_REQUIREMENTS%% + all_whl_requirements_by_package = %%ALL_WHL_REQUIREMENTS_BY_PACKAGE%% all_whl_requirements = all_whl_requirements_by_package.values() diff --git a/python/private/pypi/unified_hub_repo.bzl b/python/private/pypi/unified_hub_repo.bzl index ddd15c0d86..1bd69773c7 100644 --- a/python/private/pypi/unified_hub_repo.bzl +++ b/python/private/pypi/unified_hub_repo.bzl @@ -25,6 +25,7 @@ define_pypi_package_targets( extra_aliases = {extra_aliases}, hubs = {hubs}, pkg_hubs = {pkg_hubs}, + testonly = {testonly}, ) """ @@ -79,6 +80,10 @@ def _unified_hub_repo_impl(rctx): extra_aliases_by_pkg.setdefault(pkg, {})[alias] = alias_hubs # 3. Generate package subpackages + testonly_packages = { + pkg_name: None + for pkg_name in rctx.attr.testonly_packages + } for pkg_name, pkg_hubs in rctx.attr.packages.items(): extra_aliases = extra_aliases_by_pkg.get(pkg_name, {}) rctx.file( @@ -89,6 +94,7 @@ def _unified_hub_repo_impl(rctx): hubs = hubs, pkg_hubs = pkg_hubs, pkg_name = pkg_name, + testonly = pkg_name in testonly_packages, ), ) @@ -130,6 +136,10 @@ unified_hub_repo = repository_rule( default = False, doc = "Whether to generate a requirements.bzl with the per-package `requirement` macros.", ), + "testonly_packages": attr.string_list( + default = [], + doc = "Packages that are testonly in all of the hubs that have them.", + ), }, doc = "Private repository rule creating the automatic Unified PyPI Hub.", ) diff --git a/python/private/pypi/unified_hub_setup.bzl b/python/private/pypi/unified_hub_setup.bzl index b19410fd4b..3ee8ae25d3 100644 --- a/python/private/pypi/unified_hub_setup.bzl +++ b/python/private/pypi/unified_hub_setup.bzl @@ -31,7 +31,7 @@ _STANDARD_ALIASES = [ EXTRACTED_WHEEL_FILES, ] -def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub = None): +def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub = None, testonly = False): """Define the targets for a PyPI package in the unified PyPI hub. Args: @@ -40,6 +40,7 @@ def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub extra_aliases: dict mapping extra alias names to lists of hubs that support them. hubs: list of all concrete hub names. default_hub: the hub to use by default. + testonly: whether all targets should be marked as testonly. """ pkg_name = name @@ -47,6 +48,7 @@ def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub native.alias( name = pkg_name, actual = ":pkg", + testonly = testonly, ) all_aliases = _STANDARD_ALIASES + sorted(extra_aliases.keys()) @@ -100,6 +102,7 @@ def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub native.alias( name = alias_name, actual = select(select_map), + testonly = testonly, ) # Generate missing package error targets diff --git a/python/private/pypi/whl_config_repo.bzl b/python/private/pypi/whl_config_repo.bzl index b7cea5a8b7..df15ce044d 100644 --- a/python/private/pypi/whl_config_repo.bzl +++ b/python/private/pypi/whl_config_repo.bzl @@ -15,6 +15,8 @@ def _whl_config_repo_impl(rctx): rctx.attr._config_template, substitutions = { "%%PACKAGES%%": render.dict(rctx.attr.whl_map or {}, value_repr = lambda x: "None"), + # There are no testonly packages in WORKSPACE. + "%%TESTONLY_PACKAGES%%": "[]", }, ) diff --git a/python/private/pypi/whl_library_deps_targets.bzl b/python/private/pypi/whl_library_deps_targets.bzl index e549f52a47..6d883e8455 100644 --- a/python/private/pypi/whl_library_deps_targets.bzl +++ b/python/private/pypi/whl_library_deps_targets.bzl @@ -11,6 +11,7 @@ load( "PY_LIBRARY_IMPL_LABEL", "PY_LIBRARY_PUBLIC_LABEL", "PY_SRCS_LABEL", + "TESTONLY_IMPL_PREFIX", "WHEEL_FILE", "WHEEL_FILE_IMPL_LABEL", "WHEEL_FILE_PUBLIC_LABEL", @@ -26,6 +27,7 @@ def whl_library_deps_targets( requires_dist = [], extras = [], include = [], + testonly_deps = [], group_deps = [], group_name = None, dep_template, @@ -53,6 +55,9 @@ def whl_library_deps_targets( depending on the wheel `METADATA`. Optional because some packages don't request them. include: {type}`list[str]` The list of packages to include. + testonly_deps: {type}`list[str]` The packages that are `testonly` in + the hub. The targets created here are not `testonly`, so they + depend on the targets that the `testonly` targets of the hub wrap. group_name: {type}`str | None` name of the dependency group (if any). dep_template: {type}`str | None` The dep_template to use. tags: {type}`list[str]` The tags set on the targets. @@ -157,7 +162,9 @@ def whl_library_deps_targets( data = _deps( deps = [], package_deps = package_deps, - tmpl = dep_template.format(name = "{}", target = WHEEL_FILE_PUBLIC_LABEL), + dep_template = dep_template, + target = WHEEL_FILE_PUBLIC_LABEL, + testonly_deps = testonly_deps, ), visibility = impl_vis, ) @@ -173,7 +180,9 @@ def whl_library_deps_targets( # `pyi_srcs`, see `tests/base_rules/py_library`. deps = [repo_label(PY_SRCS_LABEL)], package_deps = package_deps, - tmpl = dep_template.format(name = "{}", target = PY_LIBRARY_PUBLIC_LABEL), + dep_template = dep_template, + target = PY_LIBRARY_PUBLIC_LABEL, + testonly_deps = testonly_deps, ), # Disable precompilation on this wrapper target to prevent duplicate # pyc generation; the underlying PY_SRCS_LABEL target handles it. @@ -213,12 +222,20 @@ def _config_settings(dependencies_with_markers, rules, **kwargs): **kwargs ) -def _deps(deps, package_deps, tmpl): - deps = [] + deps + [tmpl.format(d) for d in sorted(package_deps.deps)] +def _deps(deps, package_deps, *, dep_template, target, testonly_deps): + testonly_deps = {d: None for d in testonly_deps} + + def label(dep): + return dep_template.format( + name = dep, + target = TESTONLY_IMPL_PREFIX + target if dep in testonly_deps else target, + ) + + deps = [] + deps + [label(d) for d in sorted(package_deps.deps)] for dep in package_deps.deps_select: deps = deps + select({ - ":is_include_{}_true".format(dep): [tmpl.format(dep)], + ":is_include_{}_true".format(dep): [label(dep)], "//conditions:default": [], }) diff --git a/python/private/pypi/whl_library_targets.bzl b/python/private/pypi/whl_library_targets.bzl index a1cc727460..49d0265e0f 100644 --- a/python/private/pypi/whl_library_targets.bzl +++ b/python/private/pypi/whl_library_targets.bzl @@ -29,6 +29,7 @@ def whl_library_targets( extras = [], entry_points = {}, include = [], + testonly_deps = [], group_deps = [], group_name = None, dep_template = None, @@ -58,6 +59,8 @@ def whl_library_targets( extras: {type}`list[str]` The list of requested extras. This essentially includes extra transitive dependencies in the final targets depending on the wheel `METADATA`. entry_points: {type}`list[dict]` A list of parsed entry point definitions. include: {type}`list[str]` The list of packages to include. + testonly_deps: {type}`list[str]` The packages that are `testonly` in + the hub. group_name: {type}`str | None` name of the dependency group (if any). dep_template: {type}`str | None` The dep_template to use. data_exclude: {type}`list[str]` The globs for data attribute exclusion. @@ -99,6 +102,7 @@ def whl_library_targets( group_name = group_name, # must specify group_deps together extras = extras, # only needed if requires_dist is present include = include, # only needed if requires_dist is present + testonly_deps = testonly_deps, # only needed if requires_dist is present repo = None, # set aliases in the same repo aliases = {}, **kwargs diff --git a/tests/integration/unified_pypi/BUILD.bazel b/tests/integration/unified_pypi/BUILD.bazel index 78f9a857ee..7974a42947 100644 --- a/tests/integration/unified_pypi/BUILD.bazel +++ b/tests/integration/unified_pypi/BUILD.bazel @@ -1,4 +1,5 @@ load("@pypi//:requirements.bzl", "requirement") +load("@pypi_testonly//:requirements.bzl", "all_requirements", "all_testonly_requirements") load("@rules_python//python:py_binary.bzl", "py_binary") load("@rules_python//python:py_test.bzl", "py_test") @@ -123,3 +124,52 @@ py_binary( tags = ["manual"], deps = ["@pypi_filtered//six"], ) + +# The pypi_testonly hub only exposes testonly packages. +py_test( + name = "test_testonly", + srcs = ["test_iniconfig.py"], + main = "test_iniconfig.py", + deps = ["@pypi_testonly//iniconfig"], +) + +# A testonly package can depend on another testonly package. +py_test( + name = "test_testonly_dep", + srcs = ["test_dateutil.py"], + main = "test_dateutil.py", + deps = ["@pypi_testonly//python_dateutil"], +) + +py_test( + name = "test_testonly_unified", + srcs = ["test_iniconfig.py"], + config_settings = { + "@rules_python//python/config_settings:venv": "pypi_testonly", + }, + main = "test_iniconfig.py", + deps = ["@pypi//iniconfig"], +) + +py_test( + name = "test_all_testonly_requirements", + srcs = ["test_iniconfig.py"], + main = "test_iniconfig.py", + deps = all_testonly_requirements, +) + +# The testonly packages are not in `all_requirements`. +py_binary( + name = "bin_all_requirements", + srcs = ["test_default.py"], + main = "test_default.py", + deps = ["@pypi//colorama"] + all_requirements, +) + +py_binary( + name = "bin_testonly", + srcs = ["test_iniconfig.py"], + main = "test_iniconfig.py", + tags = ["manual"], + deps = ["@pypi_testonly//iniconfig"], +) diff --git a/tests/integration/unified_pypi/MODULE.bazel b/tests/integration/unified_pypi/MODULE.bazel index 70e01ccdac..74bd8ffbfe 100644 --- a/tests/integration/unified_pypi/MODULE.bazel +++ b/tests/integration/unified_pypi/MODULE.bazel @@ -67,6 +67,20 @@ pip.configure( ) use_repo(pip, "pypi_filtered") +# `pypi_testonly` only exposes testonly packages. +pip.parse( + hub_name = "pypi_testonly", + pyproject_toml = "//:pyproject_testonly.toml", + python_version = "3.11", + requirements_lock = "//:requirements_testonly.txt", +) +pip.configure( + testonly = True, + dependency_groups = ["test"], + hub_name = "pypi_testonly", +) +use_repo(pip, "pypi_testonly") + pip.default(default_hub = "pypi_b") pip.default(unified_hub_requirements_bzl = True) pip.dep( diff --git a/tests/integration/unified_pypi/pyproject_testonly.toml b/tests/integration/unified_pypi/pyproject_testonly.toml new file mode 100644 index 0000000000..080ddd7de6 --- /dev/null +++ b/tests/integration/unified_pypi/pyproject_testonly.toml @@ -0,0 +1,6 @@ +[project] +name = "unified-pypi" +version = "0.0.0" + +[dependency-groups] +test = ["iniconfig", "python-dateutil", "six"] diff --git a/tests/integration/unified_pypi/requirements_testonly.txt b/tests/integration/unified_pypi/requirements_testonly.txt new file mode 100644 index 0000000000..92807aa513 --- /dev/null +++ b/tests/integration/unified_pypi/requirements_testonly.txt @@ -0,0 +1,9 @@ +iniconfig==2.1.0 \ + --hash=sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7 \ + --hash=sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760 +python-dateutil==2.9.0.post0 \ + --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ + --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 diff --git a/tests/integration/unified_pypi/test_dateutil.py b/tests/integration/unified_pypi/test_dateutil.py new file mode 100644 index 0000000000..4b444e951e --- /dev/null +++ b/tests/integration/unified_pypi/test_dateutil.py @@ -0,0 +1,5 @@ +import dateutil +import six + +assert dateutil.__version__ +assert six.__version__ diff --git a/tests/integration/unified_pypi/test_iniconfig.py b/tests/integration/unified_pypi/test_iniconfig.py new file mode 100644 index 0000000000..45bc1a5008 --- /dev/null +++ b/tests/integration/unified_pypi/test_iniconfig.py @@ -0,0 +1,3 @@ +import iniconfig + +assert iniconfig.IniConfig diff --git a/tests/integration/unified_pypi_test.py b/tests/integration/unified_pypi_test.py index f59a19fb42..90a53a8e80 100644 --- a/tests/integration/unified_pypi_test.py +++ b/tests/integration/unified_pypi_test.py @@ -33,6 +33,26 @@ def test_configure_hides_unexposed_packages_in_unified_hub(self): 'ERROR: PyPI package "six" is not available when building under PyPI hub "pypi_filtered"\\. Try adding it to the requirements of this hub', ) + def test_configure_testonly(self): + self.run_bazel( + "test", + "//:test_testonly", + "//:test_testonly_dep", + "//:test_testonly_unified", + "//:test_all_testonly_requirements", + ) + self.run_bazel("build", "//:bin_all_requirements") + result = self.run_bazel("build", "//:bin_testonly", check=False) + self.assertNotEqual( + result.exit_code, + 0, + "Expected the testonly package to be rejected in a binary", + ) + self.assert_result_matches( + result, + r"non-test target '//:bin_testonly' depends on testonly", + ) + def test_default_fallback_hub(self): self.run_bazel("test", "//:test_default") diff --git a/tests/pypi/extension/extension_tests.bzl b/tests/pypi/extension/extension_tests.bzl index f1974cf88c..a316371e1e 100644 --- a/tests/pypi/extension/extension_tests.bzl +++ b/tests/pypi/extension/extension_tests.bzl @@ -161,6 +161,8 @@ def _parse_modules(env, **kwargs): exposed_packages = subjects.dict, hub_group_map = subjects.dict, hub_whl_map = subjects.dict, + testonly_packages = subjects.dict, + unified_testonly_packages = subjects.collection, unified_hub_requirements_bzl = subjects.bool, whl_libraries = subjects.dict, whl_mods = subjects.dict, @@ -869,9 +871,9 @@ def _configure_parse_modules(env, *modules): minor_mapping = {"3.15": "3.15.19"}, ) -def _configure_parse(**kwargs): +def _configure_parse(hub_name = "pypi_a", **kwargs): return _parse( - hub_name = "pypi_a", + hub_name = hub_name, python_version = "3.15", simpleapi_skip = ["simple", "other-pkg", "transitive-pkg"], requirements_lock = "requirements.txt", @@ -892,7 +894,10 @@ def _test_configure(env): ) pypi.exposed_packages().contains_exactly({"pypi_a": ["simple"]}) - pypi.configured_hubs().contains_exactly({"pypi_a": ["simple"]}) + pypi.configured_hubs().contains_exactly({"pypi_a": struct( + packages = ["simple"], + testonly_packages = [], + )}) _tests.append(_test_configure) @@ -929,10 +934,112 @@ def _test_configure_platform_specific(env): ) pypi.exposed_packages().contains_exactly({"pypi_a": ["simple"]}) - pypi.configured_hubs().contains_exactly({"pypi_a": ["other_pkg", "simple"]}) + pypi.configured_hubs().contains_exactly({"pypi_a": struct( + packages = ["other_pkg", "simple"], + testonly_packages = [], + )}) _tests.append(_test_configure_platform_specific) +def _test_configure_testonly(env): + pypi = _configure_parse_modules( + env, + _mod( + name = "rules_python", + parse = [_configure_parse(pyproject_toml = "pyproject.toml")], + configure = [ + _configure(hub_name = "pypi_a", dependency_groups = ["default"]), + _configure(hub_name = "pypi_a", dependency_groups = ["dev", "test"], testonly = True), + ], + ), + ) + + pypi.exposed_packages().contains_exactly({"pypi_a": ["other_pkg", "simple"]}) + + # `simple` is also selected by the non-testonly tag. + pypi.configured_hubs().contains_exactly({"pypi_a": struct( + packages = ["other_pkg", "simple"], + testonly_packages = ["other_pkg"], + )}) + +_tests.append(_test_configure_testonly) + +def _test_configure_testonly_unified(env): + pypi = _configure_parse_modules( + env, + _mod( + name = "rules_python", + parse = [ + _configure_parse(hub_name = "pypi_a", pyproject_toml = "pyproject.toml"), + _configure_parse(hub_name = "pypi_b", pyproject_toml = "pyproject.toml"), + ], + configure = [ + _configure(hub_name = "pypi_a", dependency_groups = ["default"], testonly = True), + _configure(hub_name = "pypi_b", dependency_groups = ["default"]), + ], + ), + ) + + pypi.testonly_packages().contains_exactly({"pypi_a": ["simple"], "pypi_b": []}) + + # The testonly is enforced by the hub that the unified hub alias points + # to, so a package is only marked as testonly in the unified hub if it is + # testonly in all of the hubs that have it. + pypi.unified_testonly_packages().contains_exactly([]) + +_tests.append(_test_configure_testonly_unified) + +def _test_configure_testonly_unified_all_hubs(env): + pypi = _configure_parse_modules( + env, + _mod( + name = "rules_python", + parse = [ + _configure_parse(hub_name = "pypi_a", pyproject_toml = "pyproject.toml"), + _configure_parse(hub_name = "pypi_b", pyproject_toml = "pyproject.toml"), + # This hub is not configured, so all of its packages are + # public and not testonly. + _configure_parse(hub_name = "pypi_c", pyproject_toml = "pyproject.toml"), + ], + configure = [ + _configure(hub_name = "pypi_a", dependency_groups = ["default"], testonly = True), + # `other_pkg` is only public in this hub. + _configure(hub_name = "pypi_b", dependency_groups = ["default", "dev"], testonly = True), + ], + ), + ) + + pypi.testonly_packages().contains_exactly({ + "pypi_a": ["simple"], + "pypi_b": ["other_pkg", "simple"], + }) + + # `simple` is not testonly in `pypi_c` and so is `other_pkg`. + pypi.unified_testonly_packages().contains_exactly([]) + +_tests.append(_test_configure_testonly_unified_all_hubs) + +def _test_configure_testonly_unified_agreeing_hubs(env): + pypi = _configure_parse_modules( + env, + _mod( + name = "rules_python", + parse = [ + _configure_parse(hub_name = "pypi_a", pyproject_toml = "pyproject.toml"), + _configure_parse(hub_name = "pypi_b", pyproject_toml = "pyproject.toml"), + ], + configure = [ + _configure(hub_name = "pypi_a", dependency_groups = ["default"], testonly = True), + _configure(hub_name = "pypi_b", dependency_groups = ["default", "dev"], testonly = True), + ], + ), + ) + + # `other_pkg` is only public in `pypi_b`, where it is testonly. + pypi.unified_testonly_packages().contains_exactly(["other_pkg", "simple"]) + +_tests.append(_test_configure_testonly_unified_agreeing_hubs) + def _test_configure_default_pyproject(env): # The `pip.default` pyproject.toml is used for the hubs of the root module. pypi = _configure_parse_modules( @@ -949,7 +1056,10 @@ def _test_configure_default_pyproject(env): ), ) - pypi.configured_hubs().contains_exactly({"pypi_a": ["other_pkg"]}) + pypi.configured_hubs().contains_exactly({"pypi_a": struct( + packages = ["other_pkg"], + testonly_packages = [], + )}) _tests.append(_test_configure_default_pyproject) diff --git a/tests/pypi/extension/pip_parse.bzl b/tests/pypi/extension/pip_parse.bzl index d048f99bd0..8214333497 100644 --- a/tests/pypi/extension/pip_parse.bzl +++ b/tests/pypi/extension/pip_parse.bzl @@ -4,12 +4,14 @@ def configure( *, dependency_groups = [], hub_name, - pyproject_toml = None): + pyproject_toml = None, + testonly = False): """Simulate the PyPI extension configure tag class for testing.""" return struct( dependency_groups = dependency_groups, hub_name = hub_name, pyproject_toml = pyproject_toml, + testonly = testonly, ) def pip_parse( diff --git a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl index d3a390d9bb..4e2c4b3421 100644 --- a/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl +++ b/tests/pypi/generate_whl_library_build_bazel/generate_whl_library_build_bazel_tests.bzl @@ -22,7 +22,7 @@ _tests = [] def _test_all_workspace(env): want = """\ load("@package_metadata//rules:package_metadata.bzl", "package_metadata") -load("@pypi//:config.bzl", "packages") +load("@pypi//:config.bzl", "packages", "testonly_packages") load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") package(default_visibility = ["//visibility:public"]) @@ -59,6 +59,7 @@ whl_library_targets( "pypi_name=foo", "pypi_version=0", ], + testonly_deps = testonly_packages, ) package_metadata( @@ -96,7 +97,7 @@ _tests.append(_test_all_workspace) def _test_all(env): want = """\ load("@package_metadata//rules:package_metadata.bzl", "package_metadata") -load("@pypi//:config.bzl", "packages") +load("@pypi//:config.bzl", "packages", "testonly_packages") load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") package(default_visibility = ["//visibility:public"]) @@ -133,6 +134,7 @@ whl_library_targets( "pypi_name=foo", "pypi_version=0", ], + testonly_deps = testonly_packages, ) package_metadata( @@ -170,7 +172,7 @@ _tests.append(_test_all) def _test_all_with_loads(env): want = """\ load("@package_metadata//rules:package_metadata.bzl", "package_metadata") -load("@pypi//:config.bzl", "packages") +load("@pypi//:config.bzl", "packages", "testonly_packages") load("@rules_python//python/private/pypi:whl_library_targets.bzl", "whl_library_targets") package(default_visibility = ["//visibility:public"]) @@ -207,6 +209,7 @@ whl_library_targets( "pypi_name=foo", "pypi_version=0", ], + testonly_deps = testonly_packages, ) package_metadata( diff --git a/tests/pypi/hub_exposure/hub_exposure_tests.bzl b/tests/pypi/hub_exposure/hub_exposure_tests.bzl index 1f2b13622c..24f6e58482 100644 --- a/tests/pypi/hub_exposure/hub_exposure_tests.bzl +++ b/tests/pypi/hub_exposure/hub_exposure_tests.bzl @@ -28,11 +28,13 @@ def _hub(*, module_name = "root", pyproject = None): def _configure( hub_name = "hub", dependency_groups = [], - pyproject_toml = None): + pyproject_toml = None, + testonly = False): return mocks.tag( hub_name = hub_name, dependency_groups = dependency_groups, pyproject_toml = pyproject_toml, + testonly = testonly, ) def _module(name = "root", is_root = True, configure = []): @@ -54,6 +56,9 @@ def _exposure(*modules, hubs = None, default_pyproject = None): ) return got, failures +def _packages(got): + return {hub: info.packages for hub, info in got.items()} + def _test_not_configured(env): got, failures = _exposure(_module()) env.expect.that_collection(failures).contains_exactly([]) @@ -75,9 +80,9 @@ def _test_configure(env): env.expect.where(groups = groups).that_collection( failures, ).contains_exactly([]) - env.expect.where(groups = groups).that_dict(got).contains_exactly( - {"hub": want}, - ) + env.expect.where(groups = groups).that_dict( + _packages(got), + ).contains_exactly({"hub": want}) _tests.append(_test_configure) @@ -99,7 +104,7 @@ def _test_configure_combines_tags(env): _configure(dependency_groups = ["dev"]), ])) env.expect.that_collection(failures).contains_exactly([]) - env.expect.that_dict(got).contains_exactly( + env.expect.that_dict(_packages(got)).contains_exactly( {"hub": ["other_pkg", "simple"]}, ) @@ -110,7 +115,7 @@ def _test_configure_pyproject_precedence(env): got, _ = _exposure(_module(configure = [ _configure(pyproject_toml = "other.toml", dependency_groups = ["*"]), ])) - env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["other_pkg"]}) # The `pip.default` value is used for the hubs of the root module. got, failures = _exposure( @@ -119,7 +124,7 @@ def _test_configure_pyproject_precedence(env): default_pyproject = "pyproject.toml", ) env.expect.that_collection(failures).contains_exactly([]) - env.expect.that_dict(got).contains_exactly({"hub": ["simple"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["simple"]}) _tests.append(_test_configure_pyproject_precedence) @@ -145,7 +150,7 @@ def _test_configure_builder(env): hubs = {"hub": _hub(pyproject = "pyproject.toml")}, ) env.expect.that_collection(failures).contains_exactly([]) - env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["other_pkg"]}) # The tags before it use the `pip.parse` value. got, failures = _exposure( @@ -156,7 +161,7 @@ def _test_configure_builder(env): hubs = {"hub": _hub(pyproject = "pyproject.toml")}, ) env.expect.that_collection(failures).contains_exactly([]) - env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg", "simple"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["other_pkg", "simple"]}) # It is not used by the other modules. hubs = {"hub": _hub(module_name = "dep")} @@ -189,7 +194,7 @@ def _test_configure_module_precedence(env): ), hubs = hubs, ) - env.expect.that_dict(got).contains_exactly({"hub": ["other_pkg"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["other_pkg"]}) # The root module wins over the owner. got, _ = _exposure( @@ -201,7 +206,7 @@ def _test_configure_module_precedence(env): ), hubs = hubs, ) - env.expect.that_dict(got).contains_exactly({"hub": ["simple"]}) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["simple"]}) # Other modules are ignored. got, _ = _exposure( @@ -245,6 +250,40 @@ def _test_configure_errors(env): _tests.append(_test_configure_errors) +def _test_configure_testonly(env): + got, failures = _exposure(_module(configure = [ + _configure(dependency_groups = ["default"]), + _configure(dependency_groups = ["dev", "test"], testonly = True), + ])) + env.expect.that_collection(failures).contains_exactly([]) + env.expect.that_dict(_packages(got)).contains_exactly({"hub": ["other_pkg", "simple"]}) + + # `simple` is also selected by the non-testonly tag. + env.expect.that_collection(got["hub"].testonly_packages).contains_exactly(["other_pkg"]) + + got, _ = _exposure(_module(configure = [ + _configure(dependency_groups = ["*"], testonly = True), + ])) + env.expect.that_collection(got["hub"].testonly_packages).contains_exactly(["other_pkg", "simple"]) + + # The hub that exposes all of the packages behaves as if it was not + # configured, so the packages can't be made testonly. + got, failures = _exposure(_module(configure = [ + _configure(dependency_groups = ["*", "transitive"], testonly = True), + ])) + env.expect.that_collection(failures).contains_exactly([ + "pip.configure() for hub 'hub' cannot use `testonly` when exposing all of the packages with [\"*\", \"transitive\"]", + ]) + + # The testonly packages need to be selected. + got, failures = _exposure(_module(configure = [_configure(testonly = True)])) + env.expect.that_str(got).equals(None) + env.expect.that_collection(failures).contains_exactly([ + "pip.configure() for hub 'hub' uses `testonly`, which needs the `dependency_groups` of the testonly packages", + ]) + +_tests.append(_test_configure_testonly) + def hub_exposure_test_suite(name): """Create the test suite. diff --git a/tests/pypi/pkg_aliases/pkg_aliases_test.bzl b/tests/pypi/pkg_aliases/pkg_aliases_test.bzl index 2d54bd34db..fdec8877fc 100644 --- a/tests/pypi/pkg_aliases/pkg_aliases_test.bzl +++ b/tests/pypi/pkg_aliases/pkg_aliases_test.bzl @@ -55,6 +55,76 @@ def _test_legacy_aliases(env): _tests.append(_test_legacy_aliases) +def _testonly_mocks(): + got = {} + + def _add(kind): + return lambda name, **kwargs: got.setdefault(name, (kind, kwargs.get("testonly", False))) + + return got, struct( + native = struct( + alias = _add("alias"), + filegroup = _add("filegroup"), + ), + rules = struct( + py_library = _add("py_library"), + ), + ) + +def _test_testonly_aliases(env): + got, mocks = _testonly_mocks() + pkg_aliases( + name = "foo", + actual = "repo", + testonly = True, + native = mocks.native, + rules = mocks.rules, + ) + + # Bazel does not enforce `testonly` on aliases, so the public targets are + # wrapped. + env.expect.that_dict(got).contains_exactly({ + "data": ("filegroup", True), + "dist_info": ("filegroup", True), + "extracted_whl_files": ("filegroup", True), + "foo": ("alias", True), + "pkg": ("py_library", True), + "srcs": ("alias", True), + "whl": ("filegroup", True), + "whl_file": ("alias", True), + "_testonly_data": ("alias", False), + "_testonly_dist_info": ("alias", False), + "_testonly_extracted_whl_files": ("alias", False), + "_testonly_pkg": ("alias", False), + "_testonly_whl": ("alias", False), + }) + +_tests.append(_test_testonly_aliases) + +def _test_testonly_group_aliases(env): + got, mocks = _testonly_mocks() + pkg_aliases( + name = "foo", + actual = "repo", + group_name = "my_group", + testonly = True, + native = mocks.native, + rules = mocks.rules, + ) + + # The private targets are used by the non-testonly group libraries. + env.expect.that_dict(got).contains_at_least({ + "foo": ("alias", True), + "pkg": ("py_library", True), + "whl": ("filegroup", True), + "_pkg": ("alias", False), + "_testonly_pkg": ("alias", False), + "_testonly_whl": ("alias", False), + "_whl": ("alias", False), + }) + +_tests.append(_test_testonly_group_aliases) + def _test_config_setting_aliases(env): # Use this function as it is used in pip_repository got = {} diff --git a/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl index 13bee38ff5..38699f130b 100644 --- a/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl +++ b/tests/pypi/render_pkg_aliases/render_pkg_aliases_test.bzl @@ -58,6 +58,37 @@ pkg_aliases( _tests.append(_test_legacy_aliases) +def _test_testonly_aliases(env): + actual = render_pkg_aliases( + aliases = { + "bar": "pypi_bar", + "foo": "pypi_foo", + }, + testonly_packages = ["Foo"], + ) + + env.expect.that_str(actual["foo/BUILD.bazel"]).equals("""\ +load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases") + +package(default_visibility = ["//visibility:public"]) + +pkg_aliases( + name = "foo", + actual = "pypi_foo", + testonly = True, +)""") + env.expect.that_str(actual["bar/BUILD.bazel"]).equals("""\ +load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases") + +package(default_visibility = ["//visibility:public"]) + +pkg_aliases( + name = "bar", + actual = "pypi_bar", +)""") + +_tests.append(_test_testonly_aliases) + def _test_hidden_aliases(env): actual = render_pkg_aliases( aliases = { diff --git a/tests/pypi/whl_library/testdata/packages.bzl b/tests/pypi/whl_library/testdata/packages.bzl index e4a9b0af4c..3c0683c461 100644 --- a/tests/pypi/whl_library/testdata/packages.bzl +++ b/tests/pypi/whl_library/testdata/packages.bzl @@ -4,3 +4,5 @@ packages = [ "optional_dep", "pkg", ] + +testonly_packages = [] diff --git a/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl b/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl index e8659ff642..2bfa74afda 100644 --- a/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl +++ b/tests/pypi/whl_library_deps_targets/whl_library_deps_targets_tests.bzl @@ -91,6 +91,52 @@ def _test_whl_library_deps_targets(env): _tests.append(_test_whl_library_deps_targets) +def _test_whl_library_deps_targets_testonly_deps(env): + filegroup_calls = [] + py_library_calls = [] + + whl_library_deps_targets( + name = "foo-0-py3-none-any.whl", + metadata_name = "Foo", + dep_template = "@pypi//{name}:{target}", + requires_dist = [ + "bar", + "bar-baz; python_version < \"8.2\"", + "qux", + ], + include = ["foo", "bar", "bar_baz", "qux"], + testonly_deps = ["bar", "bar_baz"], + # Overrides for testing + repo = None, + aliases = None, + extras = [], + native = struct( + filegroup = lambda **kwargs: filegroup_calls.append(kwargs), + alias = lambda **kwargs: None, + ), + rules = struct( + py_library = lambda **kwargs: py_library_calls.append(kwargs), + env_marker_setting = lambda **kwargs: None, + ), + ) + + # The targets are not testonly, so they can't depend on the testonly + # targets of the hub. + env.expect.that_collection([c["data"] for c in filegroup_calls]).contains_exactly([ + ["@pypi//bar:_testonly_whl", "@pypi//qux:whl"] + select({ + ":is_include_bar_baz_true": ["@pypi//bar_baz:_testonly_whl"], + "//conditions:default": [], + }), + ]) + env.expect.that_collection([c["deps"] for c in py_library_calls]).contains_exactly([ + ["srcs", "@pypi//bar:_testonly_pkg", "@pypi//qux:pkg"] + select({ + ":is_include_bar_baz_true": ["@pypi//bar_baz:_testonly_pkg"], + "//conditions:default": [], + }), + ]) + +_tests.append(_test_whl_library_deps_targets_testonly_deps) + def _test_whl_library_deps_targets_no_deps(env): alias_calls = [] filegroup_calls = []