From b6d06e4b55cfcd1ef724a516a2ca7a2ee7e81480 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:11:47 -0800 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=94=A7=20build(lint):=20pin=20simplin?= =?UTF-8?q?t=200.12.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .pre-commit-config.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 012a475..e04d528 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -42,7 +42,7 @@ repos: priority: 3 args: ["--fix", "--unsafe-fixes", "--exit-non-zero-on-fix"] - repo: https://github.com/gaborbernat/simplint-pre-commit - rev: "5f12b15e1199c42bdeb3e13ea1c8b45952fbd802" # frozen: v0.11.0 + rev: "a12d8eaac290be24041a3e2778c636c56453722e" # frozen: v0.12.2 hooks: - id: simplint priority: 4 From 35ee999d7dec250a800ab4f271daeeca0121245a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:11:55 -0800 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=8E=A8=20style(lint):=20apply=20simpl?= =?UTF-8?q?int=200.12.2=20fixes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/python_sbom/_formats/_spdx.py | 5 +++-- src/python_sbom/_model/_metadata.py | 3 ++- src/python_sbom/_model/_names.py | 5 +++-- src/python_sbom/_model/_record.py | 5 +++-- src/python_sbom/_validate/_schemas.py | 4 ++-- tests/examples/conftest.py | 5 +++-- 6 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/python_sbom/_formats/_spdx.py b/src/python_sbom/_formats/_spdx.py index 4e75952..bd76e27 100644 --- a/src/python_sbom/_formats/_spdx.py +++ b/src/python_sbom/_formats/_spdx.py @@ -6,6 +6,7 @@ import json import re from datetime import UTC, datetime +from types import MappingProxyType from typing import TYPE_CHECKING, Final, NotRequired, TypedDict from python_sbom._model._graph import walk_components # simplint: ignore[private-import-path] # avoid root export @@ -29,7 +30,7 @@ ) # SPDX 2.3 JSON names every CycloneDX 1.6 hash algorithm, but by names of its own -_HASH_ALGORITHMS: Final[dict[str, str]] = { +_HASH_ALGORITHMS: Final[MappingProxyType[str, str]] = MappingProxyType({ "MD5": "MD5", "SHA-1": "SHA1", "SHA-256": "SHA256", @@ -42,7 +43,7 @@ "BLAKE2b-384": "BLAKE2b-384", "BLAKE2b-512": "BLAKE2b-512", "BLAKE3": "BLAKE3", -} +}) _LICENSE_REF: Final[re.Pattern[str]] = re.compile(r"LicenseRef-[A-Za-z0-9.-]+") _SPDX_ID_PATTERN: Final[re.Pattern[str]] = re.compile(r"[^A-Za-z0-9.]+") diff --git a/src/python_sbom/_model/_metadata.py b/src/python_sbom/_model/_metadata.py index 8b8aeaa..e8d7b1f 100644 --- a/src/python_sbom/_model/_metadata.py +++ b/src/python_sbom/_model/_metadata.py @@ -6,6 +6,7 @@ from dataclasses import dataclass from email.parser import HeaderParser from email.policy import compat32 +from types import MappingProxyType from typing import TYPE_CHECKING, Final, Literal, TypeAlias from packaging.metadata import parse_email @@ -35,7 +36,7 @@ # the empty line that ends the headers, as the email parser ends them; a line of whitespace continues a header _BODY: Final[re.Pattern[str]] = re.compile(r"^\r?\n", re.MULTILINE) # unparsed keys a field by its header name, lowercased, which is the RawMetadata key with dashes except for these -_HEADERS: Final[dict[str, str]] = {"classifiers": "classifier", "license_files": "license-file"} +_HEADERS: Final[MappingProxyType[str, str]] = MappingProxyType({"classifiers": "classifier", "license_files": "license-file"}) def parse_metadata(text: str) -> CoreMetadata: diff --git a/src/python_sbom/_model/_names.py b/src/python_sbom/_model/_names.py index 080fc51..bf43ac5 100644 --- a/src/python_sbom/_model/_names.py +++ b/src/python_sbom/_model/_names.py @@ -3,6 +3,7 @@ from __future__ import annotations import re +from types import MappingProxyType from typing import Final from packageurl import PackageURL @@ -15,7 +16,7 @@ # the label normalization and mapping cyclonedx-py applies to Project-URL entries, so the same metadata yields the same # reference types whichever generator produced the document, plus the well-known labels of PEP 753 it lacks; funding # labels have no CycloneDX type and fall to "other" -_URL_LABEL_TO_REFERENCE_TYPE: Final[dict[str, str]] = { +_URL_LABEL_TO_REFERENCE_TYPE: Final[MappingProxyType[str, str]] = MappingProxyType({ "bugtracker": "issue-tracker", "issuetracker": "issue-tracker", "issues": "issue-tracker", @@ -38,7 +39,7 @@ "repository": "vcs", "github": "vcs", "chat": "chat", -} +}) def sbom_property(project: str, key: str) -> str: diff --git a/src/python_sbom/_model/_record.py b/src/python_sbom/_model/_record.py index 580b008..ce5f918 100644 --- a/src/python_sbom/_model/_record.py +++ b/src/python_sbom/_model/_record.py @@ -5,6 +5,7 @@ import base64 import binascii from itertools import starmap +from types import MappingProxyType from typing import TYPE_CHECKING, Final from installer.records import RecordEntry @@ -17,13 +18,13 @@ from collections.abc import Iterable # the algorithms a wheel RECORD may name, as CycloneDX spells them -_ALGORITHMS: Final[dict[str, str]] = { +_ALGORITHMS: Final[MappingProxyType[str, str]] = MappingProxyType({ "md5": "MD5", "sha1": "SHA-1", "sha256": "SHA-256", "sha384": "SHA-384", "sha512": "SHA-512", -} +}) def record_rows(rows: Iterable[tuple[str, str, str]], where: str) -> list[RecordRow]: diff --git a/src/python_sbom/_validate/_schemas.py b/src/python_sbom/_validate/_schemas.py index ababc7e..7a6b4e7 100644 --- a/src/python_sbom/_validate/_schemas.py +++ b/src/python_sbom/_validate/_schemas.py @@ -109,9 +109,9 @@ def _license_problems( # references serves the newest; Apache-2.0, see the LICENSE beside them. Format assertion is on, as in CycloneDX's own # Draft 7 validation, and offline, so a reference missing from the registry fails instead of reaching the network _SCHEMAS: Final[Traversable] = files(__package__) / "schemas" -_REFERENCED: Final[list[dict[str, Json]]] = [ +_REFERENCED: Final[tuple[dict[str, Json], ...]] = tuple( json.loads((_SCHEMAS / name).read_text(encoding="utf-8")) for name in ("spdx.schema.json", "jsf-0.82.schema.json") -] +) _VALIDATOR: Final[Draft7Validator] = Draft7Validator( json.loads((_SCHEMAS / "bom-1.6.schema.json").read_text(encoding="utf-8")), validate_formats=True, diff --git a/tests/examples/conftest.py b/tests/examples/conftest.py index 5dd3735..606b0d9 100644 --- a/tests/examples/conftest.py +++ b/tests/examples/conftest.py @@ -10,6 +10,7 @@ import zipfile from dataclasses import dataclass from pathlib import Path +from types import MappingProxyType from typing import TYPE_CHECKING, Final, Protocol import pytest @@ -23,9 +24,9 @@ _PROMPT: Final[re.Pattern[str]] = re.compile(r"^\$ ", re.MULTILINE) # a frontend's isolated environment would install python-sbom from PyPI; the environment the test runs in holds the # checkout's -_ADDED: Final[dict[tuple[str, ...], list[str]]] = { +_ADDED: Final[MappingProxyType[tuple[str, ...], list[str]]] = MappingProxyType({ ("python", "-m", "build"): ["--no-isolation", "--skip-dependency-check"] -} +}) @dataclass(frozen=True, slots=True, kw_only=True) From 6e50f754fbe175978ffd7b8aa442b7fe726652c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:12:52 -0800 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=9A=A8=20fix(lint):=20keep=20the=20se?= =?UTF-8?q?eder=20table=20a=20dict=20literal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/_seeder/src/seeder/embed/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/_seeder/src/seeder/embed/__init__.py b/tests/_seeder/src/seeder/embed/__init__.py index aad2835..7c0af05 100644 --- a/tests/_seeder/src/seeder/embed/__init__.py +++ b/tests/_seeder/src/seeder/embed/__init__.py @@ -4,7 +4,7 @@ # the layout of virtualenv's seed/wheels/embed/__init__.py: another assignment comes before the table BUNDLE_FOLDER = Path(__file__).absolute().parent # simplint: ignore[missing-final] # virtualenv fixture -BUNDLE_SUPPORT = { # simplint: ignore[missing-final] # virtualenv fixture +BUNDLE_SUPPORT = { # simplint: ignore[missing-final, mutable-module-constant] # read by ast as a dict literal "3.14": {"pip": "pip-1.0-py3-none-any.whl"}, "3.15": {"pip": "pip-1.0-py3-none-any.whl"}, } From c647200942d5c6e0505f1076e10c9c7b11b49d36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:12:52 -0800 Subject: [PATCH 4/8] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(tests):=20fre?= =?UTF-8?q?eze=20the=20public=20name=20set?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/test_public_api.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_public_api.py b/tests/test_public_api.py index d6fab3d..b5f760c 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -22,7 +22,7 @@ _Hint = object # simplint: ignore[imprecise-annotation] # hints are arbitrary typing objects -_PUBLIC: Final[set[str]] = { +_PUBLIC: Final[frozenset[str]] = frozenset({ "BundledWheelInfo", "Component", "Contact", @@ -44,7 +44,7 @@ "SbomError", "Settings", "__version__", -} +}) def test_public_api() -> None: From e5acac388bbd02b3bd96bb2ebca7479eed7a3dda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:13:19 -0800 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=8E=A8=20style:=20format=20with=20ruf?= =?UTF-8?q?f?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/python_sbom/_model/_metadata.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/python_sbom/_model/_metadata.py b/src/python_sbom/_model/_metadata.py index e8d7b1f..0bf5cf1 100644 --- a/src/python_sbom/_model/_metadata.py +++ b/src/python_sbom/_model/_metadata.py @@ -36,7 +36,10 @@ # the empty line that ends the headers, as the email parser ends them; a line of whitespace continues a header _BODY: Final[re.Pattern[str]] = re.compile(r"^\r?\n", re.MULTILINE) # unparsed keys a field by its header name, lowercased, which is the RawMetadata key with dashes except for these -_HEADERS: Final[MappingProxyType[str, str]] = MappingProxyType({"classifiers": "classifier", "license_files": "license-file"}) +_HEADERS: Final[MappingProxyType[str, str]] = MappingProxyType({ + "classifiers": "classifier", + "license_files": "license-file", +}) def parse_metadata(text: str) -> CoreMetadata: From e62d492a71906f35da829f72dae9e989eeba06f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 10:14:39 -0800 Subject: [PATCH 6/8] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(tests):=20gro?= =?UTF-8?q?up=20the=20document=20mutations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/_validate/test_document.py | 54 +++++++++++++++++--------------- 1 file changed, 28 insertions(+), 26 deletions(-) diff --git a/tests/_validate/test_document.py b/tests/_validate/test_document.py index 9c63826..c5cddb6 100644 --- a/tests/_validate/test_document.py +++ b/tests/_validate/test_document.py @@ -180,33 +180,35 @@ def test_component_without_bom_ref(describe: Describe) -> None: assert validate_document(json.dumps(loaded).encode(), None) == ["components lack a bom-ref: ['nameless']"] -@pytest.mark.parametrize( - "mutate", - [ - pytest.param( - lambda loaded: loaded["formulation"][0]["workflows"][0].pop("resourceReferences"), - id="workflow-without-resources", - ), - pytest.param( - lambda loaded: loaded["formulation"][0]["workflows"][0]["resourceReferences"].append({ - "externalReference": {"type": "other", "url": "https://example.org"} - }), - id="workflow-external-resource", - ), - pytest.param( - lambda loaded: loaded["metadata"]["properties"].append({"name": "example:extra"}), - id="property-without-value", - ), - pytest.param( - lambda loaded: loaded["metadata"]["component"]["properties"].append({"name": "example:extra"}), - id="root-property-without-value", - ), - pytest.param( - lambda loaded: loaded["metadata"].update(supplier={"url": ["https://example.org"]}), - id="supplier-without-name", - ), - ], +_WORKFLOW_MUTATIONS: Final[tuple[pytest.ParameterSet, ...]] = ( + pytest.param( + lambda loaded: loaded["formulation"][0]["workflows"][0].pop("resourceReferences"), + id="workflow-without-resources", + ), + pytest.param( + lambda loaded: loaded["formulation"][0]["workflows"][0]["resourceReferences"].append({ + "externalReference": {"type": "other", "url": "https://example.org"} + }), + id="workflow-external-resource", + ), +) +_METADATA_MUTATIONS: Final[tuple[pytest.ParameterSet, ...]] = ( + pytest.param( + lambda loaded: loaded["metadata"]["properties"].append({"name": "example:extra"}), + id="property-without-value", + ), + pytest.param( + lambda loaded: loaded["metadata"]["component"]["properties"].append({"name": "example:extra"}), + id="root-property-without-value", + ), + pytest.param( + lambda loaded: loaded["metadata"].update(supplier={"url": ["https://example.org"]}), + id="supplier-without-name", + ), ) + + +@pytest.mark.parametrize("mutate", [*_WORKFLOW_MUTATIONS, *_METADATA_MUTATIONS]) def test_schema_valid_variations_pass(describe: Describe, mutate: Callable[[dict[str, Json]], None]) -> None: loaded = json.loads(dumps(describe())) mutate(loaded) From bf5758fa60a93de6185219b8fd3222bfedefb21a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 12:20:56 -0800 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=94=A7=20build(lint):=20drop=20the=20?= =?UTF-8?q?inline-regex=20Ruff=20ignore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index a1fb7cc..dac9244 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -217,7 +217,6 @@ lint.ignore = [ "undocumented-public-init", # undocumented-public-api (simplint SMP903) covers the public API instead "undocumented-public-method", # undocumented-public-api (simplint SMP903) covers the public API instead "undocumented-public-nested-class", # undocumented-public-api (simplint SMP903) covers the public API instead - "unnecessary-regular-expression-compile", # conflicts with simplint inline-regex ] lint.per-file-ignores."bench/**/*.py" = [ "import-private-name", # Benchmarks time the private entry points the public API wraps From da902b61196210dc7389c66bd85af0dd9b0dec1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bern=C3=A1t=20G=C3=A1bor?= Date: Fri, 13 Nov 2026 12:21:09 -0800 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=8E=A8=20style:=20order=20definitions?= =?UTF-8?q?=20below=20their=20users?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/python_sbom/backend.py | 36 ++++++++++++++--------------- tests/_wheel/test_bundled.py | 8 +++---- tests/conftest.py | 18 +++++++-------- tests/examples/conftest.py | 18 +++++++-------- tests/hatch/test_hook.py | 8 +++---- tests/test_public_api.py | 44 ++++++++++++++++++------------------ 6 files changed, 66 insertions(+), 66 deletions(-) diff --git a/src/python_sbom/backend.py b/src/python_sbom/backend.py index c1e2ef8..bb739b9 100644 --- a/src/python_sbom/backend.py +++ b/src/python_sbom/backend.py @@ -65,6 +65,24 @@ def _wrapped() -> _Backend: return _load(Path.cwd()) +@cache +def _load(root: Path) -> _Backend: + # PEP 517 runs every hook from the project directory, which holds the pyproject.toml naming the backend + if (reference := settings_from_pyproject(root).build_backend) is None: + msg = ( + f"{root / 'pyproject.toml'} sets build-backend = 'python_sbom.backend' but names no backend to wrap; set" + " build-backend in [tool.python-sbom], such as 'mesonpy'" + ) + raise SbomError(msg) + module, _, attribute = reference.partition(":") + if module == __name__: + msg = f"[tool.python-sbom] build-backend names {reference}, which would wrap itself" + raise SbomError(msg) + loaded = importlib.import_module(module) + # PEP 517 requires every backend to define the two mandatory hooks + return cast("_Backend", reduce(getattr, attribute.split("."), loaded) if attribute else loaded) + + def build_sdist(sdist_directory: str, config_settings: ConfigSettings = None) -> str: """ Build an sdist with the wrapped backend, then record the source revision in it. @@ -91,24 +109,6 @@ def __getattr__(name: str) -> _Hook: raise AttributeError(msg) -@cache -def _load(root: Path) -> _Backend: - # PEP 517 runs every hook from the project directory, which holds the pyproject.toml naming the backend - if (reference := settings_from_pyproject(root).build_backend) is None: - msg = ( - f"{root / 'pyproject.toml'} sets build-backend = 'python_sbom.backend' but names no backend to wrap; set" - " build-backend in [tool.python-sbom], such as 'mesonpy'" - ) - raise SbomError(msg) - module, _, attribute = reference.partition(":") - if module == __name__: - msg = f"[tool.python-sbom] build-backend names {reference}, which would wrap itself" - raise SbomError(msg) - loaded = importlib.import_module(module) - # PEP 517 requires every backend to define the two mandatory hooks - return cast("_Backend", reduce(getattr, attribute.split("."), loaded) if attribute else loaded) - - __all__ = [ "ConfigSettings", "build_sdist", diff --git a/tests/_wheel/test_bundled.py b/tests/_wheel/test_bundled.py index da86cf7..74ef122 100644 --- a/tests/_wheel/test_bundled.py +++ b/tests/_wheel/test_bundled.py @@ -58,6 +58,10 @@ def test_bundled_wheel(tmp_path: Path, write_wheel: WriteWheel) -> None: ] +def _bundled(data: bytes, path: str) -> BundledWheel: + return read_bundled_wheels([path], lambda _: BytesIO(data))[0] + + @pytest.mark.parametrize( ("files", "message"), [ @@ -264,10 +268,6 @@ def test_vendor_manifest_needs_exact_pins( _bundled(wheel.read_bytes(), "pip-1.0-py3-none-any.whl") -def _bundled(data: bytes, path: str) -> BundledWheel: - return read_bundled_wheels([path], lambda _: BytesIO(data))[0] - - def test_bundled_wheels_come_in_the_order_given(tmp_path: Path, write_wheel: WriteWheel) -> None: # read side by side, yet reported in order, the first broken wheel's error included good = write_wheel(tmp_path / "pip-1.0-py3-none-any.whl", _PIP).read_bytes() diff --git a/tests/conftest.py b/tests/conftest.py index 355deac..30663be 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -185,15 +185,6 @@ def describe( # ruff: ignore[too-many-arguments] # each a part of the wheel a t return describe -@pytest.fixture -def context_for(settings: Settings) -> ContextFor: - def context(root: Path, artifact: Path) -> ProviderContext: - identity = project_identity(parse_metadata("Name: Example\nVersion: 1.0\n"), settings) - return ProviderContext(root=root, settings=settings, identity=identity, read=artifact_read(artifact)) - - return context - - def artifact_read(artifact: Path) -> Callable[[PurePosixPath], bytes]: # opens the artifact for each read, as a test context outlives no build that would hold it open def read(path: PurePosixPath) -> bytes: @@ -201,3 +192,12 @@ def read(path: PurePosixPath) -> bytes: return opened.provider_read(path) return read + + +@pytest.fixture +def context_for(settings: Settings) -> ContextFor: + def context(root: Path, artifact: Path) -> ProviderContext: + identity = project_identity(parse_metadata("Name: Example\nVersion: 1.0\n"), settings) + return ProviderContext(root=root, settings=settings, identity=identity, read=artifact_read(artifact)) + + return context diff --git a/tests/examples/conftest.py b/tests/examples/conftest.py index 606b0d9..0ec0fd0 100644 --- a/tests/examples/conftest.py +++ b/tests/examples/conftest.py @@ -29,15 +29,6 @@ }) -@dataclass(frozen=True, slots=True, kw_only=True) -class Played: - # an example project of the docs, copied and taken through one of its documented sessions: each command with the - # lines the docs show under it, and with the lines it printed - directory: Path - expected: list[tuple[str, list[str]]] - output: list[tuple[str, list[str]]] - - class ReadSbom(Protocol): def __call__(self, wheel: Path) -> Document: ... @@ -73,6 +64,15 @@ def _run(command: str, directory: Path) -> list[str]: return result.stdout.splitlines() if name == "python-sbom" else [] +@dataclass(frozen=True, slots=True, kw_only=True) +class Played: + # an example project of the docs, copied and taken through one of its documented sessions: each command with the + # lines the docs show under it, and with the lines it printed + directory: Path + expected: list[tuple[str, list[str]]] + output: list[tuple[str, list[str]]] + + @pytest.fixture def read_sbom() -> ReadSbom: def read(wheel: Path) -> Document: diff --git a/tests/hatch/test_hook.py b/tests/hatch/test_hook.py index 0aa983f..1593e3e 100644 --- a/tests/hatch/test_hook.py +++ b/tests/hatch/test_hook.py @@ -44,10 +44,6 @@ def initialize(self, version, build_data): """ -def sbom_of(wheel: Path, name: str = _SBOM) -> Document: - return json.loads(zipfile.ZipFile(wheel).read(name)) - - def test_wheel_carries_valid_sbom(project: Path, build_wheel: BuildWheel) -> None: assert validate(build_wheel(project), frozenset({"MIT"})) == [] @@ -71,6 +67,10 @@ def test_sbom_lists_dependencies_a_later_hook_adds(retagged_wheel: Path) -> None ] +def sbom_of(wheel: Path, name: str = _SBOM) -> Document: + return json.loads(zipfile.ZipFile(wheel).read(name)) + + def test_sbom_names_the_retagged_wheel(retagged_wheel: Path) -> None: references = sbom_of(retagged_wheel)["metadata"]["component"]["externalReferences"] assert {reference["type"]: reference["url"] for reference in references}["attestation"] == ( diff --git a/tests/test_public_api.py b/tests/test_public_api.py index b5f760c..172f4c2 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -55,6 +55,11 @@ def test_hatch_api() -> None: assert set(python_sbom.hatch.__all__) == {"SbomBuildHook"} +@pytest.mark.parametrize("name", sorted(_PUBLIC - {"__version__"}), ids=str) +def test_public_types_only_reach_public_types(name: str) -> None: + assert reached(getattr(python_sbom, name)) - exported() == set() + + def reached(start: _Hint) -> set[_Hint]: # every python_sbom type a hint of a public name leads to, through fields, members and nested hints; a private type # ends the walk there, so the leak is what gets reported even when its own hints do not resolve @@ -79,6 +84,21 @@ def reached(start: _Hint) -> set[_Hint]: return {item for item in found if _ours(item)} +def _ours(item: _Hint) -> bool: + return getattr(item, "__module__", "").startswith("python_sbom") + + +def _names() -> dict[str, _Hint]: + # the annotations name types the modules import only for type checking, so every module's names resolve them + modules = [ + pathlib, + collections.abc, + typing, + *(importlib.import_module(found.name) for found in pkgutil.walk_packages(python_sbom.__path__, "python_sbom.")), + ] + return dict(member for module in modules for member in inspect.getmembers(module)) + + def _members(cls: type) -> Iterator[_Hint]: # read the class dictionaries, since attribute access hides a property's getter and unwraps class and static methods for owner in inspect.getmro(cls): @@ -96,13 +116,8 @@ def _members(cls: type) -> Iterator[_Hint]: yield value -def _ours(item: _Hint) -> bool: - return getattr(item, "__module__", "").startswith("python_sbom") - - -@pytest.mark.parametrize("name", sorted(_PUBLIC - {"__version__"}), ids=str) -def test_public_types_only_reach_public_types(name: str) -> None: - assert reached(getattr(python_sbom, name)) - exported() == set() +def exported() -> set[_Hint]: + return {getattr(python_sbom, name) for name in _PUBLIC} | {python_sbom.hatch.SbomBuildHook} def test_hook_only_reaches_public_types() -> None: @@ -135,18 +150,3 @@ def leak(_: Settings) -> CoreMetadata: monkeypatch.setattr(Settings, "leak", property(leak), raising=False) assert reached(Settings) - exported() == {CoreMetadata} - - -def exported() -> set[_Hint]: - return {getattr(python_sbom, name) for name in _PUBLIC} | {python_sbom.hatch.SbomBuildHook} - - -def _names() -> dict[str, _Hint]: - # the annotations name types the modules import only for type checking, so every module's names resolve them - modules = [ - pathlib, - collections.abc, - typing, - *(importlib.import_module(found.name) for found in pkgutil.walk_packages(python_sbom.__path__, "python_sbom.")), - ] - return dict(member for module in modules for member in inspect.getmembers(module))