diff --git a/application_checks.py b/application_checks.py index f20102d..06b2fe1 100644 --- a/application_checks.py +++ b/application_checks.py @@ -2,6 +2,7 @@ import json import sys +import traceback def django_template(): @@ -91,8 +92,10 @@ def numpy_array(): sys.path.insert(0, sys.argv[2]) try: CHECKS[sys.argv[1]]() - except Exception as exc: - outcome = {"status": "error", "detail": f"{type(exc).__name__}: {exc}"} + except Exception: + # The end of the traceback, with the wheel directory shortened. + lines = traceback.format_exc().replace(sys.argv[2], "").strip().splitlines() + outcome = {"status": "error", "detail": "\n".join(lines[-15:])} else: outcome = {"status": "passed", "detail": ""} print(json.dumps(outcome)) diff --git a/applications.py b/applications.py index 2443c76..b283183 100644 --- a/applications.py +++ b/applications.py @@ -1,6 +1,7 @@ """Provision pinned third-party wheels and collect application results.""" import hashlib +import inspect import json import platform import shutil @@ -9,6 +10,8 @@ from urllib.request import urlopen from zipfile import BadZipFile, ZipFile +from application_checks import CHECKS as SCENARIOS + @dataclass(frozen=True) class Wheel: @@ -108,5 +111,6 @@ def application_results(executables, directory, invoke, numpy): except ValueError: print(f"{runtime} returned unreadable output for {name}") outcomes[runtime] = {"status": "blocked", "detail": ""} - results.append({"id": name, "package": package, "version": version, "outcomes": outcomes}) + results.append({"id": name, "package": package, "version": version, + "code": inspect.getsource(SCENARIOS[name]), "outcomes": outcomes}) return results diff --git a/dashboard.py b/dashboard.py index 0d2cbf6..1b1cba4 100644 --- a/dashboard.py +++ b/dashboard.py @@ -276,7 +276,7 @@ def render_applications(report, copy): fragment = anchor("scenario", row["id"]) cells = [ f'{permalink(fragment, copy)}{escape(row["package"])} {escape(row["version"])}' - f'{escape(title)}' + f'{escape(title)}{code_details(row.get("code"), copy)}' ] cells.extend(f'{detailed_badge(row["outcomes"][runtime["id"]], copy)}' for runtime in runtimes) listing.append(f'' + "".join(cells) + "") @@ -317,6 +317,13 @@ def package_cell(outcome, copy): f'{escape(copy["blockerVia"])} {escape(blocker["name"])}') +def code_details(code, copy): + """The code of an application scenario, folded under its name.""" + if not code: + return "" + return f'
{escape(copy["scenarioCode"])}
{escape(code)}
' + + def check_details(row, copy): """The functional check a package runs after its import, when it has one.""" if not row.get("check"): diff --git a/dashboard_content.py b/dashboard_content.py index c290002..c73e1b0 100644 --- a/dashboard_content.py +++ b/dashboard_content.py @@ -26,6 +26,7 @@ "importOnly": "Import only", "noCheck": "Import only: no functional check yet", "checkTitle": "Functional check", + "scenarioCode": "Code", "checkLevels": "{functional} with a functional check ยท {imported} import only", "copyReproduction": "Copy to reproduce", "copied": "Copied", diff --git a/package_bench.py b/package_bench.py index 246b9b8..0dfd174 100644 --- a/package_bench.py +++ b/package_bench.py @@ -73,8 +73,9 @@ raise ImportError(f"{name} resolved outside the package directory") shipped = getattr(module, "__version__", "") bundled = f"The interpreter ships its own {name} {shipped}: this release installs only its metadata." -except Exception as exc: - outcome = {"status": "importError", "detail": f"{type(exc).__name__}: {exc}"} +except Exception: + lines = traceback.format_exc().strip().splitlines() + outcome = {"status": "importError", "detail": "\\n".join(lines[-15:])} else: outcome = {"status": "passed", "detail": bundled.replace(" ", " "), "level": "functional" if check else "import"} if check: @@ -82,7 +83,7 @@ exec(compile(check, "", "exec"), {"__name__": "__check__"}) except Exception: lines = traceback.format_exc().strip().splitlines() - outcome = {"status": "functionError", "detail": "\\n".join(lines[-6:]), "level": "functional"} + outcome = {"status": "functionError", "detail": "\\n".join(lines[-15:]), "level": "functional"} print(json.dumps(outcome)) """ diff --git a/tests/test_dashboard.py b/tests/test_dashboard.py index 567144e..f5fac70 100644 --- a/tests/test_dashboard.py +++ b/tests/test_dashboard.py @@ -54,6 +54,7 @@ def report(**overrides): }], "applications": [{ "id": "numpy-array", "package": "NumPy", "version": "2.4.4", + "code": "def numpy_array():\n import numpy as np\n", "outcomes": {"cpython": passed(), "pypy": {"status": "otherAbi", "detail": "loads pp80"}}, }], @@ -101,6 +102,10 @@ def test_the_former_french_page_redirects_to_english(self): pages, _ = render(report()) self.assertIn('location.replace("../" + location.search + location.hash)', pages["fr"]) + def test_shows_the_code_of_each_scenario(self): + pages, _ = render(report()) + self.assertIn(f'{COPY["scenarioCode"]}
def numpy_array():', pages["en"])
+
     def test_accepts_reports_without_optional_measurements(self):
         legacy = report(applications=[], packages=None)
         pages, _ = render(legacy)
diff --git a/tests/test_package_bench.py b/tests/test_package_bench.py
index 169f318..b3c07fe 100644
--- a/tests/test_package_bench.py
+++ b/tests/test_package_bench.py
@@ -291,6 +291,23 @@ def test_a_failing_check_is_a_functional_error(self):
         self.assertEqual(outcome["status"], "functionError")
         self.assertIn("AssertionError: wrong value", outcome["detail"])
 
+    def test_an_import_error_keeps_its_traceback(self):
+        import json
+        import subprocess
+        import sys
+        with TemporaryDirectory() as site:
+            Path(site, "demo").mkdir()
+            Path(site, "demo", "__init__.py").write_text("raise RuntimeError('broken on import')\n", encoding="utf-8")
+            Path(site, "demo-1.0.dist-info").mkdir()
+            Path(site, "demo-1.0.dist-info", "METADATA").write_text(
+                "Metadata-Version: 2.1\nName: demo\nVersion: 1.0\n", encoding="utf-8")
+            completed = subprocess.run([sys.executable, "-I", "-c", package_bench.IMPORT_PACKAGE, site, "demo", "1.0",
+                                        "demo", ""], capture_output=True, text=True, timeout=60)
+        outcome = json.loads(completed.stdout.splitlines()[-1])
+        self.assertEqual(outcome["status"], "importError")
+        self.assertIn("Traceback (most recent call last)", outcome["detail"])
+        self.assertIn("RuntimeError: broken on import", outcome["detail"])
+
     def test_every_check_names_a_ranked_project(self):
         import json
         from smoke import SMOKE