diff mbox series

[7/7] oeqa/selftest/oelib: add tests for license_finder

Message ID 20261201034910.25521-8-tim.orling@konsulko.com
State New
Headers show
Series go-mod-update-modules: identify licenses with licensecheck | expand

Commit Message

Tim Orling Dec. 1, 2026, 3:49 a.m. UTC
Cover files without license text, the license files of the nearest
directory, and how licensecheck results become SPDX expressions.
scan_licenses() is tested with a stand-in for licensecheck, so no build
is needed.

AI-Generated: Claude Opus 5.5
Signed-off-by: Tim Orling <tim.orling@konsulko.com>
---
 .../selftest/cases/oelib/license_finder.py    | 146 ++++++++++++++++++
 1 file changed, 146 insertions(+)
 create mode 100644 meta/lib/oeqa/selftest/cases/oelib/license_finder.py
diff mbox series

Patch

diff --git a/meta/lib/oeqa/selftest/cases/oelib/license_finder.py b/meta/lib/oeqa/selftest/cases/oelib/license_finder.py
new file mode 100644
index 0000000000..866ce8c785
--- /dev/null
+++ b/meta/lib/oeqa/selftest/cases/oelib/license_finder.py
@@ -0,0 +1,146 @@ 
+#
+# Copyright OpenEmbedded Contributors
+#
+# SPDX-License-Identifier: MIT
+#
+
+import json
+import os
+import stat
+import sys
+import tempfile
+from unittest.case import TestCase
+
+import oe.license_finder as lf
+
+COMMON_LICENSE_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..",
+                                  "files", "common-licenses")
+
+
+class Datastore:
+    """Just enough of a datastore for license_finder."""
+    def __init__(self, **values):
+        self.values = values
+
+    def getVar(self, name, expand=True):
+        return self.values.get(name)
+
+    def expand(self, s):
+        return s
+
+
+def datastore():
+    return Datastore(COMMON_LICENSE_DIR=os.path.normpath(COMMON_LICENSE_DIR), LICENSE_PATH="", BBPATH="")
+
+
+class TempDirTestCase(TestCase):
+    def setUp(self):
+        self.tmp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.tmp.cleanup)
+
+    def write(self, name, text):
+        path = os.path.join(self.tmp.name, name)
+        os.makedirs(os.path.dirname(path), exist_ok=True)
+        with open(path, "w") as f:
+            f.write(text)
+        return path
+
+
+class TestCrunch(TempDirTestCase):
+    def test_no_license_text(self):
+        # Only a copyright line, like common-licenses/Proprietary only a title
+        path = self.write("COPYRIGHT", "Copyright (c) 2026 Example Corp.\nAll rights reserved.\n")
+        self.assertIsNone(lf._crunch_license(path))
+        self.assertIsNone(lf._crunch_license(os.path.join(COMMON_LICENSE_DIR, "Proprietary")))
+        self.assertIsNotNone(lf._crunch_license(os.path.join(COMMON_LICENSE_DIR, "MIT")))
+
+    def test_no_match_on_empty_text(self):
+        path = self.write("COPYRIGHT", "Copyright (c) 2026 Example Corp.\n")
+        self.assertNotIn(None, lf._crunch_known_licenses(datastore()))
+        [(node, _, _)] = lf.match_licenses([path], self.tmp.name, datastore())
+        self.assertEqual(node.to_string(), "Unknown")
+
+
+class TestFindLicenseFiles(TempDirTestCase):
+    def test_nearest_directory(self):
+        # A module with its own license and one for code taken from Go
+        self.write("mod/LICENSE", "MIT\n")
+        self.write("mod/GO_LICENSE", "BSD-3-Clause\n")
+        self.write("mod/pkg/file.go", "package pkg\n")
+        top = os.path.join(self.tmp.name, "mod")
+        found = lf.find_license_files(top, True, os.path.join(top, "pkg"))
+        self.assertEqual(sorted(os.path.basename(f) for f in found), ["GO_LICENSE", "LICENSE"])
+
+    def test_nearest_directory_only(self):
+        self.write("mod/LICENSE", "MIT\n")
+        self.write("mod/pkg/LICENSE", "BSD-3-Clause\n")
+        top = os.path.join(self.tmp.name, "mod")
+        found = lf.find_license_files(top, True, os.path.join(top, "pkg"))
+        self.assertEqual(found, [os.path.join(top, "pkg", "LICENSE")])
+
+
+class TestLicensecheckExpression(TestCase):
+    available = {"Apache-2.0", "BSD-3-Clause", "GPL-2.0-only", "GPL-2.0-or-later", "MIT", "MPL-2.0"}
+
+    def expression(self, percent, ids, text=""):
+        result = {"percent": percent,
+                  "matches": [{"id": i, "start": 0, "end": len(text)} for i in ids]}
+        return lf._licensecheck_expression(result, text, self.available, 80.0)[0]
+
+    def test_choice(self):
+        # As in github.com/spdx/tools-golang, the choice spans two lines
+        text = ("may be used, at your option,\nunder either:\n* Apache\n"
+                "* GPL version 2, or (at your option) any later version")
+        self.assertEqual(self.expression(99, ["Apache-2.0", "GPL-2.0"], text),
+                         "Apache-2.0 OR GPL-2.0-or-later")
+
+    def test_gpl_later_is_no_choice(self):
+        text = "or (at your option) any later version"
+        self.assertEqual(self.expression(95, ["MIT", "GPL-2.0"], text), "GPL-2.0-or-later AND MIT")
+
+    def test_gpl_only(self):
+        self.assertEqual(self.expression(99, ["GPL-2.0"], "version 2 of the License"), "GPL-2.0-only")
+
+    def test_partial_coverage(self):
+        # A list of third-party licenses: all of them, never a choice
+        text = "licensed under either of the licenses below"
+        self.assertEqual(self.expression(74, ["MIT", "Apache-2.0", "MPL-2.0"], text),
+                         "Apache-2.0 AND MIT AND MPL-2.0")
+
+    def test_no_text(self):
+        self.assertIsNone(self.expression(95, ["Zlib"]))
+        self.assertIsNone(self.expression(0, []))
+
+    def test_urls_are_not_licenses(self):
+        result = {"percent": 90, "matches": [{"id": "MIT", "start": 0, "end": 10, "url": True}]}
+        self.assertIsNone(lf._licensecheck_expression(result, "", self.available, 80.0)[0])
+
+
+class TestScanLicenses(TempDirTestCase):
+    def licensecheck(self):
+        """A licensecheck that finds nothing, as for texts it does not know."""
+        path = self.write("licensecheck", "#!%s\nimport json, sys\n"
+                          "for f in sys.argv[1:]:\n"
+                          "    print(json.dumps({'file': f, 'percent': 0, 'matches': []}))\n"
+                          % sys.executable)
+        os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
+        return path
+
+    def scan(self, text):
+        path = self.write("LICENSE", text)
+        node, _ = lf.scan_licenses([path], self.licensecheck(), datastore())[path]
+        return node.to_string() if node else None
+
+    def test_spdx_header(self):
+        self.assertEqual(self.scan("SPDX-License-Identifier: Apache-2.0 OR MIT\n"), "Apache-2.0 OR MIT")
+        self.assertEqual(self.scan("`SPDX-License-Identifier: MPL-2.0 AND BSD-3-Clause`\n"),
+                         "MPL-2.0 AND BSD-3-Clause")
+
+    def test_public_domain(self):
+        self.assertEqual(self.scan("All of the code has been dedicated to the public domain.\n"),
+                         "LicenseRef-PD")
+        self.assertEqual(self.scan("All these files have been put\ninto the public domain.\n"),
+                         "LicenseRef-PD")
+
+    def test_unknown(self):
+        self.assertIsNone(self.scan("Copyright (c) Example. See LICENSE for the full license text.\n"))