|
| 1 | +# Copyright (c) 2025 - 2025, Oracle and/or its affiliates. All rights reserved. |
| 2 | +# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/. |
| 3 | + |
| 4 | +"""This module tests the existing-policy flag supported by the policy engine.""" |
| 5 | + |
| 6 | +import argparse |
| 7 | +import os |
| 8 | +from pathlib import Path |
| 9 | +from unittest.mock import MagicMock, patch |
| 10 | + |
| 11 | +from macaron.__main__ import verify_policy |
| 12 | + |
| 13 | + |
| 14 | +def test_verify_existing_policy_success(tmp_path: Path) -> None: |
| 15 | + """When an existing policy is provided and package-url is valid, verify_policy returns EX_OK.""" |
| 16 | + db_file = tmp_path / "macaron.db" |
| 17 | + db_file.write_text("") |
| 18 | + |
| 19 | + # Use a MagicMock for the handler. |
| 20 | + mock_handler = MagicMock() |
| 21 | + |
| 22 | + # Fake run_policy_engine and generate_vsa that returns a fixed result. |
| 23 | + fake_run = MagicMock(return_value={"passed_policies": [["check-component"]], "failed_policies": []}) |
| 24 | + fake_generate_vsa = MagicMock(return_value=None) |
| 25 | + |
| 26 | + # Fake PolicyReporter class: when called, returns an instance with generate method. |
| 27 | + fake_policy_reporter_cls = MagicMock() |
| 28 | + fake_policy_reporter_inst = MagicMock() |
| 29 | + fake_policy_reporter_inst.generate.return_value = None |
| 30 | + fake_policy_reporter_cls.return_value = fake_policy_reporter_inst |
| 31 | + |
| 32 | + with ( |
| 33 | + patch("macaron.__main__.run_policy_engine", fake_run), |
| 34 | + patch("macaron.__main__.generate_vsa", fake_generate_vsa), |
| 35 | + patch("macaron.__main__.access_handler.get_handler", return_value=mock_handler), |
| 36 | + patch("macaron.__main__.PolicyReporter", fake_policy_reporter_cls), |
| 37 | + ): |
| 38 | + policy_args = argparse.Namespace( |
| 39 | + database=str(db_file), |
| 40 | + show_prelude=False, |
| 41 | + file=None, |
| 42 | + existing_policy="malware-detection", |
| 43 | + package_url="pkg:pypi/django", |
| 44 | + ) |
| 45 | + result = verify_policy(policy_args) |
| 46 | + assert result == os.EX_OK |
| 47 | + |
| 48 | + |
| 49 | +def test_verify_existing_policy_not_found(tmp_path: Path) -> None: |
| 50 | + """Requesting a non-existent policy returns usage error.""" |
| 51 | + db_file = tmp_path / "macaron.db" |
| 52 | + db_file.write_text("") |
| 53 | + policy_args = argparse.Namespace( |
| 54 | + database=str(db_file), |
| 55 | + show_prelude=False, |
| 56 | + file=None, |
| 57 | + existing_policy="no-such-policy", |
| 58 | + package_url="pkg:pypi/django", |
| 59 | + ) |
| 60 | + result = verify_policy(policy_args) |
| 61 | + assert result == os.EX_USAGE |
0 commit comments