Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/cfnlint/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""
6 changes: 5 additions & 1 deletion src/cfnlint/runner/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()


Expand Down
27 changes: 10 additions & 17 deletions src/cfnlint/schema/_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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():
Expand Down
7 changes: 4 additions & 3 deletions src/cfnlint/schema/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
7 changes: 4 additions & 3 deletions src/cfnlint/schema/other_schema_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
28 changes: 28 additions & 0 deletions test/unit/module/runner/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
16 changes: 8 additions & 8 deletions test/unit/module/schema/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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):
Expand Down
19 changes: 7 additions & 12 deletions test/unit/module/schema/test_other_schema_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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")
Expand Down
30 changes: 18 additions & 12 deletions test/unit/module/schema/test_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
Loading