diff --git a/docs/pypi/download.md b/docs/pypi/download.md index ad8b40e70d..6b29515e15 100644 --- a/docs/pypi/download.md +++ b/docs/pypi/download.md @@ -243,6 +243,59 @@ 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. + +#### Venvs + +Set {attr}`pip.configure.venv` to create a venv, a named selection of the +packages of a hub, instead of changing the hub: + +```starlark +pip.configure( + hub_name = "pypi_hub", + venv = "pypi_hub_docs", + dependency_groups = ["default", "group:docs"], +) +``` + +The venv is used through the [Unified @pypi Hub](unified-pypi-hub) by setting +`--@rules_python//python/config_settings:venv=pypi_hub_docs`. It resolves the +`@pypi//` labels to the packages of `pypi_hub`, so nothing is downloaded +twice, and the packages that are not selected are reported as missing. A venv +does not create a new repository and does not change the hub. + +A venv name must not collide with a hub and a venv can't be used with two +different hubs. The packages of a venv are testonly if they are testonly in +the hub. The venvs can't be used when a hub is named `pypi`, because such a hub +replaces the unified hub. + :::{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/news/4429.added.md b/news/4429.added.md new file mode 100644 index 0000000000..c2b0d5d902 --- /dev/null +++ b/news/4429.added.md @@ -0,0 +1,4 @@ +(pypi) Added {attr}`pip.configure.venv` to create a named selection of the +packages of a hub that can be used through the unified `@pypi` hub with the +{flag}`--venv` flag +([#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..11b4557f27 100644 --- a/python/private/pypi/extension.bzl +++ b/python/private/pypi/extension.bzl @@ -378,29 +378,51 @@ You cannot use both the additive_build_content and additive_build_content_file a packages = out.whl_map.keys(), ) - configured_hubs = hub_exposure( + configured = hub_exposure( module_ctx, hubs = hubs, default_pyproject = config.pyproject_toml, _fail = _fail, ) - if configured_hubs == None: + if configured == None: return None # 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} + configured_hubs = {} + venvs = {} + testonly_packages = {} + unified_testonly_packages = {} + for hub_name, info in configured.items(): + if hub_name != info.hub: + venvs[hub_name] = info + continue + + configured_hubs[hub_name] = info + 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, + venvs = venvs, config = config, declared_deps = declared_deps, default_hub = config.default_hub or renamed_default_hub, @@ -409,7 +431,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 = { @@ -432,12 +460,17 @@ def _create_unified_hub_repo(mods): packages = {} extra_aliases = {} - for hub_name in hubs: + # The venvs are named selections of the packages of a hub, which can be + # selected with the same `venv` flag as the hubs. + venvs = {name: info.hub for name, info in mods.venvs.items()} + for hub_name in hubs + sorted(venvs): # The hubs configured with `pip.configure` only expose some packages. - hub_packages = mods.configured_hubs.get( - hub_name, - mods.hub_whl_map[hub_name], - ) + if hub_name in venvs: + hub_packages = mods.venvs[hub_name].packages + elif hub_name in mods.configured_hubs: + hub_packages = mods.configured_hubs[hub_name].packages + else: + hub_packages = mods.hub_whl_map[hub_name] for pkg_name in hub_packages: norm_pkg = normalize_name(pkg_name) if norm_pkg not in packages: @@ -445,7 +478,7 @@ def _create_unified_hub_repo(mods): if hub_name not in packages[norm_pkg]: packages[norm_pkg].append(hub_name) - extra = mods.extra_aliases.get(hub_name, {}).get(norm_pkg, []) + extra = mods.extra_aliases.get(venvs.get(hub_name, hub_name), {}).get(norm_pkg, []) for alias_name in extra: qual_alias = "%s:%s" % (norm_pkg, alias_name) if qual_alias not in extra_aliases: @@ -469,6 +502,8 @@ def _create_unified_hub_repo(mods): hubs = hubs, packages = packages, requirements_bzl = mods.unified_hub_requirements_bzl, + venvs = venvs, + testonly_packages = mods.unified_testonly_packages, ) def _pip_impl(module_ctx): @@ -548,7 +583,12 @@ def _pip_impl(module_ctx): for name, args in mods.whl_libraries.items(): whl_library(name = name, **args) + # The venvs may select the packages that their hub does not expose. + venv_hubs = {info.hub: None for info in mods.venvs.values()} for hub_name, whl_map in mods.hub_whl_map.items(): + extra_internal_visibility = [] + if hub_name in venv_hubs: + extra_internal_visibility = ["@pypi//:__subpackages__"] hub_repository( name = hub_name, repo_name = hub_name, @@ -562,7 +602,11 @@ 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, []), + extra_internal_visibility = extra_internal_visibility, + 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 +1222,46 @@ 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 +::: +""", + ), + "venv": attr.string( + mandatory = False, + doc = """\ +Create a venv instead of configuring the hub. Defaults to {attr}`hub_name`. + +A venv is a named selection of the packages of the hub that is used through +the [Unified @pypi Hub](unified-pypi-hub) by setting +{flag}`--@rules_python//python/config_settings:venv` to its name. It does not +create a new repository and the hub itself is not changed. The packages that +are not selected are reported as missing, like the packages that are not in a +hub. + +The name must not collide with a hub and a venv can't be used with two +different hubs. Multiple tags with the same `venv` are combined and each of +them needs the {attr}`dependency_groups` of its packages. `testonly` is not +supported for venvs. The venvs can't be used when a hub is named `pypi`, +because such a hub replaces the unified 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..44b8ae86a0 100644 --- a/python/private/pypi/hub_exposure.bzl +++ b/python/private/pypi/hub_exposure.bzl @@ -18,10 +18,22 @@ 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 and venvs mapped + to a struct with: + * `hub`: {type}`str` the hub that provides the packages. For a venv + this is different from the key. + * `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. + + A venv is a named selection of the packages of a hub that is used + through the unified `@pypi` hub. """ # The root module wins over the owner of the hub when both configure it. @@ -30,7 +42,7 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): root_configured = {} for mod in root_modules: for tag in mod.tags.configure: - if tag.dependency_groups: + if tag.venv in ("", tag.hub_name) and tag.dependency_groups: root_configured[tag.hub_name] = None configured = {} @@ -49,17 +61,29 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): return None info = hubs[hub] + venv = tag.venv or hub if not mod.is_root and mod.name != info.module_name: # Only the root module and the module that created the hub can # configure it. continue - if not mod.is_root and hub in root_configured: + if venv == hub and not mod.is_root and hub in root_configured: continue + if venv != hub: + err = _venv_error(venv, hub, hubs = hubs, configured = configured, testonly = tag.testonly) + if err: + _fail(err) + return None if tag.pyproject_toml: 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 + if venv != hub: + _fail("pip.configure() venv '{}' needs the `dependency_groups` of its packages".format(venv)) + return None continue pyproject = last_pyproject.get(hub) or info.pyproject @@ -79,19 +103,52 @@ def hub_exposure(module_ctx, *, hubs, default_pyproject = None, _fail = fail): ) if selection == None: return None - if selection.all: + packages = selection.packages + if selection.all and venv != hub: + packages = info.packages + elif 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. - exposed = configured.setdefault(hub, {}) - for name in selection.packages: + # Multiple tags for the same hub or venv are combined. + exposed = configured.setdefault(venv, struct(hub = hub, packages = {})).packages + for name in packages: # 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) - for hub, packages in configured.items() - if hub not in exposes_all + name: struct( + hub = info.hub, + packages = sorted(info.packages), + testonly_packages = sorted([pkg for pkg, testonly in info.packages.items() if testonly]), + ) + for name, info in configured.items() + if name not in exposes_all } + +def _venv_error(venv, hub, *, hubs, configured, testonly): + if venv in hubs: + return "pip.configure() venv '{}' conflicts with the hub of the same name".format(venv) + + # `pypi` is the unified hub and `auto` is the default value of the + # `//python/config_settings:venv` flag. + if venv in ("pypi", "auto"): + return "pip.configure() venv name '{}' is reserved".format(venv) + + # A hub named `pypi` takes the place of the unified hub, so there would be + # nothing to select the venv with. + if "pypi" in hubs: + return "pip.configure() venv '{}' needs the unified `@pypi` hub, which is not created when a hub is named 'pypi'. Rename the hub or set RULES_PYTHON_PYPI_HUB_RESERVED=1 to rename it automatically".format(venv) + if venv in configured and configured[venv].hub != hub: + return "pip.configure() venv '{}' is used with both hub '{}' and hub '{}'".format( + venv, + configured[venv].hub, + hub, + ) + if testonly: + return "pip.configure() does not support `testonly` for the venv '{}', the packages are testonly only if they are testonly in the hub '{}'".format(venv, hub) + return None diff --git a/python/private/pypi/hub_repository.bzl b/python/private/pypi/hub_repository.bzl index c401168873..861c852ff6 100644 --- a/python/private/pypi/hub_repository.bzl +++ b/python/private/pypi/hub_repository.bzl @@ -32,15 +32,18 @@ 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) for key, values in rctx.attr.whl_map.items() }, exposed_packages = exposed_packages, + extra_internal_visibility = rctx.attr.extra_internal_visibility, 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 +60,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, }) @@ -81,6 +95,10 @@ hub_repository = repository_rule( doc = "Extra aliases to make for specific wheels in the hub repo.", mandatory = True, ), + "extra_internal_visibility": attr.string_list( + default = [], + doc = "The extra visibility of the packages that are not exposed, e.g. for the unified hub.", + ), "groups": attr.string_list_dict( mandatory = False, ), @@ -114,6 +132,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..f5421717ee 100644 --- a/python/private/pypi/render_pkg_aliases.bzl +++ b/python/private/pypi/render_pkg_aliases.bzl @@ -94,6 +94,8 @@ def render_pkg_aliases( requirement_cycles = None, extra_hub_aliases = {}, exposed_packages = None, + testonly_packages = [], + extra_internal_visibility = [], **kwargs): """Create alias declarations for each PyPI package. @@ -110,6 +112,9 @@ 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. + extra_internal_visibility: The extra visibility of the packages that + are not exposed. **kwargs: Extra kwargs to pass to the rules. Returns: @@ -134,6 +139,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 = { @@ -143,7 +153,7 @@ def render_pkg_aliases( internal_visibility = _internal_visibility( aliases, has_groups = bool(requirement_cycles), - ) + ) + extra_internal_visibility files = {} for name, pkg_aliases in aliases.items(): @@ -157,6 +167,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..8f5521bfeb 100644 --- a/python/private/pypi/unified_hub_repo.bzl +++ b/python/private/pypi/unified_hub_repo.bzl @@ -25,6 +25,8 @@ define_pypi_package_targets( extra_aliases = {extra_aliases}, hubs = {hubs}, pkg_hubs = {pkg_hubs}, + testonly = {testonly}, + venvs = {venvs}, ) """ @@ -58,7 +60,9 @@ def dist_info_requirement(name): ''' def _unified_hub_repo_impl(rctx): - hubs = rctx.attr.hubs + # The venvs are selected with the same flag as the hubs. + venvs = rctx.attr.venvs + hubs = rctx.attr.hubs + sorted(venvs) default_hub = rctx.attr.default_hub or None # 1. Generate Root BUILD.bazel with shared config settings @@ -79,6 +83,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 +97,8 @@ def _unified_hub_repo_impl(rctx): hubs = hubs, pkg_hubs = pkg_hubs, pkg_name = pkg_name, + testonly = pkg_name in testonly_packages, + venvs = dict(sorted(venvs.items())), ), ) @@ -130,6 +140,14 @@ 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.", + ), + "venvs": attr.string_dict( + default = {}, + doc = "The venvs mapped to the hubs that provide their packages.", + ), }, 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..884f7029a6 100644 --- a/python/private/pypi/unified_hub_setup.bzl +++ b/python/private/pypi/unified_hub_setup.bzl @@ -31,15 +31,18 @@ _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, venvs = {}): """Define the targets for a PyPI package in the unified PyPI hub. Args: name: normalized PyPI package name, serving as the main target name. pkg_hubs: list of hubs that contain this package. extra_aliases: dict mapping extra alias names to lists of hubs that support them. - hubs: list of all concrete hub names. + hubs: list of all concrete hub and venv names. default_hub: the hub to use by default. + testonly: whether all targets should be marked as testonly. + venvs: dict mapping the venv names to the hubs that provide their + packages. """ pkg_name = name @@ -47,6 +50,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()) @@ -62,7 +66,7 @@ def define_pypi_package_targets(name, pkg_hubs, extra_aliases, hubs, default_hub if is_supported: select_map["//:_is_venv_" + hub] = "@{hub}//{pkg}:{alias}".format( - hub = hub, + hub = venvs.get(hub, hub), pkg = pkg_name, alias = alias_name, ) @@ -100,6 +104,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..1e84e4fd7d 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,85 @@ 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"], +) + +# The venvs of pypi_b resolve to the pypi_b packages. +py_test( + name = "test_venv_colorama", + srcs = ["test_default.py"], + config_settings = { + "@rules_python//python/config_settings:venv": "pypi_b_colorama", + }, + main = "test_default.py", + deps = ["@pypi//colorama"], +) + +py_test( + name = "test_venv_dev", + srcs = ["test_default.py"], + config_settings = { + "@rules_python//python/config_settings:venv": "pypi_b_dev", + }, + main = "test_default.py", + deps = ["@pypi//colorama"], +) + +# six is not selected by the pypi_b_colorama venv: +py_binary( + name = "bin_venv_six", + srcs = ["bin_six_a.py"], + config_settings = { + "@rules_python//python/config_settings:venv": "pypi_b_colorama", + }, + main = "bin_six_a.py", + tags = ["manual"], + deps = ["@pypi//six"], +) diff --git a/tests/integration/unified_pypi/MODULE.bazel b/tests/integration/unified_pypi/MODULE.bazel index 70e01ccdac..3a907d7ec9 100644 --- a/tests/integration/unified_pypi/MODULE.bazel +++ b/tests/integration/unified_pypi/MODULE.bazel @@ -53,6 +53,21 @@ pip.parse( ) use_repo(pip, "pypi_b") +# The venvs are selections of the `pypi_b` packages that are used through the +# unified hub. +pip.configure( + dependency_groups = ["default"], + hub_name = "pypi_b", + pyproject_toml = "//:pyproject_venvs.toml", + venv = "pypi_b_colorama", +) +pip.configure( + dependency_groups = ["*"], + hub_name = "pypi_b", + pyproject_toml = "//:pyproject_venvs.toml", + venv = "pypi_b_dev", +) + # `pypi_filtered` only exposes the `[project] dependencies` of the # `pyproject.toml`, the other packages are not public. pip.parse( @@ -67,6 +82,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/pyproject_venvs.toml b/tests/integration/unified_pypi/pyproject_venvs.toml new file mode 100644 index 0000000000..55420aa1b5 --- /dev/null +++ b/tests/integration/unified_pypi/pyproject_venvs.toml @@ -0,0 +1,7 @@ +[project] +name = "unified-pypi" +version = "0.0.0" +dependencies = ["colorama"] + +[dependency-groups] +dev = ["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..7f014db0dd 100644 --- a/tests/integration/unified_pypi_test.py +++ b/tests/integration/unified_pypi_test.py @@ -33,6 +33,42 @@ 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_configure_venvs(self): + self.run_bazel( + "test", "//:test_venv_colorama", "//:test_venv_dev", "//:test_default" + ) + self.run_bazel("cquery", "//:bin_venv_six") + result = self.run_bazel("build", "//:bin_venv_six", check=False) + self.assertNotEqual( + result.exit_code, + 0, + "Expected build to fail during execution phase", + ) + self.assert_result_matches( + result, + 'ERROR: PyPI package "six" is not available when building under PyPI hub "pypi_b_colorama"\\. Try adding it to the requirements of this hub', + ) + 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..20600cb6b2 100644 --- a/tests/pypi/extension/extension_tests.bzl +++ b/tests/pypi/extension/extension_tests.bzl @@ -156,11 +156,14 @@ def _parse_modules(env, **kwargs): parse_modules(**kwargs), attrs = dict( configured_hubs = subjects.dict, + venvs = subjects.dict, declared_deps = subjects.dict, default_hub = subjects.str, 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 +872,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 +895,11 @@ 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( + hub = "pypi_a", + packages = ["simple"], + testonly_packages = [], + )}) _tests.append(_test_configure) @@ -929,10 +936,114 @@ 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( + hub = "pypi_a", + 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( + hub = "pypi_a", + 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 +1060,11 @@ def _test_configure_default_pyproject(env): ), ) - pypi.configured_hubs().contains_exactly({"pypi_a": ["other_pkg"]}) + pypi.configured_hubs().contains_exactly({"pypi_a": struct( + hub = "pypi_a", + packages = ["other_pkg"], + testonly_packages = [], + )}) _tests.append(_test_configure_default_pyproject) @@ -970,6 +1085,31 @@ def _test_not_configured_exposes_all(env): _tests.append(_test_not_configured_exposes_all) +def _test_configure_venvs(env): + pypi = _configure_parse_modules( + env, + _mod( + name = "rules_python", + parse = [_configure_parse(pyproject_toml = "pyproject.toml")], + configure = [ + _configure(hub_name = "pypi_a", venv = "venv_dev", dependency_groups = ["dev"]), + ], + ), + ) + + # The hub itself is not configured. + pypi.exposed_packages().contains_exactly({ + "pypi_a": ["other_pkg", "simple", "transitive_pkg"], + }) + pypi.configured_hubs().contains_exactly({}) + pypi.venvs().contains_exactly({"venv_dev": struct( + hub = "pypi_a", + packages = ["other_pkg"], + testonly_packages = [], + )}) + +_tests.append(_test_configure_venvs) + def extension_test_suite(name): """Create the test suite. diff --git a/tests/pypi/extension/pip_parse.bzl b/tests/pypi/extension/pip_parse.bzl index d048f99bd0..588bb65119 100644 --- a/tests/pypi/extension/pip_parse.bzl +++ b/tests/pypi/extension/pip_parse.bzl @@ -4,12 +4,16 @@ def configure( *, dependency_groups = [], hub_name, - pyproject_toml = None): + pyproject_toml = None, + testonly = False, + venv = ""): """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, + venv = venv, ) 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..282431874d 100644 --- a/tests/pypi/hub_exposure/hub_exposure_tests.bzl +++ b/tests/pypi/hub_exposure/hub_exposure_tests.bzl @@ -28,11 +28,15 @@ def _hub(*, module_name = "root", pyproject = None): def _configure( hub_name = "hub", dependency_groups = [], - pyproject_toml = None): + pyproject_toml = None, + testonly = False, + venv = ""): return mocks.tag( hub_name = hub_name, dependency_groups = dependency_groups, pyproject_toml = pyproject_toml, + testonly = testonly, + venv = venv, ) def _module(name = "root", is_root = True, configure = []): @@ -54,6 +58,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 +82,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 +106,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 +117,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 +126,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 +152,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 +163,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 +196,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 +208,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 +252,110 @@ 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 _test_configure_venvs(env): + got, failures = _exposure(_module(configure = [ + _configure(venv = "dev", dependency_groups = ["dev"]), + _configure(venv = "dev", dependency_groups = ["default"]), + _configure(venv = "main", dependency_groups = ["default"]), + _configure(venv = "all", dependency_groups = ["*", "transitive"]), + ])) + env.expect.that_collection(failures).contains_exactly([]) + + # The hub itself is not configured. + env.expect.that_dict(_packages(got)).contains_exactly({ + # A venv with all of the packages includes the transitive ones. + "all": ["other_pkg", "simple", "transitive_pkg"], + "dev": ["other_pkg", "simple"], + "main": ["simple"], + }) + env.expect.that_str(got["dev"].hub).equals("hub") + env.expect.that_str(got["main"].hub).equals("hub") + +_tests.append(_test_configure_venvs) + +def _test_configure_venv_errors(env): + hubs = { + "hub": _hub(pyproject = "pyproject.toml"), + "other": _hub(pyproject = "pyproject.toml"), + } + for configure, want in [ + ([_configure(venv = "other")], "pip.configure() venv 'other' conflicts with the hub of the same name"), + ([_configure(venv = "pypi")], "pip.configure() venv name 'pypi' is reserved"), + ([_configure(venv = "auto")], "pip.configure() venv name 'auto' is reserved"), + ([_configure(venv = "dev", dependency_groups = ["*"]), _configure(hub_name = "other", venv = "dev")], "pip.configure() venv 'dev' is used with both hub 'hub' and hub 'other'"), + ([_configure(venv = "dev")], "pip.configure() venv 'dev' needs the `dependency_groups` of its packages"), + ([_configure(venv = "dev", testonly = True)], "pip.configure() does not support `testonly` for the venv 'dev', the packages are testonly only if they are testonly in the hub 'hub'"), + ]: + _, failures = _exposure(_module(configure = configure), hubs = hubs) + env.expect.that_collection(failures).contains_exactly([want]) + +_tests.append(_test_configure_venv_errors) + +def _test_configure_venv_with_pypi_hub(env): + # A hub named `pypi` replaces the unified hub, which the venvs need. It + # does not matter which hub the venv is for. + hubs = { + "hub": _hub(pyproject = "pyproject.toml"), + "pypi": _hub(pyproject = "pyproject.toml"), + } + for hub_name in ["hub", "pypi"]: + got, failures = _exposure( + _module(configure = [ + _configure(hub_name = hub_name, venv = "dev", dependency_groups = ["dev"]), + ]), + hubs = hubs, + ) + env.expect.where(hub_name = hub_name).that_str(got).equals(None) + env.expect.where(hub_name = hub_name).that_collection(failures).contains_exactly([ + "pip.configure() venv 'dev' needs the unified `@pypi` hub, which is not created when a hub is named 'pypi'. Rename the hub or set RULES_PYTHON_PYPI_HUB_RESERVED=1 to rename it automatically", + ]) + + # The hub named `pypi` can still be configured itself. + got, failures = _exposure( + _module(configure = [ + _configure(hub_name = "pypi", dependency_groups = ["dev"]), + ]), + hubs = hubs, + ) + env.expect.that_collection(failures).contains_exactly([]) + env.expect.that_dict(_packages(got)).contains_exactly({"pypi": ["other_pkg"]}) + +_tests.append(_test_configure_venv_with_pypi_hub) + 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..2aaafc80eb 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 = { @@ -120,6 +151,32 @@ pkg_aliases( _tests.append(_test_hidden_aliases_in_groups) +def _test_hidden_aliases_extra_internal_visibility(env): + actual = render_pkg_aliases( + aliases = { + "bar": "pypi_bar", + "foo": "pypi_foo", + }, + exposed_packages = ["foo"], + extra_internal_visibility = ["@pypi//:__subpackages__"], + ) + + env.expect.that_str(actual["bar/BUILD.bazel"]).equals("""\ +load("@rules_python//python/private/pypi:pkg_aliases.bzl", "pkg_aliases") + +package(default_visibility = [ + "@pypi_bar//:__pkg__", + "@pypi_foo//:__pkg__", + "@pypi//:__subpackages__", +]) + +pkg_aliases( + name = "bar", + actual = "pypi_bar", +)""") + +_tests.append(_test_hidden_aliases_extra_internal_visibility) + def _test_bzlmod_aliases(env): # Use this function as it is used in pip_repository actual = render_multiplatform_pkg_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 = []