diff --git a/.github/workflows/odh-python-gates.yml b/.github/workflows/odh-python-gates.yml new file mode 100644 index 0000000000..e808fa688f --- /dev/null +++ b/.github/workflows/odh-python-gates.yml @@ -0,0 +1,49 @@ +name: ODH Python Gate Checks + +on: + pull_request: + branches: [main, master] + paths: + - ".github/workflows/odh-python-gates.yml" + - "e2e/python/**" + - "e2e/rust/tests/odh/tier_plan.py" + - "e2e/rust/tests/odh/tiers.toml" + - "mise.toml" + - "mise.lock" + - "odh/python-gates.toml" + - "odh/requirements.in" + - "odh/requirements.txt" + - "odh/scripts/**" + - "proto/**" + - "python/**" + - "pyproject.toml" + - "tasks/python.toml" + - "tasks/test-odh.toml" + - "uv.lock" + workflow_dispatch: + +jobs: + test: + name: ODH Python gate tooling + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + # This check uses Python and uv only. Avoid installing the complete + # repository toolchain (Rust, Docker helpers, Helm, etc.), which is + # unrelated to the gate tooling and can time out on hosted runners. + - uses: jdx/mise-action@e6a8b3978addb5a52f2b4cd9d91eafa7f0ab959d # v4.2.0 + with: + install: false + experimental: true + + - name: Install Python tools + run: mise install --locked python uv + + - name: Test ODH Python gate tooling + run: mise run --skip-tools test:odh-python-gates diff --git a/deploy/konflux/e2e-odh/README.md b/deploy/konflux/e2e-odh/README.md index 038cc01da7..8dc888f8bf 100644 --- a/deploy/konflux/e2e-odh/README.md +++ b/deploy/konflux/e2e-odh/README.md @@ -9,11 +9,13 @@ by sandbox lifecycle tests, and Git for repository workloads. At runtime, the image entrypoint reads the fork-local tier plan, deploys each phase's gateway mode through the shared Quay deployment script, runs the -phase-specific nextest selection from the precompiled archive, and tears down -that deployment before moving to the next phase. Local `mise run e2e:odh*` -tasks use the same plan, entrypoint, and deployment path. Tier 2, `odh`, and -`full` run shared mode followed by managed-workspace mode; each logical tier -runs image provenance once in the shared phase. The entrypoint preserves +phase's configured runners (the precompiled nextest selection and, when +selected, the Python gateway E2E), and tears down that deployment before moving +to the next phase. Local `mise run e2e:odh*` tasks use the same plan, +entrypoint, and deployment path. Tier 2, `odh`, and `full` run shared mode +followed by managed-workspace mode; Tier 2's shared phase also runs the Python +gateway E2E. Each logical tier runs image provenance once in the shared phase. +The entrypoint preserves cleanup on failures and signals, continues after a test-phase failure, and merges the ordered JUnit files into one `e2e-odh--xunit.xml` for Jenkins discovery plus `e2e-odh-.html`. Phase reports remain available as @@ -47,8 +49,9 @@ take precedence. See [runtime image selection](../../../e2e/rust/tests/odh/READM for selection rules, permissions, and fallback behavior. The image also carries a fully prefetched Python 3.11 test environment and -generated protobuf bindings, so later named Python test modes can execute -without runtime dependency downloads. +generated protobuf bindings. The `python` entrypoint mode uses that environment +to run the supported upstream Python gateway E2E on OpenShift without runtime +dependency downloads. Konflux onboarding must use the `linux-m2xlarge/*` builders and retain the three Hermeto prefetch inputs: Cargo at `.` and `e2e/rust`, plus the locked diff --git a/e2e/rust/tests/odh/AGENTS.md b/e2e/rust/tests/odh/AGENTS.md index 232e5f73e7..b6422ae81d 100644 --- a/e2e/rust/tests/odh/AGENTS.md +++ b/e2e/rust/tests/odh/AGENTS.md @@ -82,6 +82,10 @@ a rule and the README disagree, fix the drift rather than guessing. - Add tests by creating a `.rs` file under the right tier and a `mod` line in that tier's `mod.rs`, and map upstream binaries/filters in `tiers.toml`. Do not add new one-off `mise` tasks for individual test lanes. +- The sole narrow exception is `e2e:odh:python`: it is the plan-backed, + full upstream Python gateway-E2E suite, not an individual test lane. It + must continue to use the same tier-plan resolver and shared entrypoint as + every other ODH task. - Keep the standard tier entry points (`e2e:odh:smoke|tier1|tier2|tier3`, `e2e:odh`, and `e2e:odh:full`) stable. The OpenShift AI Shift-Left pipeline consumes those tiers as diff --git a/e2e/rust/tests/odh/README.md b/e2e/rust/tests/odh/README.md index c9eb2bf702..c1958361d7 100644 --- a/e2e/rust/tests/odh/README.md +++ b/e2e/rust/tests/odh/README.md @@ -203,10 +203,34 @@ context you happen to have active elsewhere. This means: | `mise run e2e:odh:full` | All upstream e2e + e2e-kubernetes + ODH tests (see caveat below), including image provenance | | `mise run e2e:odh:smoke` | Smoke tier: mapped upstream tests + ODH `smoke::` (includes image provenance) | | `mise run e2e:odh:tier1` | Tier 1: mapped upstream tests + ODH `tier1::` + image provenance | -| `mise run e2e:odh:tier2` | Tier 2: mapped upstream tests + ODH `tier2::` + image provenance | +| `mise run e2e:odh:tier2` | Tier 2: mapped upstream tests + ODH `tier2::` + supported Python gateway E2E + image provenance | | `mise run e2e:odh:tier3` | Tier 3: mapped upstream tests + ODH `tier3::` + image provenance | +| `mise run e2e:odh:python` | Supported upstream Python gateway E2E in the shared OpenShift mode | | `cargo nextest run --config-file "$PWD/.config/nextest.toml" --tool-config-file "odh:$PWD/e2e/rust/tests/odh/nextest.toml" --profile e2e-odh --manifest-path e2e/rust/Cargo.toml --features e2e-odh --test odh -E 'test(=module::test_name)'` | A single ODH test function | +### Python gateway E2E + +`e2e:odh:python` reuses the public ODH entrypoint: it deploys the shared +OpenShift gateway, imports the example provider profiles, runs upstream +`e2e/python`, and tears the deployment down. It writes the phase-scoped report +`e2e-odh-python-shared-python.xml` and merged `e2e-odh-python-xunit.xml` plus HTML +companion in `results/`. `odh/python-gates.toml` contains the exact tests that cannot run +on the current OpenShift lane (host-only fixtures, unrestricted egress, the +missing Python workload image, and the pending upstream deletion-timeout +decision). It does not run the Rust image-provenance check. Gate entries are +collection-validated so an upstream rename cannot +silently leave a stale exclusion. The phase also fails when the JUnit report +shows no executed test case, so a suite that skips every collected case cannot +report success. The Python tests also run as part of the tier2 shared phase, +riding the same gateway deployment. + +The public `mise` tasks that include the Python runner (`e2e:odh:python` and +`e2e:odh:tier2`) provision `python:dev` first. If invoking +`odh/scripts/e2e-odh-entrypoint.sh` directly for one of those plan-backed +tiers, prepare that environment yourself with `mise run python:dev`; this is +intentional so the entrypoint fails before deploying when the test interpreter +is unavailable. + Example, running the Smoke tier against a real cluster: ```bash @@ -306,10 +330,10 @@ mode. Phase JUnit files are named `e2e-odh--.xml`; the entrypoint merges them into `e2e-odh--xunit.xml` for Jenkins discovery and `e2e-odh-.html` in `results/`. -### Every `e2e:odh*` task runs the image provenance check +### Image provenance runs in every nextest-backed tier `smoke::image_provenance::test_sandbox_gateway_supervisor_images` runs in the -shared phase of every logical tier. An empty phase fails instead of passing +shared phase of every nextest-backed tier. An empty phase fails instead of passing with an empty report. ## Image provenance verification @@ -413,7 +437,7 @@ locally with: The local build tags the image as `odh-openshell-e2e`. -The image accepts `smoke`, `tier1`, `tier2`, `tier3`, `odh`, or `full` +The image accepts `smoke`, `tier1`, `tier2`, `tier3`, `odh`, `full`, or `python` as its first argument; `smoke` is the default. The Shift-Left job mounts cluster credentials and a writable report directory, then passes environment variables through `--env-file`: diff --git a/e2e/rust/tests/odh/tier_plan.py b/e2e/rust/tests/odh/tier_plan.py index 8db32d1a92..251d61a3dd 100644 --- a/e2e/rust/tests/odh/tier_plan.py +++ b/e2e/rust/tests/odh/tier_plan.py @@ -16,6 +16,9 @@ GLOBAL_EXCLUSIONS_KEY = "global_test_exclusions" _BINARY = re.compile(r"[A-Za-z0-9_-]+\Z") _FILTER = re.compile(r"[A-Za-z0-9_:]+\Z") +# The runners a phase may execute, in order. "nextest" runs the Rust test +# selection; "python" runs the upstream Python gateway E2E suite. +_RUNNERS = frozenset({"nextest", "python"}) def _validate_mode(mode_name: str, mode: dict) -> dict: @@ -76,6 +79,7 @@ def load_plan(tier: str, plan_path: Path = PLAN_FILE) -> dict: if name in modes and name != base_mode ) names: set[str] = set() + report_paths: set[str] = set() resolved = [] for phase_name, phase_config in phase_tables: phase = phase_config @@ -87,6 +91,20 @@ def load_plan(tier: str, plan_path: Path = PLAN_FILE) -> dict: names.add(name) if not isinstance(mode_name, str) or mode_name not in modes: raise ValueError(f"unknown mode {mode_name!r} in tier {tier!r}") + runners = phase.get("runners", ["nextest"]) + if not isinstance(runners, list) or not runners or any( + not isinstance(runner, str) or runner not in _RUNNERS for runner in runners + ): + raise ValueError(f"invalid runner in phase {name!r}; known: {', '.join(sorted(_RUNNERS))}") + if len(set(runners)) != len(runners): + raise ValueError(f"duplicate runner in phase {name!r}") + for runner in runners: + report_path = f"{name}{'-python' if runner == 'python' else ''}" + if report_path in report_paths: + raise ValueError( + f"duplicate derived report path for phase {name!r}: {report_path!r}" + ) + report_paths.add(report_path) binaries = phase.get("upstream_tests", []) exclusions = phase.get("upstream_test_exclusions", {}) excluded_binaries = phase.get("excluded_binaries", []) @@ -115,11 +133,31 @@ def load_plan(tier: str, plan_path: Path = PLAN_FILE) -> dict: for flag in ("all_binaries", "all_odh_tests", "include_image_provenance"): if flag in phase and not isinstance(phase[flag], bool): raise ValueError(f"phase {name!r} {flag} must be a boolean") - if not binaries and not odh_filter and not phase.get("all_binaries") and not phase.get("all_odh_tests") and not phase.get("odh_only") and not phase.get("include_image_provenance"): + has_nextest_selection = ( + binaries + or exclusions + or excluded_binaries + or odh_filter + or excluded_odh_filters + or any( + phase.get(flag, False) + for flag in ( + "all_binaries", + "all_odh_tests", + "odh_only", + "include_image_provenance", + ) + ) + ) + if "nextest" not in runners and has_nextest_selection: + raise ValueError( + f"phase {name!r} declares a nextest selection but runners omit nextest" + ) + if "nextest" in runners and not binaries and not odh_filter and not phase.get("all_binaries") and not phase.get("all_odh_tests") and not phase.get("odh_only") and not phase.get("include_image_provenance"): raise ValueError(f"phase {name!r} selects no tests") if "odh_only" in phase and not isinstance(phase["odh_only"], bool): raise ValueError(f"phase {name!r} odh_only must be a boolean") - resolved.append({**phase, "name": name, "mode": mode_name, "upstream_tests": binaries, + resolved.append({**phase, "name": name, "mode": mode_name, "runners": runners, "upstream_tests": binaries, "upstream_test_exclusions": exclusions, "odh_filter": odh_filter, "global_test_exclusions": global_exclusions, "all_odh_tests": phase.get("all_odh_tests", phase.get("odh_only", False)), @@ -147,6 +185,8 @@ def load_mode(mode_name: str, plan_path: Path = PLAN_FILE) -> dict: def nextest_filter(phase: dict) -> str: + if "nextest" not in phase.get("runners", ["nextest"]): + raise ValueError(f"phase {phase['name']!r} runs no nextest selection") terms = [] odh_filter = phase["odh_filter"] if odh_filter: diff --git a/e2e/rust/tests/odh/tiers.toml b/e2e/rust/tests/odh/tiers.toml index 5d067c22f8..711ab764bc 100644 --- a/e2e/rust/tests/odh/tiers.toml +++ b/e2e/rust/tests/odh/tiers.toml @@ -45,6 +45,10 @@ description = "Medium/low priority positive tests" upstream_tests = ["workspace_lifecycle"] odh_filter = "tier2::" excluded_odh_filters = ["tier2::managed_identity::"] +# The Python gateway suite rides tier2's shared deployment: the DevTestOps +# CI only runs smoke through tier3, so the Python lane would never execute +# in CI unless it shares a tier. +runners = ["nextest", "python"] [tier2.managed] description = "Managed-workspace lifecycle tests" @@ -56,6 +60,13 @@ description = "Negative and destructive tests" upstream_tests = [] odh_filter = "tier3::" +[python] +description = "Supported upstream Python gateway E2E on OpenShift" +# Single-phase tier over the shared gateway mode; the python runner writes +# the e2e-odh-python-shared-python.xml phase report. Gate the unsupported tests +# through odh/python-gates.toml (validated strictly before deployment). +runners = ["python"] + [odh] description = "All ODH-specific tests" odh_only = true diff --git a/e2e/rust/tests/workspace_namespace_managed.rs b/e2e/rust/tests/workspace_namespace_managed.rs index a8f97cf5ef..0c65930f00 100644 --- a/e2e/rust/tests/workspace_namespace_managed.rs +++ b/e2e/rust/tests/workspace_namespace_managed.rs @@ -227,9 +227,10 @@ async fn managed_creates_namespace_with_labels() { "openshell" ); assert_eq!(policy["spec"]["ingress"][0]["ports"][0]["port"], 2222); + let gateway_namespace = std::env::var("NAMESPACE").unwrap_or_else(|_| "openshell".into()); assert_eq!( policy["spec"]["ingress"][0]["from"][0]["namespaceSelector"]["matchLabels"]["kubernetes.io/metadata.name"], - "openshell" + gateway_namespace ); assert!( policy["spec"]["ingress"][0]["from"][0]["podSelector"]["matchLabels"] diff --git a/mise.toml b/mise.toml index c439847388..1e5ead83ff 100644 --- a/mise.toml +++ b/mise.toml @@ -74,7 +74,7 @@ DOCKER_BUILDKIT = "1" [vars] # Python paths to include in formatting/linting -python_paths = "python/ tasks/scripts/*.py e2e/mcp-conformance/*.py deploy/sbom/*.py deploy/konflux/e2e-odh/*.py" +python_paths = "python/ tasks/scripts/*.py e2e/mcp-conformance/*.py deploy/sbom/*.py deploy/konflux/e2e-odh/*.py odh/scripts/*.py" [task_config] includes = ["tasks/*.toml"] diff --git a/odh/python-gates.toml b/odh/python-gates.toml new file mode 100644 index 0000000000..0effed9923 --- /dev/null +++ b/odh/python-gates.toml @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Upstream Python gateway E2E that cannot yet run on the downstream OpenShift +# lane. Each entry is an exact upstream node ID (without parametrization), so +# an upstream rename or removal fails the entrypoint's collection preflight. +# OIDC tests retain their own upstream skip conditions and are owned by the +# separate downstream Keycloak/OIDC lane. + +[[gate]] +category = "docker-host" +reason = "requires a fake inference endpoint on the test host, which sandbox pods cannot reach through host.openshell.internal" +tests = [ + "e2e/python/test_sandbox_providers.py::test_imported_openai_profile_allows_native_endpoint_with_attached_provider", + "e2e/python/test_sandbox_providers.py::test_imported_anthropic_profile_allows_native_endpoint_with_attached_provider", +] + +[[gate]] +category = "egress" +reason = "requires sandbox egress to PyPI or GitHub, which downstream CI clusters do not guarantee" +tests = [ + "e2e/python/test_sandbox_venv.py::test_pip_install_in_sandbox", + "e2e/python/test_sandbox_venv.py::test_uv_pip_install_in_sandbox", + "e2e/python/test_sandbox_venv.py::test_uv_run_with_ephemeral_dependency", + "e2e/python/test_sandbox_providers.py::test_github_provider_allows_https_git_clone", +] + +[[gate]] +category = "workload-image" +reason = "requires Python or /sandbox/.venv in the sandbox; the current OpenShift workload is Ubuntu, while upstream builds e2e/python/Dockerfile.workload locally" +tests = [ + "e2e/python/test_sandbox_exec_python.py::test_exec_python_accepts_bound_methods", + "e2e/python/test_sandbox_exec_python.py::test_exec_python_surfaces_callable_errors", + "e2e/python/test_sandbox_landlock.py::test_landlock_blocks_write_to_read_only_path", + "e2e/python/test_sandbox_landlock.py::test_landlock_allows_write_to_read_write_path", + "e2e/python/test_sandbox_landlock.py::test_landlock_allows_read_on_read_only_path", + "e2e/python/test_sandbox_landlock.py::test_landlock_blocks_access_outside_policy", + "e2e/python/test_sandbox_api.py::test_sandbox_api_crud_and_exec", + "e2e/python/test_sandbox_policy.py::test_policy_applies_to_exec_commands", + "e2e/python/test_sandbox_policy.py::test_transparent_tcp_policy_denies_unauthorized_connections", + "e2e/python/test_sandbox_providers.py::test_provider_credentials_available_as_env_vars", + "e2e/python/test_sandbox_providers.py::test_endpointless_profile_credentials_fail_closed_without_policy_binding", + "e2e/python/test_sandbox_providers.py::test_nvidia_provider_injects_nvidia_api_key_env_var", + "e2e/python/test_sandbox_providers.py::test_endpointless_profile_credentials_use_explicit_policy_binding", + "e2e/python/test_sandbox_providers.py::test_attach_detach_updates_credentials_for_later_exec_launches", + "e2e/python/test_sandbox_venv.py::test_sandbox_venv_in_path", + "e2e/python/test_sandbox_providers.py::test_google_metadata_sdk_discovery", +] + +[[gate]] +category = "workload-fixture" +reason = "upstream Python E2E builds and selects e2e/python/Dockerfile.workload; this OpenShift lane uses the product-default Ubuntu workload, so these no-image sandbox tests never reach Ready" +tests = [ + "e2e/python/test_exec_admission.py::test_exec_request_timeout_keeps_launch_unresolved", + "e2e/python/test_sandbox_api.py::test_mutation_replay_preserves_sandbox_lifecycle_and_replacement", +] + +[[gate]] +category = "lifecycle-timeout" +reason = "the shared Python fixture's 30-second delete RPC deadline is shorter than the Kubernetes driver's bounded Pod-termination wait; an upstream fixture-timeout correction is being validated before these tests are re-enabled" +tests = [ + "e2e/python/test_exec_admission.py::test_exec_request_id_never_relaunches_or_replays_output", + "e2e/python/test_exec_admission.py::test_exec_client_cancellation_does_not_clear_launch_admission", + "e2e/python/test_policy_validation.py::test_update_policy_rejects_immutable_fields", + "e2e/python/test_sandbox_api.py::test_sandbox_interactive_exec_honors_tty", + "e2e/python/test_sandbox_api.py::test_interactive_exec_drains_output_after_request_eof", + "e2e/python/test_sandbox_landlock.py::test_landlock_blocks_user_owned_path_outside_policy", + "e2e/python/test_sandbox_providers.py::test_credentials_not_in_persisted_spec_environment", +] diff --git a/odh/requirements.in b/odh/requirements.in index bf383ce22c..d691b524f3 100644 --- a/odh/requirements.in +++ b/odh/requirements.in @@ -12,4 +12,6 @@ grpcio-tools>=1.60 mypy-protobuf>=5.1 httpx>=0.27 protobuf>=4.25 -pytest>=8.0 +pytest>=9.0.3 +pytest-asyncio>=0.23 +pytest-xdist>=3.0 diff --git a/odh/requirements.txt b/odh/requirements.txt index e7e53a9a50..f469027ee3 100644 --- a/odh/requirements.txt +++ b/odh/requirements.txt @@ -18,6 +18,10 @@ colorama==0.4.6 ; sys_platform == 'win32' \ --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \ --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6 # via pytest +execnet==2.1.2 \ + --hash=sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd \ + --hash=sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec + # via pytest-xdist googleapis-common-protos==1.75.3 \ --hash=sha256:57c435ac2c68b108999b6db075d9053e4d7a936ba57b4a3d45667b1346f1738a \ --hash=sha256:a018d2bf098ca9fb6faa08d5bb780e2a2c2f73c566f069761331386c9596d3f2 @@ -162,9 +166,20 @@ pygments==2.20.0 \ --hash=sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f \ --hash=sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176 # via pytest -pytest==9.0.2 \ - --hash=sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b \ - --hash=sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11 +pytest==9.2.0 \ + --hash=sha256:07acdcf88ec174f907dc01af70bf52d49b014bbab03faeeade31c96b18c2e588 \ + --hash=sha256:97c4f3b1f3c7414aa36465e09b8220f1d03627993bd51b1282e193753c80557b + # via + # -r odh/requirements.in + # pytest-asyncio + # pytest-xdist +pytest-asyncio==1.4.0 \ + --hash=sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1 \ + --hash=sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42 + # via -r odh/requirements.in +pytest-xdist==3.8.0 \ + --hash=sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88 \ + --hash=sha256:7e578125ec9bc6050861aa93f2d59f1d8d085595d6551c2c90b6f4fad8d3a9f1 # via -r odh/requirements.in setuptools==80.10.2 \ --hash=sha256:8b0e9d10c784bf7d262c4e5ec5d4ec94127ce206e8738f29a437945fbc219b70 \ @@ -180,3 +195,4 @@ typing-extensions==4.15.0 \ # via # anyio # grpcio + # pytest-asyncio diff --git a/odh/scripts/check-python-e2e-requirements.py b/odh/scripts/check-python-e2e-requirements.py new file mode 100755 index 0000000000..4fbf773bc8 --- /dev/null +++ b/odh/scripts/check-python-e2e-requirements.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Verify odh/requirements.in mirrors the root dev group's pytest plugins. + +The Konflux e2e image installs odh/requirements.txt (compiled from +requirements.in) with no network at test time, so a pytest plugin that +exists in the dev environment but not in the image surfaces only as an +import error during collection inside the image. This check compares the +pytest-* entries of both files — names and version constraints — so the +drift fails locally instead. +""" + +from __future__ import annotations + +import re +import sys +import tomllib +from pathlib import Path +from typing import TypeAlias + +from packaging.requirements import InvalidRequirement, Requirement +from packaging.version import InvalidVersion, Version + +ROOT = Path(__file__).resolve().parents[2] +IMAGE_MARKER_ENVIRONMENT = { + "python_version": "3.11", + "python_full_version": "3.11.0", +} + + +def normalize_name(name: str) -> str: + """Return a distribution name in its PEP 503 canonical form.""" + return re.sub(r"[-_.]+", "-", name).lower() + + +# pytest plugins deliberately absent from the e2e image, each with the +# reason the exclusion is intentional. Keys use the same canonical form as +# parsed requirements so alternate valid spellings do not create false drift. +ALLOWED_MISSING: dict[str, str] = { + normalize_name("pytest-cov"): "coverage is not collected in the e2e image", +} +PluginMap: TypeAlias = dict[str, list[Requirement]] + + +def parse_pytest_requirement(raw: str, source: str) -> tuple[str, Requirement] | None: + """Parse a pytest PEP 508 requirement and return its canonical name.""" + raw = re.sub(r"\s+#.*$", "", raw.removesuffix("\\")).strip() + try: + requirement = Requirement(raw) + except InvalidRequirement as error: + if raw.lower().startswith("pytest"): + raise SystemExit( + f"{source}: invalid pytest requirement {raw!r}: {error}" + ) from error + return None + + name = normalize_name(requirement.name) + if not name.startswith("pytest"): + return None + return name, requirement + + +def add_plugin( + plugins: PluginMap, plugin: tuple[str, Requirement], source: str +) -> None: + name, requirement = plugin + del source + plugins.setdefault(name, []).append(requirement) + + +def dev_pytest_plugins(root: Path) -> PluginMap: + with (root / "pyproject.toml").open("rb") as stream: + pyproject = tomllib.load(stream) + dev = pyproject.get("dependency-groups", {}).get("dev", []) + if not isinstance(dev, list): + raise SystemExit("pyproject.toml: [dependency-groups].dev must be an array") + plugins: PluginMap = {} + for requirement in dev: + if not isinstance(requirement, str): + continue + plugin = parse_pytest_requirement( + requirement, "pyproject.toml dependency-groups.dev" + ) + if plugin is not None: + add_plugin(plugins, plugin, "pyproject.toml dependency-groups.dev") + return plugins + + +def pytest_plugins_from_file(path: Path) -> PluginMap: + plugins: PluginMap = {} + for line in path.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + plugin = parse_pytest_requirement(line, str(path)) + if plugin is not None: + add_plugin(plugins, plugin, str(path)) + return plugins + + +def image_pytest_plugins(root: Path) -> PluginMap: + return pytest_plugins_from_file(root / "odh" / "requirements.in") + + +def compiled_image_pytest_plugins(root: Path) -> PluginMap: + return pytest_plugins_from_file(root / "odh" / "requirements.txt") + + +def locked_version(requirement: Requirement) -> Version | None: + """Extract the single concrete version from a compiled requirement.""" + versions = [ + specifier.version + for specifier in requirement.specifier + if specifier.operator in {"==", "==="} and "*" not in specifier.version + ] + if len(versions) != 1: + return None + try: + return Version(versions[0]) + except InvalidVersion: + return None + + +def compiled_requirement_satisfies( + required: Requirement, compiled: Requirement +) -> bool: + """Return whether the locked package can satisfy the image requirement.""" + if compiled.marker is not None and not compiled.marker.evaluate( + IMAGE_MARKER_ENVIRONMENT + ): + return False + if required.url is not None: + return compiled.url == required.url + if compiled.url is not None: + return False + version = locked_version(compiled) + return version is not None and version in required.specifier + + +def requirement_keys(requirements: list[Requirement]) -> set[tuple[object, ...]]: + """Return normalized PEP 508 fields for possibly marker-split entries.""" + return { + ( + normalize_name(requirement.name), + tuple(sorted(requirement.extras)), + str(requirement.specifier), + requirement.url, + str(requirement.marker) if requirement.marker is not None else "", + ) + for requirement in requirements + } + + +def main(argv: list[str]) -> int: + root = Path(argv[1]).resolve() if len(argv) > 1 else ROOT + dev = dev_pytest_plugins(root) + image = image_pytest_plugins(root) + compiled = compiled_image_pytest_plugins(root) + errors: list[str] = [] + for name, requirements in dev.items(): + if name not in image: + if name in ALLOWED_MISSING: + continue + errors.append( + f"{name} ({', '.join(map(str, requirements))}) is in the dev group" + " but not in odh/requirements.in" + ) + elif requirement_keys(image[name]) != requirement_keys(requirements): + errors.append( + f"{name}: dev group requires {', '.join(map(str, requirements))}," + f" odh/requirements.in requires {', '.join(map(str, image[name]))}" + ) + if name not in compiled: + errors.append( + f"{name} is required by odh/requirements.in but absent from" + " compiled odh/requirements.txt" + ) + else: + for requirement in image.get(name, requirements): + if not any( + compiled_requirement_satisfies(requirement, candidate) + for candidate in compiled[name] + ): + errors.append( + f"{name}: compiled odh/requirements.txt has" + f" {', '.join(map(str, compiled[name]))}, which does not satisfy" + f" odh/requirements.in {requirement}" + ) + for name in image: + if name not in dev: + errors.append(f"{name} is in odh/requirements.in but not in the dev group") + for name in compiled: + if name not in image: + errors.append( + f"{name} is in compiled odh/requirements.txt but not in odh/requirements.in" + ) + if errors: + print( + "ERROR: pytest plugin drift between pyproject.toml [dependency-groups].dev" + " and odh/requirements.in:", + file=sys.stderr, + ) + for error in errors: + print(f" - {error}", file=sys.stderr) + print( + "Mirror the change in odh/requirements.in (and recompile requirements.txt)" + " or extend ALLOWED_MISSING with a reason.", + file=sys.stderr, + ) + return 1 + print( + f"ok: {len(image)} pytest plugin(s) mirrored" + " between the dev group and odh/requirements.in" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/odh/scripts/e2e-odh-entrypoint.sh b/odh/scripts/e2e-odh-entrypoint.sh index 2fad6a45b9..68b607364e 100755 --- a/odh/scripts/e2e-odh-entrypoint.sh +++ b/odh/scripts/e2e-odh-entrypoint.sh @@ -6,6 +6,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +source "${SCRIPT_DIR}/python-e2e-common.sh" export OPENSHELL_BIN="${OPENSHELL_BIN:-${ROOT}/target/debug/openshell}" # Retry transient discovery failures at most three times, with 1s/2s backoff. @@ -189,14 +190,18 @@ MERGE_SCRIPT="${OPENSHELL_E2E_REPORT_MERGER:-${SCRIPT_DIR}/merge-e2e-odh-reports PYTHON_BIN="${PYTHON_BIN:-python3}" TIER="${1:-}" if [[ -z "${TIER}" || $# -ne 1 ]]; then - echo "Usage: $0 " >&2 + echo "Usage: $0 " >&2 exit 2 fi plan_json="$("${PYTHON_BIN}" "${PLAN_RESOLVER}" "${TIER}" "${TIERS_FILE}")" -phase_lines="$(printf '%s' "${plan_json}" | "${PYTHON_BIN}" -c 'import json,sys; print(chr(10).join(p["name"]+"|"+p["mode"] for p in json.load(sys.stdin)["phases"]))')" +phase_lines="$(printf '%s' "${plan_json}" | "${PYTHON_BIN}" -c 'import json,sys; print(chr(10).join(p["name"]+"|"+p["mode"]+"|"+",".join(p["runners"]) for p in json.load(sys.stdin)["phases"]))')" phase_count=0 while IFS= read -r _; do ((phase_count+=1)); done <<< "${phase_lines}" +has_python_runner=0 +if printf '%s' "${plan_json}" | "${PYTHON_BIN}" -c 'import json,sys; sys.exit(0 if any("python" in p["runners"] for p in json.load(sys.stdin)["phases"]) else 1)'; then + has_python_runner=1 +fi deploy_enabled="${OPENSHELL_E2E_DEPLOY_GATEWAY:-1}" if [[ "${deploy_enabled}" == 0 && "${phase_count}" -gt 1 ]]; then echo "ERROR: OPENSHELL_E2E_DEPLOY_GATEWAY=0 only supports single-phase tiers; this tier uses multiple gateway modes" >&2 @@ -257,12 +262,29 @@ results_dir="${OPENSHELL_E2E_RESULTS_DIR:-${ROOT}/results}" mkdir -p "${results_dir}" results_dir="$(cd "${results_dir}" && pwd)" export OPENSHELL_E2E_RESULTS_DIR="${results_dir}" -phase_reports=() +report_files=() +runner_report_path() { + local phase="$1" runner="$2" + case "${runner}" in + nextest) printf '%s/e2e-odh-%s-%s.xml\n' "${results_dir}" "${TIER}" "${phase}" ;; + python) printf '%s/e2e-odh-%s-%s-python.xml\n' "${results_dir}" "${TIER}" "${phase}" ;; + *) + echo "ERROR: unknown runner ${runner} for ${TIER}/${phase}" >&2 + return 1 + ;; + esac +} for phase_line in ${phase_lines}; do phase="${phase_line%%|*}" - phase_report="${results_dir}/e2e-odh-${TIER}-${phase}.xml" - phase_reports+=("${phase_report}") - rm -f "${phase_report}" "${phase_report%.xml}.html" + phase_rest="${phase_line#*|}" + runners="${phase_rest#*|}" + IFS=',' read -r -a phase_runners <<< "${runners}" + for runner in "${phase_runners[@]}"; do + report_path="$(runner_report_path "${phase}" "${runner}")" || exit 2 + report_files+=("${report_path}") + rm -f "${report_path}" + [[ "${runner}" != nextest ]] || rm -f "${report_path%.xml}.html" + done done merged_report="${results_dir}/e2e-odh-${TIER}-xunit.xml" html_report="${results_dir}/e2e-odh-${TIER}.html" @@ -308,7 +330,14 @@ cleanup_managed_namespaces() { cleanup() { local result=$? trap - EXIT - trap '' INT TERM + trap '' INT TERM HUP + if [[ -n "${child_pid:-}" ]]; then + # Cluster teardown must not race a live test suite: stop the child + # tree first even when the EXIT trap fires without INT/TERM. + stop_child_tree TERM "${child_pid}" + wait "${child_pid}" 2>/dev/null || true + child_pid="" + fi if [[ -n "${active_state}" ]]; then if ! cleanup_managed_namespaces "${active_state}"; then echo "ERROR: managed-workspace namespace cleanup failed" >&2 @@ -327,32 +356,117 @@ cleanup() { fi exit "${result}" } +# Children run in their own process group (see run_child), so the +# negative-PID kill reaches the whole tree: the Python tier executes +# through a Bash wrapper whose interpreter and xdist workers are +# grandchildren that a single-PID signal never reaches. Mirrors stop_child +# TERM the child's process group, wait a bounded grace period, then KILL — +# the e2e/run.sh stop_child pattern, with the group resumed first: a +# stopped member cannot handle TERM and would otherwise burn the whole +# grace period. Before setsid() creates that group, the unreaped launcher PID +# is still this shell's direct child and can be signalled safely; once the +# group exists, only group signals reach the whole execution tree. +stop_child_tree() { + local signal="$1" pid="$2" _ group_ready=0 + # os.setsid() runs in the launcher after fork. Briefly wait for its process + # group so an immediately arriving cancellation cannot miss the whole tree. + for _ in $(seq 1 20); do + if [[ "$(ps -o pgid= -p "${pid}" 2>/dev/null | tr -d '[:space:]')" == "${pid}" ]]; then + group_ready=1 + break + fi + kill -0 "${pid}" 2>/dev/null || return 0 + sleep 0.05 + done + if [[ "${group_ready}" != 1 ]]; then + # The launcher is still a direct, unreaped child. Do not wait forever + # for a group that has not appeared: stop it before teardown can start. + kill -"${signal}" "${pid}" 2>/dev/null || true + return 0 + fi + kill -CONT -- "-${pid}" 2>/dev/null || true + kill -"${signal}" -- "-${pid}" 2>/dev/null || true + for _ in $(seq 1 30); do + kill -0 -- "-${pid}" 2>/dev/null || return 0 + sleep 1 + done + kill -KILL -- "-${pid}" 2>/dev/null || true +} + stop_child() { local signal="$1" code="$2" - trap '' INT TERM + trap '' INT TERM HUP if [[ -n "${child_pid}" ]]; then - kill -"${signal}" "${child_pid}" 2>/dev/null || true - wait "${child_pid}" || true + stop_child_tree "${signal}" "${child_pid}" + wait "${child_pid}" 2>/dev/null || true child_pid="" fi exit "${code}" } +restore_signal_traps() { + trap 'stop_child TERM 130' INT + trap 'stop_child TERM 143' TERM + trap 'stop_child TERM 129' HUP +} run_child() { - local result=0 - "$@" & + local result=0 pending_signal="" + # Launch in a new session, the e2e/run.sh start_child pattern: the + # child never receives the terminal's SIGTTIN (a stdin-reading child + # in a job-control group would stop and hang the wait forever), and + # an SSH disconnect's SIGHUP reaches this entrypoint alone — where + # the traps below tear the whole tree down — instead of killing the + # children mid-flight with nothing left to clean up the cluster. + # Defer teardown while the launcher is being forked. A signal can otherwise + # reach the parent before $! is stored, leaving the launched process alive. + trap 'pending_signal=INT' INT + trap 'pending_signal=TERM' TERM + trap 'pending_signal=HUP' HUP + "${PYTHON_BIN}" -c $'import os, sys\nos.setsid()\nos.execvp(sys.argv[1], sys.argv[1:])' "$@" & child_pid=$! - wait "${child_pid}" || result=$? + restore_signal_traps + case "${pending_signal}" in + INT) stop_child TERM 130 ;; + TERM) stop_child TERM 143 ;; + HUP) stop_child TERM 129 ;; + esac + wait "${child_pid}" 2>/dev/null || result=$? child_pid="" return "${result}" } trap cleanup EXIT -trap 'stop_child TERM 130' INT -trap 'stop_child TERM 143' TERM -phase_index=0 +restore_signal_traps +# An SSH disconnect delivers SIGHUP to this entrypoint only (the children +# run in their own sessions): tear the tree down instead of leaving +# orphans running against the cluster. +trap 'stop_child TERM 129' HUP + +# Flags shared by the strict gate check and the real Python run so the two +# cannot drift apart. +# The python_files pattern is shared with run-python-e2e.sh through the +# environment (an array cannot cross the exec boundary into the runner's +# own session) so the strict gate check and the real run cannot drift. +export OPENSHELL_E2E_PYTEST_PYTHON_FILES="test_*.py *_test.py" +export PYTHON_BIN + +# When a phase runs the Python suite, verify its gates before any +# deployment: a gates file referencing tests the current collection does +# not contain must cost seconds, not a gateway deployment. The check is a +# single-process collection on purpose — under xdist the strict failure +# cannot surface cleanly (the worker crashes instead of reporting the +# UsageError), which is also why the real run does not set STRICT itself. +if [[ "${has_python_runner}" == 1 ]]; then + if ! run_child env OPENSHELL_E2E_OIDC=0 OPENSHELL_ODH_PYTHON_GATES_STRICT=1 \ + "${SCRIPT_DIR}/run-python-e2e.sh" --collect-only; then + echo "ERROR: Python E2E preflight failed; see preceding output" >&2 + exit 2 + fi +fi + for phase_line in ${phase_lines}; do phase="${phase_line%%|*}" - mode="${phase_line#*|}" - phase_report="${phase_reports[phase_index]}" + phase_rest="${phase_line#*|}" + mode="${phase_rest%%|*}" + runners="${phase_rest#*|}" phase_deploy_status=0 phase_test_status=0 phase_managed_cleanup_status=0 @@ -376,7 +490,34 @@ for phase_line in ${phase_lines}; do fi fi if [[ "${phase_test_status}" == 0 ]]; then - run_child "${TEST_SCRIPT}" "${TIER}" "${phase}" "${phase_report}" || phase_test_status=$? + # The runners come from the tier plan in execution order: the + # nextest selection writes the phase report, and the python + # runner shares the phase's deployment and appends its own + # report (the merge skips missing reports, so include it even + # on failure to surface what ran). + IFS=',' read -r -a phase_runners <<< "${runners}" + for runner in "${phase_runners[@]}"; do + if [[ "${phase_test_status}" != 0 ]]; then + echo "WARNING: skipping ${runner} runner for ${TIER}/${phase} after an earlier runner failed" >&2 + break + fi + report_path="$(runner_report_path "${phase}" "${runner}")" || { + phase_test_status=$? + break + } + case "${runner}" in + nextest) + run_child "${TEST_SCRIPT}" "${TIER}" "${phase}" "${report_path}" || phase_test_status=$? + ;; + python) + run_child "${SCRIPT_DIR}/run-python-e2e.sh" "${report_path}" || phase_test_status=$? + ;; + *) + echo "ERROR: unknown runner ${runner} for ${TIER}/${phase}" >&2 + phase_test_status=1 + ;; + esac + done fi else echo "ERROR: deployment/preflight failed for ${TIER}/${phase} (${phase_deploy_status})" >&2 @@ -407,14 +548,23 @@ for phase_line in ${phase_lines}; do if [[ "${status}" == 0 && "${phase_test_status}" != 0 ]]; then status="${phase_test_status}"; fi if [[ "${status}" == 0 && "${phase_managed_cleanup_status}" != 0 ]]; then status="${phase_managed_cleanup_status}"; fi if [[ "${teardown_failed}" == 1 ]]; then break; fi - ((phase_index+=1)) done -run_child "${PYTHON_BIN}" "${MERGE_SCRIPT}" "${TIER}" "${phase_reports[@]}" || { - merge_status=$? - echo "ERROR: failed to merge ODH phase reports" >&2 - [[ "${status}" != 0 ]] || status="${merge_status}" -} +report_available=0 +for report_path in "${report_files[@]}"; do + if [[ -f "${report_path}" ]]; then + report_available=1 + break + fi +done + +if [[ "${report_available}" == 1 ]]; then + run_child "${PYTHON_BIN}" "${MERGE_SCRIPT}" "${TIER}" "${report_files[@]}" || { + merge_status=$? + echo "ERROR: failed to merge ODH phase reports" >&2 + [[ "${status}" != 0 ]] || status="${merge_status}" + } +fi if [[ -f "${merged_report}" ]]; then if command -v xsltproc >/dev/null 2>&1; then xsltproc --stringparam title "e2e-odh-${TIER}" "${ROOT}/scripts/junit-to-html.xsl" "${merged_report}" > "${html_report}" || echo "WARNING: failed to render HTML report" >&2 diff --git a/odh/scripts/merge-e2e-odh-reports.py b/odh/scripts/merge-e2e-odh-reports.py index 738d9d4ed1..33de156632 100755 --- a/odh/scripts/merge-e2e-odh-reports.py +++ b/odh/scripts/merge-e2e-odh-reports.py @@ -5,6 +5,7 @@ from __future__ import annotations +import contextlib import os import sys import tempfile @@ -36,16 +37,26 @@ def merge(tier: str, paths: list[Path], results_dir: Path) -> Path: raise ValueError("no phase reports were available to merge") for suite in suites: cases.extend(suite.iter("testcase")) + + def case_time(case: ET.Element) -> float: + try: + return float(case.get("time", "0")) + except ValueError: + return 0.0 + totals = { "tests": len(cases), - "failures": sum(1 for case in cases for child in case if child.tag == "failure"), + "failures": sum( + 1 for case in cases for child in case if child.tag == "failure" + ), "errors": sum(1 for case in cases for child in case if child.tag == "error"), "skipped": sum(1 for case in cases for child in case if child.tag == "skipped"), - "time": f"{sum(float(case.get('time', '0')) for case in cases):.6f}", + "time": f"{sum(case_time(case) for case in cases):.6f}", } root = ET.Element("testsuites", {key: str(value) for key, value in totals.items()}) for suite in suites: root.append(suite) + ET.indent(root, space=" ") xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True) results_dir.mkdir(parents=True, exist_ok=True) xml_path = results_dir / f"e2e-odh-{tier}-xunit.xml" @@ -53,25 +64,30 @@ def merge(tier: str, paths: list[Path], results_dir: Path) -> Path: try: with os.fdopen(fd, "wb") as stream: stream.write(xml_bytes) - os.replace(temporary, xml_path) + Path(temporary).replace(xml_path) except BaseException: - try: - os.unlink(temporary) - except FileNotFoundError: - pass + with contextlib.suppress(FileNotFoundError): + Path(temporary).unlink() raise return xml_path def main(argv: list[str]) -> int: if len(argv) < 3: - print("Usage: merge-e2e-odh-reports.py ...", file=sys.stderr) + print( + "Usage: merge-e2e-odh-reports.py ...", + file=sys.stderr, + ) return 2 tier = argv[1] if not tier.replace("-", "").replace("_", "").isalnum(): print(f"invalid tier name: {tier!r}", file=sys.stderr) return 2 - results_dir = Path(os.environ.get("OPENSHELL_E2E_RESULTS_DIR", Path(__file__).resolve().parents[2] / "results")) + results_dir = Path( + os.environ.get( + "OPENSHELL_E2E_RESULTS_DIR", Path(__file__).resolve().parents[2] / "results" + ) + ) try: xml_path = merge(tier, [Path(arg) for arg in argv[2:]], results_dir) except (OSError, ET.ParseError, ValueError) as exc: diff --git a/odh/scripts/pytest_odh_gates.py b/odh/scripts/pytest_odh_gates.py new file mode 100644 index 0000000000..05b79a8b74 --- /dev/null +++ b/odh/scripts/pytest_odh_gates.py @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Apply explicit, validated OpenShift capability gates to upstream pytest E2E.""" + +from __future__ import annotations + +import os +import re +import tomllib +from pathlib import Path + +import pytest + +GATES_ENV = "OPENSHELL_ODH_PYTHON_GATES" +STRICT_ENV = "OPENSHELL_ODH_PYTHON_GATES_STRICT" +_CATEGORY = re.compile(r"[a-z][a-z0-9-]*\Z") + + +def load_gates(path: Path) -> dict[str, tuple[str, str]]: + try: + with path.open("rb") as stream: + parsed = tomllib.load(stream) + except (OSError, tomllib.TOMLDecodeError) as error: + raise pytest.UsageError(f"{path}: cannot load gates: {error}") from error + if "gate" not in parsed: + raise pytest.UsageError(f"{path}: missing required 'gate' array of tables") + gates = parsed["gate"] + if not isinstance(gates, list): + raise pytest.UsageError(f"{path}: 'gate' must be an array of tables") + selected: dict[str, tuple[str, str]] = {} + for gate in gates: + if not isinstance(gate, dict): + raise pytest.UsageError(f"{path}: each gate must be a table") + category, reason, tests = ( + gate.get("category"), + gate.get("reason"), + gate.get("tests"), + ) + if not isinstance(category, str) or not _CATEGORY.fullmatch(category): + raise pytest.UsageError(f"{path}: invalid gate category {category!r}") + if not isinstance(reason, str) or not reason.strip(): + raise pytest.UsageError(f"{path}: gate {category!r} needs a reason") + if not isinstance(tests, list) or not tests: + raise pytest.UsageError(f"{path}: gate {category!r} needs tests") + for node_id in tests: + if not isinstance(node_id, str) or "::" not in node_id or "[" in node_id: + raise pytest.UsageError(f"{path}: invalid test node ID {node_id!r}") + if node_id in selected: + raise pytest.UsageError(f"{path}: test {node_id!r} is gated twice") + selected[node_id] = (category, reason.strip()) + return selected + + +@pytest.hookimpl(tryfirst=True) +def pytest_collection_modifyitems(items: list[pytest.Item]) -> None: + gates_path = os.environ.get(GATES_ENV) + if not gates_path: + return + gates = load_gates(Path(gates_path)) + matched: set[str] = set() + for item in items: + node_id = item.nodeid.split("[", 1)[0] + if gate := gates.get(node_id): + category, reason = gate + matched.add(node_id) + item.add_marker(pytest.mark.skip(reason=f"ODH gate [{category}]: {reason}")) + stale = sorted(gates.keys() - matched) + if stale and os.environ.get(STRICT_ENV) == "1": + raise pytest.UsageError( + f"{gates_path}: gated tests were not collected: {', '.join(stale)}" + ) diff --git a/odh/scripts/python-e2e-common.sh b/odh/scripts/python-e2e-common.sh new file mode 100644 index 0000000000..3514f66547 --- /dev/null +++ b/odh/scripts/python-e2e-common.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# Shared Python E2E interpreter and environment setup for the preflight and runner. + +resolve_python_test_bin() { + local root="$1" python_test_bin parent_dir + if [[ -n "${OPENSHELL_E2E_PYTHON:-}" ]]; then + python_test_bin="${OPENSHELL_E2E_PYTHON}" + if [[ "${python_test_bin}" != */* ]]; then + python_test_bin="$(command -v -- "${python_test_bin}" 2>/dev/null || true)" + elif [[ "${python_test_bin}" != /* ]]; then + parent_dir="$(cd -- "$(dirname -- "${python_test_bin}")" 2>/dev/null && pwd -P || true)" + if [[ -n "${parent_dir}" ]]; then + python_test_bin="${parent_dir}/$(basename -- "${python_test_bin}")" + fi + fi + elif [[ -n "${UV_PROJECT_ENVIRONMENT:-}" ]]; then + python_test_bin="${UV_PROJECT_ENVIRONMENT}/bin/python" + [[ "${python_test_bin}" == /* ]] || python_test_bin="${root}/${python_test_bin}" + else + python_test_bin="${root}/.venv/bin/python" + fi + if [[ -z "${python_test_bin}" || ! -x "${python_test_bin}" ]]; then + echo "ERROR: Python E2E interpreter not found (OPENSHELL_E2E_PYTHON=${OPENSHELL_E2E_PYTHON:-}, resolved='${python_test_bin:-}')" >&2 + return 2 + fi + printf '%s\n' "${python_test_bin}" +} + +prepare_python_e2e_environment() { + local root="$1" script_dir="$2" + export PYTHONPATH="${root}/python:${script_dir}${PYTHONPATH:+:${PYTHONPATH}}" + export OPENSHELL_ODH_PYTHON_GATES="${root}/odh/python-gates.toml" +} diff --git a/odh/scripts/run-python-e2e.sh b/odh/scripts/run-python-e2e.sh new file mode 100755 index 0000000000..38afb33210 --- /dev/null +++ b/odh/scripts/run-python-e2e.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Run the supported upstream Python gateway E2E suite and post-process its +# JUnit report. Invoked by e2e-odh-entrypoint.sh through run_child, which +# exec's this script into its own session — a shell function cannot be +# exec'd, so the runner lives here as an executable like the nextest and +# merge helpers. +# +# Environment contract with the entrypoint: +# OPENSHELL_E2E_DEPLOY_GATEWAY 0 in no-deploy mode (drives the endpoint +# override rejection below) +# OPENSHELL_E2E_PYTEST_PYTHON_FILES the python_files pattern shared with +# the entrypoint's strict gate check +# E2E_PARALLEL xdist worker count +# OPENSHELL_E2E_PYTHON optional interpreter override +# UV_PROJECT_ENVIRONMENT optional uv project environment + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +source "${SCRIPT_DIR}/python-e2e-common.sh" +PYTHON_BIN="${PYTHON_BIN:-python3}" +mode="${1:-}" + +# A leftover endpoint override would split a no-deploy run: the SDK +# session fixtures resolve the gateway from metadata.json while +# test_security_tls.py honors the override, so one pytest run can talk +# to two different gateways. The deploy branch unsets it; reject it +# here because no-deploy has no gateway to re-point. +if [[ "${mode}" != "--collect-only" && "${OPENSHELL_E2E_DEPLOY_GATEWAY:-1}" == 0 && -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ]]; then + echo "ERROR: OPENSHELL_GATEWAY_ENDPOINT is set, but no-deploy mode has no gateway to re-point: unset it before running the Python suite" >&2 + exit 2 +fi +python_test_bin="$(resolve_python_test_bin "${ROOT}")" || exit 2 + +prepare_python_e2e_environment "${ROOT}" "${SCRIPT_DIR}" +pytest_args=( + -p no:cacheprovider + -p pytest_odh_gates + -o "python_files=${OPENSHELL_E2E_PYTEST_PYTHON_FILES:-test_*.py *_test.py}" + -m "not gpu" + e2e/python +) +if [[ "${mode}" == "--collect-only" ]]; then + if [[ $# -ne 1 ]]; then + echo "Usage: $0 |--collect-only" >&2 + exit 2 + fi + echo "==> Collecting ODH Python gateway E2E gates" + collect_status=0 + collect_output="$(cd "${ROOT}" && "${python_test_bin}" -m pytest "${pytest_args[@]}" -p no:xdist --collect-only -q 2>&1)" || collect_status=$? + if [[ "${collect_status}" != 0 ]]; then + printf '%s\n' "${collect_output}" >&2 + fi + exit "${collect_status}" +fi +if [[ -z "${mode}" || $# -ne 1 ]]; then + echo "Usage: $0 |--collect-only" >&2 + exit 2 +fi +report="${mode}" +[[ "${report}" == /* ]] || report="${ROOT}/${report}" +status=0 +echo "==> Running ODH Python gateway E2E" +(cd "${ROOT}" && OPENSHELL_E2E_OIDC=0 \ + "${python_test_bin}" -m pytest "${pytest_args[@]}" -n "${E2E_PARALLEL:-5}" \ + --junitxml "${report}") || status=$? + +# Strip skipped testcases from the JUnit report and require at least one +# executed case in the same pass: DevTestOps CI parses the XML and would +# create a Jira for every skipped case, and this lane intentionally skips +# a sizeable share of its collected cases through gates, so an upstream +# or environment change that skips the remaining supported tests must +# fail the phase instead of reporting a vacuous pass. The helper also +# recomputes the suite attributes so the merged report stays +# self-consistent. +if [[ -f "${report}" ]]; then + strip_status=0 + "${python_test_bin}" "${SCRIPT_DIR}/strip-skipped-testcases.py" "${report}" || strip_status=$? + case "${strip_status}" in + 0) ;; + 1) + if [[ "${status}" == 0 ]]; then + echo "ERROR: Python gateway E2E executed no test cases (every collected case was skipped)" >&2 + status=1 + fi + ;; + *) + echo "ERROR: failed to post-process JUnit report ${report} (${strip_status})" >&2 + [[ "${status}" != 0 ]] || status="${strip_status}" + ;; + esac +fi +if [[ "${status}" == 5 ]]; then + echo "ERROR: Python gateway E2E selected no tests" >&2 +fi +if [[ ! -f "${report}" ]]; then + echo "ERROR: Python gateway E2E did not write a JUnit report" >&2 + [[ "${status}" != 0 ]] || status=1 +fi +exit "${status}" diff --git a/odh/scripts/strip-skipped-testcases.py b/odh/scripts/strip-skipped-testcases.py new file mode 100755 index 0000000000..f18f9870c5 --- /dev/null +++ b/odh/scripts/strip-skipped-testcases.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +"""Strip skipped testcases from a JUnit report, keeping it self-consistent. + +DevTestOps CI parses the XML and would create a Jira for every skipped +case, so the python lane removes them after the run. Each suite's +attributes (tests/skipped/failures/errors/time) are recomputed from the +surviving cases so the report does not disagree with itself once +merge-e2e-odh-reports.py recalculates the root totals from surviving +cases; the number of stripped cases is printed to stderr for audit. + +Exit codes: 0 = at least one executed case remains, 1 = every collected +case was skipped (vacuous pass), 2 = the report cannot be parsed. +""" + +from __future__ import annotations + +import contextlib +import sys +import tempfile +import xml.etree.ElementTree as ET +from pathlib import Path + + +def strip_skipped(path: str) -> int: + """Remove skipped cases from `path` in place; return executed cases.""" + tree = ET.parse(path) + root = tree.getroot() + suites = [root] if root.tag == "testsuite" else root.findall(".//testsuite") + executed = 0 + stripped = 0 + for suite in suites: + kept = failures = errors = 0 + time_total = 0.0 + for case in list(suite.findall("testcase")): + if case.find("skipped") is not None: + suite.remove(case) + stripped += 1 + continue + kept += 1 + if case.find("failure") is not None: + failures += 1 + if case.find("error") is not None: + errors += 1 + with contextlib.suppress(ValueError): + time_total += float(case.get("time", "0")) + executed += kept + suite.set("tests", str(kept)) + suite.set("skipped", "0") + suite.set("failures", str(failures)) + suite.set("errors", str(errors)) + suite.set("time", f"{time_total:.6f}") + ET.indent(tree, space=" ") + temp_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="wb", + dir=Path(path).parent, + prefix=f".{Path(path).name}.", + delete=False, + ) as stream: + temp_path = Path(stream.name) + tree.write(stream, encoding="utf-8", xml_declaration=True) + temp_path.replace(path) + except OSError: + if temp_path is not None: + with contextlib.suppress(FileNotFoundError): + temp_path.unlink() + raise + print( + f"stripped {stripped} skipped testcase(s); {executed} executed remain", + file=sys.stderr, + ) + return executed + + +def main(argv: list[str]) -> int: + if len(argv) != 2: + print(f"Usage: {argv[0]} ", file=sys.stderr) + return 2 + try: + executed = strip_skipped(argv[1]) + except ET.ParseError as error: + print(f"{argv[1]}: cannot parse JUnit report: {error}", file=sys.stderr) + return 2 + except OSError as error: + print(f"{argv[1]}: cannot read or write JUnit report: {error}", file=sys.stderr) + return 2 + return 0 if executed > 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv)) diff --git a/odh/scripts/tests/test-check-python-e2e-requirements.sh b/odh/scripts/tests/test-check-python-e2e-requirements.sh new file mode 100755 index 0000000000..c5eb6eee9b --- /dev/null +++ b/odh/scripts/tests/test-check-python-e2e-requirements.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Exercise check-python-e2e-requirements.py: the dev group's pytest plugins +# must be mirrored in odh/requirements.in (names and pins), an allowlisted +# exclusion is tolerated, and any drift fails with the offending entry. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +CHECK="${SCRIPT_DIR}/../check-python-e2e-requirements.py" + +PYTHON_BIN="${PYTHON_BIN:-${ROOT}/.venv/bin/python}" +if [[ ! -x "${PYTHON_BIN}" ]]; then + PYTHON_BIN="$(command -v python3)" +fi + +echo ">> the current repository passes the mirror check" +"${PYTHON_BIN}" "${CHECK}" "${ROOT}" + +WORKDIR="$(mktemp -d)" +trap 'rm -rf "${WORKDIR}"' EXIT +mkdir -p "${WORKDIR}/odh" + +reset_inputs() { + cp "${ROOT}/pyproject.toml" "${WORKDIR}/pyproject.toml" + cp "${ROOT}/odh/requirements.in" "${WORKDIR}/odh/requirements.in" + cp "${ROOT}/odh/requirements.txt" "${WORKDIR}/odh/requirements.txt" +} + +reset_inputs + +expect_failure() { + local label="$1" + local expected="${2:-}" + local output + if output="$("${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" 2>&1)"; then + echo "FAIL: ${label} passed, expected drift failure" >&2 + return 1 + fi + if [[ -n "${expected}" && "${output}" != *"${expected}"* ]]; then + echo "FAIL: ${label} did not report '${expected}'" >&2 + echo "${output}" >&2 + return 1 + fi + echo "ok: ${label} rejected" +} + +sed_in_place() { + local expression="$1" file="$2" before after + before="$(cksum < "${file}")" + if sed --version > /dev/null 2>&1; then + sed -i "$@" + else + sed -i '' "$@" + fi + after="$(cksum < "${file}")" + if [[ "${before}" == "${after}" ]]; then + echo "FAIL: fixture edit did not change ${file}: ${expression}" >&2 + exit 1 + fi +} + +echo ">> equivalent PEP 503 spellings do not create drift" +sed_in_place 's/pytest-xdist/pytest_xdist/' "${WORKDIR}/pyproject.toml" +if ! "${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" > /dev/null 2>&1; then + echo "FAIL: equivalent pytest package spelling was rejected" >&2 + exit 1 +fi +echo "ok: equivalent package spelling accepted" +reset_inputs + +echo ">> pytest requirements with extras are parsed and mirrored" +sed_in_place 's/pytest-xdist>=3.0/pytest-xdist[extra]>=3.0/' "${WORKDIR}/pyproject.toml" +sed_in_place 's/pytest-xdist>=3.0/pytest-xdist[extra]>=3.0/' "${WORKDIR}/odh/requirements.in" +if ! "${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" > /dev/null 2>&1; then + echo "FAIL: mirrored pytest requirement with extras was rejected" >&2 + exit 1 +fi +echo "ok: pytest requirement with extras accepted" +reset_inputs + +echo ">> inline comments in requirements files are accepted" +sed_in_place 's/^pytest>=9.0.3$/pytest>=9.0.3 # core runner/' "${WORKDIR}/odh/requirements.in" +if ! "${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" > /dev/null 2>&1; then + echo "FAIL: inline requirement comment was rejected" >&2 + exit 1 +fi +echo "ok: inline requirement comment accepted" +reset_inputs + +echo ">> marker-split universal-lock pins are accepted" +printf 'pytest==9.2.0 ; python_version < "3.12"\n' >> "${WORKDIR}/odh/requirements.txt" +if ! "${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" > /dev/null 2>&1; then + echo "FAIL: marker-split compiled requirement was rejected" >&2 + exit 1 +fi +echo "ok: marker-split compiled requirement accepted" +reset_inputs + +echo ">> invalid pytest requirement syntax cannot be ignored" +sed_in_place 's/pytest-xdist>=3.0/pytest-xdist[extra>=3.0/' "${WORKDIR}/pyproject.toml" +expect_failure "invalid pytest requirement" "invalid pytest requirement" +reset_inputs + +echo ">> a dev-group plugin missing from the image is drift" +awk ' + /^ "pytest-xdist>=3.0",$/ { + print + print " \"pytest-fixturecheck>=1.0\"," + next + } + { print } +' "${WORKDIR}/pyproject.toml" > "${WORKDIR}/pyproject.toml.tmp" +mv "${WORKDIR}/pyproject.toml.tmp" "${WORKDIR}/pyproject.toml" +expect_failure "unmirrored new dev plugin" +reset_inputs + +echo ">> requirements.txt must include each image pytest plugin" +awk ' + /^ "pytest-xdist>=3.0",$/ { + print + print " \"pytest-fixturecheck>=1.0\"," + next + } + { print } +' "${WORKDIR}/pyproject.toml" > "${WORKDIR}/pyproject.toml.tmp" +mv "${WORKDIR}/pyproject.toml.tmp" "${WORKDIR}/pyproject.toml" +printf 'pytest-fixturecheck>=1.0\n' >> "${WORKDIR}/odh/requirements.in" +expect_failure "stale compiled image requirements" "compiled odh/requirements.txt" +reset_inputs + +echo ">> a compiled-only pytest plugin is stale drift" +printf 'pytest-stale-plugin==1.0\n' >> "${WORKDIR}/odh/requirements.txt" +expect_failure "compiled-only pytest plugin" "compiled odh/requirements.txt" +reset_inputs + +echo ">> requirements.txt must satisfy each image pytest plugin pin" +sed_in_place 's/pytest>=9.0.3/pytest>=99.0/' "${WORKDIR}/pyproject.toml" +sed_in_place 's/pytest>=9.0.3/pytest>=99.0/' "${WORKDIR}/odh/requirements.in" +expect_failure "stale compiled pytest version" "does not satisfy odh/requirements.in" +reset_inputs + +echo ">> a pin that differs between the two files is drift" +sed_in_place 's/^pytest>=.*$/pytest>=1.0/' "${WORKDIR}/odh/requirements.in" +expect_failure "diverged pytest pin" +reset_inputs + +echo ">> an image plugin absent from the dev group is drift" +printf 'pytest-subprocess>=1.0\n' >> "${WORKDIR}/odh/requirements.in" +expect_failure "image-only plugin" +reset_inputs + +echo ">> the allowlisted exclusion is tolerated" +sed_in_place '/^ "pytest-cov>=4.0",$/d' "${WORKDIR}/pyproject.toml" +if ! "${PYTHON_BIN}" "${CHECK}" "${WORKDIR}" > /dev/null 2>&1; then + echo "FAIL: allowlisted pytest-cov exclusion was rejected" >&2 + exit 1 +fi +echo "ok: allowlisted exclusion tolerated" + +echo "requirements mirror checks passed" diff --git a/odh/scripts/tests/test-e2e-odh-entrypoint.sh b/odh/scripts/tests/test-e2e-odh-entrypoint.sh new file mode 100755 index 0000000000..7f97a4bc86 --- /dev/null +++ b/odh/scripts/tests/test-e2e-odh-entrypoint.sh @@ -0,0 +1,338 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# A deployment failure before the Python runner must not leave an old Python +# report to be picked up as raw evidence by a later invocation. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +ENTRYPOINT="${SCRIPT_DIR}/../e2e-odh-entrypoint.sh" + +WORKDIR="$(mktemp -d)" +RELATIVE_REPORT_DIR="" +RELATIVE_REPORT_DIR_CREATED=0 +cleanup() { + rm -rf "${WORKDIR}" + if [[ "${RELATIVE_REPORT_DIR_CREATED}" == 1 ]]; then + rmdir -- "${RELATIVE_REPORT_DIR}" 2>/dev/null || true + fi +} +trap cleanup EXIT +RESULTS_DIR="${WORKDIR}/results" +STALE_PYTHON_REPORT="${RESULTS_DIR}/e2e-odh-python-shared-python.xml" +MERGED_REPORT="${RESULTS_DIR}/e2e-odh-python-xunit.xml" +KUBECONFIG_FILE="${WORKDIR}/kubeconfig" +DEPLOY_SCRIPT="${WORKDIR}/fail-deploy.sh" +LOG_FILE="${WORKDIR}/entrypoint.log" +BIN_DIR="${WORKDIR}/bin" + +mkdir -p "${RESULTS_DIR}" +printf '\n' > "${STALE_PYTHON_REPORT}" +printf '\n' > "${MERGED_REPORT}" +printf 'apiVersion: v1\nkind: Config\n' > "${KUBECONFIG_FILE}" +printf '#!/usr/bin/env bash\nexit 1\n' > "${DEPLOY_SCRIPT}" +chmod +x "${DEPLOY_SCRIPT}" +mkdir -p "${BIN_DIR}" +printf '#!/usr/bin/env bash\nexit 0\n' > "${BIN_DIR}/oc" +chmod +x "${BIN_DIR}/oc" + +PYTHON_TEST_BIN="${PYTHON_BIN:-${ROOT}/.venv/bin/python}" +if [[ ! -x "${PYTHON_TEST_BIN}" ]]; then + PYTHON_TEST_BIN="$(command -v python3)" +fi +if ! PYTHONPATH="${ROOT}/python:${ROOT}/odh/scripts" "${PYTHON_TEST_BIN}" -c 'import pytest, tomllib, openshell, pytest_odh_gates' >/dev/null 2>&1; then + echo "SKIP: no Python E2E test interpreter available (PYTHON_BIN=${PYTHON_TEST_BIN})" >&2 + exit 0 +fi + +if KUBECONFIG="${KUBECONFIG_FILE}" \ + OPENSHELL_E2E_RESULTS_DIR="${RESULTS_DIR}" \ + OPENSHELL_E2E_DEPLOY_SCRIPT="${DEPLOY_SCRIPT}" \ + OPENSHELL_E2E_PYTHON="${PYTHON_TEST_BIN}" \ + PYTHON_BIN="${PYTHON_TEST_BIN}" \ + PATH="${BIN_DIR}:${PATH}" \ + "${ENTRYPOINT}" python > "${LOG_FILE}" 2>&1; then + echo "FAIL: python entrypoint unexpectedly succeeded with a failing deployment" >&2 + exit 1 +fi + +[[ ! -e "${STALE_PYTHON_REPORT}" ]] || { + echo "FAIL: stale Python report survived a deployment failure" >&2 + exit 1 +} +[[ ! -e "${MERGED_REPORT}" ]] || { + echo "FAIL: stale merged report survived a deployment failure" >&2 + exit 1 +} +grep -q 'deployment/preflight failed for python/shared' "${LOG_FILE}" || { + echo "FAIL: fake deployment failure was not observed" >&2 + cat "${LOG_FILE}" >&2 + exit 1 +} +if grep -q 'could not list managed-workspace namespaces' "${LOG_FILE}"; then + echo "FAIL: entrypoint fixture reached a real or missing oc binary" >&2 + cat "${LOG_FILE}" >&2 + exit 1 +fi +if grep -q 'failed to merge ODH phase reports' "${LOG_FILE}"; then + echo "FAIL: deployment failure was obscured by an empty-report merge failure" >&2 + cat "${LOG_FILE}" >&2 + exit 1 +fi + +echo "entrypoint clears stale Python reports before deployment" + +# A runner failure must retain its original pytest exit status even if the +# resulting report happens to contain only skipped test cases. Otherwise an +# infrastructure/collection error (for example pytest's exit 2) is rewritten +# as the unrelated "every test was skipped" failure. +FAKE_PYTEST_PYTHON="${WORKDIR}/fake-pytest-python.sh" +RUNNER_REPORT="${WORKDIR}/runner.xml" +RUNNER_LOG="${WORKDIR}/runner.log" +cat > "${FAKE_PYTEST_PYTHON}" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +while [[ $# -gt 0 ]]; do + case "$1" in + --junitxml) + report="$2" + shift 2 + ;; + *) shift ;; + esac +done +printf '\n' > "${report}" +exit 2 +SH +chmod +x "${FAKE_PYTEST_PYTHON}" + +if PYTHON_BIN="${PYTHON_TEST_BIN}" \ + OPENSHELL_E2E_PYTHON="${FAKE_PYTEST_PYTHON}" \ + "${SCRIPT_DIR}/../run-python-e2e.sh" "${RUNNER_REPORT}" > "${RUNNER_LOG}" 2>&1; then + echo "FAIL: fake pytest failure unexpectedly succeeded" >&2 + exit 1 +else + status=$? + [[ "${status}" == 2 ]] || { + echo "FAIL: fake pytest failure exited ${status}, expected 2" >&2 + cat "${RUNNER_LOG}" >&2 + exit 1 + } +fi +if grep -q 'executed no test cases' "${RUNNER_LOG}"; then + echo "FAIL: a pytest failure was misreported as an all-skipped run" >&2 + cat "${RUNNER_LOG}" >&2 + exit 1 +fi +echo "entrypoint preserves a failing Python runner status" + +# Collection diagnostics are normally quiet, but must remain visible when +# pytest rejects a module during preflight. Pytest sends import failures to +# stdout, so dropping only stdout makes the entrypoint's failure guidance +# misleading. +FAKE_COLLECTION_PYTHON="${WORKDIR}/fake-collection-python.sh" +COLLECTION_LOG="${WORKDIR}/collection.log" +cat > "${FAKE_COLLECTION_PYTHON}" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +echo 'ERROR collecting e2e/python/test_broken.py' +echo 'ModuleNotFoundError: No module named broken_module' +exit 2 +SH +chmod +x "${FAKE_COLLECTION_PYTHON}" +if PYTHON_BIN="${PYTHON_TEST_BIN}" \ + OPENSHELL_E2E_PYTHON="${FAKE_COLLECTION_PYTHON}" \ + "${SCRIPT_DIR}/../run-python-e2e.sh" --collect-only > "${COLLECTION_LOG}" 2>&1; then + echo "FAIL: fake collection error unexpectedly succeeded" >&2 + exit 1 +else + status=$? + [[ "${status}" == 2 ]] || { + echo "FAIL: fake collection error exited ${status}, expected 2" >&2 + cat "${COLLECTION_LOG}" >&2 + exit 1 + } +fi +grep -q 'ERROR collecting e2e/python/test_broken.py' "${COLLECTION_LOG}" || { + echo "FAIL: collection diagnostics were discarded" >&2 + cat "${COLLECTION_LOG}" >&2 + exit 1 +} +echo "runner preserves failing collection diagnostics" + +# A direct no-deploy run must reject an endpoint override before attempting to +# resolve an interpreter or collect tests: the endpoint would split the suite +# between the metadata-selected gateway and the explicitly selected endpoint. +NO_DEPLOY_LOG="${WORKDIR}/no-deploy-endpoint.log" +if OPENSHELL_E2E_DEPLOY_GATEWAY=0 \ + OPENSHELL_GATEWAY_ENDPOINT="https://example.invalid" \ + "${SCRIPT_DIR}/../run-python-e2e.sh" "${WORKDIR}/unused.xml" > "${NO_DEPLOY_LOG}" 2>&1; then + echo "FAIL: no-deploy endpoint override unexpectedly succeeded" >&2 + exit 1 +else + status=$? + [[ "${status}" == 2 ]] || { + echo "FAIL: no-deploy endpoint override exited ${status}, expected 2" >&2 + cat "${NO_DEPLOY_LOG}" >&2 + exit 1 + } +fi +grep -q 'OPENSHELL_GATEWAY_ENDPOINT is set' "${NO_DEPLOY_LOG}" || { + echo "FAIL: no-deploy endpoint override did not explain the rejection" >&2 + cat "${NO_DEPLOY_LOG}" >&2 + exit 1 +} +echo "runner rejects an endpoint override in no-deploy mode" + +# A nonzero, non-0 value keeps deployment enabled. The entrypoint and direct +# runner must agree so callers cannot get a contradictory endpoint rejection. +FAKE_SUCCESS_PYTHON="${WORKDIR}/fake-success-python.sh" +RELATIVE_REPORT_NAME="results/$(basename "${WORKDIR}")-relative.xml" +RELATIVE_REPORT="${ROOT}/${RELATIVE_REPORT_NAME}" +RELATIVE_REPORT_DIR="${ROOT}/results" +if [[ ! -d "${RELATIVE_REPORT_DIR}" ]]; then + mkdir -- "${RELATIVE_REPORT_DIR}" + RELATIVE_REPORT_DIR_CREATED=1 +fi +cat > "${FAKE_SUCCESS_PYTHON}" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +while [[ $# -gt 0 ]]; do + case "$1" in + --junitxml) + printf '\n' > "$2" + shift 2 + ;; + *) shift ;; + esac +done +SH +chmod +x "${FAKE_SUCCESS_PYTHON}" +( + cd "${WORKDIR}" + PYTHON_BIN="${PYTHON_TEST_BIN}" \ + OPENSHELL_E2E_PYTHON="${FAKE_SUCCESS_PYTHON}" \ + OPENSHELL_E2E_DEPLOY_GATEWAY=false \ + OPENSHELL_GATEWAY_ENDPOINT="https://example.invalid" \ + "${SCRIPT_DIR}/../run-python-e2e.sh" "${RELATIVE_REPORT_NAME}" +) +[[ -f "${RELATIVE_REPORT}" ]] || { + echo "FAIL: relative report path was not resolved against the repository root" >&2 + exit 1 +} +rm -f "${RELATIVE_REPORT}" +echo "runner preserves deploy mode and resolves relative reports" + +# Tier 2 executes shared nextest, shared Python, then managed nextest. The +# merger must receive the reports in that same order rather than grouping them +# by runner type. +ORDERED_RESULTS_DIR="${WORKDIR}/ordered-results" +ORDERED_DEPLOY="${WORKDIR}/successful-deploy.sh" +ORDERED_PHASE_RUNNER="${WORKDIR}/phase-runner.sh" +ORDERED_MERGER="${WORKDIR}/capture-merge.py" +ORDERED_ARGS="${WORKDIR}/merge-args" +ORDERED_OPENSHELL="${WORKDIR}/openshell" +cat > "${ORDERED_DEPLOY}" <<'SH' +#!/usr/bin/env bash +exit 0 +SH +cat > "${ORDERED_PHASE_RUNNER}" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +printf '\n' > "$3" +SH +cat > "${ORDERED_OPENSHELL}" <<'SH' +#!/usr/bin/env bash +exit 0 +SH +cat > "${ORDERED_MERGER}" <<'PY' +import os +import sys +from pathlib import Path + +Path(os.environ["ORDERED_ARGS"]).write_text("\n".join(sys.argv[2:]) + "\n") +PY +chmod +x "${ORDERED_DEPLOY}" "${ORDERED_PHASE_RUNNER}" "${ORDERED_OPENSHELL}" +KUBECONFIG="${KUBECONFIG_FILE}" \ + OPENSHELL_E2E_RESULTS_DIR="${ORDERED_RESULTS_DIR}" \ + OPENSHELL_E2E_DEPLOY_SCRIPT="${ORDERED_DEPLOY}" \ + OPENSHELL_E2E_PHASE_RUNNER="${ORDERED_PHASE_RUNNER}" \ + OPENSHELL_E2E_REPORT_MERGER="${ORDERED_MERGER}" \ + OPENSHELL_E2E_PYTHON="${FAKE_SUCCESS_PYTHON}" \ + OPENSHELL_BIN="${ORDERED_OPENSHELL}" \ + ORDERED_ARGS="${ORDERED_ARGS}" \ + PYTHON_BIN="${PYTHON_TEST_BIN}" \ + PATH="${BIN_DIR}:${PATH}" \ + "${ENTRYPOINT}" tier2 > "${WORKDIR}/ordered.log" 2>&1 +expected_order="${ORDERED_RESULTS_DIR}/e2e-odh-tier2-shared.xml +${ORDERED_RESULTS_DIR}/e2e-odh-tier2-shared-python.xml +${ORDERED_RESULTS_DIR}/e2e-odh-tier2-managed.xml" +[[ "$(cat "${ORDERED_ARGS}")" == "${expected_order}" ]] || { + echo "FAIL: merger report order did not match Tier 2 execution order" >&2 + cat "${ORDERED_ARGS}" >&2 + exit 1 +} +echo "entrypoint merges reports in phase execution order" + +# Model cancellation during the small interval between forking the launcher +# and setsid(). The entrypoint must signal the direct child instead of waiting +# forever for a process group that has not been created yet. +SESSION_MARKER="${WORKDIR}/setsid-pending" +SESSION_PYTHON="${WORKDIR}/slow-session-python.sh" +SLOW_DEPLOY="${WORKDIR}/slow-deploy.sh" +cat > "${SESSION_PYTHON}" <<'SH' +#!/usr/bin/env bash +set -euo pipefail +if [[ "$1" == '-c' && "$2" == *'os.setsid()'* ]]; then + exec "${REAL_PYTHON}" -c 'import os, sys, time; open(os.environ["SESSION_MARKER"], "w").close(); time.sleep(2); os.setsid(); os.execvp(sys.argv[1], sys.argv[1:])' "${@:3}" +fi +exec "${REAL_PYTHON}" "$@" +SH +cat > "${SLOW_DEPLOY}" <<'SH' +#!/usr/bin/env bash +sleep 30 +SH +chmod +x "${SESSION_PYTHON}" "${SLOW_DEPLOY}" + +KUBECONFIG="${KUBECONFIG_FILE}" \ +OPENSHELL_E2E_RESULTS_DIR="${RESULTS_DIR}" \ +OPENSHELL_E2E_DEPLOY_SCRIPT="${SLOW_DEPLOY}" \ +GATEWAY_IMAGE="quay.io/opendatahub/odh-openshell-gateway@sha256:0000000000000000000000000000000000000000000000000000000000000000" \ +SANDBOX_IMAGE="quay.io/opendatahub/odh-openshell-sandbox@sha256:0000000000000000000000000000000000000000000000000000000000000000" \ +SUPERVISOR_IMAGE="quay.io/opendatahub/odh-openshell-supervisor@sha256:0000000000000000000000000000000000000000000000000000000000000000" \ +PYTHON_BIN="${SESSION_PYTHON}" \ +REAL_PYTHON="${PYTHON_TEST_BIN}" \ +SESSION_MARKER="${SESSION_MARKER}" \ +"${ENTRYPOINT}" smoke > "${WORKDIR}/cancellation.log" 2>&1 & +entrypoint_pid=$! +for _ in $(seq 1 100); do + [[ -f "${SESSION_MARKER}" ]] && break + sleep 0.05 +done +[[ -f "${SESSION_MARKER}" ]] || { + echo "FAIL: test launcher never reached the pre-setsid window" >&2 + kill -KILL "${entrypoint_pid}" 2>/dev/null || true + wait "${entrypoint_pid}" 2>/dev/null || true + exit 1 +} +( + sleep 5 + if kill -0 "${entrypoint_pid}" 2>/dev/null; then + touch "${WORKDIR}/cancellation-timeout" + kill -KILL "${entrypoint_pid}" 2>/dev/null || true + fi +) & +watchdog_pid=$! +kill -TERM "${entrypoint_pid}" +wait "${entrypoint_pid}" 2>/dev/null || true +kill "${watchdog_pid}" 2>/dev/null || true +wait "${watchdog_pid}" 2>/dev/null || true +[[ ! -e "${WORKDIR}/cancellation-timeout" ]] || { + echo "FAIL: entrypoint did not exit after cancellation before setsid" >&2 + cat "${WORKDIR}/cancellation.log" >&2 + exit 1 +} +echo "entrypoint cancels a pre-setsid launcher promptly" diff --git a/odh/scripts/tests/test-pytest-odh-gates.sh b/odh/scripts/tests/test-pytest-odh-gates.sh new file mode 100755 index 0000000000..96c6aed8e4 --- /dev/null +++ b/odh/scripts/tests/test-pytest-odh-gates.sh @@ -0,0 +1,125 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Exercise the pytest_odh_gates plugin's gates-loading error handling: a +# missing or malformed gates file must surface as a clean pytest UsageError +# naming the file, not as a pytest INTERNALERROR with a raw traceback. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +PLUGIN_DIR="${ROOT}/odh/scripts" + +WORKDIR="$(mktemp -d)" +trap 'rm -rf "${WORKDIR}"' EXIT + +# Prefer the project interpreter; the plugin requires both pytest and Python +# 3.11's tomllib module. A caller may still override it explicitly. +PYTHON_BIN="${PYTHON_BIN:-${ROOT}/.venv/bin/python}" +if [[ ! -x "${PYTHON_BIN}" ]]; then + PYTHON_BIN="$(command -v python3)" +fi +if ! "${PYTHON_BIN}" -c 'import pytest, tomllib' >/dev/null 2>&1; then + echo "SKIP: no Python 3.11+ interpreter with pytest available (PYTHON_BIN=${PYTHON_BIN})" >&2 + exit 0 +fi + +mkdir -p "${WORKDIR}/case" +cat > "${WORKDIR}/case/test_dummy.py" <<'PY' +def test_dummy(): + pass +PY + +run_gates() { + local gates_path="$1" strict="$2" + ( + cd "${WORKDIR}/case" + PYTHONPATH="${PLUGIN_DIR}:${ROOT}/python" \ + OPENSHELL_ODH_PYTHON_GATES="${gates_path}" \ + OPENSHELL_ODH_PYTHON_GATES_STRICT="${strict}" \ + "${PYTHON_BIN}" -m pytest -p pytest_odh_gates -q test_dummy.py 2>&1 + ) +} + +expect_usage_error() { + local label="$1" gates_path="$2" expected="$3" output status + if output="$(run_gates "${gates_path}" 1)"; then + status=0 + else + status=$? + fi + if [[ "${status}" == 0 ]]; then + echo "FAIL: ${label} passed, expected a pytest UsageError" >&2 + return 1 + fi + if grep -q "INTERNALERROR" <<<"${output}"; then + echo "FAIL: ${label} surfaced as a pytest INTERNALERROR instead of a UsageError" >&2 + return 1 + fi + grep -q -- "${expected}" <<<"${output}" || { + echo "FAIL: ${label} did not report the gates load failure clearly" >&2 + printf '%s\n' "${output}" >&2 + return 1 + } + echo "ok: ${label} reports a clean UsageError" +} + +expect_usage_error "missing gates file" "${WORKDIR}/does-not-exist.toml" "cannot load gates" + +printf 'this is [ not toml' > "${WORKDIR}/malformed.toml" +expect_usage_error "malformed gates TOML" "${WORKDIR}/malformed.toml" "cannot load gates" + +printf '[wrong]\n' > "${WORKDIR}/missing-gate.toml" +expect_usage_error "missing gate key" "${WORKDIR}/missing-gate.toml" "missing required 'gate'" + +cat > "${WORKDIR}/stale.toml" <<'TOML' +[[gate]] +category = "stale" +reason = "exercise strict collection validation" +tests = ["test_dummy.py::test_renamed_upstream_case"] +TOML +expect_usage_error "stale gate in strict mode" "${WORKDIR}/stale.toml" "gated tests were not collected" + +cat > "${WORKDIR}/duplicate.toml" <<'TOML' +[[gate]] +category = "one" +reason = "first declaration" +tests = ["test_dummy.py::test_dummy"] + +[[gate]] +category = "two" +reason = "second declaration" +tests = ["test_dummy.py::test_dummy"] +TOML +expect_usage_error "duplicate gated test" "${WORKDIR}/duplicate.toml" "is gated twice" + +cat > "${WORKDIR}/parametrized.toml" <<'TOML' +[[gate]] +category = "invalid" +reason = "gates must name the unparameterized node" +tests = ["test_dummy.py::test_dummy[value]"] +TOML +expect_usage_error "parameterized gate node ID" "${WORKDIR}/parametrized.toml" "invalid test node ID" + +# Control: a valid gates file loads and the run still passes with the gate +# applied as a skip (no strict mode, so an unmatched gate is not an error). +cat > "${WORKDIR}/valid.toml" <<'TOML' +[[gate]] +category = "control" +reason = "verify gates load" +tests = ["test_dummy.py::test_dummy"] +TOML +if ! run_gates "${WORKDIR}/valid.toml" 0 > "${WORKDIR}/control.log" 2>&1; then + echo "FAIL: valid gates file failed the control run:" >&2 + cat "${WORKDIR}/control.log" >&2 + exit 1 +fi +grep -q "1 skipped" "${WORKDIR}/control.log" || { + echo "FAIL: control gate did not skip the matching test:" >&2 + cat "${WORKDIR}/control.log" >&2 + exit 1 +} + +echo "pytest_odh_gates error handling checks passed" diff --git a/odh/scripts/tests/test-strip-skipped-testcases.sh b/odh/scripts/tests/test-strip-skipped-testcases.sh new file mode 100755 index 0000000000..d5fd3dbd52 --- /dev/null +++ b/odh/scripts/tests/test-strip-skipped-testcases.sh @@ -0,0 +1,119 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Exercise strip-skipped-testcases.py: skipped cases are removed, the suite +# attributes are recomputed from the surviving cases (so the report stays +# self-consistent after the merge script recalculates root totals), a fully +# skipped report exits 1 for the vacuous-pass check, and malformed XML +# exits 2 instead of crashing with a traceback. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HELPER="${SCRIPT_DIR}/../strip-skipped-testcases.py" +MERGER="${SCRIPT_DIR}/../merge-e2e-odh-reports.py" + +PYTHON_BIN="${PYTHON_BIN:-$(command -v python3)}" + +WORKDIR="$(mktemp -d)" +trap 'rm -rf "${WORKDIR}"' EXIT + +cat > "${WORKDIR}/mixed.xml" <<'XML' + + + + + + +XML + +if ! "${PYTHON_BIN}" "${HELPER}" "${WORKDIR}/mixed.xml" 2>"${WORKDIR}/stderr.log"; then + echo "FAIL: mixed report exited nonzero, expected 0" >&2 + cat "${WORKDIR}/stderr.log" >&2 + exit 1 +fi +grep -q "stripped 1 skipped" "${WORKDIR}/stderr.log" || { + echo "FAIL: audit line for the stripped case missing" >&2 + exit 1 +} +remaining="$(grep -c "&2; exit 1; } +for expected in 'tests="2"' 'skipped="0"' 'failures="1"' 'errors="0"'; do + grep -q -- "${expected}" "${WORKDIR}/mixed.xml" || { + echo "FAIL: suite attribute ${expected} not recomputed from surviving cases" >&2 + exit 1 + } +done +grep -q 'time="2.000000"' "${WORKDIR}/mixed.xml" || { + echo "FAIL: suite time not recomputed from surviving cases" >&2 + exit 1 +} +grep -q '^ &2 + exit 1 +} +echo "ok: mixed report stripped with consistent attributes" + +cat > "${WORKDIR}/all-skipped.xml" <<'XML' + + + + + +XML +if "${PYTHON_BIN}" "${HELPER}" "${WORKDIR}/all-skipped.xml" 2>/dev/null; then + echo "FAIL: fully skipped report exited 0, expected 1 (vacuous pass)" >&2 + exit 1 +else + status=$? + [[ "${status}" == 1 ]] || { echo "FAIL: fully skipped report exited ${status}, expected 1" >&2; exit 1; } +fi +[[ "$(grep -c "&2 + exit 1 +} +echo "ok: fully skipped report exits 1" + +printf ' "${WORKDIR}/malformed.xml" +if "${PYTHON_BIN}" "${HELPER}" "${WORKDIR}/malformed.xml" 2>"${WORKDIR}/malformed.log"; then + echo "FAIL: malformed report exited 0, expected 2" >&2 + exit 1 +else + status=$? + [[ "${status}" == 2 ]] || { echo "FAIL: malformed report exited ${status}, expected 2" >&2; exit 1; } +fi +grep -q "cannot parse" "${WORKDIR}/malformed.log" || { + echo "FAIL: malformed report error was not clear" >&2 + exit 1 +} +echo "ok: malformed report exits 2 with a clear error" + +if "${PYTHON_BIN}" "${HELPER}" "${WORKDIR}" 2>"${WORKDIR}/io-error.log"; then + echo "FAIL: directory report exited 0, expected 2" >&2 + exit 1 +else + status=$? + [[ "${status}" == 2 ]] || { echo "FAIL: directory report exited ${status}, expected 2" >&2; exit 1; } +fi +grep -q "cannot read or write" "${WORKDIR}/io-error.log" || { + echo "FAIL: I/O report error was not clear" >&2 + exit 1 +} +echo "ok: I/O errors exit 2 with a clear error" + +cat > "${WORKDIR}/nonnumeric-time.xml" <<'XML' + + +XML +OPENSHELL_E2E_RESULTS_DIR="${WORKDIR}" "${PYTHON_BIN}" "${MERGER}" tier2 "${WORKDIR}/nonnumeric-time.xml" > /dev/null || { + echo "FAIL: merger rejected a report the stripper accepts because time is nonnumeric" >&2 + exit 1 +} +grep -q 'time="0.000000"' "${WORKDIR}/e2e-odh-tier2-xunit.xml" || { + echo "FAIL: merger did not normalize a nonnumeric testcase time" >&2 + exit 1 +} +echo "ok: merger tolerates nonnumeric testcase times" + +echo "strip-skipped-testcases checks passed" diff --git a/odh/scripts/tests/test-tier-plan.sh b/odh/scripts/tests/test-tier-plan.sh new file mode 100755 index 0000000000..5a32a9dd8c --- /dev/null +++ b/odh/scripts/tests/test-tier-plan.sh @@ -0,0 +1,158 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Exercise the tier plan resolver's runner support: the python tier is plan +# data (no entrypoint special case), a phase may run several runners, the +# python runner reports are phase-scoped, unknown runners are rejected, and a +# python-only phase needs no nextest test selection. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" +PLAN_RESOLVER="${ROOT}/e2e/rust/tests/odh/tier_plan.py" +TIERS_FILE="${ROOT}/e2e/rust/tests/odh/tiers.toml" + +PYTHON_BIN="${PYTHON_BIN:-$(command -v python3)}" + +plan_json() { + "${PYTHON_BIN}" "${PLAN_RESOLVER}" "$1" "${TIERS_FILE}" +} + +expect_error() { + local label="$1" tier="$2" + if plan_json "${tier}" > /dev/null 2>&1; then + echo "FAIL: ${label} resolved, expected a validation error" >&2 + return 1 + fi + echo "ok: ${label} rejected" +} + +echo ">> the python tier resolves from plan data with the python runner only" +python_plan="$(plan_json python)" +python_phases="$(printf '%s' "${python_plan}" | "${PYTHON_BIN}" -c ' +import json, sys +plan = json.load(sys.stdin) +phases = plan["phases"] +assert len(phases) == 1, "expected 1 phase, got %d" % len(phases) +phase = phases[0] +assert phase["mode"] == "shared", phase["mode"] +assert phase["runners"] == ["python"], phase["runners"] +print("ok") +')" +printf '%s\n' "${python_phases}" + +echo ">> tier2's shared phase runs nextest and the python ride-along as data" +tier2_plan="$(plan_json tier2)" +printf '%s' "${tier2_plan}" | "${PYTHON_BIN}" -c ' +import json, sys +plan = json.load(sys.stdin) +shared = next(p for p in plan["phases"] if p["name"] == "shared") +assert shared["runners"] == ["nextest", "python"], shared["runners"] +managed = next(p for p in plan["phases"] if p["name"] == "managed") +assert managed["runners"] == ["nextest"], managed["runners"] +print("ok") +' + +echo ">> tiers without a runners key default to nextest only" +printf '%s' "$(plan_json smoke)" | "${PYTHON_BIN}" -c ' +import json, sys +plan = json.load(sys.stdin) +assert all(p["runners"] == ["nextest"] for p in plan["phases"]) +print("ok") +' + +echo ">> every declared tier still resolves" +while IFS= read -r tier; do + plan_json "${tier}" > /dev/null || { + echo "FAIL: tier ${tier} stopped resolving" >&2 + exit 1 + } +done < <("${PYTHON_BIN}" -c ' +import tomllib +with open("'"${TIERS_FILE}"'", "rb") as stream: + raw = tomllib.load(stream) +for key in raw: + if key not in {"modes", "global_test_exclusions"}: + print(key) +') +echo "ok: all tiers resolve" + +echo ">> validation: unknown runner, phase-scoped python runner, python-only without selection" +WORKDIR="$(mktemp -d)" +trap 'rm -rf "${WORKDIR}"' EXIT + +sed 's/^runners = \["python"\]$/runners = ["pythn"]/' "${TIERS_FILE}" > "${WORKDIR}/bad-runner.toml" +if "${PYTHON_BIN}" "${PLAN_RESOLVER}" python "${WORKDIR}/bad-runner.toml" > /dev/null 2>&1; then + echo "FAIL: unknown runner accepted" >&2 + exit 1 +fi +echo "ok: unknown runner rejected" + +cp "${TIERS_FILE}" "${WORKDIR}/dup-python.toml" +printf '\n[python.managed]\ndescription = "second python phase"\nrunners = ["python"]\n' >> "${WORKDIR}/dup-python.toml" +if ! duplicate_plan="$("${PYTHON_BIN}" "${PLAN_RESOLVER}" python "${WORKDIR}/dup-python.toml")"; then + echo "FAIL: phase-scoped python runners were rejected" >&2 + exit 1 +fi +if [[ "${duplicate_plan}" != *'"name": "managed"'* ]]; then + echo "FAIL: second python phase did not resolve" >&2 + exit 1 +fi +echo "ok: python runner may appear in multiple phases" + +cp "${TIERS_FILE}" "${WORKDIR}/python-rust-selection.toml" +sed_in_place() { + if sed --version > /dev/null 2>&1; then + sed -i "$@" + else + sed -i '' "$@" + fi +} +sed_in_place '/^runners = \["python"\]$/a\ +upstream_tests = ["workspace_lifecycle"]' "${WORKDIR}/python-rust-selection.toml" +if selection_error="$("${PYTHON_BIN}" "${PLAN_RESOLVER}" python "${WORKDIR}/python-rust-selection.toml" 2>&1)"; then + echo "FAIL: python-only phase accepted a nextest selection" >&2 + exit 1 +fi +if [[ "${selection_error}" != *"runners omit nextest"* ]]; then + echo "FAIL: expected python/nextest selection validation, got: ${selection_error}" >&2 + exit 1 +fi +echo "ok: python-only phase rejects a nextest selection" + +sed 's/^runners = \["python"\]$/runners = ["python", "python"]/' "${TIERS_FILE}" > "${WORKDIR}/same-phase-duplicate.toml" +if duplicate_phase_error="$("${PYTHON_BIN}" "${PLAN_RESOLVER}" python "${WORKDIR}/same-phase-duplicate.toml" 2>&1)"; then + echo "FAIL: duplicate runner within one phase accepted" >&2 + exit 1 +fi +if [[ "${duplicate_phase_error}" != *"duplicate runner"* ]]; then + echo "FAIL: expected same-phase duplicate validation, got: ${duplicate_phase_error}" >&2 + exit 1 +fi +echo "ok: duplicate runner within one phase rejected" + +cp "${TIERS_FILE}" "${WORKDIR}/duplicate-report-path.toml" +cat >> "${WORKDIR}/duplicate-report-path.toml" <<'TOML' + +[modes.shared-python] +expected_helm_values = { server = { drivers = { kubernetes = { workspaceMode = "shared" } } } } + +[python.shared-python] +description = "report path collision" +mode = "shared-python" +runners = ["nextest"] +upstream_tests = ["workspace_lifecycle"] +TOML +if report_path_error="$("${PYTHON_BIN}" "${PLAN_RESOLVER}" python "${WORKDIR}/duplicate-report-path.toml" 2>&1)"; then + echo "FAIL: duplicate derived report path accepted" >&2 + exit 1 +fi +if [[ "${report_path_error}" != *"duplicate derived report path"* ]]; then + echo "FAIL: expected report-path validation, got: ${report_path_error}" >&2 + exit 1 +fi +echo "ok: duplicate derived report paths rejected" + +echo "tier plan runner checks passed" diff --git a/odh/scripts/tests/test_discover_e2e_images.sh b/odh/scripts/tests/test_discover_e2e_images.sh index d2edc4fb49..92edb8641c 100755 --- a/odh/scripts/tests/test_discover_e2e_images.sh +++ b/odh/scripts/tests/test_discover_e2e_images.sh @@ -141,6 +141,19 @@ set -euo pipefail printf 'phase|%s\n' "$*" >> "${FAKE_OC_WORK_DIR}/calls" printf '\n' "$2" > "$3" FAKEPHASE + cat > "${WORK_DIR}/bin/python-e2e" <<'FAKEPYTHON' +#!/usr/bin/env bash +set -euo pipefail +while [[ $# -gt 0 ]]; do + case "$1" in + --junitxml) + printf '\n' > "$2" + shift 2 + ;; + *) shift ;; + esac +done +FAKEPYTHON cat > "${WORK_DIR}/bin/openshell" <<'FAKECLI' #!/usr/bin/env bash printf 'openshell|%s\n' "$*" >> "${FAKE_OC_WORK_DIR}/calls" @@ -166,6 +179,7 @@ FAKESLEEP export OPENSHELL_BIN="${WORK_DIR}/bin/openshell" export OPENSHELL_E2E_DEPLOY_SCRIPT="${WORK_DIR}/bin/deploy" export OPENSHELL_E2E_PHASE_RUNNER="${WORK_DIR}/bin/phase" + export OPENSHELL_E2E_PYTHON="${WORK_DIR}/bin/python-e2e" } teardown() { diff --git a/tasks/test-odh.toml b/tasks/test-odh.toml index 0190e80520..c240939ca7 100644 --- a/tasks/test-odh.toml +++ b/tasks/test-odh.toml @@ -25,6 +25,11 @@ description = "Run ODH scenarios and managed-workspace tests in their gateway mo depends = ["build:openshell-cli"] run = "odh/scripts/e2e-odh-entrypoint.sh odh" +["e2e:odh:python"] +description = "Run supported upstream Python gateway E2E against an OpenShift deployment" +depends = ["build:openshell-cli", "python:dev"] +run = "odh/scripts/e2e-odh-entrypoint.sh python" + ["e2e:odh:full"] description = "Run all feature-enabled e2e binaries across shared and managed gateway modes" depends = ["build:openshell-cli"] @@ -42,7 +47,9 @@ run = "odh/scripts/e2e-odh-entrypoint.sh tier1" ["e2e:odh:tier2"] description = "Run Tier 2: upstream + ODH, medium/low priority positive tests" -depends = ["build:openshell-cli"] +# tier2's shared phase also runs the Python gateway suite, which needs the +# project environment a fresh checkout does not have yet. +depends = ["build:openshell-cli", "python:dev"] run = "odh/scripts/e2e-odh-entrypoint.sh tier2" ["e2e:odh:tier3"] @@ -50,6 +57,22 @@ description = "Run Tier 3: upstream + ODH, negative and destructive tests" depends = ["build:openshell-cli"] run = "odh/scripts/e2e-odh-entrypoint.sh tier3" +["test:odh-python-gates"] +description = "Test the ODH Python E2E gates tooling without a cluster" +depends = ["python:dev"] +run = """ +odh/scripts/tests/test-pytest-odh-gates.sh +odh/scripts/tests/test-strip-skipped-testcases.sh +odh/scripts/tests/test-tier-plan.sh +odh/scripts/tests/test-check-python-e2e-requirements.sh +odh/scripts/tests/test-e2e-odh-entrypoint.sh +OPENSHELL_E2E_OIDC=0 \ +OPENSHELL_ODH_PYTHON_GATES_STRICT=1 \ +"$PWD/odh/scripts/run-python-e2e.sh" --collect-only +""" +hide = true +run_windows = "echo Skipping test:odh-python-gates: the Unix ODH scripts do not apply on Windows." + ["test:odh-deploy-digests"] description = "Test ODH deploy script image-digest plumbing without a cluster" run = "odh/scripts/tests/test-openshell-deploy-from-quay.sh"