public inbox for git-commits@fedoraproject.org
help / color / mirror / Atom feed
From: Karolina Surma <ksurma@redhat.com>
To: git-commits@fedoraproject.org
Subject: [rpms/pyproject-rpm-macros] f45: Add %pyproject_verify_license macro to check the upstream metadata
Date: Tue, 13 Oct 2026 09:29:36 GMT	[thread overview]
Message-ID: <179188377656.1.10107680895231089956.rpms-pyproject-rpm-macros-0eeab9e54c27@fedoraproject.org> (raw)

            A new commit has been pushed.

            Repo   : rpms/pyproject-rpm-macros
            Branch : f45
            Commit : 0eeab9e54c27d08cd2fddde3c449d7c297acaf63
            Author : Karolina Surma <ksurma@redhat.com>
            Date   : 2026-10-12T17:03:36+02:00
            Stats  : +709/-1 in 8 file(s)
            URL    : https://src.fedoraproject.org/rpms/pyproject-rpm-macros/c/0eeab9e54c27d08cd2fddde3c449d7c297acaf63?branch=f45

            Log:
            Add %pyproject_verify_license macro to check the upstream metadata

%pyproject_verify_license takes the spec %license and compares it with
PEP 639 project.license metadata.
The pre-PEP 639 nested way of declaring the license as a table with either
text or file is not supported.
%pyproject_verify_license can take a positional argument, if Fedora's
declaration of license is not comparable with the upstream one, and
that's expected.
It can be used during any phase of the rpm build, and was designed with
%prep in mind for a quick feedback loop before the time- and
resource-heavy build phase is spawn.

Assisted-By: Claude Opus 4.8

---
diff --git a/README.md b/README.md
index 58930e2..599b4cc 100644
--- a/README.md
+++ b/README.md
@@ -428,6 +428,101 @@ in `%pyproject_save_files` and `%{pyproject_files}`:
     %files -n python3-package-b -f %{pyproject_files -D package_b}
 
 
+Verifying the License: tag against upstream
+-------------------------------------------
+
+[PEP 639] lets upstream projects declare a normalized SPDX license expression
+in the `project.license` key of `pyproject.toml`.
+`%pyproject_verify_license` compares that declaration against the spec's `License:` tag
+and fails the build if they don't semantically agree.
+The is useful to notice upstream changed their license declaration and
+the License: tag needs to be updated accordingly.
+It only needs `pyproject.toml` to be present, so it can be run at any point once the sources
+are unpacked.
+Put it as early as the constraints below allow, so that a license mismatch fails the build
+before any expensive work (the test suite, the build, or the `%generate_buildrequires` rounds).
+
+* **At the start of `%check`**, before the test suite runs:
+
+```
+%check
+%pyproject_verify_license
+# ... tests follow
+```
+
+* **At the start of `%build` (or `%conf`)**, before the potentially long build runs:
+
+```
+%build
+%pyproject_verify_license
+# ... build follows
+```
+
+* **In `%prep`**, before any expensive `%generate_buildrequires` rounds. However, if you
+do that, you need to explicitly declare BuildRequires for `pyproject-rpm-macros`,
+`python3-devel` and, if your Python 3 version is lower than 3.11, also `python3-tomli`:
+
+```
+BuildRequires:  pyproject-rpm-macros
+BuildRequires:  python3-devel
+# only on Python < 3.11, where tomllib is not in the standard library:
+BuildRequires:  (python3dist(tomli) if python3-devel < 3.11)
+...
+%prep
+%autosetup -p1
+%pyproject_verify_license
+```
+
+The comparison is semantic, not textual: operand order (`MIT OR BSD-3-Clause` vs `BSD-3-Clause OR MIT`)
+and identifier/operator case are treated as equal.
+It does not resolve deprecated SPDX ids and their replacements (e.g. `GPL-2.0+` vs `GPL-2.0-or-later`),
+validate identifiers against the SPDX list, or perform boolean absorption/distribution
+(`(MIT OR BSD-3-Clause) AND MIT` is not reduced to `MIT`).
+
+`%pyproject_verify_license` always fails the build when:
+
+* `pyproject.toml` is not present or is not valid TOML,
+* `project.license` is missing from `pyproject.toml`,
+* `license` is listed in `project.dynamic` (its value isn't statically known),
+* `project.license` is not a string (e.g. the deprecated `{text = …}`/`{file = …}` table form),
+* either the upstream or the spec license expression fails to parse, or
+* the two expressions are parseable but not semantically equivalent.
+
+If `pyproject.toml` is not in the current directory, point at its directory with `-d`/`--directory`:
+
+    %pyproject_verify_license --directory subdir
+
+By default, the spec's `License:` tag (`%{license}`) is the value compared against upstream.
+To compare a different expression instead (for example, when a subpackage's license differs
+from the main package's `License:` tag), pass it as a positional argument:
+
+    %pyproject_verify_license MIT AND BSD-3-Clause
+
+In many cases, using RPM macros for this is more convenient:
+
+    # Upstream just declares partial license, but we also bundle libfoo with extra licenses
+    %global upstream_license MIT
+    License: %{upstream_license} AND BSD-3-Clause
+
+    ...
+    %pyproject_verify_license %{upstream_license}
+
+A common pitfall: if the spec declares more than one `License:` tag (for example, one per
+subpackage), `%{license}` expands to the *last* one defined, which may not be the expression
+you want to compare against upstream.
+In that case, don't rely on the implicit `%{license}` default.
+Instead, pin the expression to compare in a `%global upstream_license` (as shown above)
+and pass it explicitly:
+
+    %global upstream_license MIT
+    License: %{upstream_license}
+    ...
+    %package doc
+    License: CC-BY-SA-4.0
+    ...
+    %pyproject_verify_license %{upstream_license}
+
+
 Performing an import check on all importable modules
 ----------------------------------------------------
 
@@ -661,6 +756,12 @@ Here is a complete reference of all options:
 | `-f FILE`  | `--filelist FILE`         | Custom path to a filelist (optional, advanced usage)                                            |
 | `-F`       | `--no-filelist`           | Skip %files section entirely (optional, advanced usage)                                         |
 
+### `%pyproject_verify_license`
+
+| Short    | Long              | Description                                                    |
+|----------|-------------------|----------------------------------------------------------------|
+| `-d DIR` | `--directory DIR` | Source root directory containing pyproject.toml (default: CWD) |
+
 ### `%tox`
 
 | Short       | Long              | Description          |

diff --git a/macros.pyproject b/macros.pyproject
index 7c72902..5459b5d 100644
--- a/macros.pyproject
+++ b/macros.pyproject
@@ -236,6 +236,21 @@ fi\
 %{__pyproject_getopt_restore}
 
 
+# Compares the spec %%license tag (or an explicitly given expression) against
+# the upstream PEP 639 project.license string in pyproject.toml, failing the
+# build on any mismatch or ambiguity.
+%pyproject_verify_license(-) \
+%{lua:require("fedora.rpm.pyproject_getopt").getopt({
+    {short="d", long="directory", value=true},
+})}\
+%{expand:\\\
+%{?__pyproject_opt_d:pushd "%{__pyproject_opt_d}"}
+%{__python3} -Bs %{_rpmconfigdir}/redhat/pyproject_verify_license.py \\
+  '%{?__pyproject_positional_args}%{!?__pyproject_positional_args:%{license}}'
+%{?__pyproject_opt_d:popd}
+%{__pyproject_getopt_restore}}
+
+
 %default_toxenv py%{python3_version_nodots}
 %toxenv %{default_toxenv}
 

diff --git a/plan.fmf b/plan.fmf
index ccbcfbf..a4dad74 100644
--- a/plan.fmf
+++ b/plan.fmf
@@ -109,6 +109,9 @@ discover:
     - name: config-settings-test
       path: /tests
       test: ./mocktest.sh config-settings-test
+    - name: verify_license
+      path: /tests
+      test: ./mocktest.sh verify-license-test
     - name: isort_c9s
       path: /tests
       test: ID=centos VERSION_ID=9 ./mocktest.sh python-isort

diff --git a/pyproject-rpm-macros.spec b/pyproject-rpm-macros.spec
index e0e30c7..12f675f 100644
--- a/pyproject-rpm-macros.spec
+++ b/pyproject-rpm-macros.spec
@@ -14,7 +14,7 @@ License:        MIT
 #   Increment Y and reset Z when new macros or features are added
 #   Increment Z when this is a bugfix or a cosmetic change
 # Dropping support for EOL Fedoras is *not* considered a breaking change
-Version:        1.23.2
+Version:        1.24.0
 Release:        1%{?dist}
 
 # Macro files
@@ -29,6 +29,7 @@ Source:         pyproject_patch_metadata.py
 Source:         pyproject_preprocess_record.py
 Source:         pyproject_requirements_txt.py
 Source:         pyproject_save_files.py
+Source:         pyproject_verify_license.py
 Source:         pyproject_wheel.py
 
 # Implementation files, Lua
@@ -43,6 +44,7 @@ Source:         test_pyproject_getopt_consistency.py
 Source:         test_pyproject_getopt_parser.py
 Source:         test_pyproject_requirements_txt.py
 Source:         test_pyproject_save_files.py
+Source:         test_pyproject_verify_license.py
 
 # Test data
 Source:         pyproject_buildrequires_testcases.yaml
@@ -146,6 +148,7 @@ install -pm 644 pyproject_requirements_txt.py %{buildroot}%{_rpmconfigdir}/redha
 install -pm 644 pyproject_wheel.py %{buildroot}%{_rpmconfigdir}/redhat/
 install -pm 644 pyproject_patch_metadata.py %{buildroot}%{_rpmconfigdir}/redhat/
 install -pm 644 pyproject_dependency_overrides.py %{buildroot}%{_rpmconfigdir}/redhat/
+install -pm 644 pyproject_verify_license.py %{buildroot}%{_rpmconfigdir}/redhat/
 
 
 %if %{with tests}
@@ -168,6 +171,7 @@ export HOSTNAME="rpmbuild"  # to speedup tox in network-less mock, see rhbz#1856
 %{_rpmconfigdir}/redhat/pyproject_wheel.py
 %{_rpmconfigdir}/redhat/pyproject_patch_metadata.py
 %{_rpmconfigdir}/redhat/pyproject_dependency_overrides.py
+%{_rpmconfigdir}/redhat/pyproject_verify_license.py
 %{_rpmluadir}/fedora/rpm/pyproject_getopt.lua
 
 %doc README.md
@@ -179,6 +183,11 @@ export HOSTNAME="rpmbuild"  # to speedup tox in network-less mock, see rhbz#1856
 
 
 %changelog
+* Wed Sep 30 2026 Karolina Surma <ksurma@redhat.com> - 1.24.0-1
+- Add %%pyproject_verify_license to assert the spec License: tag matches
+  the upstream PEP 639 project.license declared in pyproject.toml
+- Resolves: rhbz#2490289
+
 * Sun Jul 26 2026 Miro Hrončok <mhroncok@redhat.com> - 1.23.2-1
 - Fixup a regression in %%pyproject_extras_subpkg
 

diff --git a/pyproject_verify_license.py b/pyproject_verify_license.py
new file mode 100644
index 0000000..b32b121
--- /dev/null
+++ b/pyproject_verify_license.py
@@ -0,0 +1,230 @@
+"""
+Minimal, stdlib-only SPDX license-expression comparator.
+
+Compares two SPDX license expressions for semantic equivalence.
+AND/OR are treated as commutative, associative and idempotent;
+"A WITH B" is atomic. It does not resolve SPDX synonyms
+(GPL-2.0+ != GPL-2.0-or-later), validate identifiers,
+or perform boolean absorption.
+
+Expressions are parsed straight into order-independent canonical keys (nested
+tuples); two expressions are equivalent if their keys compare equal.
+"""
+
+import argparse
+import re
+import sys
+
+try:
+    # tomllib is in the standard library since 3.11.0b1
+    import tomllib
+except ImportError:
+    import tomli as tomllib
+
+
+class LicenseExpressionError(ValueError):
+    """Raised when a license expression string cannot be parsed."""
+
+
+class LicenseVerificationError(Exception):
+    """A reportable reason the license check failed."""
+
+
+class LicenseExpression:
+    """An SPDX license expression parsed into an order-independent canonical key.
+
+    The input string is parsed on construction into a nested-tuple ``key``; two
+    expressions are equivalent iff their keys compare equal, so instances can be
+    compared directly:
+
+    >>> LicenseExpression("MIT OR Apache-2.0") == LicenseExpression("Apache-2.0 OR MIT")
+    True
+    >>> LicenseExpression("GPL-2.0+") == LicenseExpression("GPL-2.0-or-later")
+    False
+
+    AND/OR are treated as commutative, associative and idempotent; "A WITH B" is
+    atomic. Synonyms are not resolved and identifiers are not validated.
+
+    Raise LicenseExpressionError on syntactically invalid or empty input.
+
+    The grammar (SPDX operator precedence: `WITH` > `AND` > `OR`):
+
+        or_expr   := and_expr ( "OR"  and_expr )*
+        and_expr  := with_expr ( "AND" with_expr )*
+        with_expr := primary ( "WITH" EXCEPTION_ID )?   # left side must be a bare license id
+        primary   := "(" or_expr ")" | LICENSE_ID
+    """
+
+    _KEYWORDS = {"AND", "OR", "WITH"}
+    _TOKEN_RE = re.compile(r"\s*(\(|\)|[^\s()]+)")
+
+    def __init__(self, expression):
+        if expression is None:
+            raise LicenseExpressionError("Expression is None")
+        self.expression = expression
+        self.tokens = self._TOKEN_RE.findall(expression)
+        if not self.tokens:
+            raise LicenseExpressionError("Empty license expression")
+        self.pos = 0
+        self.key = self._parse_or()
+        if self._peek() is not None:
+            raise LicenseExpressionError(f"Unexpected token: {self._peek()}")
+
+    def __eq__(self, other):
+        if not isinstance(other, LicenseExpression):
+            return NotImplemented
+        return self.key == other.key
+
+    def __hash__(self):
+        return hash(self.key)
+
+    def __repr__(self):
+        return f"{type(self).__name__}({self.expression!r})"
+
+    def _peek(self):
+        return self.tokens[self.pos] if self.pos < len(self.tokens) else None
+
+    def _advance(self):
+        tok = self._peek()
+        self.pos += 1
+        return tok
+
+    def _accept(self, keyword):
+        tok = self._peek()
+        if tok not in (None, "(", ")") and tok.upper() == keyword:
+            self.pos += 1
+            return True
+        return False
+
+    def _parse_or(self):
+        operands = [self._parse_and()]
+        while self._accept("OR"):
+            operands.append(self._parse_and())
+        return operands[0] if len(operands) == 1 else self._junction("or", operands)
+
+    def _parse_and(self):
+        operands = [self._parse_with()]
+        while self._accept("AND"):
+            operands.append(self._parse_with())
+        return operands[0] if len(operands) == 1 else self._junction("and", operands)
+
+    def _parse_with(self):
+        parenthesized = self._peek() == "("
+        node = self._parse_primary()
+        if self._accept("WITH"):
+            if parenthesized or not (isinstance(node, tuple) and node[0] == "license"):
+                raise LicenseExpressionError("WITH must follow a single license id")
+            exc = self._advance()
+            if exc in (None, "(", ")") or exc.upper() in self._KEYWORDS:
+                raise LicenseExpressionError("Expected an exception id after WITH")
+            node = ("with", node, exc.lower())
+        return node
+
+    def _parse_primary(self):
+        tok = self._advance()
+        if tok is None:
+            raise LicenseExpressionError("Unexpected end of expression")
+        if tok == "(":
+            node = self._parse_or()
+            if self._advance() != ")":
+                raise LicenseExpressionError("Missing closing parenthesis")
+            return node
+        if tok == ")":
+            raise LicenseExpressionError("Unexpected ')'")
+        if tok.upper() in self._KEYWORDS:
+            raise LicenseExpressionError(f"Unexpected operator: {tok}")
+        return ("license", tok.lower())
+
+    @staticmethod
+    def _junction(operator, operands):
+        """Combine operands under AND/OR: flatten same-operator nesting,
+        deduplicate, and collapse singletons -- yielding a
+        commutative/associative/idempotent key."""
+        keys = set()
+        for op in operands:
+            if isinstance(op, tuple) and op[0] == operator:
+                keys.update(op[1])
+            else:
+                keys.add(op)
+        if len(keys) == 1:
+            return next(iter(keys))
+        return (operator, tuple(sorted(keys)))
+
+
+def read_project_license(pyproject_path):
+    """Return the static SPDX string from [project].license, or raise."""
+    try:
+        with open(pyproject_path, "rb") as f:
+            data = tomllib.load(f)
+    except FileNotFoundError:
+        raise LicenseVerificationError(
+            f"{pyproject_path} not found; cannot verify the license."
+        )
+    except tomllib.TOMLDecodeError as e:
+        raise LicenseVerificationError(
+            f"{pyproject_path} is not valid TOML: {e}"
+        )
+
+    project = data.get("project", {})
+    # We don't expect the metadata to be malformed like that,
+    # but being defensive just to be sure
+    if not isinstance(project, dict):
+        raise LicenseVerificationError(
+            "project is not a table, it cannot be processed."
+        )
+    dynamic = project.get("dynamic", [])
+    if not isinstance(dynamic, list):
+        raise LicenseVerificationError(
+            "project.dynamic is not a list, it cannot be processed."
+        )
+    if "license" in dynamic:
+        raise LicenseVerificationError(
+            "project.license is declared dynamic, so it cannot be verified."
+        )
+    if "license" not in project:
+        raise LicenseVerificationError(
+            "project.license is not set in pyproject.toml."
+        )
+    license_value = project["license"]
+    if not isinstance(license_value, str):
+        raise LicenseVerificationError(
+            "project.license is not a string SPDX expression (found "
+            f"{type(license_value).__name__}). The deprecated table form "
+            "({text=…}/{file=…}) is not supported."
+        )
+    return license_value
+
+
+def verify(spec_license, pyproject_path="pyproject.toml"):
+    upstream = read_project_license(pyproject_path)
+    try:
+        match = LicenseExpression(spec_license) == LicenseExpression(upstream)
+    except LicenseExpressionError as e:
+        raise LicenseVerificationError(
+            f"Cannot parse a license expression: {e}"
+        )
+    if not match:
+        raise LicenseVerificationError(
+            f"Spec License tag {spec_license} does not match upstream "
+            f"project.license {upstream}."
+        )
+
+
+def argparser():
+    parser = argparse.ArgumentParser(prog='%pyproject_verify_license')
+    parser.add_argument('spec_license')
+    return parser
+
+
+def main(argv=None):
+    args = argparser().parse_args(argv)
+    try:
+        verify(args.spec_license)
+    except LicenseVerificationError as e:
+        print(f"ERROR: {e}", file=sys.stderr)
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main())

diff --git a/test_pyproject_getopt_consistency.py b/test_pyproject_getopt_consistency.py
index ef9967e..8ad45f1 100644
--- a/test_pyproject_getopt_consistency.py
+++ b/test_pyproject_getopt_consistency.py
@@ -23,6 +23,7 @@ MACROS_README = (
     "pyproject_check_import",
     "pyproject_extras_subpkg",
     "pyproject_save_files",
+    "pyproject_verify_license",
     "pyproject_wheel",
     "tox",
 )

diff --git a/test_pyproject_verify_license.py b/test_pyproject_verify_license.py
new file mode 100644
index 0000000..97c842a
--- /dev/null
+++ b/test_pyproject_verify_license.py
@@ -0,0 +1,191 @@
+import pytest
+
+from pyproject_verify_license import LicenseVerificationError, LicenseExpressionError
+from pyproject_verify_license import argparser, main, verify, LicenseExpression
+
+
+EQUIVALENT = [
+    ("MIT OR Apache-2.0", "Apache-2.0 OR MIT"),  # commutativity
+    ("(MIT AND BSD-3-Clause) AND ISC", "MIT AND (BSD-3-Clause AND ISC)"),  # associativity
+    ("MIT AND MIT", "MIT"),  # idempotence
+    ("mit or apache-2.0", "MIT OR Apache-2.0"),  # case-fold
+    ("(MIT OR BSD-3-Clause) AND MIT", "MIT AND (BSD-3-Clause OR MIT)"),  # nested mixed
+    ("Apache-2.0 WITH LLVM-exception", "apache-2.0 WITH llvm-exception"),  # WITH atomic
+    ("(MIT AND BSD-3-Clause) OR ISC", "MIT AND BSD-3-Clause OR ISC"),
+    ("(MIT WITH X)", "MIT WITH X"),
+]
+
+NOT_EQUIVALENT = [
+    ("MIT", "BSD-3-Clause"),  # different licenses
+    ("Apache-2.0 WITH LLVM-exception", "Apache-2.0"),  # WITH vs bare
+    ("GPL-2.0", "GPL-2.0+"),  # bare vs or-later
+    ("GPL-2.0+", "GPL-2.0-or-later"),  # no deprecated-spelling synonym resolution
+    ("LGPL-2.1", "LGPL-2.1-only"),  # no deprecated-spelling synonym resolution
+    ("bzip2-1.0.5", "bzip2-1.0.6"),  # no synonym resolution
+    ("(MIT OR BSD-3-Clause) AND MIT", "MIT"),  # no boolean absorption
+]
+
+INVALID = [
+    "MIT AND",  # dangling operator
+    "(MIT OR BSD-3-Clause",  # missing parenthesis
+    "(MIT OR BSD-3-Clause) WITH LLVM-exception",  # bad WITH left-hand side
+    "",  # empty
+    "   ",  # whitespace only
+    "MIT OR OR Apache-2.0",  # unexpected operator
+    "(MIT WITH X) WITH Y",
+    "(MIT) WITH X",
+]
+
+
+@pytest.mark.parametrize("expr1, expr2", EQUIVALENT)
+def test_equivalent(expr1, expr2):
+    assert (LicenseExpression(expr1) == LicenseExpression(expr2))
+
+
+@pytest.mark.parametrize("expr1, expr2", NOT_EQUIVALENT)
+def test_not_equivalent(expr1, expr2):
+    assert not (LicenseExpression(expr1) == LicenseExpression(expr2))
+
+
+@pytest.mark.parametrize("expression", INVALID)
+def test_invalid(expression):
+    with pytest.raises(LicenseExpressionError):
+        LicenseExpression(expression)
+
+
+def test_none_is_invalid():
+    with pytest.raises(LicenseExpressionError):
+        LicenseExpression(None)
+
+
+def write_pyproject(tmp_path, content):
+    path = tmp_path / "pyproject.toml"
+    path.write_text(content)
+    return path
+
+
+def test_missing_pyproject_toml(tmp_path):
+    with pytest.raises(LicenseVerificationError, match="not found"):
+        verify("MIT", tmp_path / "pyproject.toml")
+
+
+def test_invalid_toml(tmp_path):
+    path = write_pyproject(tmp_path, "this is not [ valid toml")
+    with pytest.raises(LicenseVerificationError, match="not valid TOML"):
+        verify("MIT", path)
+
+
+def test_missing_license_key(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+    """)
+    with pytest.raises(LicenseVerificationError, match="not set in pyproject.toml"):
+        verify("MIT", path)
+
+
+def test_dynamic_license(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        dynamic = ["license"]
+    """)
+    with pytest.raises(LicenseVerificationError, match="declared dynamic"):
+        verify("MIT", path)
+
+
+def test_non_string_license(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = {text = "MIT"}
+    """)
+    with pytest.raises(LicenseVerificationError, match="not a string SPDX expression"):
+        verify("MIT", path)
+
+
+def test_unparseable_license(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "MIT AND"
+    """)
+    with pytest.raises(LicenseVerificationError, match="Cannot parse a license expression"):
+        verify("MIT", path)
+
+
+def test_unparseable_spec_license(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "MIT"
+    """)
+    with pytest.raises(LicenseVerificationError, match="Cannot parse a license expression"):
+        verify("MIT AND", path)
+
+
+def test_mismatch(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "Apache-2.0"
+    """)
+    with pytest.raises(LicenseVerificationError, match="does not match upstream"):
+        verify("MIT", path)
+
+
+def test_success(tmp_path):
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "MIT AND BSD-3-Clause"
+    """)
+    verify("BSD-3-Clause and MIT", path)
+
+
+def test_gnu_family_deprecated_spelling_not_resolved(tmp_path):
+    # GPL-2.0+ and GPL-2.0-or-later are the same license, but this module does
+    # not resolve deprecated-spelling synonyms, so they are treated as a mismatch.
+    path = write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "GPL-2.0-or-later"
+    """)
+    with pytest.raises(LicenseVerificationError, match="does not match upstream"):
+        verify("GPL-2.0+", path)
+
+
+def test_cli_positional_argument_required():
+    with pytest.raises(SystemExit):
+        argparser().parse_args([])
+
+
+def test_cli_success(tmp_path, monkeypatch):
+    write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "MIT"
+    """)
+    monkeypatch.chdir(tmp_path)
+    assert main(["MIT"]) == 0
+
+
+def test_cli_failure(tmp_path, monkeypatch, capsys):
+    write_pyproject(tmp_path, """
+        [project]
+        name = "spam"
+        version = "1.0"
+        license = "Apache-2.0"
+    """)
+    monkeypatch.chdir(tmp_path)
+    assert main(["MIT"]) == 1
+    assert "does not match upstream" in capsys.readouterr().err

diff --git a/tests/verify-license-test.spec b/tests/verify-license-test.spec
new file mode 100644
index 0000000..0acc48e
--- /dev/null
+++ b/tests/verify-license-test.spec
@@ -0,0 +1,158 @@
+Name:           verify-license-test
+Version:        0
+Release:        0%{?dist}
+
+Summary:        ...
+# A fake license declaration for testing purposes
+License:        MIT AND BSD-3-Clause
+
+BuildRequires:  python3-devel
+BuildRequires:  pyproject-rpm-macros
+BuildRequires:  (python3dist(tomli) if python3-devel < 3.11)
+
+
+%description
+Fake spec file to test %%pyproject_verify_license
+
+
+%prep
+cat > pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+license = "MIT AND BSD-3-Clause"
+EOF
+
+# %%pyproject_verify_license only needs pyproject.toml, so it must work in %%prep
+%pyproject_verify_license
+
+mkdir equivalent
+# same license, written in a different (but semantically equivalent) way
+cat > equivalent/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+license = "bsd-3-clause and mit"
+EOF
+
+mkdir mismatch
+cat > mismatch/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+license = "Apache-2.0"
+EOF
+
+mkdir dynamic
+cat > dynamic/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+dynamic = ["license"]
+EOF
+
+mkdir no-license
+cat > no-license/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+EOF
+
+mkdir table-license
+cat > table-license/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+license = {text = "MIT AND BSD-3-Clause"}
+EOF
+
+mkdir bad-expression
+cat > bad-expression/pyproject.toml <<EOF
+[project]
+name = "verify-license-test"
+version = "0"
+license = "MIT AND"
+EOF
+
+mkdir broken
+cat > broken/pyproject.toml <<EOF
+this is not valid [ toml
+EOF
+
+# an existing directory with no pyproject.toml at all
+mkdir no-pyproject
+
+
+%generate_buildrequires
+%pyproject_buildrequires --no-use-build-system
+
+
+%check
+# Assert a failing macro aborts the build by running it in a fresh `sh -e`.
+# A subshell or `if`/`&&` condition would disable `set -e`, letting the macro's
+# trailing popd mask the failure.
+assert_check_fails() {
+    if sh -e; then
+        echo "ERROR: expected %%pyproject_verify_license to fail the build" >&2
+        exit 1
+    fi
+}
+
+# matching license succeeds
+%pyproject_verify_license
+
+# case/order-insensitive equivalent expression succeeds
+%pyproject_verify_license --directory equivalent
+
+# --directory must restore the original CWD afterwards (pushd/popd are paired)
+_before_dir=$(pwd -P)
+%pyproject_verify_license --directory equivalent
+test "$(pwd -P)" = "$_before_dir"
+
+# mismatched license fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory mismatch}
+EOF
+
+# an explicit positional argument overrides the spec License: tag and is compared instead
+%pyproject_verify_license --directory mismatch Apache-2.0
+
+# ... and still fails the build when it doesn't match
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory equivalent Apache-2.0}
+EOF
+
+# dynamic license fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory dynamic}
+EOF
+
+# missing license key fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory no-license}
+EOF
+
+# non-string (deprecated table form) license fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory table-license}
+EOF
+
+# unparseable license expression fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory bad-expression}
+EOF
+
+# unparseable license expression given as argument fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory equivalent bsd-3-clause and}
+EOF
+
+# invalid TOML fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory broken}
+EOF
+
+# missing pyproject.toml fails the build
+assert_check_fails <<'EOF'
+%{pyproject_verify_license --directory no-pyproject}
+EOF

                 reply	other threads:[~2026-10-13  9:29 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=179188377656.1.10107680895231089956.rpms-pyproject-rpm-macros-0eeab9e54c27@fedoraproject.org \
    --to=ksurma@redhat.com \
    --cc=git-commits@fedoraproject.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox