diff --git a/src/cfnlint/exceptions.py b/src/cfnlint/exceptions.py index 13d708389d..ac4b0b83aa 100644 --- a/src/cfnlint/exceptions.py +++ b/src/cfnlint/exceptions.py @@ -96,3 +96,10 @@ def __init__(self, msg: str, config: ConfigMixIn): """ super().__init__(msg) self.config = config + + +class SchemaPatchError(CfnLintExitException): + """ + An exception that is raised when an override spec cannot be read or a JSON + patch in it cannot be applied to the schema it names. + """ diff --git a/src/cfnlint/runner/cli.py b/src/cfnlint/runner/cli.py index d9f2cac97a..522f6d30db 100644 --- a/src/cfnlint/runner/cli.py +++ b/src/cfnlint/runner/cli.py @@ -351,7 +351,11 @@ def main() -> None: except Exception as e: print(e) sys.exit(1) - runner = Runner(config) + try: + runner = Runner(config) + except CfnLintExitException as e: + LOGGER.error(str(e)) + sys.exit(e.exit_code) runner.cli() diff --git a/src/cfnlint/schema/_patch.py b/src/cfnlint/schema/_patch.py index d11830e0b9..1389009a11 100644 --- a/src/cfnlint/schema/_patch.py +++ b/src/cfnlint/schema/_patch.py @@ -6,16 +6,13 @@ from __future__ import annotations import json -import logging -import sys from dataclasses import dataclass from typing import Dict, Sequence +from cfnlint.exceptions import SchemaPatchError from cfnlint.schema.manager import PROVIDER_SCHEMA_MANAGER from cfnlint.schema.other_schema_manager import OTHER_SCHEMA_MANAGER -LOGGER = logging.getLogger(__name__) - @dataclass class SchemaPatch: @@ -43,22 +40,18 @@ def patch(filename: str, regions: Sequence[str]): OTHER_SCHEMA_MANAGER.patch(schema_patch, region) except IOError as e: if e.errno == 2: - LOGGER.error("Override spec file not found: %s", filename) - sys.exit(1) + msg = f"Override spec file not found: {filename}" elif e.errno == 21: - LOGGER.error( - "Override spec file references a directory, not a file: %s", - filename, - ) - sys.exit(1) + msg = f"Override spec file references a directory, not a file: {filename}" elif e.errno == 13: - LOGGER.error( - "Permission denied when accessing override spec file: %s", filename - ) - sys.exit(1) + msg = f"Permission denied when accessing override spec file: {filename}" + else: + msg = f"Override spec file {filename} could not be read: {e}" + raise SchemaPatchError(msg) from e except ValueError as err: - LOGGER.error("Override spec file %s is malformed: %s", filename, err) - sys.exit(1) + raise SchemaPatchError( + f"Override spec file {filename} is malformed: {err}" + ) from err def reset(): diff --git a/src/cfnlint/schema/manager.py b/src/cfnlint/schema/manager.py index 7c820a371d..e2281fe8bd 100644 --- a/src/cfnlint/schema/manager.py +++ b/src/cfnlint/schema/manager.py @@ -10,13 +10,13 @@ import os import re import shutil -import sys import tempfile import zipfile from functools import lru_cache from pathlib import Path from typing import TYPE_CHECKING, Any, Iterator, Sequence +from cfnlint.exceptions import SchemaPatchError from cfnlint.helpers import ( REGIONS, get_cache_dir, @@ -535,8 +535,9 @@ def patch(self, patch: SchemaPatch, region: str) -> None: try: schema.patch(patches=patches) except Exception as e: - print(f"Error applying patch {patches} for {resource_type}: {e}") - sys.exit(1) + raise SchemaPatchError( + f"Error applying patch {patches} for {resource_type}: {e}" + ) from e @lru_cache(maxsize=None) def get_type_getatts(self, resource_type: str, region: str) -> AttributeDict: diff --git a/src/cfnlint/schema/other_schema_manager.py b/src/cfnlint/schema/other_schema_manager.py index b85b514487..18f2bcda0f 100644 --- a/src/cfnlint/schema/other_schema_manager.py +++ b/src/cfnlint/schema/other_schema_manager.py @@ -9,12 +9,12 @@ import json import logging import os -import sys from functools import lru_cache from typing import TYPE_CHECKING, Any import jsonpatch +from cfnlint.exceptions import SchemaPatchError from cfnlint.helpers import load_resource from cfnlint.schema._exceptions import SchemaNotFoundError @@ -122,8 +122,9 @@ def patch(self, patch: SchemaPatch, region: str) -> None: self._schemas[schema_path], in_place=True ) except Exception as e: - print(f"Error applying patch {patches} for {schema_path}: {e}") - sys.exit(1) + raise SchemaPatchError( + f"Error applying patch {patches} for {schema_path}: {e}" + ) from e OTHER_SCHEMA_MANAGER: OtherSchemaManager = OtherSchemaManager() diff --git a/test/unit/module/runner/test_cli.py b/test/unit/module/runner/test_cli.py index 80573199c5..b074458f90 100644 --- a/test/unit/module/runner/test_cli.py +++ b/test/unit/module/runner/test_cli.py @@ -291,3 +291,31 @@ def test_main_config_file_error_none_config(self, mock_config): with self.assertRaises(SystemExit): main() mock_print.assert_called_once_with("Invalid key 'bad'") + + +class TestMainOverrideSpec(BaseTestCase): + """main() turns a bad override spec into an exit code, not a traceback""" + + @patch( + "sys.argv", + [ + "cfn-lint", + "--override-spec", + "/nonexistent/spec.json", + "-t", + "test/fixtures/templates/good/generic.yaml", + ], + ) + def test_missing_override_spec_exits_one(self): + from cfnlint.runner.cli import main + from cfnlint.schema import _patch + + _patch.reset() + try: + with self.assertLogs("cfnlint.runner.cli", level="ERROR") as logs: + with self.assertRaises(SystemExit) as e: + main() + self.assertEqual(e.exception.code, 1) + self.assertIn("Override spec file not found", logs.output[0]) + finally: + _patch.reset() diff --git a/test/unit/module/schema/test_manager.py b/test/unit/module/schema/test_manager.py index 9a11918c2e..f85b334848 100644 --- a/test/unit/module/schema/test_manager.py +++ b/test/unit/module/schema/test_manager.py @@ -12,6 +12,7 @@ from test.testlib.testcase import BaseTestCase from unittest.mock import MagicMock, patch +from cfnlint.exceptions import SchemaPatchError from cfnlint.helpers import get_cache_dir from cfnlint.schema._patch import SchemaPatch from cfnlint.schema._schema import Schema @@ -460,9 +461,7 @@ def setUp(self) -> None: self.manager = _make_manager() self.schema_patch = [{"op": "add", "path": "/cfnSchema", "value": ["test"]}] - @patch("cfnlint.schema.manager.print") - @patch("cfnlint.schema.manager.sys.exit") - def test_patch_failure(self, mock_exit, mock_print): + def test_patch_failure(self): """Test when patching a schema fails""" mock_schema = MagicMock() mock_schema.patch.side_effect = Exception("Invalid patch operation") @@ -472,14 +471,15 @@ def test_patch_failure(self, mock_exit, mock_print): resource_type = "AWS::EC2::Instance" patch = SchemaPatch([], [], {resource_type: self.schema_patch}) - self.manager.patch(patch, "us-east-1") + with self.assertRaises(SchemaPatchError) as raised: + self.manager.patch(patch, "us-east-1") - mock_print.assert_called_with( + self.assertEqual( + str(raised.exception), f"Error applying patch {self.schema_patch} for " - f"{resource_type}: Invalid patch operation" + f"{resource_type}: Invalid patch operation", ) - - mock_exit.assert_called_with(1) + self.assertEqual(raised.exception.exit_code, 1) class TestReadSchemaDate(BaseTestCase): diff --git a/test/unit/module/schema/test_other_schema_manager.py b/test/unit/module/schema/test_other_schema_manager.py index b211a24204..71d603811e 100644 --- a/test/unit/module/schema/test_other_schema_manager.py +++ b/test/unit/module/schema/test_other_schema_manager.py @@ -9,6 +9,7 @@ from test.testlib.testcase import BaseTestCase from unittest.mock import MagicMock, mock_open, patch +from cfnlint.exceptions import SchemaPatchError from cfnlint.schema._patch import SchemaPatch from cfnlint.schema.other_schema_manager import OtherSchemaManager, SchemaNotFoundError @@ -109,11 +110,7 @@ def test_patch_schema_not_found(self, mock_json_patch, mock_load_resource): @patch("cfnlint.schema.other_schema_manager.load_resource") @patch("cfnlint.schema.other_schema_manager.jsonpatch.JsonPatch") - @patch("cfnlint.schema.other_schema_manager.sys.exit") - @patch("cfnlint.schema.other_schema_manager.print") - def test_patch_failure( - self, mock_print, mock_exit, mock_json_patch, mock_load_resource - ): + def test_patch_failure(self, mock_json_patch, mock_load_resource): """Test when patching a schema fails""" # Setup the schema to be loaded successfully mock_load_resource.return_value = self.test_schema @@ -128,17 +125,15 @@ def test_patch_failure( patch = SchemaPatch([], [], {schema_path: self.schema_patch}) # Apply the patch - self.manager.patch(patch, "us-east-1") + with self.assertRaises(SchemaPatchError) as raised: + self.manager.patch(patch, "us-east-1") - # Verify that print was called with the error message - mock_print.assert_called_with( + self.assertEqual( + str(raised.exception), f"Error applying patch {self.schema_patch} for " - f"{schema_path}: Invalid patch operation" + f"{schema_path}: Invalid patch operation", ) - # Verify that sys.exit was called with exit code 1 - mock_exit.assert_called_with(1) - @patch("cfnlint.schema.other_schema_manager.open", new_callable=mock_open) @patch("cfnlint.schema.other_schema_manager.os.walk") @patch("cfnlint.schema.other_schema_manager.os.path.join") diff --git a/test/unit/module/schema/test_patch.py b/test/unit/module/schema/test_patch.py index 2d6dab38ae..4ceb828643 100644 --- a/test/unit/module/schema/test_patch.py +++ b/test/unit/module/schema/test_patch.py @@ -3,6 +3,7 @@ from test.testlib.testcase import BaseTestCase from unittest.mock import mock_open, patch +from cfnlint.exceptions import SchemaPatchError from cfnlint.schema._patch import SchemaPatch from cfnlint.schema._patch import patch as schema_patch from cfnlint.schema._patch import reset @@ -81,39 +82,44 @@ def test_patch_file_not_found_error(self): err = FileNotFoundError() err.errno = 2 mock_builtin_open.side_effect = [err] - with self.assertRaises(SystemExit) as mock_exit: + with self.assertRaises(SchemaPatchError) as raised: schema_patch("bad", regions=["us-east-1"]) - self.assertEqual(mock_exit.type, SystemExit) - self.assertEqual(mock_exit.value.code == 1) + self.assertEqual(raised.exception.exit_code, 1) def test_patch_file_is_dir(self): with patch("builtins.open", mock_open()) as mock_builtin_open: err = IOError() err.errno = 21 mock_builtin_open.side_effect = [err] - with self.assertRaises(SystemExit) as mock_exit: + with self.assertRaises(SchemaPatchError) as raised: schema_patch("bad", regions=["us-east-1"]) - self.assertEqual(mock_exit.type, SystemExit) - self.assertEqual(mock_exit.value.code == 1) + self.assertEqual(raised.exception.exit_code, 1) def test_patch_permission_error(self): with patch("builtins.open", mock_open()) as mock_builtin_open: err = PermissionError() err.errno = 13 mock_builtin_open.side_effect = [err] - with self.assertRaises(SystemExit) as mock_exit: + with self.assertRaises(SchemaPatchError) as raised: schema_patch("bad", regions=["us-east-1"]) - self.assertEqual(mock_exit.type, SystemExit) - self.assertEqual(mock_exit.value.code == 1) + self.assertEqual(raised.exception.exit_code, 1) + + def test_patch_other_io_error(self): + with patch("builtins.open", mock_open()) as mock_builtin_open: + err = IOError() + err.errno = 5 + mock_builtin_open.side_effect = [err] + with self.assertRaises(SchemaPatchError) as raised: + schema_patch("bad", regions=["us-east-1"]) + self.assertEqual(raised.exception.exit_code, 1) def test_patch_value_error(self): with patch("builtins.open", mock_open()) as mock_builtin_open: err = ValueError() mock_builtin_open.side_effect = [err] - with self.assertRaises(SystemExit) as mock_exit: + with self.assertRaises(SchemaPatchError) as raised: schema_patch("bad", regions=["us-east-1"]) - self.assertEqual(mock_exit.type, SystemExit) - self.assertEqual(mock_exit.value.code == 1) + self.assertEqual(raised.exception.exit_code, 1) @patch("cfnlint.schema._patch.PROVIDER_SCHEMA_MANAGER") @patch("cfnlint.schema._patch.OTHER_SCHEMA_MANAGER")