hc99 commited on
Commit
26e6f31
·
verified ·
1 Parent(s): e18c302

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/aws-cloudformation__cfn-lint/.pre-commit-config.yaml +44 -0
  2. testbed/aws-cloudformation__cfn-lint/.pre-commit-hooks.yaml +18 -0
  3. testbed/aws-cloudformation__cfn-lint/CHANGELOG.md +0 -0
  4. testbed/aws-cloudformation__cfn-lint/CODE_OF_CONDUCT.md +4 -0
  5. testbed/aws-cloudformation__cfn-lint/CONTRIBUTING.md +104 -0
  6. testbed/aws-cloudformation__cfn-lint/Dockerfile +7 -0
  7. testbed/aws-cloudformation__cfn-lint/LICENSE +14 -0
  8. testbed/aws-cloudformation__cfn-lint/MANIFEST.in +2 -0
  9. testbed/aws-cloudformation__cfn-lint/NOTICE +2 -0
  10. testbed/aws-cloudformation__cfn-lint/README.md +364 -0
  11. testbed/aws-cloudformation__cfn-lint/custom_rules.txt +3 -0
  12. testbed/aws-cloudformation__cfn-lint/pyproject.toml +211 -0
  13. testbed/aws-cloudformation__cfn-lint/setup.cfg +2 -0
  14. testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/__init__.py +4 -0
  15. testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-instance.yaml +20 -0
  16. testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml +14 -0
  17. testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-networkinterface.yaml +17 -0
  18. testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-subnet.yaml +19 -0
  19. testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/__init__.py +0 -0
  20. testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/test_validator_cfn.py +366 -0
  21. testbed/aws-cloudformation__cfn-lint/test/integration/rules/__init__.py +0 -0
  22. testbed/aws-cloudformation__cfn-lint/test/integration/rules/test_rules.py +32 -0
  23. testbed/aws-cloudformation__cfn-lint/test/integration/test_good_templates.py +228 -0
  24. testbed/aws-cloudformation__cfn-lint/test/integration/test_integration_templates.py +104 -0
  25. testbed/aws-cloudformation__cfn-lint/test/integration/test_patches.py +28 -0
  26. testbed/aws-cloudformation__cfn-lint/test/integration/test_quickstart_templates_non_strict.py +71 -0
  27. testbed/aws-cloudformation__cfn-lint/test/integration/test_schema_files.py +282 -0
  28. testbed/aws-cloudformation__cfn-lint/test/testlib/__init__.py +4 -0
  29. testbed/aws-cloudformation__cfn-lint/test/testlib/testcase.py +33 -0
  30. testbed/aws-cloudformation__cfn-lint/test/unit/__init__.py +4 -0
  31. testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/__init__.py +4 -0
  32. testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/test_cfn_json.py +109 -0
  33. testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_yaml/test_yaml.py +77 -0
  34. testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/__init__.py +4 -0
  35. testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_condition.py +97 -0
  36. testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_conditions.py +331 -0
  37. testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_equals.py +74 -0
  38. testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_rules.py +524 -0
  39. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/__init__.py +4 -0
  40. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_cli_args.py +137 -0
  41. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_file_args.py +137 -0
  42. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_mixin.py +265 -0
  43. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_logging.py +41 -0
  44. testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_template_args.py +105 -0
  45. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/__init__.py +0 -0
  46. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/__init__.py +0 -0
  47. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_conditions.py +299 -0
  48. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_equals_sort.py +105 -0
  49. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_context.py +108 -0
  50. testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_create_context.py +115 -0
testbed/aws-cloudformation__cfn-lint/.pre-commit-config.yaml ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.6.0
4
+ hooks:
5
+ - id: check-ast
6
+ - id: check-json
7
+ exclude: "(test/fixtures/templates/bad/json_parse.json|test/fixtures/templates/bad/core/config_invalid_json.json|test/fixtures/templates/bad/duplicate.json)"
8
+ - id: check-toml
9
+ - id: check-vcs-permalinks
10
+ - id: check-yaml
11
+ exclude: "test/fixtures/templates/"
12
+ args: [--unsafe]
13
+ - id: debug-statements
14
+ - id: end-of-file-fixer
15
+ - id: mixed-line-ending
16
+ args: [--fix, auto]
17
+ - id: trailing-whitespace
18
+ - repo: https://github.com/psf/black
19
+ rev: 24.8.0
20
+ hooks:
21
+ - id: black
22
+ - repo: https://github.com/PyCQA/isort
23
+ rev: 5.13.2
24
+ hooks:
25
+ - id: isort
26
+ - repo: https://github.com/charliermarsh/ruff-pre-commit
27
+ rev: "v0.5.7"
28
+ hooks:
29
+ - id: ruff
30
+ - repo: https://github.com/PyCQA/bandit
31
+ rev: "1.7.9"
32
+ hooks:
33
+ - id: bandit
34
+ additional_dependencies:
35
+ - "bandit[toml]"
36
+ args: ["-c", "pyproject.toml"]
37
+ - repo: https://github.com/pre-commit/mirrors-mypy
38
+ rev: "v1.11.1"
39
+ hooks:
40
+ - id: mypy
41
+ additional_dependencies:
42
+ - "types-PyYAML"
43
+ - "types-regex"
44
+ - "types-requests"
testbed/aws-cloudformation__cfn-lint/.pre-commit-hooks.yaml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - id: cfn-python-lint
2
+ name: AWS CloudFormation Linter
3
+ description: 'cfn-lint is a tool for finding issues with CloudFormation templates'
4
+ entry: cfn-lint
5
+ language: python
6
+ files: \.(json|yaml|yml)$
7
+ - id: cfn-lint # we have removed most identifications to cfn-python-lint
8
+ name: AWS CloudFormation Linter
9
+ description: 'cfn-lint is a tool for finding issues with CloudFormation templates'
10
+ entry: cfn-lint
11
+ language: python
12
+ files: \.(json|yaml|yml)$
13
+ - id: cfn-lint-rc # Provide a configuration to use with .cfnlintrc
14
+ name: AWS CloudFormation Linter
15
+ description: 'cfn-lint is a tool for finding issues with CloudFormation templates'
16
+ entry: cfn-lint
17
+ language: python
18
+ pass_filenames: false
testbed/aws-cloudformation__cfn-lint/CHANGELOG.md ADDED
The diff for this file is too large to render. See raw diff
 
testbed/aws-cloudformation__cfn-lint/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ## Code of Conduct
2
+ This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3
+ For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4
+ opensource-codeofconduct@amazon.com with any additional questions or comments.
testbed/aws-cloudformation__cfn-lint/CONTRIBUTING.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing Guidelines
2
+
3
+ Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4
+ documentation, we greatly value feedback and contributions from our community.
5
+
6
+ Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7
+ information to effectively respond to your bug report or contribution.
8
+
9
+
10
+ ## Reporting Bugs/Feature Requests
11
+
12
+ We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13
+
14
+ When filing an issue, please check [existing open](https://github.com/aws-cloudformation/cfn-python-lint/issues), or [recently closed](https://github.com/aws-cloudformation/cfn-python-lint/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already
15
+ reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16
+
17
+ * A reproducible test case or series of steps
18
+ * The version of our code being used
19
+ * Any modifications you've made relevant to the bug
20
+ * Anything unusual about your environment or deployment
21
+
22
+ ## Development Environment
23
+
24
+ 1. You will need Python 3 >= 3.5. Verify which version you have by running `python --version`.
25
+
26
+ > If you don't have it installed, download it [here](https://www.python.org/downloads/). When you do this, `pip` should be installed automatically.
27
+
28
+ 1. Install `cfn-lint` from source by forking the repository and then doing a developer install:
29
+
30
+ ```bash
31
+ # fork the repository
32
+ git clone https://github.com/<YOUR-USERNAME>/cfn-python-lint.git
33
+ cd cfn-python-lint
34
+ pip3 install -e .
35
+ ```
36
+
37
+ 1. Run `pip3 show cfn-lint`. The `Location` printed should be the folder from the step above.
38
+ 1. You should now be able to modify the source code and see the changes immediately by running any of the `cfn-lint` commands. (Note: run `pip3 install -e .` again to re-install changes).
39
+
40
+ ## Running the tests
41
+
42
+ The unit tests (and `pylint` for linting the Python code) are processed by [`tox`](https://tox.readthedocs.io/en/latest/). The configuration file is [tox.ini](/tox.ini).
43
+
44
+ Make sure Tox is installed and then run Tox by just calling it:
45
+
46
+ ```bash
47
+ # Install Tox
48
+ $ pip install tox
49
+
50
+ # Run all tests (This command is also used when validating a Pull Request)
51
+ $ tox
52
+
53
+ # Run a specific test suite
54
+ $ tox -e py37 # Run all unit tests against Python 3.7
55
+ ```
56
+ Tox test suites available:
57
+ * **py37**: Unit tests (Python 3.7)
58
+ * **py38**: Unit tests (Python 3.8)
59
+ * **py39**: Unit tests (Python 3.9)
60
+ * **py310**: Unit tests (Python 3.10)
61
+ * **py311**: Unit tests (Python 3.11)
62
+ * **py312**: Unit tests (Python 3.12)
63
+ * **py313**: Unit tests (Python 3.13)
64
+ * **style**: Python syntax check
65
+
66
+ ## Contributing via Pull Requests
67
+ Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
68
+
69
+ 1. You are working against the latest source on the *main* branch.
70
+ 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
71
+ 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
72
+
73
+ To send us a pull request, please:
74
+
75
+ 1. Fork the repository.
76
+ 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
77
+ 3. Ensure local tests pass.
78
+ 4. Commit to your fork using clear commit messages.
79
+ 5. Send us a pull request, answering any default questions in the pull request interface.
80
+ 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
81
+
82
+ GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
83
+ [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
84
+
85
+
86
+ ## Finding contributions to work on
87
+ Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws-cloudformation/cfn-python-lint/labels/help%20wanted) issues is a great place to start.
88
+
89
+
90
+ ## Code of Conduct
91
+ This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
92
+ For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
93
+ opensource-codeofconduct@amazon.com with any additional questions or comments.
94
+
95
+
96
+ ## Security issue notifications
97
+ If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public GitHub issue.
98
+
99
+
100
+ ## Licensing
101
+
102
+ See the [LICENSE](https://github.com/aws-cloudformation/cfn-python-lint/blob/main/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
103
+
104
+ We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
testbed/aws-cloudformation__cfn-lint/Dockerfile ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ FROM public.ecr.aws/docker/library/python:3.13-alpine3.20
2
+
3
+ RUN pip install cfn-lint[full]
4
+ RUN pip install pydot
5
+
6
+ ENTRYPOINT ["cfn-lint"]
7
+ CMD ["--help"]
testbed/aws-cloudformation__cfn-lint/LICENSE ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT No Attribution
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this
4
+ software and associated documentation files (the "Software"), to deal in the Software
5
+ without restriction, including without limitation the rights to use, copy, modify,
6
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
7
+ permit persons to whom the Software is furnished to do so.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
10
+ INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
11
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
12
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
13
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
14
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
testbed/aws-cloudformation__cfn-lint/MANIFEST.in ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ include README.md LICENSE
2
+ recursive-include test *
testbed/aws-cloudformation__cfn-lint/NOTICE ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ cfn-flip
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
testbed/aws-cloudformation__cfn-lint/README.md ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AWS CloudFormation Linter
2
+
3
+ <img alt="[cfn-lint logo]" src="https://github.com/aws-cloudformation/cfn-python-lint/blob/main/logo.png?raw=true" width="150" align="right">
4
+
5
+ [![Testing](https://github.com/aws-cloudformation/cfn-python-lint/actions/workflows/test.yaml/badge.svg?branch=main)](https://github.com/aws-cloudformation/cfn-python-lint/actions/workflows/test.yaml)
6
+ [![PyPI version](https://badge.fury.io/py/cfn-lint.svg)](https://badge.fury.io/py/cfn-lint)
7
+ [![PyPI downloads](https://pepy.tech/badge/cfn-lint/week)](https://pypistats.org/packages/cfn-lint)
8
+ [![PyPI downloads](https://pepy.tech/badge/cfn-lint/month)](https://pypistats.org/packages/cfn-lint)
9
+ [![codecov](https://codecov.io/gh/aws-cloudformation/cfn-lint/branch/main/graph/badge.svg)](https://codecov.io/gh/aws-cloudformation/cfn-python-lint)
10
+ [![Discord Shield](https://img.shields.io/discord/981586120448020580?logo=discord)](https://discord.gg/KENDm6DHCv)
11
+
12
+ Validate AWS CloudFormation yaml/json templates against the [AWS CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) and additional checks. Includes checking valid values for resource properties and best practices.
13
+
14
+ ### Warning
15
+
16
+ This is an attempt to provide validation for AWS CloudFormation templates properties and
17
+ their values. For values things can get pretty complicated (mappings, joins, splits,
18
+ conditions, and nesting those functions inside each other) so it's a best effort to
19
+ validate those values but the promise is to not fail if we can't understand or translate
20
+ all the things that could be going on.
21
+
22
+ ## Contribute
23
+
24
+ We encourage you to contribute to `cfn-lint`! Please check out the [Contributing Guidelines](https://github.com/aws-cloudformation/cfn-lint/blob/main/CONTRIBUTING.md) for more information on how to proceed.
25
+
26
+ ## Community
27
+
28
+ Join us on Discord! Connect & interact with CloudFormation developers &
29
+ experts, find channels to discuss and get help for cfn-lint, CloudFormation registry, StackSets,
30
+ Guard and more:
31
+
32
+ [![Join our Discord](https://discordapp.com/api/guilds/981586120448020580/widget.png?style=banner3)](https://discord.gg/9zpd7TTRwq)
33
+
34
+ #### Serverless Application Model
35
+
36
+ The Serverless Application Model (SAM) is supported by the linter. The template is
37
+ transformed using [AWS SAM](https://github.com/awslabs/serverless-application-model) before the linter processes the template.
38
+
39
+ _To get information about the [SAM Transformation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html), run the linter with `--info`_
40
+
41
+ ## Install
42
+
43
+ Python 3.8+ is supported.
44
+
45
+ ### Pip
46
+
47
+ `pip install cfn-lint`. If pip is not available, run
48
+ `python setup.py clean --all` then `python setup.py install`.
49
+
50
+ #### Optional dependencies
51
+
52
+ `cfn-lint` has optional dependencies based on certain features you may need.
53
+
54
+ * `pip install cfn-lint[full]` for installing all the optional dependencies. This will install all the dependencies for graph, junit, and sarif.
55
+ * `pip install cfn-lint[graph]` for installing `pydot` to draw and output template graphs
56
+ * `pip install cfn-lint[junit]` for installing the packages to output the `junit` format
57
+ * `pip install cfn-lint[sarif]` for installing the packages to output the `sarif` format
58
+
59
+
60
+ ### Homebrew (macOS)
61
+
62
+ `brew install cfn-lint`
63
+
64
+ ### Docker
65
+
66
+ In `cfn-lint` source tree:
67
+
68
+ ```shell
69
+ docker build --tag cfn-lint:latest .
70
+ ```
71
+
72
+ In repository to be linted:
73
+
74
+ ```shell
75
+ docker run --rm -v `pwd`:/data cfn-lint:latest /data/template.yaml
76
+ ```
77
+
78
+ ### Editor Plugins
79
+
80
+ There are IDE plugins available to get direct linter feedback from you favorite editor:
81
+
82
+ - [Atom](https://atom.io/packages/atom-cfn-lint)
83
+ - [Emacs](https://www.emacswiki.org/emacs/CfnLint)
84
+ - NeoVim 0.2.0+/Vim 8
85
+ - [ALE](https://github.com/w0rp/ale#supported-languages)
86
+ - [Coc](https://github.com/joenye/coc-cfn-lint)
87
+ - [Syntastic](https://github.com/speshak/vim-cfn)
88
+ - [Sublime](https://packagecontrol.io/packages/SublimeLinter-contrib-cloudformation)
89
+ - [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=kddejong.vscode-cfn-lint)
90
+ - [IntelliJ IDEA](https://plugins.jetbrains.com/plugin/10973-cfn-lint)
91
+
92
+ ### [GitHub Action](https://github.com/marketplace/actions/cfn-lint-action)
93
+
94
+ ### [Online demo](https://github.com/PatMyron/cfn-lint-online)
95
+
96
+ ## Basic Usage
97
+
98
+ - `cfn-lint template.yaml`
99
+ - `cfn-lint -t template.yaml`
100
+
101
+ Multiple files can be linted by either specifying multiple specific files:
102
+
103
+ - `cfn-lint template1.yaml template2.yaml`
104
+ - `cfn-lint -t template1.yaml template2.yaml`
105
+
106
+ or by using wildcards (globbing):
107
+
108
+ Lint all `yaml` files in `path`:
109
+
110
+ - `cfn-lint path/*.yaml`
111
+
112
+ Lint all `yaml` files in `path` and all subdirectories (recursive):
113
+
114
+ - `cfn-lint path/**/*.yaml`
115
+
116
+ _Note_: If using sh/bash/zsh, you must enable globbing.
117
+ (`shopt -s globstar` for sh/bash, `setopt extended_glob` for zsh).
118
+
119
+ ##### Exit Codes
120
+
121
+ `cfn-lint` will return a non zero exit if there are any issues with your template. The value is dependent on the severity of the issues found. For each level of discovered error `cfn-lint` will use bitwise OR to determine the final exit code. This will result in these possibilities.
122
+
123
+ - 0 is no issue was found
124
+ - 2 is an error
125
+ - 4 is a warning
126
+ - 6 is an error and a warning
127
+ - 8 is an informational
128
+ - 10 is an error and informational
129
+ - 12 is an warning and informational
130
+ - 14 is an error and a warning and an informational
131
+
132
+ ###### Configuring Exit Codes
133
+
134
+ `cfn-lint` allows you to configure exit codes. You can provide the parameter `--non-zero-exit-code` with a value of `informational`, `warning`, `error`, or `none`. `cfn-lint` will determine the exit code based on the match severity being the value of the parameter `--non-zero-exit-code` and higher. The exit codes will remain the same as above.
135
+
136
+ The order of severity is as follows:
137
+
138
+ 1. `informational` _default_
139
+ 1. `warning`
140
+ 1. `error`
141
+ 1. `none` _Exit code will always be 0 unless there is a syntax error_
142
+
143
+ ##### Specifying the template as an input stream
144
+
145
+ The template to be linted can also be passed using standard input:
146
+
147
+ - `cat path/template.yaml | cfn-lint -`
148
+
149
+ ##### Specifying the template with other parameters
150
+
151
+ - `cfn-lint -r us-east-1 ap-south-1 -- template.yaml`
152
+ - `cfn-lint -r us-east-1 ap-south-1 -t template.yaml`
153
+
154
+ ## Configuration
155
+
156
+ ### Command Line
157
+
158
+ From a command prompt run `cfn-lint <path to template>` to run standard linting of the template.
159
+
160
+ ### Config File
161
+
162
+ It will look for a configuration file in the following locations (by order of preference):
163
+
164
+ - `.cfnlintrc`, `.cfnlintrc.yaml` or `.cfnlintrc.yml` in the current working directory
165
+ - `~/.cfnlintrc` for the home directory
166
+
167
+ In that file you can specify settings from the parameter section below.
168
+
169
+ Example:
170
+
171
+ ```yaml
172
+ templates:
173
+ - test/fixtures/templates/good/**/*.yaml
174
+ ignore_templates:
175
+ - codebuild.yaml
176
+ include_checks:
177
+ - I
178
+ custom_rules: custom_rules.txt
179
+ ```
180
+
181
+ ### Parameters
182
+
183
+ Optional parameters:
184
+
185
+ | Command Line | Metadata | Options | Description |
186
+ | -------------------------- | -------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
187
+ | -h, --help | | | Get description of cfn-lint |
188
+ | -z, --custom-rules | | filename | Text file containing user-defined custom rules. See [here](#Custom-Rules) for more information |
189
+ | -t, --template | | filename | Alternative way to specify Template file path to the file that needs to be tested by cfn-lint |
190
+ | -f, --format | format | quiet, parseable, json, junit, pretty, sarif | Output format |
191
+ | -l, --list-rules | | | List all the rules |
192
+ | -r, --regions | regions | [REGIONS [REGIONS ...]], ALL_REGIONS | Test the template against many regions. [Supported regions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) |
193
+ | -b, --ignore-bad-template | ignore_bad_template | | Ignores bad template errors |
194
+ | --ignore-templates | | IGNORE_TEMPLATES [IGNORE_TEMPLATES ...] | Ignore templates from being scanned |
195
+ | -a, --append-rules | append_rules | [RULESPATH [RULESPATH ...]] | Specify one or more rules paths using one or more --append-rules arguments. Each path can be either a directory containing python files, or an import path to a module. |
196
+ | -i, --ignore-checks | ignore_checks | [IGNORE_CHECKS [IGNORE_CHECKS ...]] | Only check rules whose ID do not match or prefix these values. Examples: <br />- A value of `W` will disable all warnings<br />- `W2` disables all Warnings for Parameter rules.<br />- `W2001` will disable rule `W2001` |
197
+ | -e, --include-experimental | include_experimental | | Whether rules that still in an experimental state should be included in the checks |
198
+ | -c, --include-checks | | INCLUDE_CHECKS [INCLUDE_CHECKS ...] | Include rules whose id match these values |
199
+ | -m, --mandatory-checks | | | Rules to check regardless of ignore configuration |
200
+ | --non-zero-exit-code | | informational (default), warning, error, none] | Exit code will be non zero from the specified rule class and higher |
201
+ | -x, --configure-rule | | CONFIGURE_RULES [CONFIGURE_RULES ...] | Provide configuration for a rule. Format RuleId:key=value. Example: E3012:strict=true |
202
+ | -D, --debug | | | Specify to enable debug logging. Debug logging outputs detailed information about rules processing, useful for debugging rules. |
203
+ | -I, --info | | | Specify to enable logging. Outputs additional information about the template processing. |
204
+ | -u, --update-specs | | | Update the [CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html). You may need sudo to run this. You will need internet access when running this command |
205
+ | -o, --override-spec | | filename | Spec-style file containing custom definitions. Can be used to override CloudFormation specifications. More info [here](#customize-specifications) |
206
+ | -g, --build-graph | | | Creates a file in the same directory as the template that models the template's resources in [DOT format](<https://en.wikipedia.org/wiki/DOT_(graph_description_language)>) |
207
+ | -s, --registry-schemas | | | one or more directories of [CloudFormation Registry](https://aws.amazon.com/blogs/aws/cloudformation-update-cli-third-party-resource-support-registry/) [Resource Schemas](https://github.com/aws-cloudformation/aws-cloudformation-resource-schema/) |
208
+ | -v, --version | | | Version of cfn-lint |
209
+
210
+ ### Info Rules
211
+
212
+ To maintain backwards compatibility `info` rules are not included by default. To include these rules you will need to include `-c I` or `--include-checks I`
213
+
214
+ ### Metadata
215
+
216
+ #### Template Based Metadata
217
+
218
+ Inside the root level Metadata key you can configure cfn-lint using the supported parameters.
219
+
220
+ ```yaml
221
+ Metadata:
222
+ cfn-lint:
223
+ config:
224
+ regions:
225
+ - us-east-1
226
+ - us-east-2
227
+ ignore_checks:
228
+ - E2530
229
+ ```
230
+
231
+ #### Resource Based Metadata
232
+
233
+ Inside a resources Metadata key you can configure cfn-lint to ignore checks. This will filter out failures for the resource in which the Metadata belongs. Keep in mind that [`AWS::Serverless` resources may lose metadata during the Serverless transform](https://github.com/awslabs/serverless-application-model/issues/450#issuecomment-643420308)
234
+
235
+ ```yaml
236
+ Resources:
237
+ myInstance:
238
+ Type: AWS::EC2::Instance
239
+ Metadata:
240
+ cfn-lint:
241
+ config:
242
+ ignore_checks:
243
+ - E3030
244
+ Properties:
245
+ InstanceType: nt.x4superlarge
246
+ ImageId: ami-abc1234
247
+ ```
248
+
249
+ ### Precedence
250
+
251
+ cfn-lint applies configurations from several sources. The rules at lower levels are overridden by those at higher levels.
252
+
253
+ 1. cfnlintrc configurations
254
+ 2. Template Metadata configurations
255
+ 3. CLI parameters
256
+
257
+ ### Configure Rules
258
+
259
+ Certain rules support configuration properties. You can configure these rules by using `configure_rules` parameter.
260
+
261
+ From the command line the format is `RuleId:key=value`, for example: `E3012:strict=true`.
262
+ From the cfnlintrc or Metadata section the format is
263
+
264
+ ```yaml
265
+ Metadata:
266
+ cfn-lint:
267
+ config:
268
+ configure_rules:
269
+ RuleId:
270
+ key: value
271
+ ```
272
+
273
+ The configurable rules have a non-empty Config entry in the table [here](docs/rules.md#rules-1).
274
+
275
+ ### Getting Started Guides
276
+
277
+ There are [getting started guides](/docs/getting_started) available in the documentation section to help with integrating `cfn-lint` or creating rules.
278
+
279
+ ## Rules
280
+
281
+ This linter checks the AWS CloudFormation template by processing a collection of Rules, where every rule handles a specific function check or validation of the template.
282
+
283
+ This collection of rules can be extended with custom rules using the `--append-rules` argument.
284
+
285
+ More information describing how rules are set up and an overview of all the Rules that are applied by this linter are documented [here](docs/rules.md).
286
+
287
+ ## Custom Rules
288
+
289
+ The linter supports the creation of custom one-line rules which compare any resource with a property using pre-defined operators. These custom rules take the following format:
290
+
291
+ ```
292
+ <Resource Type> <Property[*]> <Operator> <Value> [Error Level] [Custom Error Message]
293
+ ```
294
+
295
+ ### Example
296
+
297
+ A separate custom rule text file must be created.
298
+
299
+ The example below validates `example_template.yml` does not use any EC2 instances of size `m4.16xlarge`
300
+
301
+ _custom_rule.txt_
302
+
303
+ ```
304
+ AWS::EC2::Instance InstanceType NOT_EQUALS "m4.16xlarge" WARN "This is an expensive instance type, don't use it"
305
+ ```
306
+
307
+ _example_template.yml_
308
+
309
+ ```yaml
310
+ AWSTemplateFormatVersion: "2010-09-09"
311
+ Resources:
312
+ myInstance:
313
+ Type: AWS::EC2::Instance
314
+ Properties:
315
+ InstanceType: m4.16xlarge
316
+ ImageId: ami-asdfef
317
+ ```
318
+
319
+ The custom rule can be added to the [configuration file](#Config-File) or ran as a [command line argument](#Parameters)
320
+
321
+ The linter will produce the following output, running `cfn-lint example_template.yml -z custom_rules.txt`:
322
+
323
+ ```
324
+ W9001 This is an expensive instance type, don't use it
325
+ mqtemplate.yml:6:17
326
+ ```
327
+
328
+ More information describing how custom rules are setup and an overview of all operators available is documented [here](docs/custom_rules.md).
329
+
330
+ ## Customize specifications
331
+
332
+ The linter follows the [AWS CloudFormation resource provider schemas](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-type-schemas.html) by default. However, for your use case specific requirements might exist. For example, within your organisation it might be mandatory to use [Tagging](https://aws.amazon.com/answers/account-management/aws-tagging-strategies/).
333
+
334
+ The linter provides the possibility to implement these customized specifications using the `--override-spec` argument.
335
+
336
+ More information about how this feature works is documented [here](docs/customize_specifications.md)
337
+
338
+ ## pre-commit
339
+
340
+ If you'd like cfn-lint to be run automatically when making changes to files in your Git repository, you can install [pre-commit](https://pre-commit.com/) and add the following text to your repositories' `.pre-commit-config.yaml`:
341
+
342
+ ```yaml
343
+ repos:
344
+ - repo: https://github.com/aws-cloudformation/cfn-lint
345
+ rev: v1.19.0 # The version of cfn-lint to use
346
+ hooks:
347
+ - id: cfn-lint
348
+ files: path/to/cfn/dir/.*\.(json|yml|yaml)$
349
+ ```
350
+
351
+ If you are using a `.cfnlintrc` and specifying the `templates` or `ignore_templates` we would recommend using the `.cfnlintrc` exlusively to determine which files should be scanned and then using:
352
+
353
+ ```yaml
354
+ repos:
355
+ - repo: https://github.com/aws-cloudformation/cfn-lint
356
+ rev: v1.19.0 # The version of cfn-lint to use
357
+ hooks:
358
+ - id: cfn-lint-rc
359
+ ```
360
+
361
+ _Note: When mixing .cfnlintrc ignore_templates and files option in your .pre-commit-config.yaml cfn-lint may return a file not found error_
362
+
363
+ - If you exclude the `files:` line above, every json/yml/yaml file will be checked.
364
+ - You can see available cfn-lint versions on the [releases page](https://github.com/aws-cloudformation/cfn-python-lint/releases).
testbed/aws-cloudformation__cfn-lint/custom_rules.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #Comments can be made with a '#' symbol at the start of the line
2
+ #Syntax: <Resource Type> <Property[*]> <Operator> <Value>
3
+ #Example: AWS::EC2::Instance InstanceType EQUALS "p3.2xlarge"
testbed/aws-cloudformation__cfn-lint/pyproject.toml ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = [
3
+ "setuptools >= 65.5.1",
4
+ ]
5
+ build-backend = "setuptools.build_meta"
6
+
7
+ [tool.setuptools.packages.find]
8
+ where = ["src"]
9
+
10
+ [tool.setuptools.dynamic]
11
+ version = {attr = "cfnlint.version.__version__"}
12
+ readme = {file = ["README.md"], content-type = "text/markdown"}
13
+
14
+ [project]
15
+ name = "cfn-lint"
16
+ description = "Checks CloudFormation templates for practices and behaviour that could potentially be improved"
17
+ requires-python = ">=3.8"
18
+ license = {text = "MIT no attribution"}
19
+ keywords = ["aws", "cloudformation", "lint"]
20
+ authors = [
21
+ {email = "kddejong@amazon.com"},
22
+ {name = "Kevin DeJong"},
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 5 - Production/Stable",
26
+ "Intended Audience :: Developers",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Natural Language :: English",
29
+ "Operating System :: OS Independent",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.8",
32
+ "Programming Language :: Python :: 3.9",
33
+ "Programming Language :: Python :: 3.10",
34
+ "Programming Language :: Python :: 3.11",
35
+ "Programming Language :: Python :: 3.12",
36
+ "Programming Language :: Python :: 3.13",
37
+ ]
38
+ dynamic = ["version", "readme"]
39
+ dependencies = [
40
+ "pyyaml>5.4",
41
+ "aws-sam-translator>=1.91.0",
42
+ "jsonpatch",
43
+ "networkx>=2.4,<4",
44
+ "sympy>=1.0.0",
45
+ "regex",
46
+ "typing_extensions",
47
+ ]
48
+
49
+ [project.optional-dependencies]
50
+ graph = [
51
+ "pydot"
52
+ ]
53
+ junit = [
54
+ "junit-xml~=1.9"
55
+ ]
56
+ sarif = [
57
+ "jschema_to_python~=1.2.3",
58
+ "sarif-om~=1.0.4",
59
+ ]
60
+ full = [
61
+ "junit-xml~=1.9",
62
+ "jschema_to_python~=1.2.3",
63
+ "sarif-om~=1.0.4",
64
+ "pydot"
65
+ ]
66
+
67
+ [project.scripts]
68
+ cfn-lint = "cfnlint.runner:main"
69
+
70
+ [tool.setuptools.package-data]
71
+ cfnlint = ["data/**/*.json"]
72
+
73
+ [project.urls]
74
+ Homepage = "https://github.com/aws-cloudformation/cfn-lint"
75
+ Documentation = "https://github.com/aws-cloudformation/cfn-lint"
76
+ Issues = "https://github.com/aws-cloudformation/cfn-lint/issues"
77
+ Changelog = "https://github.com/aws-cloudformation/cfn-lint/blob/main/CHANGELOG.md"
78
+ Source = "https://github.com/aws-cloudformation/cfn-lint"
79
+
80
+ [tool.isort]
81
+ profile = "black"
82
+
83
+ [tool.black]
84
+ skip-string-normalization = false
85
+ line-length = 88
86
+
87
+ [tool.bandit]
88
+ skips = ["B101", "B303", "B310", "B110", "B112", "B324", "B404", "B603", "B607"]
89
+ exclude_dirs = ["tests", "scripts"]
90
+
91
+ [tool.ruff]
92
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
93
+ lint.select = ["E", "F"]
94
+ lint.ignore = []
95
+
96
+ # Allow autofix for all enabled rules (when `--fix`) is provided.
97
+ lint.fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
98
+ lint.unfixable = []
99
+
100
+ # Exclude a variety of commonly ignored directories.
101
+ exclude = [
102
+ ".bzr",
103
+ ".direnv",
104
+ ".eggs",
105
+ ".git",
106
+ ".git-rewrite",
107
+ ".hg",
108
+ ".mypy_cache",
109
+ ".nox",
110
+ ".pants.d",
111
+ ".pytype",
112
+ ".ruff_cache",
113
+ ".svn",
114
+ ".tox",
115
+ ".venv",
116
+ "__pypackages__",
117
+ "_build",
118
+ "buck-out",
119
+ "build",
120
+ "dist",
121
+ "node_modules",
122
+ "venv",
123
+ ]
124
+ # Same as Black.
125
+ line-length = 88
126
+
127
+ [tool.ruff.lint.per-file-ignores]
128
+ "__init__.py" = ["F401"]
129
+
130
+ [tool.pytest.ini_options]
131
+ addopts = [
132
+ "-m not data"
133
+ ]
134
+ markers = [
135
+ "data: marks tests as slow (deselect with '-m \"not data\"')",
136
+ ]
137
+ testpaths = [
138
+ "test",
139
+ ]
140
+
141
+ [tool.coverage.run]
142
+ branch = true
143
+ source = [
144
+ "src/cfnlint"
145
+ ]
146
+
147
+ [tool.coverage.report]
148
+ skip_empty = true
149
+ skip_covered = true
150
+ show_missing = true
151
+ sort = "Cover"
152
+ exclude_lines = [
153
+ "pragma: no cover",
154
+ "if TYPE_CHECKING:"
155
+ ]
156
+
157
+ [tool.mypy]
158
+ python_version = "3.10"
159
+ warn_return_any = true
160
+ warn_unused_configs = true
161
+ files = [
162
+ "src/cfnlint/**/*.py"
163
+ ]
164
+ exclude = [
165
+ "src/cfnlint/data/"
166
+ ]
167
+
168
+ # Per-module options:
169
+ [[tool.mypy.overrides]]
170
+ module = "networkx.*"
171
+ ignore_missing_imports = true
172
+
173
+ [[tool.mypy.overrides]]
174
+ module = "pydot.*"
175
+ ignore_missing_imports = true
176
+
177
+ [[tool.mypy.overrides]]
178
+ module = "pygraphviz.*"
179
+ ignore_missing_imports = true
180
+
181
+ [[tool.mypy.overrides]]
182
+ module = "importlib_resources.*"
183
+ ignore_missing_imports = true
184
+
185
+ [[tool.mypy.overrides]]
186
+ module = "samtranslator.*"
187
+ ignore_missing_imports = true
188
+
189
+ [[tool.mypy.overrides]]
190
+ module = "sarif_om.*"
191
+ ignore_missing_imports = true
192
+
193
+ [[tool.mypy.overrides]]
194
+ module = "jschema_to_python.*"
195
+ ignore_missing_imports = true
196
+
197
+ [[tool.mypy.overrides]]
198
+ module = "junit_xml.*"
199
+ ignore_missing_imports = true
200
+
201
+ [[tool.mypy.overrides]]
202
+ module = "jsonpatch.*"
203
+ ignore_missing_imports = true
204
+
205
+ [[tool.mypy.overrides]]
206
+ module = "urllib2.*"
207
+ ignore_missing_imports = true
208
+
209
+ [[tool.mypy.overrides]]
210
+ module = "json.*"
211
+ ignore_missing_imports = true
testbed/aws-cloudformation__cfn-lint/setup.cfg ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [metadata]
2
+ description_file = README.md
testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-instance.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Resources:
2
+ NetworkInterface:
3
+ Type: AWS::EC2::NetworkInterface
4
+ Properties:
5
+ Description: foobar
6
+ SourceDestCheck: false
7
+ SubnetId: subnet-0abc1def2345a678b
8
+ Instance:
9
+ Type: AWS::EC2::Instance
10
+ Properties:
11
+ ImageId: ami-abcdefgh
12
+ InstanceType: t2.micro
13
+ NetworkInterfaces:
14
+ - AssociateCarrierIpAddress: true
15
+ AssociatePublicIpAddress: true
16
+ DeviceIndex: "0"
17
+ NetworkInterfaceId: !Ref NetworkInterface
18
+ Tags:
19
+ - Key: foo
20
+ Value: bar
testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Resources:
2
+ LaunchTemplate:
3
+ Type: AWS::EC2::LaunchTemplate
4
+ Properties:
5
+ LaunchTemplateData:
6
+ ImageId: ami-abcdefgh
7
+ InstanceType: t2.micro
8
+ UserData: !Base64 "#!/bin/bash\necho 'Hello World' > /var/www/html/index.html"
9
+ NetworkInterfaces:
10
+ - AssociateCarrierIpAddress: true
11
+ AssociatePublicIpAddress: true
12
+ DeviceIndex: 0
13
+ NetworkInterfaceId: !Ref NetworkInterface
14
+ LaunchTemplateName: MyLaunchTemplate
testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-networkinterface.yaml ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Parameters:
2
+ SubnetId:
3
+ Type: AWS::EC2::Subnet::Id
4
+ SecurityGroupId:
5
+ Type: AWS::EC2::SecurityGroup::Id
6
+ Resources:
7
+ NetworkInterface:
8
+ Type: AWS::EC2::NetworkInterface
9
+ Properties:
10
+ Description: "a network interface"
11
+ GroupSet:
12
+ - !Ref SecurityGroupId
13
+ SourceDestCheck: false
14
+ SubnetId: !Ref SubnetId
15
+ Ipv6Addresses:
16
+ - Ipv6Address: abc
17
+ Ipv6AddressCount: 1
testbed/aws-cloudformation__cfn-lint/test/fixtures/templates/integration/aws-ec2-subnet.yaml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Parameters:
2
+ Vpc:
3
+ Type: AWS::EC2::VPC::Id
4
+ Resources:
5
+ Subnet1:
6
+ Type: AWS::EC2::Subnet
7
+ Properties:
8
+ VpcId: !Ref Vpc
9
+ CidrBlock: 10.0.0.0/24
10
+ Ipv4NetmaskLength: 10
11
+ Subnet2:
12
+ Type: AWS::EC2::Subnet
13
+ Properties:
14
+ VpcId: !Ref Vpc
15
+ Subnet3:
16
+ Type: AWS::EC2::Subnet
17
+ Properties:
18
+ VpcId: !Ref Vpc
19
+ Ipv4IpamPoolId: test
testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/__init__.py ADDED
File without changes
testbed/aws-cloudformation__cfn-lint/test/integration/jsonschema/test_validator_cfn.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import unittest
10
+ from collections import deque
11
+ from typing import List
12
+
13
+ import jsonpatch
14
+
15
+ from cfnlint.decode import decode_str
16
+ from cfnlint.helpers import FUNCTIONS
17
+ from cfnlint.jsonschema import CfnTemplateValidator, ValidationError
18
+ from cfnlint.template import Template
19
+
20
+
21
+ def build_template(patch: jsonpatch.JsonPatch | None) -> Template:
22
+ """
23
+ Build a template object from a dict
24
+ """
25
+ template_obj = {
26
+ "AWSTemplateFormatVersion": "2010-09-09",
27
+ "Conditions": {
28
+ "IsUsEast1": {"Fn::Equals": ["true", {"Ref": "AWS::Region"}]},
29
+ "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]},
30
+ },
31
+ "Resources": {
32
+ "MyResource": {
33
+ "Type": "AWS::Test::Type",
34
+ "Properties": {
35
+ "Name": "Name",
36
+ "Tags": [
37
+ {"Key": "Name", "Value": "Value"},
38
+ ],
39
+ },
40
+ }
41
+ },
42
+ }
43
+
44
+ if patch is not None:
45
+ jsonpatch.apply_patch(template_obj, patch, True)
46
+
47
+ template, _ = decode_str(json.dumps(template_obj))
48
+ if template:
49
+ return Template("", template, regions=["us-east-1"])
50
+
51
+ raise Exception("Template is invalid")
52
+
53
+
54
+ def build_schema(patch: jsonpatch.JsonPatch | None):
55
+ schema = {
56
+ "properties": {
57
+ "Name": {
58
+ "type": "string",
59
+ },
60
+ "Tags": {
61
+ "type": "array",
62
+ "items": {
63
+ "type": "object",
64
+ "properties": {
65
+ "Key": {"type": "string"},
66
+ "Value": {"type": "string"},
67
+ },
68
+ },
69
+ },
70
+ },
71
+ "type": "object",
72
+ }
73
+
74
+ if patch is not None:
75
+ jsonpatch.apply_patch(schema, patch, True)
76
+
77
+ return schema
78
+
79
+
80
+ class TestValidatorCfnConditions(unittest.TestCase):
81
+ """
82
+ Integration testing of the CfnTemplateValidator class
83
+ with a Template that allows us to exhaust scenario
84
+ """
85
+
86
+ def run_test(
87
+ self,
88
+ template_patches: jsonpatch.JsonPatch,
89
+ schema_patches: jsonpatch.JsonPatch,
90
+ expected_errs: List[ValidationError],
91
+ ):
92
+ """
93
+ Run the test
94
+ """
95
+ cfn = build_template(template_patches)
96
+ schema = build_schema(schema_patches)
97
+
98
+ props = (
99
+ cfn.template.get("Resources", {})
100
+ .get("MyResource", {})
101
+ .get("Properties", {})
102
+ )
103
+
104
+ context = cfn.context.evolve(functions=FUNCTIONS)
105
+ validator = CfnTemplateValidator(schema=schema, cfn=cfn, context=context)
106
+ errs = list(validator.iter_errors(props))
107
+
108
+ self.assertEqual(len(errs), len(expected_errs), f"Received: {errs!r}")
109
+ for i, err in enumerate(errs):
110
+ self.assertEqual(expected_errs[i].message, err.message)
111
+ self.assertEqual(expected_errs[i].path, err.path)
112
+ self.assertEqual(expected_errs[i].validator, err.validator)
113
+ self.assertEqual(expected_errs[i].validator_value, err.validator_value)
114
+
115
+ def test_required(self):
116
+ schema_patch = jsonpatch.JsonPatch(
117
+ patch=[{"op": "add", "path": "/required", "value": ["Name"]}],
118
+ )
119
+ self.run_test(
120
+ template_patches=None,
121
+ schema_patches=schema_patch,
122
+ expected_errs=[],
123
+ )
124
+
125
+ self.run_test(
126
+ template_patches=jsonpatch.JsonPatch(
127
+ patch=[
128
+ {"op": "remove", "path": "/Resources/MyResource/Properties/Name"}
129
+ ],
130
+ ),
131
+ schema_patches=schema_patch,
132
+ expected_errs=[
133
+ ValidationError(
134
+ "'Name' is a required property",
135
+ validator="required",
136
+ validator_value=["Name"],
137
+ ),
138
+ ],
139
+ )
140
+
141
+ self.run_test(
142
+ template_patches=jsonpatch.JsonPatch(
143
+ patch=[
144
+ {
145
+ "op": "replace",
146
+ "path": "/Resources/MyResource/Properties/Name",
147
+ "value": {
148
+ "Fn::If": [
149
+ "IsUsEast1",
150
+ "Name",
151
+ {"Ref": "AWS::NoValue"},
152
+ ]
153
+ },
154
+ }
155
+ ],
156
+ ),
157
+ schema_patches=schema_patch,
158
+ expected_errs=[
159
+ ValidationError(
160
+ "'Name' is a required property",
161
+ validator="required",
162
+ validator_value=["Name"],
163
+ ),
164
+ ],
165
+ )
166
+
167
+ def test_unique_items(self):
168
+ schema_patch = jsonpatch.JsonPatch(
169
+ [
170
+ {"op": "add", "path": "/properties/Tags/uniqueItems", "value": True},
171
+ ]
172
+ )
173
+ self.run_test(
174
+ template_patches=None,
175
+ schema_patches=schema_patch,
176
+ expected_errs=[],
177
+ )
178
+
179
+ self.run_test(
180
+ template_patches=jsonpatch.JsonPatch(
181
+ [
182
+ {
183
+ "op": "add",
184
+ "path": "/Resources/MyResource/Properties/Tags/-",
185
+ "value": {"Key": "Name", "Value": "Value"},
186
+ },
187
+ ]
188
+ ),
189
+ schema_patches=schema_patch,
190
+ expected_errs=[
191
+ ValidationError(
192
+ message=(
193
+ "[{'Key': 'Name', 'Value': 'Value'}, "
194
+ "{'Key': 'Name', 'Value': 'Value'}] has "
195
+ "non-unique elements"
196
+ ),
197
+ path=deque(["Tags"]),
198
+ validator="uniqueItems",
199
+ validator_value=True,
200
+ ),
201
+ ],
202
+ )
203
+
204
+ self.run_test(
205
+ template_patches=jsonpatch.JsonPatch(
206
+ [
207
+ {
208
+ "op": "add",
209
+ "path": "/Resources/MyResource/Properties/Tags/-",
210
+ "value": {
211
+ "Fn::If": [
212
+ "IsUsEast1",
213
+ {"Key": "Name", "Value": "Value"},
214
+ {"Key": "Foo", "Value": "Bar"},
215
+ ]
216
+ },
217
+ },
218
+ ]
219
+ ),
220
+ schema_patches=schema_patch,
221
+ expected_errs=[
222
+ ValidationError(
223
+ message=(
224
+ "[{'Key': 'Name', 'Value': 'Value'}, "
225
+ "{'Key': 'Name', 'Value': 'Value'}] has "
226
+ "non-unique elements"
227
+ ),
228
+ path=deque(["Tags"]),
229
+ validator="uniqueItems",
230
+ validator_value=True,
231
+ ),
232
+ ],
233
+ )
234
+
235
+ self.run_test(
236
+ template_patches=jsonpatch.JsonPatch(
237
+ [
238
+ {
239
+ "op": "replace",
240
+ "path": "/Resources/MyResource/Properties/Tags",
241
+ "value": [
242
+ {
243
+ "Fn::If": [
244
+ "IsUsEast1",
245
+ {"Key": "Name", "Value": "Value"},
246
+ {"Ref": "AWS::NoValue"},
247
+ ],
248
+ },
249
+ {
250
+ "Fn::If": [
251
+ "IsUsEast1",
252
+ {"Ref": "AWS::NoValue"},
253
+ {"Key": "Name", "Value": "Value"},
254
+ ],
255
+ },
256
+ ],
257
+ },
258
+ ]
259
+ ),
260
+ schema_patches=schema_patch,
261
+ expected_errs=[],
262
+ )
263
+
264
+ self.run_test(
265
+ template_patches=jsonpatch.JsonPatch(
266
+ [
267
+ {
268
+ "op": "replace",
269
+ "path": "/Resources/MyResource/Properties/Tags",
270
+ "value": [
271
+ {
272
+ "Fn::If": [
273
+ "IsUsEast1",
274
+ {"Key": "Name", "Value": "Value"},
275
+ {"Ref": "AWS::NoValue"},
276
+ ],
277
+ },
278
+ {
279
+ "Fn::If": [
280
+ "IsNotUsEast1",
281
+ {"Ref": "AWS::NoValue"},
282
+ {"Key": "Name", "Value": "Value"},
283
+ ],
284
+ },
285
+ ],
286
+ },
287
+ ]
288
+ ),
289
+ schema_patches=schema_patch,
290
+ expected_errs=[
291
+ ValidationError(
292
+ message=(
293
+ "[{'Key': 'Name', 'Value': 'Value'}, "
294
+ "{'Key': 'Name', 'Value': 'Value'}] has "
295
+ "non-unique elements"
296
+ ),
297
+ path=deque(["Tags"]),
298
+ validator="uniqueItems",
299
+ validator_value=True,
300
+ ),
301
+ ],
302
+ )
303
+
304
+ def test_dependencies(self):
305
+ schema_patch = jsonpatch.JsonPatch(
306
+ [
307
+ {"op": "add", "path": "/dependencies", "value": {"Name": ["Tags"]}},
308
+ ]
309
+ )
310
+ self.run_test(
311
+ template_patches=None,
312
+ schema_patches=schema_patch,
313
+ expected_errs=[],
314
+ )
315
+
316
+ self.run_test(
317
+ template_patches=jsonpatch.JsonPatch(
318
+ [
319
+ {"op": "remove", "path": "/Resources/MyResource/Properties/Tags"},
320
+ ]
321
+ ),
322
+ schema_patches=schema_patch,
323
+ expected_errs=[
324
+ ValidationError(
325
+ message="'Tags' is a dependency of 'Name'",
326
+ path=deque([]),
327
+ validator="dependencies",
328
+ validator_value={"Name": ["Tags"]},
329
+ ),
330
+ ],
331
+ )
332
+
333
+ self.run_test(
334
+ template_patches=jsonpatch.JsonPatch(
335
+ [
336
+ {
337
+ "op": "replace",
338
+ "path": "/Resources/MyResource/Properties/Tags",
339
+ "value": {
340
+ "Fn::If": [
341
+ "IsUsEast1",
342
+ {"Ref": "AWS::NoValue"},
343
+ [
344
+ {
345
+ "Fn::If": [
346
+ "IsUsEast1",
347
+ {"Ref": "AWS::NoValue"},
348
+ {"Key": "Name", "Value": "Value"},
349
+ ]
350
+ },
351
+ ],
352
+ ]
353
+ },
354
+ },
355
+ ]
356
+ ),
357
+ schema_patches=schema_patch,
358
+ expected_errs=[
359
+ ValidationError(
360
+ message="'Tags' is a dependency of 'Name'",
361
+ path=deque([]),
362
+ validator="dependencies",
363
+ validator_value={"Name": ["Tags"]},
364
+ ),
365
+ ],
366
+ )
testbed/aws-cloudformation__cfn-lint/test/integration/rules/__init__.py ADDED
File without changes
testbed/aws-cloudformation__cfn-lint/test/integration/rules/test_rules.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import pathlib
9
+
10
+ from cfnlint.helpers import load_plugins
11
+
12
+
13
+ def test_rule_descriptions():
14
+ root_dir = pathlib.Path(__file__).parent.parent.parent.parent / "src/cfnlint/rules"
15
+ rules = load_plugins(
16
+ str(root_dir),
17
+ )
18
+
19
+ descriptions = set()
20
+ shortdesc = set()
21
+
22
+ for rule in rules:
23
+ if not rule.id:
24
+ continue
25
+ assert (
26
+ rule.description not in descriptions
27
+ ), f"Duplicate description {rule.description!r}"
28
+ assert (
29
+ rule.shortdesc not in shortdesc
30
+ ), f"Duplicate shortdesc {rule.shortdesc!r}"
31
+ descriptions.add(rule.description)
32
+ shortdesc.add(rule.shortdesc)
testbed/aws-cloudformation__cfn-lint/test/integration/test_good_templates.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from pathlib import Path
7
+ from test.integration import BaseCliTestCase
8
+
9
+ from cfnlint import ConfigMixIn
10
+
11
+
12
+ class TestQuickStartTemplates(BaseCliTestCase):
13
+ """Test QuickStart Templates Parsing"""
14
+
15
+ # ruff: noqa: E501
16
+ scenarios = [
17
+ {
18
+ "filename": "test/fixtures/templates/good/generic.yaml",
19
+ "results": [],
20
+ "exit_code": 0,
21
+ },
22
+ {
23
+ "filename": "test/fixtures/templates/good/minimal.yaml",
24
+ "results": [],
25
+ "exit_code": 0,
26
+ },
27
+ {
28
+ "filename": "test/fixtures/templates/good/transform.yaml",
29
+ "results": [],
30
+ "exit_code": 0,
31
+ },
32
+ {
33
+ "filename": "test/fixtures/templates/issues/sam_w_conditions.yaml",
34
+ "results": [],
35
+ "exit_code": 0,
36
+ },
37
+ {
38
+ "filename": (
39
+ "test/fixtures/templates/bad/transform_serverless_template.yaml"
40
+ ),
41
+ "results": [
42
+ {
43
+ "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml",
44
+ "Id": "9e05773a-b0d0-f157-2955-596d9bd54749",
45
+ "Level": "Error",
46
+ "Location": {
47
+ "End": {"ColumnNumber": 2, "LineNumber": 1},
48
+ "Path": None,
49
+ "Start": {"ColumnNumber": 1, "LineNumber": 1},
50
+ },
51
+ "Message": "Error transforming template: Resource with id [myFunctionMyTimer] is invalid. Missing required property 'Schedule'.",
52
+ "ParentId": None,
53
+ "Rule": {
54
+ "Description": "Errors found when performing transformation on the template",
55
+ "Id": "E0001",
56
+ "ShortDescription": "Error found when transforming the template",
57
+ "Source": "https://github.com/aws-cloudformation/cfn-lint",
58
+ },
59
+ },
60
+ {
61
+ "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml",
62
+ "Id": "fd751fa3-7d1f-e194-7108-eb08352814c8",
63
+ "Level": "Error",
64
+ "Location": {
65
+ "End": {"ColumnNumber": 2, "LineNumber": 1},
66
+ "Path": None,
67
+ "Start": {"ColumnNumber": 1, "LineNumber": 1},
68
+ },
69
+ "Message": "Error transforming template: Resource with id [ExampleLayer] is invalid. Missing required property 'ContentUri'.",
70
+ "ParentId": None,
71
+ "Rule": {
72
+ "Description": "Errors found when performing transformation on the template",
73
+ "Id": "E0001",
74
+ "ShortDescription": "Error found when transforming the template",
75
+ "Source": "https://github.com/aws-cloudformation/cfn-lint",
76
+ },
77
+ },
78
+ {
79
+ "Filename": "test/fixtures/templates/bad/transform_serverless_template.yaml",
80
+ "Id": "74181426-e865-10eb-96fd-908dfd30a358",
81
+ "Level": "Error",
82
+ "Location": {
83
+ "End": {"ColumnNumber": 2, "LineNumber": 1},
84
+ "Path": None,
85
+ "Start": {"ColumnNumber": 1, "LineNumber": 1},
86
+ },
87
+ "Message": "Error transforming template: Resource with id [AppName] is invalid. Resource is missing the required [Location] property.",
88
+ "ParentId": None,
89
+ "Rule": {
90
+ "Description": "Errors found when performing transformation on the template",
91
+ "Id": "E0001",
92
+ "ShortDescription": "Error found when transforming the template",
93
+ "Source": "https://github.com/aws-cloudformation/cfn-lint",
94
+ },
95
+ },
96
+ ],
97
+ "exit_code": 2,
98
+ },
99
+ {
100
+ "filename": "test/fixtures/templates/good/conditions.yaml",
101
+ "results": [],
102
+ "exit_code": 0,
103
+ },
104
+ {
105
+ "filename": "test/fixtures/templates/good/resources_codepipeline.yaml",
106
+ "results": [],
107
+ "exit_code": 0,
108
+ },
109
+ {
110
+ "filename": "test/fixtures/templates/good/resources_cognito_userpool_tag_is_string_map.yaml",
111
+ "results": [],
112
+ "exit_code": 0,
113
+ },
114
+ {
115
+ "filename": "test/fixtures/templates/bad/resources_cognito_userpool_tag_is_list.yaml",
116
+ "results": [
117
+ {
118
+ "Filename": str(
119
+ Path(
120
+ "test/fixtures/templates/bad/resources_cognito_userpool_tag_is_list.yaml"
121
+ )
122
+ ),
123
+ "Id": "3732b0a0-6d44-72af-860a-88e5f8ca790c",
124
+ "Level": "Error",
125
+ "Location": {
126
+ "Start": {"ColumnNumber": 7, "LineNumber": 16},
127
+ "End": {"ColumnNumber": 19, "LineNumber": 16},
128
+ "Path": [
129
+ "Resources",
130
+ "MyCognitoUserPool",
131
+ "Properties",
132
+ "UserPoolTags",
133
+ ],
134
+ },
135
+ "Message": (
136
+ "[{'Key': 'Key1', 'Value': 'Value1'}, {'Key': 'Key2', 'Value':"
137
+ " 'Value2'}] is not of type 'object'"
138
+ ),
139
+ "ParentId": None,
140
+ "Rule": {
141
+ "Description": (
142
+ "Checks resource property values with Primitive Types for"
143
+ " values that match those types."
144
+ ),
145
+ "Id": "E3012",
146
+ "ShortDescription": "Check resource properties values",
147
+ "Source": "https://github.com/aws-cloudformation/cfn-lint/blob/main/docs/cfn-schema-specification.md#type",
148
+ },
149
+ }
150
+ ],
151
+ "exit_code": 2,
152
+ },
153
+ {
154
+ "filename": "test/fixtures/templates/good/transform_serverless_api.yaml",
155
+ "results": [],
156
+ "exit_code": 0,
157
+ },
158
+ {
159
+ "filename": (
160
+ "test/fixtures/templates/good/transform_serverless_function.yaml"
161
+ ),
162
+ "results": [],
163
+ "exit_code": 0,
164
+ },
165
+ {
166
+ "filename": (
167
+ "test/fixtures/templates/good/transform_serverless_globals.yaml"
168
+ ),
169
+ "results": [
170
+ {
171
+ "Filename": str(
172
+ Path(
173
+ "test/fixtures/templates/good/transform_serverless_globals.yaml"
174
+ )
175
+ ),
176
+ "Id": "f0f6c586-81bc-9182-de02-659a3a1a5b2c",
177
+ "Level": "Error",
178
+ "Location": {
179
+ "End": {"ColumnNumber": 13, "LineNumber": 10},
180
+ "Path": ["Resources", "myFunction", "Properties", "Runtime"],
181
+ "Start": {"ColumnNumber": 3, "LineNumber": 10},
182
+ },
183
+ "Message": "Runtime 'nodejs6.10' was deprecated on '2019-08-12'. Creation was disabled on '2019-08-12' and update on '2019-08-12'. Please consider updating to 'nodejs20.x'",
184
+ "ParentId": None,
185
+ "Rule": {
186
+ "Description": (
187
+ "Check if an EOL Lambda Runtime is specified and you cannot update the function"
188
+ ),
189
+ "Id": "E2533",
190
+ "ShortDescription": (
191
+ "Check if Lambda Function Runtimes are updatable"
192
+ ),
193
+ "Source": "https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html",
194
+ },
195
+ }
196
+ ],
197
+ "exit_code": 2,
198
+ },
199
+ {
200
+ "filename": "test/fixtures/templates/good/transform/list_transform.yaml",
201
+ "results": [],
202
+ "exit_code": 0,
203
+ },
204
+ {
205
+ "filename": (
206
+ "test/fixtures/templates/good/transform/list_transform_many.yaml"
207
+ ),
208
+ "results": [],
209
+ "exit_code": 0,
210
+ },
211
+ {
212
+ "filename": (
213
+ "test/fixtures/templates/good/transform/list_transform_not_sam.yaml"
214
+ ),
215
+ "results": [],
216
+ "exit_code": 0,
217
+ },
218
+ ]
219
+
220
+ def test_templates(self):
221
+ """Test Successful JSON Parsing"""
222
+ self.run_scenarios()
223
+
224
+ def test_module_integration(self):
225
+ """Test same templates using integration approach"""
226
+ self.run_module_integration_scenarios(
227
+ ConfigMixIn([], include_checks=["W", "E"])
228
+ )
testbed/aws-cloudformation__cfn-lint/test/integration/test_integration_templates.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from test.integration import BaseCliTestCase
7
+
8
+ from cfnlint import ConfigMixIn
9
+
10
+
11
+ class TestQuickStartTemplates(BaseCliTestCase):
12
+ """Test QuickStart Templates Parsing"""
13
+
14
+ scenarios = [
15
+ {
16
+ "filename": (
17
+ "test/fixtures/templates/integration"
18
+ "/resources-cloudformation-init.yaml"
19
+ ),
20
+ "results_filename": (
21
+ "test/fixtures/results/integration/"
22
+ "resources-cloudformation-init.json"
23
+ ),
24
+ "exit_code": 0,
25
+ },
26
+ {
27
+ "filename": "test/fixtures/templates/integration/dynamic-references.yaml",
28
+ "results_filename": (
29
+ "test/fixtures/results/integration" "/dynamic-references.json"
30
+ ),
31
+ "exit_code": 2,
32
+ },
33
+ {
34
+ "filename": "test/fixtures/templates/integration/ref-no-value.yaml",
35
+ "results_filename": ("test/fixtures/results/integration/ref-no-value.json"),
36
+ "exit_code": 2,
37
+ },
38
+ {
39
+ "filename": "test/fixtures/templates/integration/metdata.yaml",
40
+ "results_filename": ("test/fixtures/results/integration/metadata.json"),
41
+ "exit_code": 4,
42
+ },
43
+ {
44
+ "filename": ("test/fixtures/templates/integration/availability-zones.yaml"),
45
+ "results_filename": (
46
+ "test/fixtures/results/integration/availability-zones.json"
47
+ ),
48
+ "exit_code": 2,
49
+ },
50
+ {
51
+ "filename": ("test/fixtures/templates/integration/getatt-types.yaml"),
52
+ "results_filename": ("test/fixtures/results/integration/getatt-types.json"),
53
+ "exit_code": 10,
54
+ },
55
+ {
56
+ "filename": (
57
+ "test/fixtures/templates/integration/aws-ec2-networkinterface.yaml"
58
+ ),
59
+ "results_filename": (
60
+ "test/fixtures/results/integration/aws-ec2-networkinterface.json"
61
+ ),
62
+ "exit_code": 2,
63
+ },
64
+ {
65
+ "filename": ("test/fixtures/templates/integration/aws-ec2-instance.yaml"),
66
+ "results_filename": (
67
+ "test/fixtures/results/integration/aws-ec2-instance.json"
68
+ ),
69
+ "exit_code": 2,
70
+ },
71
+ {
72
+ "filename": (
73
+ "test/fixtures/templates/integration/aws-ec2-launchtemplate.yaml"
74
+ ),
75
+ "results_filename": (
76
+ "test/fixtures/results/integration/aws-ec2-launchtemplate.json"
77
+ ),
78
+ "exit_code": 2,
79
+ },
80
+ {
81
+ "filename": ("test/fixtures/templates/integration/aws-ec2-subnet.yaml"),
82
+ "results_filename": (
83
+ "test/fixtures/results/integration/aws-ec2-subnet.json"
84
+ ),
85
+ "exit_code": 2,
86
+ },
87
+ {
88
+ "filename": ("test/fixtures/templates/integration/aws-dynamodb-table.yaml"),
89
+ "results_filename": (
90
+ "test/fixtures/results/integration/aws-dynamodb-table.json"
91
+ ),
92
+ "exit_code": 2,
93
+ },
94
+ ]
95
+
96
+ def test_templates(self):
97
+ """Test same templates using integration approach"""
98
+ self.run_module_integration_scenarios(
99
+ ConfigMixIn(
100
+ [],
101
+ include_checks=["I"],
102
+ include_experimental=True,
103
+ )
104
+ )
testbed/aws-cloudformation__cfn-lint/test/integration/test_patches.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import json
7
+ import os
8
+ from test.integration import BaseCliTestCase
9
+
10
+ from jsonpatch import InvalidJsonPatch, JsonPatch
11
+
12
+
13
+ class TestPatches(BaseCliTestCase):
14
+ """Test Patches"""
15
+
16
+ def test_patches(self):
17
+ """Test ignoring certain rules"""
18
+ for root, _, files in os.walk(
19
+ "src/cfnlint/data/ExtendedProviderSchemas", topdown=True
20
+ ):
21
+ for name in files:
22
+ if name.endswith(".json"):
23
+ with open(os.path.join(root, name)) as fh:
24
+ patches = json.load(fh)
25
+ try:
26
+ JsonPatch(patches)
27
+ except InvalidJsonPatch:
28
+ raise Exception(f"Invalid patch: {name}")
testbed/aws-cloudformation__cfn-lint/test/integration/test_quickstart_templates_non_strict.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from test.integration import BaseCliTestCase
7
+
8
+ from cfnlint import ConfigMixIn
9
+
10
+
11
+ class TestQuickStartTemplates(BaseCliTestCase):
12
+ """Test QuickStart Templates Parsing"""
13
+
14
+ scenarios = [
15
+ {
16
+ "filename": "test/fixtures/templates/quickstart/nist_high_main.yaml",
17
+ "results_filename": (
18
+ "test/fixtures/results/quickstart/non_strict/nist_high_main.json"
19
+ ),
20
+ "exit_code": 14,
21
+ },
22
+ {
23
+ "filename": "test/fixtures/templates/quickstart/nist_application.yaml",
24
+ "results_filename": (
25
+ "test/fixtures/results/quickstart/non_strict/nist_application.json"
26
+ ),
27
+ "exit_code": 14,
28
+ },
29
+ {
30
+ "filename": "test/fixtures/templates/quickstart/openshift.yaml",
31
+ "results_filename": (
32
+ "test/fixtures/results/quickstart/non_strict/openshift.json"
33
+ ),
34
+ "exit_code": 12,
35
+ },
36
+ {
37
+ "filename": "test/fixtures/templates/quickstart/cis_benchmark.yaml",
38
+ "results_filename": (
39
+ "test/fixtures/results/quickstart/non_strict/cis_benchmark.json"
40
+ ),
41
+ "exit_code": 4,
42
+ },
43
+ ]
44
+
45
+ def test_templates(self):
46
+ """Test Successful JSON Parsing"""
47
+ self.maxDiff = None
48
+ self.run_scenarios(
49
+ [
50
+ "--include-checks",
51
+ "I",
52
+ "--include-experimental",
53
+ "--configure-rule",
54
+ "E3012:strict=false",
55
+ ]
56
+ )
57
+
58
+ def test_module_integration(self):
59
+ """Test same templates using integration approach"""
60
+ self.run_module_integration_scenarios(
61
+ ConfigMixIn(
62
+ [],
63
+ include_checks=["I"],
64
+ configure_rules={
65
+ "E3012": {
66
+ "strict": False,
67
+ }
68
+ },
69
+ include_experimental=True,
70
+ )
71
+ )
testbed/aws-cloudformation__cfn-lint/test/integration/test_schema_files.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import fnmatch
9
+ import json
10
+ import os
11
+ import pathlib
12
+ from typing import Any, List
13
+ from unittest import TestCase
14
+
15
+ import pytest
16
+ import regex as re
17
+
18
+ import cfnlint
19
+ from cfnlint.helpers import REGIONS, ensure_list, load_plugins, load_resource
20
+ from cfnlint.jsonschema import StandardValidator, ValidationError
21
+ from cfnlint.schema.resolver import RefResolutionError, RefResolver
22
+
23
+
24
+ @pytest.mark.data
25
+ class TestSchemaFiles(TestCase):
26
+ """Test schema files"""
27
+
28
+ _found_keywords: List[str] = [
29
+ "*",
30
+ "Conditions",
31
+ "Description",
32
+ "Mappings",
33
+ "Metadata",
34
+ "Metadata/AWS::CloudFormation::Interface",
35
+ "Metadata/cfn-lint",
36
+ "Outputs",
37
+ "Outputs/*",
38
+ "Outputs/*/Condition",
39
+ "Outputs/*/Export/Name",
40
+ "Outputs/*/Value",
41
+ "Parameters",
42
+ "Parameters/*",
43
+ "Resources",
44
+ "Resources/*",
45
+ "Resources/*/Condition",
46
+ "Resources/*/CreationPolicy",
47
+ "Resources/*/DeletionPolicy",
48
+ "Resources/*/DependsOn",
49
+ "Resources/*/DependsOn/*",
50
+ "Resources/*/Metadata",
51
+ "Resources/*/Metadata/AWS::CloudFormation::Init",
52
+ "Resources/*/Type",
53
+ "Resources/*/UpdatePolicy",
54
+ "Resources/*/UpdateReplacePolicy",
55
+ "Rules",
56
+ "Rules/*/Assertions/*/Assert",
57
+ "Rules/*/RuleCondition",
58
+ "Transform",
59
+ ]
60
+
61
+ def setUp(self) -> None:
62
+ schema_path = os.path.join(os.path.dirname(cfnlint.__file__), "data", "schemas")
63
+ self.paths = {
64
+ "extensions": os.path.join(schema_path, "extensions"),
65
+ "providers": os.path.join(schema_path, "providers"),
66
+ "other": os.path.join(schema_path, "other"),
67
+ "fixtures": os.path.join(
68
+ os.path.dirname(__file__),
69
+ "..",
70
+ "fixtures",
71
+ "schemas",
72
+ "providers",
73
+ ),
74
+ }
75
+ filename = os.path.join(
76
+ self.paths["fixtures"], "..", "json_schema", "draft7.json"
77
+ )
78
+ with open(filename, "r") as fh:
79
+ d = json.load(fh)
80
+ self.schema_draft7 = d
81
+
82
+ super().setUp()
83
+
84
+ def get_files(self, dir):
85
+ for dirpath, _, filenames in os.walk(dir):
86
+ for filename in fnmatch.filter(filenames, "*.json"):
87
+ yield dirpath, filename
88
+
89
+ def pattern(self, validator, patrn, instance, schema):
90
+ try:
91
+ re.compile(patrn)
92
+ except Exception:
93
+ yield ValidationError(f"Pattern doesn't compile: {patrn}")
94
+
95
+ def validate_basic_schema_details(
96
+ self, schema_resolver: RefResolver, filepath: str
97
+ ):
98
+ """
99
+ Validate that readOnly, writeOnly, etc are valid
100
+ """
101
+ sections = [
102
+ "readOnlyProperties",
103
+ "writeOnlyProperties",
104
+ "conditionalCreateOnlyProperties",
105
+ "nonPublicProperties",
106
+ "nonPublicDefinitions",
107
+ "createOnlyProperties",
108
+ "deprecatedProperties",
109
+ "primaryIdentifier",
110
+ ]
111
+ for section in sections:
112
+ for prop in schema_resolver.referrer.get(section, []):
113
+ try:
114
+ self.assertIsNotNone(schema_resolver.resolve_cfn_pointer(prop))
115
+ except RefResolutionError:
116
+ self.fail(f"Can't find prop {prop} for {section} in {filepath}")
117
+
118
+ def _build_keywords(self, obj: Any, schema_resolver: RefResolver, refs: list[str]):
119
+ if not isinstance(obj, dict):
120
+ yield []
121
+ return
122
+
123
+ if "$ref" in obj:
124
+ ref = obj["$ref"]
125
+ if ref in refs:
126
+ yield []
127
+ return
128
+ _, resolved_schema = schema_resolver.resolve(ref)
129
+ yield from self._build_keywords(
130
+ resolved_schema, schema_resolver, refs + [ref]
131
+ )
132
+
133
+ if "type" in obj:
134
+ if "object" in ensure_list(obj["type"]):
135
+ if "properties" in obj:
136
+ for k, v in obj["properties"].items():
137
+ for item in self._build_keywords(v, schema_resolver, refs):
138
+ yield [k] + item
139
+ if "array" in ensure_list(obj["type"]):
140
+ if "items" in obj:
141
+ for item in self._build_keywords(
142
+ obj["items"], schema_resolver, refs
143
+ ):
144
+ yield ["*"] + item
145
+
146
+ yield []
147
+
148
+ def build_keywords(self, schema_resolver):
149
+ self._found_keywords.append(
150
+ "/".join(["Resources", schema_resolver.referrer["typeName"], "Properties"])
151
+ )
152
+ for k, v in schema_resolver.referrer.get("properties").items():
153
+ for item in self._build_keywords(v, schema_resolver, []):
154
+ self._found_keywords.append(
155
+ "/".join(
156
+ [
157
+ "Resources",
158
+ schema_resolver.referrer["typeName"],
159
+ "Properties",
160
+ k,
161
+ ]
162
+ + item
163
+ )
164
+ )
165
+
166
+ def test_data_module_specs(self):
167
+ """Test data file formats"""
168
+
169
+ draft7_schema = load_resource(
170
+ "cfnlint.data.schemas.other.draft7", "schema.json"
171
+ )
172
+ store = {"http://json-schema.org/draft-07/schema": draft7_schema}
173
+ dir = self.paths["fixtures"]
174
+ for dirpath, filename in self.get_files(dir):
175
+ with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh:
176
+ store[filename] = json.load(fh)
177
+
178
+ resolver = RefResolver.from_schema(
179
+ store["provider.definition.schema.v1.json"], store=store
180
+ )
181
+
182
+ validator = (
183
+ StandardValidator({})
184
+ .extend(
185
+ validators={
186
+ "cfnLint": self.cfn_lint,
187
+ "pattern": self.pattern,
188
+ },
189
+ )(schema=store["provider.definition.schema.v1.json"])
190
+ .evolve(resolver=resolver)
191
+ )
192
+
193
+ for region in REGIONS:
194
+ dir = os.path.join(
195
+ self.paths["providers"],
196
+ region.replace("-", "_"),
197
+ )
198
+
199
+ for dirpath, filename in self.get_files(dir):
200
+ with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh:
201
+ d = json.load(fh)
202
+ # not allowed but true with this resource
203
+ if filename == "aws-cloudformation-customresource.json":
204
+ d["additionalProperties"] = False
205
+ if filename == "module.json":
206
+ continue
207
+ errs = list(validator.iter_errors(d))
208
+ self.assertListEqual(
209
+ errs, [], f"Error with {dirpath}/{filename}: {errs}"
210
+ )
211
+ schema_resolver = RefResolver(d)
212
+ self.validate_basic_schema_details(
213
+ schema_resolver, f"{dirpath}/{filename}"
214
+ )
215
+
216
+ if region == "us-east-1":
217
+ self.build_keywords(schema_resolver)
218
+
219
+ def cfn_lint(self, validator, _, keywords, schema):
220
+ keywords = ensure_list(keywords)
221
+ self._found_keywords.extend(keywords)
222
+
223
+ def test_other_specs(self):
224
+ """Test data file formats"""
225
+
226
+ draft7_schema = load_resource(
227
+ "cfnlint.data.schemas.other.draft7", "schema.json"
228
+ )
229
+ store = {"http://json-schema.org/draft-07/schema": draft7_schema}
230
+ dir = self.paths["fixtures"]
231
+ for dirpath, filename in self.get_files(dir):
232
+ with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh:
233
+ store[filename] = json.load(fh)
234
+
235
+ resolver = RefResolver.from_schema(
236
+ store["http://json-schema.org/draft-07/schema"], store=store
237
+ )
238
+
239
+ validator = (
240
+ StandardValidator({})
241
+ .extend(
242
+ validators={
243
+ "cfnLint": self.cfn_lint,
244
+ "pattern": self.pattern,
245
+ },
246
+ )(schema=store["http://json-schema.org/draft-07/schema"])
247
+ .evolve(resolver=resolver)
248
+ )
249
+
250
+ for dir_name in ["extensions", "other"]:
251
+ dir = self.paths[dir_name]
252
+
253
+ for dirpath, filename in self.get_files(dir):
254
+ with open(os.path.join(dirpath, filename), "r", encoding="utf8") as fh:
255
+ d = json.load(fh)
256
+ errs = list(validator.iter_errors(d))
257
+ self.assertListEqual(
258
+ errs, [], f"Error with {dirpath}/{filename}: {errs}"
259
+ )
260
+ schema_resolver = RefResolver(d)
261
+ self.validate_basic_schema_details(
262
+ schema_resolver, f"{dirpath}/{filename}"
263
+ )
264
+
265
+ def test_x_keywords(self):
266
+ root_dir = pathlib.Path(__file__).parent.parent.parent / "src/cfnlint/rules"
267
+ rules = load_plugins(
268
+ str(root_dir),
269
+ "CfnLintKeyword",
270
+ "cfnlint.rules.jsonschema.CfnLintKeyword",
271
+ )
272
+ rules.extend(
273
+ load_plugins(
274
+ str(root_dir),
275
+ "CfnLintJsonSchema",
276
+ "cfnlint.rules.jsonschema.CfnLintJsonSchema",
277
+ )
278
+ )
279
+
280
+ for rule in rules:
281
+ for keyword in rule.keywords:
282
+ self.assertIn(keyword, self._found_keywords, f"{keyword} not found")
testbed/aws-cloudformation__cfn-lint/test/testlib/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/testlib/testcase.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from unittest import TestCase
7
+
8
+ import cfnlint.decode.cfn_yaml
9
+
10
+
11
+ class BaseTestCase(TestCase):
12
+ """
13
+ All test cases should inherit from this class as any common
14
+ functionality that is added here will then be available to all
15
+ subclasses. This facilitates the ability to update in one spot
16
+ and allow all tests to get the update for easy maintenance.
17
+ """
18
+
19
+ def load_template(self, filename):
20
+ """Return template"""
21
+ return cfnlint.decode.cfn_yaml.load(filename)
22
+
23
+ def assertEqualListOfDicts(self, a, b):
24
+ """Compare two lists of dicts"""
25
+ assert isinstance(a, list)
26
+ assert isinstance(b, list)
27
+
28
+ def key_func(d):
29
+ """sort dict based on keys"""
30
+ items = ((k, v if v is not None else "") for k, v in d.items())
31
+ return sorted(items)
32
+
33
+ self.assertEqual(sorted(a, key=key_func), sorted(b, key=key_func))
testbed/aws-cloudformation__cfn-lint/test/unit/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_json/test_cfn_json.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from io import StringIO
7
+ from test.testlib.testcase import BaseTestCase
8
+ from unittest.mock import patch
9
+
10
+ import cfnlint.decode.cfn_json # pylint: disable=E0401
11
+ from cfnlint import ConfigMixIn
12
+ from cfnlint.config import _DEFAULT_RULESDIR
13
+ from cfnlint.rules import Rules
14
+ from cfnlint.template.template import Template # pylint: disable=E0401
15
+
16
+
17
+ class TestCfnJson(BaseTestCase):
18
+ """Test JSON Parsing"""
19
+
20
+ def setUp(self):
21
+ """SetUp template object"""
22
+ self.rules = Rules.create_from_directory(_DEFAULT_RULESDIR)
23
+ self.config = ConfigMixIn(
24
+ include_experimental=True,
25
+ )
26
+
27
+ self.filenames = {
28
+ "config_rule": {
29
+ "filename": "test/fixtures/templates/quickstart/config-rules.json",
30
+ "failures": 5,
31
+ },
32
+ "iam": {
33
+ "filename": "test/fixtures/templates/quickstart/iam.json",
34
+ "failures": 5,
35
+ },
36
+ "nat_instance": {
37
+ "filename": "test/fixtures/templates/quickstart/nat-instance.json",
38
+ "failures": 4,
39
+ },
40
+ "vpc_management": {
41
+ "filename": "test/fixtures/templates/quickstart/vpc-management.json",
42
+ "failures": 9,
43
+ },
44
+ "vpc": {
45
+ "filename": "test/fixtures/templates/quickstart/vpc.json",
46
+ "failures": 5,
47
+ },
48
+ "poller": {
49
+ "filename": "test/fixtures/templates/public/lambda-poller.json",
50
+ "failures": 1,
51
+ },
52
+ }
53
+
54
+ def test_success_parse(self):
55
+ """Test Successful JSON Parsing"""
56
+ for _, values in self.filenames.items():
57
+ filename = values.get("filename")
58
+ failures = values.get("failures")
59
+
60
+ template = cfnlint.decode.cfn_json.load(filename)
61
+ cfn = Template(filename, template, ["us-east-1"])
62
+
63
+ matches = list(self.rules.run(filename, cfn, self.config))
64
+ assert (
65
+ len(matches) == failures
66
+ ), "Expected {} failures, got {} on {}".format(failures, matches, filename)
67
+
68
+ def test_success_escape_character(self):
69
+ """Test Successful JSON Parsing"""
70
+ failures = 1
71
+ filename = "test/fixtures/templates/good/decode/parsing.json"
72
+ template = cfnlint.decode.cfn_json.load(filename)
73
+ cfn = Template(filename, template, ["us-east-1"])
74
+
75
+ matches = list(self.rules.run(filename, cfn, self.config))
76
+ assert len(matches) == failures, "Expected {} failures, got {} on {}".format(
77
+ failures, matches, filename
78
+ )
79
+
80
+ def test_success_parse_stdin(self):
81
+ """Test Successful JSON Parsing through stdin"""
82
+ for _, values in self.filenames.items():
83
+ filename = None
84
+ failures = values.get("failures")
85
+ with open(values.get("filename"), "r") as fp:
86
+ file_content = fp.read()
87
+ with patch("sys.stdin", StringIO(file_content)):
88
+ template = cfnlint.decode.cfn_json.load(filename)
89
+ cfn = Template(filename, template, ["us-east-1"])
90
+
91
+ matches = list(self.rules.run(filename, cfn, self.config))
92
+ assert (
93
+ len(matches) == failures
94
+ ), "Expected {} failures, got {} on {}".format(
95
+ failures, matches, values.get("filename")
96
+ )
97
+
98
+ def test_fail_run(self):
99
+ """Test failure run"""
100
+
101
+ filename = "test/fixtures/templates/bad/json_parse.json"
102
+
103
+ try:
104
+ cfnlint.decode.cfn_json.load(filename)
105
+ except cfnlint.decode.cfn_json.JSONDecodeError:
106
+ assert True
107
+ return
108
+
109
+ assert False
testbed/aws-cloudformation__cfn-lint/test/unit/module/cfn_yaml/test_yaml.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from io import StringIO
7
+ from test.testlib.testcase import BaseTestCase
8
+ from unittest.mock import patch
9
+
10
+ import cfnlint.decode.cfn_yaml # pylint: disable=E0401
11
+ from cfnlint.config import _DEFAULT_RULESDIR, ConfigMixIn
12
+ from cfnlint.rules import Rules
13
+ from cfnlint.template.template import Template # pylint: disable=E0401
14
+
15
+
16
+ class TestYamlParse(BaseTestCase):
17
+ """Test YAML Parsing"""
18
+
19
+ def setUp(self):
20
+ """SetUp template object"""
21
+ self.rules = Rules.create_from_directory(_DEFAULT_RULESDIR)
22
+
23
+ self.filenames = {
24
+ "config_rule": {
25
+ "filename": "test/fixtures/templates/public/lambda-poller.yaml",
26
+ "failures": 1,
27
+ },
28
+ "generic_bad": {
29
+ "filename": "test/fixtures/templates/bad/generic.yaml",
30
+ "failures": 35,
31
+ },
32
+ }
33
+
34
+ def test_success_parse(self):
35
+ """Test Successful YAML Parsing"""
36
+ for _, values in self.filenames.items():
37
+ filename = values.get("filename")
38
+ failures = values.get("failures")
39
+ template = cfnlint.decode.cfn_yaml.load(filename)
40
+ cfn = Template(filename, template, ["us-east-1"])
41
+
42
+ matches = list(self.rules.run(filename, cfn, ConfigMixIn({})))
43
+ assert (
44
+ len(matches) == failures
45
+ ), "Expected {} failures, got {} on {}".format(
46
+ failures, len(matches), filename
47
+ )
48
+
49
+ def test_success_parse_stdin(self):
50
+ """Test Successful YAML Parsing through stdin"""
51
+ for _, values in self.filenames.items():
52
+ filename = None
53
+ failures = values.get("failures")
54
+ with open(values.get("filename"), "r") as fp:
55
+ file_content = fp.read()
56
+
57
+ with patch("sys.stdin", StringIO(file_content)):
58
+ template = cfnlint.decode.cfn_yaml.load(filename)
59
+ cfn = Template(filename, template, ["us-east-1"])
60
+
61
+ matches = []
62
+ matches.extend(self.rules.run(filename, cfn, ConfigMixIn({})))
63
+ assert (
64
+ len(matches) == failures
65
+ ), "Expected {} failures, got {} on {}".format(
66
+ failures, len(matches), values.get("filename")
67
+ )
68
+
69
+ def test_map_failure(self):
70
+ """Test a failure is passed on unhashable map"""
71
+ filename = "test/fixtures/templates/bad/core/parse_invalid_map.yaml"
72
+
73
+ self.assertRaises(
74
+ cfnlint.decode.cfn_yaml.CfnParseError,
75
+ cfnlint.decode.cfn_yaml.load,
76
+ filename,
77
+ )
testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_condition.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from unittest import TestCase
7
+
8
+ from cfnlint.conditions._condition import (
9
+ ConditionAnd,
10
+ ConditionNot,
11
+ ConditionOr,
12
+ ConditionUnnammed,
13
+ )
14
+ from cfnlint.conditions._utils import get_hash
15
+
16
+
17
+ class TestCondition(TestCase):
18
+ """Test Condition"""
19
+
20
+ def test_not_condition(self):
21
+ """Test not condition"""
22
+
23
+ with self.assertRaises(ValueError):
24
+ ConditionNot(
25
+ [
26
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
27
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]},
28
+ ],
29
+ {},
30
+ )
31
+
32
+ def test_unnamed_condition(self):
33
+ """Test unnamed condition"""
34
+
35
+ with self.assertRaises(ValueError):
36
+ ConditionUnnammed(
37
+ "equals", # not a string
38
+ {},
39
+ )
40
+
41
+ def test_not_a_list(self):
42
+ """Test condition failures"""
43
+
44
+ with self.assertRaises(ValueError):
45
+ ConditionUnnammed({"Fn::And": {}}, {})
46
+
47
+ with self.assertRaises(ValueError):
48
+ ConditionUnnammed({"Condition": {}}, {})
49
+
50
+ with self.assertRaises(ValueError):
51
+ ConditionUnnammed({"BadKey": {}}, {})
52
+
53
+ def test_condition_test(self):
54
+ equals = {"Ref": "AWS::Region"}
55
+ h = get_hash(equals)
56
+ self.assertTrue(
57
+ ConditionNot(
58
+ [
59
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
60
+ ],
61
+ {},
62
+ )._test(
63
+ {h: "us-west-2"},
64
+ )
65
+ )
66
+ self.assertFalse(
67
+ ConditionNot(
68
+ [
69
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
70
+ ],
71
+ {},
72
+ )._test(
73
+ {h: "us-east-1"},
74
+ )
75
+ )
76
+ self.assertFalse(
77
+ ConditionAnd(
78
+ [
79
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
80
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]},
81
+ ],
82
+ {},
83
+ )._test(
84
+ {h: "us-east-1"},
85
+ )
86
+ )
87
+ self.assertTrue(
88
+ ConditionOr(
89
+ [
90
+ {"Fn::Equals": ["us-east-1", {"Ref": "AWS::Region"}]},
91
+ {"Fn::Equals": ["us-west-2", {"Ref": "AWS::Region"}]},
92
+ ],
93
+ {},
94
+ )._test(
95
+ {h: "us-east-1"},
96
+ )
97
+ )
testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_conditions.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import string
7
+ from unittest import TestCase
8
+
9
+ from cfnlint.conditions import UnknownSatisfisfaction
10
+ from cfnlint.conditions._utils import get_hash
11
+ from cfnlint.decode import decode_str
12
+ from cfnlint.template import Template
13
+
14
+
15
+ class TestConditions(TestCase):
16
+ """Test Conditions"""
17
+
18
+ def test_bad_condition_definition(self):
19
+ """Badly formatted condition statements will return no results"""
20
+ template = decode_str(
21
+ """
22
+ Conditions:
23
+ IsProd: !Equals [!Ref Environment, "prod", "production"]
24
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
25
+ """
26
+ )[0]
27
+
28
+ cfn = Template("", template)
29
+ self.assertEqual(
30
+ len(cfn.conditions._conditions), 1
31
+ ) # would be 2 but IsProd fails
32
+ # test coverage for KeyErrors in the following functions
33
+ self.assertTrue(
34
+ cfn.conditions.check_implies(
35
+ {
36
+ "Test": True,
37
+ },
38
+ "IsUsEast1",
39
+ )
40
+ )
41
+ self.assertEqual(
42
+ list(cfn.conditions.build_scenarios({"IsProd": None, "IsUsEast1": None})),
43
+ [],
44
+ )
45
+
46
+ def test_run_away_scenarios(self):
47
+ """We cap runaway scenarios"""
48
+ template = {
49
+ "Parameters": {},
50
+ "Conditions": {},
51
+ }
52
+ condition_names = {}
53
+ for p in string.ascii_letters[0:10]:
54
+ template["Parameters"][f"{p}Parameter"] = {
55
+ "Type": "String",
56
+ }
57
+ template["Conditions"][f"{p}Condition"] = {
58
+ "Fn::Equals": [{"Ref": f"{p}Parameter"}, "{p}"]
59
+ }
60
+ condition_names[f"{p}Condition"] = None
61
+
62
+ cfn = Template("", template)
63
+ self.assertEqual(len(cfn.conditions._conditions), 10)
64
+ self.assertEqual(
65
+ len(list(cfn.conditions.build_scenarios(condition_names))),
66
+ cfn.conditions._max_scenarios,
67
+ )
68
+
69
+ def test_check_implies(self):
70
+ """We properly validate implies scenarios"""
71
+ template = {
72
+ "Parameters": {},
73
+ "Conditions": {},
74
+ }
75
+ condition_names = []
76
+ for p in string.ascii_letters[0:4]:
77
+ template["Parameters"][f"{p}Parameter"] = {
78
+ "Type": "String",
79
+ }
80
+ template["Conditions"][f"{p}Condition"] = {
81
+ "Fn::Equals": [{"Ref": f"{p}Parameter"}, "{p}"]
82
+ }
83
+ condition_names.append(f"{p}Condition")
84
+
85
+ cfn = Template("", template)
86
+ self.assertFalse(
87
+ cfn.conditions.check_implies({"aCondition": False}, "aCondition")
88
+ )
89
+ self.assertTrue(
90
+ cfn.conditions.check_implies({"aCondition": True}, "aCondition")
91
+ )
92
+ self.assertTrue(
93
+ cfn.conditions.check_implies(
94
+ {"aCondition": True, "bCondition": False}, "aCondition"
95
+ )
96
+ )
97
+
98
+ def test_check_always_true_or_false(self):
99
+ """We properly validate static equals"""
100
+ template = decode_str(
101
+ """
102
+ Parameters:
103
+ FalseParameter:
104
+ Default: "false"
105
+ Type: String
106
+ Conditions:
107
+ IsTrue: !Equals ["true", "true"]
108
+ IsFalse: !Equals [!Ref FalseParameter, !Ref FalseParameter]
109
+ """
110
+ )[0]
111
+
112
+ cfn = Template("", template)
113
+ self.assertEqual(len(cfn.conditions._conditions), 2)
114
+ # test coverage for KeyErrors in the following functions
115
+ self.assertTrue(cfn.conditions.check_implies({"IsTrue": True}, "IsFalse"))
116
+
117
+ def test_check_never_false(self):
118
+ """With allowed values two conditions can not both be false"""
119
+ template = decode_str(
120
+ """
121
+ Parameters:
122
+ Environment:
123
+ Type: String
124
+ AllowedValues: ["prod", "dev"]
125
+ Conditions:
126
+ IsProd: !Equals [!Ref Environment, "prod"]
127
+ IsDev: !Equals [!Ref Environment, "dev"]
128
+ """
129
+ )[0]
130
+
131
+ cfn = Template("", template)
132
+ self.assertEqual(len(cfn.conditions._conditions), 2)
133
+ self.assertListEqual(
134
+ list(cfn.conditions.build_scenarios({"IsProd": None, "IsDev": None})),
135
+ [
136
+ {"IsProd": True, "IsDev": False},
137
+ {"IsProd": False, "IsDev": True},
138
+ ],
139
+ )
140
+
141
+ def test_check_can_be_false(self):
142
+ """With allowed values two conditions can both be false"""
143
+ template = decode_str(
144
+ """
145
+ Parameters:
146
+ Environment:
147
+ Type: String
148
+ AllowedValues: ["prod", "dev", "stage"]
149
+ Conditions:
150
+ IsProd: !Equals [!Ref Environment, "prod"]
151
+ IsDev: !Equals [!Ref Environment, "dev"]
152
+ """
153
+ )[0]
154
+
155
+ cfn = Template("", template)
156
+ self.assertEqual(len(cfn.conditions._conditions), 2)
157
+ self.assertListEqual(
158
+ list(cfn.conditions.build_scenarios({"IsProd": None, "IsDev": None})),
159
+ [
160
+ {"IsProd": True, "IsDev": False},
161
+ {"IsProd": False, "IsDev": True},
162
+ {"IsProd": False, "IsDev": False},
163
+ ],
164
+ )
165
+ self.assertListEqual(
166
+ list(cfn.conditions.build_scenarios({"IsProd": {True}, "IsDev": None})),
167
+ [
168
+ {"IsProd": True, "IsDev": False},
169
+ ],
170
+ )
171
+ self.assertListEqual(
172
+ list(cfn.conditions.build_scenarios({"IsProd": {False}, "IsDev": None})),
173
+ [
174
+ {"IsProd": False, "IsDev": True},
175
+ {"IsProd": False, "IsDev": False},
176
+ ],
177
+ )
178
+
179
+ def test_check_can_be_good_when_condition_value(self):
180
+ """Some times a condition Equals doesn't match to allowed values"""
181
+ template = decode_str(
182
+ """
183
+ Parameters:
184
+ Environment:
185
+ Type: String
186
+ AllowedValues: ["prod", "dev", "stage"]
187
+ Conditions:
188
+ IsGamma: !Equals [!Ref Environment, "gamma"]
189
+ IsBeta: !Equals ["beta", !Ref Environment]
190
+ """
191
+ )[0]
192
+
193
+ cfn = Template("", template)
194
+ self.assertEqual(len(cfn.conditions._conditions), 2)
195
+ self.assertListEqual(
196
+ list(cfn.conditions.build_scenarios({"IsGamma": None, "IsBeta": None})),
197
+ [
198
+ {"IsBeta": False, "IsGamma": False},
199
+ ],
200
+ )
201
+ self.assertListEqual(
202
+ list(cfn.conditions.build_scenarios({"IsGamma": None})),
203
+ [
204
+ {"IsGamma": False},
205
+ ],
206
+ )
207
+
208
+ def test_check_condition_region(self):
209
+ """Regional based condition testing"""
210
+ template = decode_str(
211
+ """
212
+ Parameters:
213
+ Environment:
214
+ Type: String
215
+ AllowedValues: ["prod", "dev", "stage"]
216
+ Conditions:
217
+ IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"]
218
+ IsUsWest2: !Equals ["us-west-2", !Ref AWS::Region]
219
+ IsProd: !Equals [!Ref Environment, "prod"]
220
+ """
221
+ )[0]
222
+
223
+ cfn = Template("", template)
224
+ self.assertEqual(len(cfn.conditions._conditions), 3)
225
+ self.assertListEqual(
226
+ cfn.conditions.build_scenerios_on_region("IsUsEast1", "us-east-1"),
227
+ [
228
+ True,
229
+ ],
230
+ )
231
+ self.assertListEqual(
232
+ cfn.conditions.build_scenerios_on_region("IsUsEast1", "us-west-2"),
233
+ [
234
+ False,
235
+ ],
236
+ )
237
+ self.assertListEqual(
238
+ cfn.conditions.build_scenerios_on_region("IsUsWest2", "us-west-2"),
239
+ [
240
+ True,
241
+ ],
242
+ )
243
+ self.assertListEqual(
244
+ cfn.conditions.build_scenerios_on_region("IsUsWest2", "us-east-1"),
245
+ [
246
+ False,
247
+ ],
248
+ )
249
+ self.assertListEqual(
250
+ cfn.conditions.build_scenerios_on_region("IsProd", "us-east-1"),
251
+ [
252
+ True,
253
+ False,
254
+ ],
255
+ )
256
+ self.assertListEqual(
257
+ cfn.conditions.build_scenerios_on_region("Foo", "us-east-1"),
258
+ [
259
+ True,
260
+ False,
261
+ ],
262
+ )
263
+
264
+ def test_test_condition(self):
265
+ """Get condition and test"""
266
+ template = decode_str(
267
+ """
268
+ Parameters:
269
+ Environment:
270
+ Type: String
271
+ AllowedValues: ["prod", "dev", "stage"]
272
+ Conditions:
273
+ IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"]
274
+ IsUsWest2: !Equals ["us-west-2", !Ref AWS::Region]
275
+ IsProd: !Equals [!Ref Environment, "prod"]
276
+ IsUsEast1AndProd: !And [!Condition IsUsEast1, !Condition IsProd]
277
+ """
278
+ )[0]
279
+
280
+ h_region = get_hash({"Ref": "AWS::Region"})
281
+ h_environment = get_hash({"Ref": "Environment"})
282
+
283
+ cfn = Template("", template)
284
+ self.assertTrue(cfn.conditions.get("IsUsEast1").test({h_region: "us-east-1"}))
285
+ self.assertFalse(cfn.conditions.get("IsProd").test({h_environment: "dev"}))
286
+ self.assertTrue(
287
+ cfn.conditions.get("IsUsEast1AndProd").test(
288
+ {h_region: "us-east-1", h_environment: "prod"}
289
+ )
290
+ )
291
+ self.assertFalse(
292
+ cfn.conditions.get("IsUsEast1AndProd").test(
293
+ {h_region: "us-east-1", h_environment: "dev"}
294
+ )
295
+ )
296
+
297
+ def test_build_scenerios_on_region_with_condition_dne(self):
298
+ """Get condition and test"""
299
+ template = decode_str(
300
+ """
301
+ Conditions:
302
+ IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"]
303
+ """
304
+ )[0]
305
+
306
+ cfn = Template("", template)
307
+ self.assertListEqual(
308
+ list(cfn.conditions.build_scenerios_on_region("IsProd", "us-east-1")),
309
+ [True, False],
310
+ )
311
+
312
+ def test_satifaction(self):
313
+ """Get condition and test"""
314
+ template = decode_str(
315
+ """
316
+ Parameters:
317
+ SecurityGroups:
318
+ Default: ""
319
+ Type: CommaDelimitedList
320
+ Conditions:
321
+ IsUsEast1: !Equals [!Ref AWS::Region, "us-east-1"]
322
+ HasSecurityGroups: !Not [ !Equals [ !Join [ '', !Ref SecurityGroups ], ''] ]
323
+ """
324
+ )[0]
325
+
326
+ cfn = Template("", template)
327
+
328
+ with self.assertRaises(UnknownSatisfisfaction):
329
+ cfn.conditions.satisfiable(
330
+ {"HasSecurityGroups": True}, {"SecurityGroups": [""]}
331
+ )
testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_equals.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from unittest import TestCase
7
+
8
+ from cfnlint.conditions._equals import Equal
9
+ from cfnlint.conditions._utils import get_hash
10
+
11
+
12
+ class TestEquals(TestCase):
13
+ """Test Equals"""
14
+
15
+ def setUp(self) -> None:
16
+ self.equals = {"Ref": "AWS::Region"}
17
+ self.equals_h = get_hash(self.equals)
18
+
19
+ self.parameter_region = {"Ref": "Region"}
20
+ self.parameter_region_h = get_hash(self.parameter_region)
21
+
22
+ self.parameter_env = {"Ref": "Environment"}
23
+ self.parameter_env_h = get_hash(self.parameter_env)
24
+
25
+ return super().setUp()
26
+
27
+ def test_equals_error_test(self):
28
+ """Test equals scenarios condition"""
29
+ equal = Equal([self.equals, "us-east-1"])
30
+
31
+ with self.assertRaises(ValueError):
32
+ equal.test({"foo": "bar"})
33
+
34
+ def test_equals_left_test(self):
35
+ """Test equals scenarios condition"""
36
+ equal = Equal([self.equals, "us-east-1"])
37
+
38
+ self.assertTrue(equal.test({self.equals_h: "us-east-1"}))
39
+ self.assertFalse(equal.test({self.equals_h: "us-west-2"}))
40
+
41
+ equal = Equal([self.equals, self.parameter_region])
42
+ self.assertTrue(
43
+ equal.test(
44
+ {
45
+ self.equals_h: self.parameter_region_h,
46
+ self.parameter_region_h: self.equals_h,
47
+ }
48
+ )
49
+ )
50
+ self.assertFalse(equal.test({self.equals_h: self.parameter_env_h}))
51
+
52
+ def test_equals_left_right(self):
53
+ """Test equals scenarios condition"""
54
+ equal = Equal(["us-east-1", self.equals])
55
+
56
+ self.assertTrue(equal.test({self.equals_h: "us-east-1"}))
57
+ self.assertFalse(equal.test({self.equals_h: "us-west-2"}))
58
+
59
+ equal = Equal([self.parameter_region, self.equals])
60
+ self.assertTrue(
61
+ equal.test(
62
+ {
63
+ self.equals_h: self.parameter_region_h,
64
+ self.parameter_region_h: self.equals_h,
65
+ }
66
+ )
67
+ )
68
+ self.assertFalse(equal.test({self.equals_h: self.parameter_env_h}))
69
+
70
+ def test_equal_string_test(self):
71
+ """Test equals scenarios condition"""
72
+ equal = Equal(["us-west-2", "us-east-1"])
73
+
74
+ self.assertFalse(equal.test({"foo": "bar"}))
testbed/aws-cloudformation__cfn-lint/test/unit/module/conditions/test_rules.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from unittest import TestCase
7
+
8
+ from cfnlint.conditions._rule import _Assertion
9
+ from cfnlint.decode import decode_str
10
+ from cfnlint.template import Template
11
+
12
+
13
+ class TestConditionsWithRules(TestCase):
14
+
15
+ def test_conditions_with_rules(self):
16
+ template = decode_str(
17
+ """
18
+ Conditions:
19
+ IsProd: !Equals [!Ref Environment, "prod"]
20
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
21
+ Rules:
22
+ Rule1:
23
+ Assertions:
24
+ - Assert:
25
+ Fn::And:
26
+ - !Equals [!Ref Environment, "prod"]
27
+ - !Equals [!Ref "AWS::Region", "us-east-1"]
28
+ Rule2:
29
+ Assertions:
30
+ - Assert:
31
+ Fn::Or:
32
+ - !Equals [!Ref Environment, "prod"]
33
+ - !Equals [!Ref "AWS::Region", "us-east-1"]
34
+ """
35
+ )[0]
36
+
37
+ cfn = Template("", template)
38
+ self.assertEqual(len(cfn.conditions._conditions), 2)
39
+ self.assertEqual(len(cfn.conditions._rules), 2)
40
+
41
+ self.assertListEqual(
42
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
43
+ [
44
+ "d0f5e92fc5233a6b011342df171f191838491056",
45
+ "362a2ca660fa34c91feeee4681e8433101d2a687",
46
+ ],
47
+ )
48
+
49
+ self.assertTrue(
50
+ cfn.conditions.satisfiable(
51
+ {"IsProd": True, "IsUsEast1": True},
52
+ {"AWS::Region": "us-east-1", "Environment": "prod"},
53
+ )
54
+ )
55
+ self.assertFalse(
56
+ cfn.conditions.satisfiable(
57
+ {"IsProd": True, "IsUsEast1": False},
58
+ {"AWS::Region": "us-west-2", "Environment": "prod"},
59
+ )
60
+ )
61
+ self.assertFalse(
62
+ cfn.conditions.satisfiable(
63
+ {"IsProd": False, "IsUsEast1": True},
64
+ {"AWS::Region": "us-east-1", "Environment": "dev"},
65
+ )
66
+ )
67
+ self.assertFalse(
68
+ cfn.conditions.satisfiable(
69
+ {"IsProd": False, "IsUsEast1": False},
70
+ {"AWS::Region": "us-west-2", "Environment": "dev"},
71
+ )
72
+ )
73
+
74
+ def test_conditions_with_rules_implies(self):
75
+ template = decode_str(
76
+ """
77
+ Conditions:
78
+ IsProd: !Equals [!Ref Environment, "prod"]
79
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
80
+ Rules:
81
+ Rule:
82
+ RuleCondition: !Equals [!Ref Environment, "prod"]
83
+ Assertions:
84
+ - Assert: !Equals [!Ref "AWS::Region", "us-east-1"]
85
+
86
+ """
87
+ )[0]
88
+
89
+ cfn = Template("", template)
90
+ self.assertEqual(len(cfn.conditions._conditions), 2)
91
+ self.assertEqual(len(cfn.conditions._rules), 1)
92
+
93
+ self.assertListEqual(
94
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
95
+ [
96
+ "d0f5e92fc5233a6b011342df171f191838491056",
97
+ "362a2ca660fa34c91feeee4681e8433101d2a687",
98
+ ],
99
+ )
100
+
101
+ self.assertTrue(
102
+ cfn.conditions.satisfiable(
103
+ {"IsProd": True, "IsUsEast1": True},
104
+ {"AWS::Region": "us-east-1", "Environment": "prod"},
105
+ )
106
+ )
107
+ self.assertFalse(
108
+ cfn.conditions.satisfiable(
109
+ {"IsProd": True, "IsUsEast1": False},
110
+ {"AWS::Region": "us-west-2", "Environment": "prod"},
111
+ )
112
+ )
113
+ self.assertTrue(
114
+ cfn.conditions.satisfiable(
115
+ {"IsProd": False, "IsUsEast1": True},
116
+ {"AWS::Region": "us-east-1", "Environment": "dev"},
117
+ )
118
+ )
119
+ self.assertTrue(
120
+ cfn.conditions.satisfiable(
121
+ {"IsProd": False, "IsUsEast1": False},
122
+ {"AWS::Region": "us-west-2", "Environment": "dev"},
123
+ )
124
+ )
125
+
126
+ def test_conditions_with_multiple_rules(self):
127
+ template = decode_str(
128
+ """
129
+ Parameters:
130
+ Environment:
131
+ Type: String
132
+ Default: dev
133
+ AllowedValues:
134
+ - dev
135
+ - stage
136
+ - prod
137
+ Conditions:
138
+ IsProd: !Equals [!Ref Environment, "prod"]
139
+ IsDev: !Equals [!Ref Environment, "dev"]
140
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
141
+ IsNotUsEast1: !Not [!Condition IsUsEast1]
142
+ Rules:
143
+ Rule1:
144
+ RuleCondition: !Equals [!Ref Environment, "prod"]
145
+ Assertions:
146
+ - Assert: !Equals [!Ref "AWS::Region", "us-east-1"]
147
+ Rule2:
148
+ RuleCondition: !Equals [!Ref Environment, "dev"]
149
+ Assertions:
150
+ - Assert: !Not [!Equals [!Ref "AWS::Region", "us-east-1"]]
151
+ """
152
+ )[0]
153
+
154
+ cfn = Template("", template)
155
+ self.assertEqual(len(cfn.conditions._conditions), 4)
156
+ self.assertEqual(len(cfn.conditions._rules), 2)
157
+
158
+ self.assertListEqual(
159
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
160
+ [
161
+ "d0f5e92fc5233a6b011342df171f191838491056",
162
+ "362a2ca660fa34c91feeee4681e8433101d2a687",
163
+ ],
164
+ )
165
+ self.assertListEqual(
166
+ [equal.hash for equal in cfn.conditions._rules[1].equals],
167
+ [
168
+ "d2dab653475dd270354fe84c4f80b54883e958bb",
169
+ "362a2ca660fa34c91feeee4681e8433101d2a687",
170
+ ],
171
+ )
172
+
173
+ self.assertTrue(
174
+ cfn.conditions.satisfiable(
175
+ {
176
+ "IsProd": True,
177
+ "IsUsEast1": True,
178
+ "IsDev": False,
179
+ "IsNotUsEast1": False,
180
+ },
181
+ {"AWS::Region": "us-east-1", "Environment": "prod"},
182
+ )
183
+ )
184
+ self.assertFalse(
185
+ cfn.conditions.satisfiable(
186
+ {
187
+ "IsProd": True,
188
+ "IsUsEast1": False,
189
+ "IsDev": False,
190
+ "IsNotUsEast1": False,
191
+ },
192
+ {"AWS::Region": "us-west-2", "Environment": "prod"},
193
+ )
194
+ )
195
+ self.assertFalse(
196
+ cfn.conditions.satisfiable(
197
+ {
198
+ "IsProd": False,
199
+ "IsUsEast1": True,
200
+ "IsDev": True,
201
+ "IsNotUsEast1": False,
202
+ },
203
+ {"AWS::Region": "us-east-1", "Environment": "dev"},
204
+ )
205
+ )
206
+ self.assertTrue(
207
+ cfn.conditions.satisfiable(
208
+ {
209
+ "IsProd": False,
210
+ "IsUsEast1": False,
211
+ "IsDev": True,
212
+ "IsNotUsEast1": True,
213
+ },
214
+ {"AWS::Region": "us-west-2", "Environment": "dev"},
215
+ )
216
+ )
217
+ self.assertTrue(
218
+ cfn.conditions.satisfiable(
219
+ {
220
+ "IsProd": False,
221
+ "IsUsEast1": True,
222
+ "IsDev": False,
223
+ "IsNotUsEast1": False,
224
+ },
225
+ {"AWS::Region": "us-east-1", "Environment": "stage"},
226
+ )
227
+ )
228
+ self.assertTrue(
229
+ cfn.conditions.satisfiable(
230
+ {
231
+ "IsProd": False,
232
+ "IsUsEast1": False,
233
+ "IsDev": False,
234
+ "IsNotUsEast1": True,
235
+ },
236
+ {"AWS::Region": "us-west-2", "Environment": "stage"},
237
+ )
238
+ )
239
+
240
+ def test_fn_equals_assertions_two(self):
241
+ template = decode_str(
242
+ """
243
+ Rules:
244
+ Rule1:
245
+ Assertions:
246
+ - Assert: !Equals ["A", "B"]
247
+ Rule2:
248
+ Assertions:
249
+ - Assert: !Equals ["A", "A"]
250
+ """
251
+ )[0]
252
+
253
+ cfn = Template("", template)
254
+ self.assertEqual(len(cfn.conditions._conditions), 0)
255
+ self.assertEqual(len(cfn.conditions._rules), 2)
256
+
257
+ self.assertListEqual(
258
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
259
+ [
260
+ "e7e68477799682e53ecb09f476128abaeba0bdae",
261
+ ],
262
+ )
263
+ self.assertListEqual(
264
+ [equal.hash for equal in cfn.conditions._rules[1].equals],
265
+ [
266
+ "da2a95009a205d5caacd42c3c11ebd4c151b3409",
267
+ ],
268
+ )
269
+
270
+ self.assertFalse(
271
+ cfn.conditions.satisfiable(
272
+ {},
273
+ {},
274
+ )
275
+ )
276
+
277
+ def test_fn_equals_assertions_one(self):
278
+ template = decode_str(
279
+ """
280
+ Rules:
281
+ Rule1:
282
+ Assertions:
283
+ - Assert: !Equals ["A", "A"]
284
+ """
285
+ )[0]
286
+
287
+ cfn = Template("", template)
288
+ self.assertEqual(len(cfn.conditions._conditions), 0)
289
+ self.assertEqual(len(cfn.conditions._rules), 1)
290
+
291
+ self.assertListEqual(
292
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
293
+ [
294
+ "da2a95009a205d5caacd42c3c11ebd4c151b3409",
295
+ ],
296
+ )
297
+
298
+ self.assertTrue(
299
+ cfn.conditions.satisfiable(
300
+ {},
301
+ {},
302
+ )
303
+ )
304
+
305
+ def test_fn_equals_assertions_ref_no_data(self):
306
+ template = decode_str(
307
+ """
308
+ Parameters:
309
+ AccountId:
310
+ Type: String
311
+ Rules:
312
+ Rule1:
313
+ Assertions:
314
+ - Assert: !Equals [!Ref AccountId, !Ref AWS::AccountId]
315
+ """
316
+ )[0]
317
+
318
+ cfn = Template("", template)
319
+ self.assertEqual(len(cfn.conditions._conditions), 0)
320
+ self.assertEqual(len(cfn.conditions._rules), 1)
321
+
322
+ self.assertListEqual(
323
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
324
+ [
325
+ "f36e61f3d5bf6cdc6ea2e7f01487af728094a439",
326
+ ],
327
+ )
328
+
329
+ self.assertTrue(
330
+ cfn.conditions.satisfiable(
331
+ {},
332
+ {},
333
+ )
334
+ )
335
+
336
+ def test_fn_equals_assertions_ref_never_satisfiable(self):
337
+ template = decode_str(
338
+ """
339
+ Parameters:
340
+ AccountId:
341
+ Type: String
342
+ Rules:
343
+ Rule1:
344
+ Assertions:
345
+ - Assert: !Equals [!Ref AccountId, !Ref AWS::AccountId]
346
+ - Assert: !Not [!Equals [!Ref AccountId, !Ref AWS::AccountId]]
347
+ """
348
+ )[0]
349
+
350
+ cfn = Template("", template)
351
+ self.assertEqual(len(cfn.conditions._conditions), 0)
352
+ self.assertEqual(len(cfn.conditions._rules), 1)
353
+
354
+ self.assertListEqual(
355
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
356
+ [
357
+ "f36e61f3d5bf6cdc6ea2e7f01487af728094a439",
358
+ "f36e61f3d5bf6cdc6ea2e7f01487af728094a439",
359
+ ],
360
+ )
361
+
362
+ self.assertFalse(
363
+ cfn.conditions.satisfiable(
364
+ {},
365
+ {},
366
+ )
367
+ )
368
+
369
+ def test_conditions_with_rules_and_parameters(self):
370
+ template = decode_str(
371
+ """
372
+ Conditions:
373
+ DeployGateway: !Equals
374
+ - !Ref 'DeployGateway'
375
+ - 'true'
376
+ DeployVpc: !Equals
377
+ - !Ref 'DeployVpc'
378
+ - 'true'
379
+ Parameters:
380
+ DeployAnything:
381
+ AllowedValues:
382
+ - 'false'
383
+ - 'true'
384
+ Type: 'String'
385
+ DeployGateway:
386
+ AllowedValues:
387
+ - 'false'
388
+ - 'true'
389
+ Type: 'String'
390
+ DeployVpc:
391
+ AllowedValues:
392
+ - 'false'
393
+ - 'true'
394
+ Type: 'String'
395
+ Rules:
396
+ DeployGateway:
397
+ Assertions:
398
+ - Assert: !Or
399
+ - !Equals
400
+ - !Ref 'DeployAnything'
401
+ - 'true'
402
+ - !Equals
403
+ - !Ref 'DeployGateway'
404
+ - 'false'
405
+ DeployVpc:
406
+ Assertions:
407
+ - Assert: !Or
408
+ - !Equals
409
+ - !Ref 'DeployGateway'
410
+ - 'true'
411
+ - !Equals
412
+ - !Ref 'DeployVpc'
413
+ - 'false'
414
+ Resources:
415
+ InternetGateway:
416
+ Condition: 'DeployGateway'
417
+ Type: 'AWS::EC2::InternetGateway'
418
+ InternetGatewayAttachment:
419
+ Condition: 'DeployVpc'
420
+ Type: 'AWS::EC2::VPCGatewayAttachment'
421
+ Properties:
422
+ InternetGatewayId: !Ref 'InternetGateway'
423
+ VpcId: !Ref 'Vpc'
424
+ """
425
+ )[0]
426
+
427
+ cfn = Template("", template)
428
+ self.assertEqual(len(cfn.conditions._conditions), 2)
429
+ self.assertEqual(len(cfn.conditions._rules), 2)
430
+
431
+ self.assertListEqual(
432
+ [equal.hash for equal in cfn.conditions._rules[0].equals],
433
+ [
434
+ "d0d70a1e66dc83d7a0fce24c2eca396af1f34e53",
435
+ "bbf5c94c1a4b5a79c7a7863fe9463884cb422450",
436
+ ],
437
+ )
438
+
439
+ self.assertTrue(
440
+ cfn.conditions.satisfiable(
441
+ {},
442
+ {},
443
+ )
444
+ )
445
+
446
+ self.assertTrue(
447
+ cfn.conditions.check_implies({"DeployVpc": True}, "DeployGateway")
448
+ )
449
+
450
+ self.assertFalse(
451
+ cfn.conditions.check_implies({"DeployVpc": False}, "DeployGateway")
452
+ )
453
+
454
+ self.assertFalse(
455
+ cfn.conditions.check_implies({"DeployGateway": False}, "DeployVpc")
456
+ )
457
+
458
+
459
+ class TestAssertion(TestCase):
460
+ def test_assertion_errors(self):
461
+ with self.assertRaises(ValueError):
462
+ _Assertion({"A": "B", "C": "D"}, {})
463
+
464
+ with self.assertRaises(ValueError):
465
+ _Assertion({"Fn::Not": {"C": "D"}}, {})
466
+
467
+ with self.assertRaises(ValueError):
468
+ _Assertion({"Not": {"C": "D"}}, {})
469
+
470
+ with self.assertRaises(ValueError):
471
+ _Assertion({"Condition": {"C": "D"}}, {})
472
+
473
+ def test_init_rules_with_list(self):
474
+ template = decode_str(
475
+ """
476
+ Conditions:
477
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
478
+ IsNotUsEast1: !Not [!Condition IsUsEast1]
479
+ Rules: []
480
+ """
481
+ )[0]
482
+
483
+ cfn = Template("", template)
484
+ self.assertListEqual(cfn.conditions._rules, [])
485
+
486
+ def test_init_rules_with_wrong_assertions_type(self):
487
+ template = decode_str(
488
+ """
489
+ Conditions:
490
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
491
+ IsNotUsEast1: !Not [!Condition IsUsEast1]
492
+ Rules:
493
+ Rule1:
494
+ Assertions: {"Foo": "Bar"}
495
+ Rule2:
496
+ Assertions:
497
+ - Assert: !Equals [!Ref "AWS::Region", "us-east-1"]
498
+ """
499
+ )[0]
500
+
501
+ cfn = Template("", template)
502
+ self.assertEqual(len(cfn.conditions._rules), 1)
503
+
504
+ def test_init_rules_with_no_keys(self):
505
+ template = decode_str(
506
+ """
507
+ Conditions:
508
+ IsUsEast1: !Equals [!Ref "AWS::Region", "us-east-1"]
509
+ IsNotUsEast1: !Not [!Condition IsUsEast1]
510
+ Rules:
511
+ Rule1:
512
+ Foo: Bar
513
+ Rule2:
514
+ Assertions:
515
+ - Assert:
516
+ Fn::Or:
517
+ - !Not [!Equals [!Ref "AWS::Region", "us-east-1"]]
518
+ - !Equals [!Ref "AWS::Region", "us-east-1"]
519
+ Rule3: []
520
+ """
521
+ )[0]
522
+
523
+ cfn = Template("", template)
524
+ self.assertEqual(len(cfn.conditions._rules), 1)
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_cli_args.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ from test.testlib.testcase import BaseTestCase
9
+ from unittest.mock import patch
10
+
11
+ import cfnlint.config # pylint: disable=E0401
12
+
13
+ LOGGER = logging.getLogger("cfnlint")
14
+
15
+
16
+ class TestArgsParser(BaseTestCase):
17
+ """Test Parser Arguments"""
18
+
19
+ def tearDown(self):
20
+ """Setup"""
21
+ for handler in LOGGER.handlers:
22
+ LOGGER.removeHandler(handler)
23
+
24
+ def test_create_parser(self):
25
+ """Test success run"""
26
+
27
+ config = cfnlint.config.CliArgs(
28
+ ["-t", "test.yaml", "--ignore-bad-template", "--format", "quiet", "--debug"]
29
+ )
30
+ self.assertEqual(config.cli_args.templates, [])
31
+ self.assertEqual(config.cli_args.template_alt, ["test.yaml"])
32
+ self.assertEqual(config.cli_args.ignore_bad_template, True)
33
+ self.assertEqual(config.cli_args.format, "quiet")
34
+ self.assertEqual(config.cli_args.debug, True)
35
+
36
+ def test_create_parser_default_param(self):
37
+ """Test success run"""
38
+
39
+ config = cfnlint.config.CliArgs(
40
+ [
41
+ "--regions",
42
+ "us-east-1",
43
+ "us-west-2",
44
+ "--",
45
+ "template1.yaml",
46
+ "template2.yaml",
47
+ ]
48
+ )
49
+ self.assertEqual(
50
+ config.cli_args.templates, ["template1.yaml", "template2.yaml"]
51
+ )
52
+ self.assertEqual(config.cli_args.template_alt, [])
53
+ self.assertEqual(config.cli_args.regions, ["us-east-1", "us-west-2"])
54
+
55
+ def test_stdout(self):
56
+ """Test success run"""
57
+
58
+ config = cfnlint.config.CliArgs(["-t", "template1.yaml"])
59
+ self.assertIsNone(config.cli_args.output_file)
60
+
61
+ def test_output_file(self):
62
+ """Test success run"""
63
+
64
+ config = cfnlint.config.CliArgs(
65
+ ["-t", "template1.yaml", "--output-file", "test_output.txt"]
66
+ )
67
+ self.assertEqual(config.cli_args.output_file, "test_output.txt")
68
+
69
+ def test_force_update_specs(self):
70
+ """Test success run"""
71
+
72
+ config = cfnlint.config.CliArgs(["--update-specs", "--force"])
73
+ self.assertEqual(config.cli_args.force, True)
74
+ self.assertEqual(config.cli_args.update_specs, True)
75
+
76
+ def test_create_parser_exend(self):
77
+ """Test success run"""
78
+
79
+ config = cfnlint.config.CliArgs(
80
+ ["-t", "template1.yaml", "-t", "template2.yaml"]
81
+ )
82
+ self.assertEqual(config.cli_args.templates, [])
83
+ self.assertEqual(
84
+ config.cli_args.template_alt, ["template1.yaml", "template2.yaml"]
85
+ )
86
+
87
+ def test_create_parser_config_file_regions(self):
88
+ """Test success run"""
89
+
90
+ config = cfnlint.config.CliArgs(
91
+ [
92
+ "--regions",
93
+ "us-west-1",
94
+ "--include-checks",
95
+ "I1234",
96
+ "--",
97
+ "template1.yaml",
98
+ ]
99
+ )
100
+ self.assertEqual(config.cli_args.templates, ["template1.yaml"])
101
+ self.assertEqual(config.cli_args.include_checks, ["I1234"])
102
+ self.assertEqual(config.cli_args.regions, ["us-west-1"])
103
+
104
+ def test_create_parser_config_file(self):
105
+ """Test success run"""
106
+
107
+ config = cfnlint.config.CliArgs(
108
+ ["--mandatory-checks", "I1234", "--", "template1.yaml"]
109
+ )
110
+ self.assertEqual(config.cli_args.templates, ["template1.yaml"])
111
+ self.assertEqual(config.cli_args.mandatory_checks, ["I1234"])
112
+
113
+ def test_create_parser_rule_configuration(self):
114
+ """Test success run"""
115
+
116
+ config = cfnlint.config.CliArgs(
117
+ ["-x", "E3012:strict=true", "-x", "E3012:key=value,E3001:key=value"]
118
+ )
119
+ self.assertEqual(
120
+ config.cli_args.configure_rules,
121
+ {"E3012": {"key": "value", "strict": "true"}, "E3001": {"key": "value"}},
122
+ )
123
+
124
+ def test_exit_code_parameter(self):
125
+ """Test values of exit code"""
126
+
127
+ for param in ["informational", "warning", "error"]:
128
+ with self.subTest():
129
+ config = cfnlint.config.CliArgs(["--non-zero-exit-code", param])
130
+ self.assertEqual(config.cli_args.non_zero_exit_code, param)
131
+
132
+ def test_exit_code_parameter_error(self):
133
+ """Test result when bad value provided"""
134
+ with open(os.devnull, "w") as devnull:
135
+ with patch("sys.stderr", devnull):
136
+ with self.assertRaises(SystemExit):
137
+ cfnlint.config.CliArgs(["--non-zero-exit-code", "bad"])
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_file_args.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import logging
7
+ from pathlib import Path
8
+ from test.testlib.testcase import BaseTestCase
9
+ from unittest.mock import patch
10
+
11
+ import cfnlint.config # pylint: disable=E0401
12
+ from cfnlint.jsonschema import ValidationError
13
+
14
+ LOGGER = logging.getLogger("cfnlint")
15
+
16
+
17
+ class TestConfigFileArgs(BaseTestCase):
18
+ """Test ConfigParser Arguments"""
19
+
20
+ def tearDown(self):
21
+ """Setup"""
22
+ for handler in LOGGER.handlers:
23
+ LOGGER.removeHandler(handler)
24
+
25
+ def test_config_parser_read_config(self):
26
+ """Testing one file successful"""
27
+ config = cfnlint.config.ConfigFileArgs(
28
+ config_file=Path("test/fixtures/configs/cfnlintrc_read.yaml")
29
+ )
30
+ self.assertEqual(
31
+ config.file_args,
32
+ {
33
+ "templates": ["test/fixtures/templates/good/**/*.yaml"],
34
+ "include_checks": ["I"],
35
+ },
36
+ )
37
+
38
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
39
+ def test_config_parser_read_config_only_one_read(self, yaml_mock):
40
+ """Testing one file successful"""
41
+ # Should only have one read here
42
+ # We aren't going to search and find the possible locations of
43
+ # cfnlintrc
44
+ yaml_mock.side_effect = [
45
+ {"regions": ["us-west-1"]},
46
+ ]
47
+ config = cfnlint.config.ConfigFileArgs(
48
+ config_file=Path("test/fixtures/configs/cfnlintrc_read.yaml")
49
+ )
50
+ self.assertEqual(config.file_args, {"regions": ["us-west-1"]})
51
+
52
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
53
+ def test_config_parser_read(self, yaml_mock):
54
+ """Testing one file successful"""
55
+ yaml_mock.side_effect = [{"regions": ["us-west-1"]}, {}]
56
+ results = cfnlint.config.ConfigFileArgs()
57
+ self.assertEqual(results.file_args, {"regions": ["us-west-1"]})
58
+
59
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
60
+ def test_config_parser_read_merge(self, yaml_mock):
61
+ """test the merge of config"""
62
+
63
+ yaml_mock.side_effect = [{"regions": ["us-west-1"]}, {"regions": ["us-east-1"]}]
64
+
65
+ results = cfnlint.config.ConfigFileArgs()
66
+ self.assertEqual(results.file_args, {"regions": ["us-east-1"]})
67
+
68
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
69
+ def test_config_parser_fail_on_bad_config(self, yaml_mock):
70
+ """test the read call to the config parser is reading two files"""
71
+
72
+ yaml_mock.side_effect = [{"regions": True}, {}]
73
+
74
+ with self.assertRaises(ValidationError):
75
+ cfnlint.config.ConfigFileArgs()
76
+
77
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
78
+ def test_config_parser_fail_on_config_rules(self, yaml_mock):
79
+ """
80
+ test the read call to the config parser is
81
+ parsing configure rules correctly
82
+ """
83
+
84
+ yaml_mock.side_effect = [{"configure_rules": {"E3012": {"strict": False}}}, {}]
85
+
86
+ results = cfnlint.config.ConfigFileArgs()
87
+ self.assertEqual(
88
+ results.file_args, {"configure_rules": {"E3012": {"strict": False}}}
89
+ )
90
+
91
+ @patch("pathlib.Path.is_file", create=True)
92
+ def test_config_parser_is_file_both(self, is_file_mock):
93
+ calls = [
94
+ True,
95
+ True,
96
+ False,
97
+ False,
98
+ ]
99
+ is_file_mock.side_effect = calls
100
+ my_config = cfnlint.config.ConfigFileArgs()
101
+ self.assertEqual(my_config._user_config_file.name, ".cfnlintrc")
102
+ self.assertEqual(my_config._project_config_file.name, ".cfnlintrc")
103
+ self.assertEqual(is_file_mock.call_count, len(calls))
104
+
105
+ @patch("pathlib.Path.is_file", create=True)
106
+ def test_config_parser_is_file_both_yaml(self, is_file_mock):
107
+ calls = [
108
+ False,
109
+ True,
110
+ False,
111
+ True,
112
+ False,
113
+ False,
114
+ ]
115
+ is_file_mock.side_effect = calls
116
+ my_config = cfnlint.config.ConfigFileArgs()
117
+ self.assertEqual(my_config._user_config_file.name, ".cfnlintrc.yaml")
118
+ self.assertEqual(my_config._project_config_file.name, ".cfnlintrc.yaml")
119
+ self.assertEqual(is_file_mock.call_count, len(calls))
120
+
121
+ @patch("pathlib.Path.is_file", create=True)
122
+ def test_config_parser_is_file_both_yml(self, is_file_mock):
123
+ calls = [
124
+ False,
125
+ False,
126
+ True,
127
+ False,
128
+ False,
129
+ True,
130
+ False,
131
+ False,
132
+ ]
133
+ is_file_mock.side_effect = calls
134
+ my_config = cfnlint.config.ConfigFileArgs()
135
+ self.assertEqual(my_config._user_config_file.name, ".cfnlintrc.yml")
136
+ self.assertEqual(my_config._project_config_file.name, ".cfnlintrc.yml")
137
+ self.assertEqual(is_file_mock.call_count, len(calls))
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_config_mixin.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import logging
7
+ import os
8
+ from pathlib import Path
9
+ from test.testlib.testcase import BaseTestCase
10
+ from unittest.mock import patch
11
+
12
+ import cfnlint.config # pylint: disable=E0401
13
+ from cfnlint.helpers import REGIONS
14
+
15
+ LOGGER = logging.getLogger("cfnlint")
16
+
17
+
18
+ class TestConfigMixIn(BaseTestCase):
19
+ """Test ConfigParser Arguments"""
20
+
21
+ def tearDown(self):
22
+ """Setup"""
23
+ for handler in LOGGER.handlers:
24
+ LOGGER.removeHandler(handler)
25
+
26
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
27
+ def test_config_mix_in(self, yaml_mock):
28
+ """Test mix in"""
29
+ yaml_mock.side_effect = [
30
+ {"include_checks": ["I", "I1111"], "regions": ["us-west-2"]},
31
+ {},
32
+ ]
33
+
34
+ config = cfnlint.config.ConfigMixIn(["--regions", "us-west-1"])
35
+ self.assertEqual(config.regions, ["us-west-1"])
36
+ self.assertEqual(config.include_checks, ["W", "E", "I", "I1111"])
37
+
38
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
39
+ def test_config_precedence(self, yaml_mock):
40
+ """Test precedence in"""
41
+
42
+ yaml_mock.side_effect = [
43
+ {
44
+ "include_checks": ["I"],
45
+ "ignore_checks": ["E3001"],
46
+ "regions": ["us-west-2"],
47
+ },
48
+ {},
49
+ ]
50
+ config = cfnlint.config.ConfigMixIn(["--include-checks", "I1234", "I4321"])
51
+ config.template_args = {
52
+ "Metadata": {
53
+ "cfn-lint": {
54
+ "config": {"include_checks": ["I9876"], "ignore_checks": ["W3001"]}
55
+ }
56
+ }
57
+ }
58
+ # config files wins
59
+ self.assertEqual(config.regions, ["us-west-2"])
60
+ # CLI should win
61
+ self.assertEqual(config.include_checks, ["W", "E", "I1234", "I4321"])
62
+ # template file wins over config file
63
+ self.assertEqual(config.ignore_checks, ["W3001"])
64
+
65
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
66
+ def test_config_file_output(self, yaml_mock):
67
+ """Test precedence in"""
68
+
69
+ yaml_mock.side_effect = [{"output_file": "test_output.txt"}, {}]
70
+ config = cfnlint.config.ConfigMixIn([])
71
+
72
+ # Config file wins
73
+ self.assertEqual(config.output_file, "test_output.txt")
74
+
75
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
76
+ def test_config_file_output_mixin(self, yaml_mock):
77
+ """Test precedence in"""
78
+
79
+ yaml_mock.side_effect = [{"output_file": "test_output.txt"}, {}]
80
+ config = cfnlint.config.ConfigMixIn(["--output-file", "test_output_2.txt"])
81
+
82
+ # CLI args win
83
+ self.assertEqual(config.output_file, "test_output_2.txt")
84
+
85
+ @patch.dict(
86
+ os.environ,
87
+ {
88
+ "HOME": os.environ.get("HOME", ""),
89
+ "USERPROFILE": os.environ.get("USERPROFILE", ""),
90
+ "HOMEPATH": os.environ.get("HOMEPATH", ""),
91
+ "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""),
92
+ },
93
+ clear=True,
94
+ )
95
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
96
+ def test_config_default_region(self, yaml_mock):
97
+ """Test precedence in"""
98
+
99
+ yaml_mock.side_effect = [{}, {}]
100
+ config = cfnlint.config.ConfigMixIn([])
101
+
102
+ # test defaults
103
+ self.assertEqual(config.regions, ["us-east-1"])
104
+
105
+ @patch.dict(
106
+ os.environ,
107
+ {
108
+ "AWS_REGION": "us-west-2",
109
+ "AWS_DEFAULT_REGION": "us-west-1",
110
+ "HOME": os.environ.get("HOME", ""),
111
+ "USERPROFILE": os.environ.get("USERPROFILE", ""),
112
+ "HOMEPATH": os.environ.get("HOMEPATH", ""),
113
+ "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""),
114
+ },
115
+ clear=True,
116
+ )
117
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
118
+ def test_config_region_from_AWS_REGION_envvar(self, yaml_mock):
119
+ """Test precedence in"""
120
+
121
+ yaml_mock.side_effect = [{}, {}]
122
+ config = cfnlint.config.ConfigMixIn([])
123
+
124
+ # test defaults
125
+ self.assertEqual(config.regions, ["us-west-2"])
126
+
127
+ @patch.dict(
128
+ os.environ,
129
+ {
130
+ "AWS_DEFAULT_REGION": "us-west-1",
131
+ "HOME": os.environ.get("HOME", ""),
132
+ "USERPROFILE": os.environ.get("USERPROFILE", ""),
133
+ "HOMEPATH": os.environ.get("HOMEPATH", ""),
134
+ "HOMEDRIVE": os.environ.get("HOMEDRIVE", ""),
135
+ },
136
+ clear=True,
137
+ )
138
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
139
+ def test_config_region_from_AWS_DEFAULT_REGION_envvar(self, yaml_mock):
140
+ """Test precedence in"""
141
+
142
+ yaml_mock.side_effect = [{}, {}]
143
+ config = cfnlint.config.ConfigMixIn([])
144
+
145
+ # test defaults
146
+ self.assertEqual(config.regions, ["us-west-1"])
147
+
148
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
149
+ def test_config_all_regions(self, yaml_mock):
150
+ """Test precedence in"""
151
+
152
+ yaml_mock.side_effect = [{"regions": ["ALL_REGIONS"]}, {}]
153
+ config = cfnlint.config.ConfigMixIn([])
154
+
155
+ # test defaults
156
+ self.assertEqual(config.regions, REGIONS)
157
+
158
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
159
+ def test_config_force_with_update_specs(self, yaml_mock):
160
+ """Test precedence in"""
161
+
162
+ yaml_mock.side_effect = [{}, {}]
163
+ config = cfnlint.config.ConfigMixIn(["--update-specs", "--force"])
164
+
165
+ # test defaults
166
+ self.assertEqual(config.force, True)
167
+ self.assertEqual(config.update_specs, True)
168
+
169
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
170
+ def test_config_expand_paths(self, yaml_mock):
171
+ """Test precedence in"""
172
+
173
+ yaml_mock.side_effect = [
174
+ {"templates": ["test/fixtures/templates/public/*.yaml"]},
175
+ {},
176
+ ]
177
+ config = cfnlint.config.ConfigMixIn([])
178
+
179
+ # test defaults
180
+ self.assertEqual(
181
+ config.templates,
182
+ [
183
+ str(
184
+ Path(
185
+ "test/fixtures/templates/public"
186
+ + os.path.sep
187
+ + "lambda-poller.yaml"
188
+ )
189
+ ),
190
+ str(
191
+ Path(
192
+ "test/fixtures/templates/public"
193
+ + os.path.sep
194
+ + "rds-cluster.yaml"
195
+ )
196
+ ),
197
+ ],
198
+ )
199
+
200
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
201
+ def test_config_expand_paths_nomatch(self, yaml_mock):
202
+ """Test precedence in"""
203
+
204
+ filename = "test/fixtures/templates/nonexistant/*.yaml"
205
+ yaml_mock.side_effect = [
206
+ {"templates": [filename]},
207
+ {},
208
+ ]
209
+ config = cfnlint.config.ConfigMixIn([])
210
+
211
+ # test defaults
212
+ self.assertEqual(config.templates, [])
213
+
214
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
215
+ def test_config_expand_ignore_templates(self, yaml_mock):
216
+ """Test ignore templates"""
217
+
218
+ yaml_mock.side_effect = [
219
+ {
220
+ "templates": ["test/fixtures/templates/bad/resources/iam/*.yaml"],
221
+ "ignore_templates": [
222
+ "test/fixtures/templates/bad/resources/iam/resource_*.yaml"
223
+ ],
224
+ },
225
+ {},
226
+ ]
227
+ config = cfnlint.config.ConfigMixIn([])
228
+
229
+ # test defaults
230
+ self.assertNotIn(
231
+ str(Path("test/fixtures/templates/bad/resources/iam/resource_policy.yaml")),
232
+ config.templates,
233
+ )
234
+ self.assertEqual(len(config.templates), 3)
235
+
236
+ @patch("cfnlint.config.ConfigFileArgs._read_config", create=True)
237
+ def test_config_merge(self, yaml_mock):
238
+ """Test merging lists"""
239
+
240
+ yaml_mock.side_effect = [
241
+ {
242
+ "include_checks": ["I"],
243
+ "ignore_checks": ["E3001"],
244
+ "regions": ["us-west-2"],
245
+ },
246
+ {},
247
+ ]
248
+ config = cfnlint.config.ConfigMixIn(
249
+ ["--include-checks", "I1234", "I4321", "--merge-configs"]
250
+ )
251
+ config.template_args = {
252
+ "Metadata": {
253
+ "cfn-lint": {
254
+ "config": {"include_checks": ["I9876"], "ignore_checks": ["W3001"]}
255
+ }
256
+ }
257
+ }
258
+ # config files wins
259
+ self.assertEqual(config.regions, ["us-west-2"])
260
+ # CLI should win
261
+ self.assertEqual(
262
+ config.include_checks, ["W", "E", "I1234", "I4321", "I9876", "I"]
263
+ )
264
+ # template file wins over config file
265
+ self.assertEqual(config.ignore_checks, ["W3001", "E3001"])
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_logging.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import logging
7
+ from test.testlib.testcase import BaseTestCase
8
+
9
+ import cfnlint.config # pylint: disable=E0401
10
+
11
+ LOGGER = logging.getLogger("cfnlint")
12
+
13
+
14
+ class TestLogging(BaseTestCase):
15
+ """Test Logging Arguments"""
16
+
17
+ def tearDown(self):
18
+ """Setup"""
19
+ for handler in LOGGER.handlers:
20
+ LOGGER.removeHandler(handler)
21
+
22
+ def test_logging_info(self):
23
+ """Test success run"""
24
+
25
+ cfnlint.config.configure_logging(False, True)
26
+ self.assertEqual(logging.INFO, LOGGER.level)
27
+ self.assertEqual(len(LOGGER.handlers), 1)
28
+
29
+ def test_logging_debug(self):
30
+ """Test debug level"""
31
+
32
+ cfnlint.config.configure_logging(True, False)
33
+ self.assertEqual(logging.DEBUG, LOGGER.level)
34
+ self.assertEqual(len(LOGGER.handlers), 1)
35
+
36
+ def test_no_logging(self):
37
+ """Test no logging level"""
38
+
39
+ cfnlint.config.configure_logging(False, False)
40
+ self.assertEqual(logging.WARNING, LOGGER.level)
41
+ self.assertEqual(len(LOGGER.handlers), 1)
testbed/aws-cloudformation__cfn-lint/test/unit/module/config/test_template_args.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import logging
7
+ from test.testlib.testcase import BaseTestCase
8
+
9
+ import cfnlint.config # pylint: disable=E0401
10
+
11
+ LOGGER = logging.getLogger("cfnlint")
12
+
13
+
14
+ class TestTempalteArgs(BaseTestCase):
15
+ """Test ConfigParser Arguments"""
16
+
17
+ def tearDown(self):
18
+ """Setup"""
19
+ for handler in LOGGER.handlers:
20
+ LOGGER.removeHandler(handler)
21
+
22
+ def test_template_args(self):
23
+ """test template args"""
24
+ config = cfnlint.config.TemplateArgs(
25
+ {
26
+ "Metadata": {
27
+ "cfn-lint": {
28
+ "config": {
29
+ "regions": ["us-east-1", "us-east-2"],
30
+ "ignore_checks": ["E2530"],
31
+ "configure_rules": {"E3012": {"strict": "false"}},
32
+ }
33
+ }
34
+ }
35
+ }
36
+ )
37
+
38
+ self.assertEqual(config.template_args["regions"], ["us-east-1", "us-east-2"])
39
+ self.assertEqual(
40
+ config.template_args["configure_rules"], {"E3012": {"strict": "false"}}
41
+ )
42
+
43
+ def test_template_args_failure_bad_format(self):
44
+ """test template args"""
45
+ config = cfnlint.config.TemplateArgs(
46
+ {
47
+ "Metadata": {
48
+ "cfn-lint": {
49
+ "config": {"configure_rules": [{"E3012": {"strict": "false"}}]}
50
+ }
51
+ }
52
+ }
53
+ )
54
+
55
+ self.assertEqual(config.template_args.get("configure_rules"), None)
56
+
57
+ def test_template_args_failure_bad_value(self):
58
+ """test template args"""
59
+ config = cfnlint.config.TemplateArgs(
60
+ {
61
+ "Metadata": {
62
+ "cfn-lint": {
63
+ "config": {
64
+ "configure_rules": [{"E3012": {"bad_value": "false"}}]
65
+ }
66
+ }
67
+ }
68
+ }
69
+ )
70
+
71
+ self.assertEqual(config.template_args.get("configure_rules"), None)
72
+
73
+ def test_template_args_failure_good_and_bad_value(self):
74
+ """test template args"""
75
+ config = cfnlint.config.TemplateArgs(
76
+ {
77
+ "Metadata": {
78
+ "cfn-lint": {
79
+ "config": {
80
+ "configure_rules": [
81
+ {
82
+ "A1": {"strict": "false"},
83
+ "E3012": {"strict": "false"},
84
+ "Z1": {"strict": "false"},
85
+ }
86
+ ]
87
+ }
88
+ }
89
+ }
90
+ }
91
+ )
92
+
93
+ self.assertEqual(config.template_args.get("configure_rules"), None)
94
+
95
+ def test_bad_template_structure(self):
96
+ """test template args"""
97
+ config = cfnlint.config.TemplateArgs([])
98
+
99
+ self.assertEqual(config._template_args, {})
100
+
101
+ def test_bad_config_structure(self):
102
+ """test template args"""
103
+ config = cfnlint.config.TemplateArgs({"Metadata": {"cfn-lint": {"config": []}}})
104
+
105
+ self.assertEqual(config._template_args, {})
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/__init__.py ADDED
File without changes
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/__init__.py ADDED
File without changes
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_conditions.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import pytest
7
+
8
+ from cfnlint.context import create_context_for_template
9
+ from cfnlint.context.conditions._conditions import Conditions
10
+ from cfnlint.context.conditions.exceptions import Unsatisfiable
11
+ from cfnlint.template import Template
12
+
13
+
14
+ def template():
15
+ return {
16
+ "AWSTemplateFormatVersion": "2010-09-09",
17
+ "Parameters": {
18
+ "Environment": {
19
+ "Type": "String",
20
+ "Default": "dev",
21
+ "AllowedValues": ["dev", "prod"],
22
+ },
23
+ "Name": {
24
+ "Type": "String",
25
+ "Default": "bi",
26
+ "AllowedValues": ["bi", "ai"],
27
+ },
28
+ "AmiId": {
29
+ "Type": "String",
30
+ "Default": "",
31
+ },
32
+ },
33
+ "Conditions": {
34
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
35
+ "IsNotUsEast1": {"Fn::Not": [{"Condition": "IsUsEast1"}]},
36
+ "IsUsWest2": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]},
37
+ "IsProd": {"Fn::Equals": [{"Ref": "Environment"}, "prod"]},
38
+ "IsDev": {"Fn::Equals": [{"Ref": "Environment"}, "dev"]},
39
+ "IsAmiProvided": {"Fn::Not": [{"Fn::Equals": [{"Ref": "AmiId"}, ""]}]},
40
+ "IsAi": {"Fn::Equals": [{"Ref": "Name"}, "ai"]},
41
+ "IsBi": {"Fn::Equals": [{"Ref": "Name"}, "bi"]},
42
+ "IsUsEast1OrUsWest2": {
43
+ "Fn::Or": [
44
+ {"Condition": "IsUsEast1"},
45
+ {"Condition": "IsUsWest2"},
46
+ ]
47
+ },
48
+ "IsUsEast1AndProd": {
49
+ "Fn::And": [
50
+ {"Condition": "IsUsEast1"},
51
+ {"Condition": "IsProd"},
52
+ ]
53
+ },
54
+ "IsStaticTrue": {"Fn::Equals": [1, "1"]},
55
+ "IsStaticFalse": {"Fn::Equals": [1, "2"]},
56
+ "TwoObjects": {
57
+ "Fn::Equals": [
58
+ {"Ref": "Environment"},
59
+ {"Ref": "AWS::Region"},
60
+ ]
61
+ },
62
+ "TwoObjectsSameHash": {
63
+ "Fn::Equals": [
64
+ {"Ref": "AWS::Region"},
65
+ {"Ref": "Environment"},
66
+ ]
67
+ },
68
+ "BadAwsFn": {"Ref": "Foo"},
69
+ "BadFn": {"Key": "Foo"},
70
+ "BadNotList": {"Fn::And": "Foo"},
71
+ "UseBadFn": {"Condition": "BadFn"},
72
+ "UseBadCondition": {"Condition": []},
73
+ "EqualsTooLong": {"Fn::Equals": ["a", "b", "c"]},
74
+ "EqualsWrongTypes": {"Fn::Equals": ["a", []]},
75
+ "NotWithTwoItems": {
76
+ "Fn::Not": [
77
+ {"Condition": "IsAi"},
78
+ {"Condition": "IsBi"},
79
+ ]
80
+ },
81
+ },
82
+ }
83
+
84
+
85
+ def test_conditions():
86
+ cfn = Template(None, template(), regions=["us-east-1"])
87
+ context = create_context_for_template(cfn)
88
+
89
+ assert len(context.conditions.conditions) == 22
90
+ assert context.conditions.conditions["IsStaticTrue"].fn_equals.is_static is True
91
+ assert context.conditions.conditions["IsStaticFalse"].fn_equals.is_static is False
92
+ assert (
93
+ context.conditions.conditions["TwoObjects"].fn_equals.hash
94
+ == context.conditions.conditions["TwoObjectsSameHash"].fn_equals.hash
95
+ )
96
+ assert context.conditions.conditions["TwoObjects"].fn_equals.is_static is None
97
+
98
+ for k in [
99
+ "IsUsEast1",
100
+ "IsNotUsEast1",
101
+ "IsUsWest2",
102
+ "IsUsEast1OrUsWest2",
103
+ "IsUsEast1AndProd",
104
+ ]:
105
+ assert context.conditions.conditions[k].is_region is True
106
+
107
+ for k in ["IsAmiProvided", "IsProd", "IsDev", "IsAi", "IsBi"]:
108
+ assert context.conditions.conditions[k].is_region is False
109
+
110
+ for k in [
111
+ "BadAwsFn",
112
+ "BadFn",
113
+ "BadNotList",
114
+ "UseBadCondition",
115
+ "EqualsTooLong",
116
+ "EqualsWrongTypes",
117
+ "NotWithTwoItems",
118
+ ]:
119
+ assert context.conditions.conditions[k].fn_equals.left.instance is None
120
+ assert context.conditions.conditions[k].fn_equals.right.instance is None
121
+ assert context.conditions.conditions[k].fn_equals.is_static is None
122
+ assert context.conditions.conditions[k].is_region is False
123
+
124
+ assert (
125
+ context.conditions.conditions["UseBadFn"].condition.fn_equals.left.instance
126
+ is None
127
+ )
128
+ assert (
129
+ context.conditions.conditions["UseBadFn"].condition.fn_equals.right.instance
130
+ is None
131
+ )
132
+ assert (
133
+ context.conditions.conditions["UseBadFn"].condition.fn_equals.is_static is None
134
+ )
135
+
136
+
137
+ @pytest.mark.parametrize(
138
+ "current_status,new_status,expected",
139
+ [
140
+ ({}, {}, {}),
141
+ ({"IsUsEast1": True}, {}, {"IsUsEast1": True}),
142
+ (
143
+ {"IsUsEast1": True},
144
+ {"IsUsEast1": False},
145
+ Unsatisfiable(
146
+ new_status={"IsUsEast1": False}, current_status={"IsUsEast1": True}
147
+ ),
148
+ ),
149
+ (
150
+ {"IsUsEast1": True},
151
+ {"IsNotUsEast1": True},
152
+ Unsatisfiable(
153
+ new_status={"IsNotUsEast1": True},
154
+ current_status={"IsUsEast1": True},
155
+ ),
156
+ ),
157
+ (
158
+ {"IsUsEast1": False, "IsUsWest2": False},
159
+ {"IsUsEast1OrUsWest2": True},
160
+ Unsatisfiable(
161
+ new_status={"IsUsEast1OrUsWest2": True},
162
+ current_status={"IsUsEast1": True},
163
+ ),
164
+ ),
165
+ (
166
+ {"IsDev": False},
167
+ {"IsProd": False},
168
+ Unsatisfiable(new_status={"IsProd": False}, current_status={"IsDev": True}),
169
+ ),
170
+ ({}, {"BadFn": True}, {"BadFn": True}),
171
+ ({}, {"BadFn": False}, {"BadFn": False}),
172
+ ],
173
+ )
174
+ def test_condition_status(current_status, new_status, expected):
175
+ cfn = Template(None, template(), regions=["us-east-1"])
176
+ context = create_context_for_template(cfn)
177
+
178
+ context = context.evolve(conditions=context.conditions.evolve(current_status))
179
+
180
+ if isinstance(expected, Exception):
181
+ with pytest.raises(ValueError):
182
+ context.conditions.evolve(new_status)
183
+ else:
184
+ context = context.evolve(conditions=context.conditions.evolve(new_status))
185
+ assert context.conditions.status == expected
186
+
187
+
188
+ @pytest.mark.parametrize(
189
+ "current_status,instance,expected",
190
+ [
191
+ ({}, {"Foo": "Bar"}, [({"Foo": "Bar"}, {})]),
192
+ (
193
+ {},
194
+ {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]},
195
+ [
196
+ ({"Foo": "Foo"}, {"IsUsEast1": True}),
197
+ ({"Bar": "Bar"}, {"IsUsEast1": False}),
198
+ ],
199
+ ),
200
+ (
201
+ {
202
+ "IsUsEast1": True,
203
+ },
204
+ {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]},
205
+ [
206
+ ({"Foo": "Foo"}, {"IsUsEast1": True}),
207
+ ],
208
+ ),
209
+ (
210
+ {
211
+ "IsUsEast1": False,
212
+ },
213
+ {"Fn::If": ["IsUsEast1", {"Foo": "Foo"}, {"Bar": "Bar"}]},
214
+ [
215
+ ({"Bar": "Bar"}, {"IsUsEast1": False}),
216
+ ],
217
+ ),
218
+ (
219
+ {},
220
+ {"Ref": "AWS::NoValue"},
221
+ [
222
+ (None, {}),
223
+ ],
224
+ ),
225
+ (
226
+ {},
227
+ [{"Foo": {"Fn::If": ["IsUsEast1", "Foo", "Bar"]}}],
228
+ [
229
+ ([{"Foo": {"Fn::If": ["IsUsEast1", "Foo", "Bar"]}}], {}),
230
+ ],
231
+ ),
232
+ (
233
+ {},
234
+ [{"Fn::If": ["IsUsEast1", {"Foo": "Bar"}, {"Ref": "AWS::NoValue"}]}],
235
+ [
236
+ ([{"Foo": "Bar"}], {"IsUsEast1": True}),
237
+ ([], {"IsUsEast1": False}),
238
+ ],
239
+ ),
240
+ (
241
+ {"IsUsEast1": True, "IsProd": True},
242
+ {
243
+ "A": {"Fn::If": ["IsUsEast1AndProd", 1, 2]},
244
+ "B": {"Fn::If": ["IsAi", 10, 11]},
245
+ },
246
+ [
247
+ (
248
+ {"A": 1, "B": 10},
249
+ {
250
+ "IsUsEast1": True,
251
+ "IsProd": True,
252
+ "IsUsEast1AndProd": True,
253
+ "IsAi": True,
254
+ },
255
+ ),
256
+ (
257
+ {"A": 1, "B": 11},
258
+ {
259
+ "IsUsEast1": True,
260
+ "IsProd": True,
261
+ "IsUsEast1AndProd": True,
262
+ "IsAi": False,
263
+ },
264
+ ),
265
+ ],
266
+ ),
267
+ (
268
+ {},
269
+ {
270
+ "A": {"Fn::If": ["IsUsEast1AndProd", 1]},
271
+ },
272
+ [
273
+ (
274
+ {"A": {"Fn::If": ["IsUsEast1AndProd", 1]}},
275
+ {},
276
+ ),
277
+ ],
278
+ ),
279
+ ],
280
+ )
281
+ def test_evolve_from_instance(current_status, instance, expected):
282
+ cfn = Template(None, template(), regions=["us-east-1"])
283
+ context = create_context_for_template(cfn)
284
+
285
+ context = context.evolve(
286
+ conditions=context.conditions.evolve(current_status),
287
+ functions=["Fn::If", "Ref"],
288
+ )
289
+
290
+ results = list(context.conditions.evolve_from_instance(instance, context))
291
+ assert len(results) == len(expected)
292
+ for result, expected_result in zip(results, expected):
293
+ assert result[0] == expected_result[0]
294
+ assert result[1].status == expected_result[1]
295
+
296
+
297
+ def test_condition_failures():
298
+ with pytest.raises(ValueError):
299
+ Conditions.create_from_instance([], {}, {})
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/conditions/test_equals_sort.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import pytest
7
+
8
+ from cfnlint.context.conditions._equals import _equals_cmp_key
9
+
10
+
11
+ @pytest.mark.parametrize(
12
+ "name,instance,expected",
13
+ [
14
+ (
15
+ "Valid",
16
+ [
17
+ "A",
18
+ "B",
19
+ {"Ref": "A"},
20
+ {"Ref": "B"},
21
+ {"Key": "Value"},
22
+ {"Fn::FindInMap": ["A", "B", "C"]},
23
+ {"Fn::FindInMap": ["X", "Y", "Z"]},
24
+ ],
25
+ [
26
+ "A",
27
+ "B",
28
+ {"Fn::FindInMap": ["X", "Y", "Z"]},
29
+ {"Fn::FindInMap": ["A", "B", "C"]},
30
+ {"Ref": "A"},
31
+ {"Ref": "B"},
32
+ {"Key": "Value"},
33
+ ],
34
+ ),
35
+ (
36
+ "Different order same results",
37
+ [
38
+ {"Fn::FindInMap": ["A", "B", "C"]},
39
+ {"Fn::FindInMap": ["X", "Y", "Z"]},
40
+ {"Ref": "B"},
41
+ {"Ref": "A"},
42
+ {"Key": "Value"},
43
+ "B",
44
+ "A",
45
+ ],
46
+ [
47
+ "A",
48
+ "B",
49
+ {"Fn::FindInMap": ["X", "Y", "Z"]},
50
+ {"Fn::FindInMap": ["A", "B", "C"]},
51
+ {"Ref": "A"},
52
+ {"Ref": "B"},
53
+ {"Key": "Value"},
54
+ ],
55
+ ),
56
+ (
57
+ "Two Refs",
58
+ [
59
+ {"Ref": "B"},
60
+ {"Ref": "A"},
61
+ ],
62
+ [
63
+ {"Ref": "A"},
64
+ {"Ref": "B"},
65
+ ],
66
+ ),
67
+ (
68
+ "Ref with non mapping",
69
+ [
70
+ {"Ref": "A"},
71
+ {"Key": "Value"},
72
+ ],
73
+ [
74
+ {"Ref": "A"},
75
+ {"Key": "Value"},
76
+ ],
77
+ ),
78
+ (
79
+ "Ref with non mapping backwards",
80
+ [
81
+ {"Key": "Value"},
82
+ {"Ref": "A"},
83
+ ],
84
+ [
85
+ {"Ref": "A"},
86
+ {"Key": "Value"},
87
+ ],
88
+ ),
89
+ (
90
+ "None functions",
91
+ [
92
+ {"Key": "Foo"},
93
+ {"Key": "Bar"},
94
+ ],
95
+ [
96
+ {"Key": "Foo"},
97
+ {"Key": "Bar"},
98
+ ],
99
+ ),
100
+ ],
101
+ )
102
+ def test_sorted(name, instance, expected):
103
+ assert expected == sorted(
104
+ instance, key=_equals_cmp_key
105
+ ), f"{name} got {sorted(instance, key=_equals_cmp_key)}"
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_context.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ import unittest
7
+ from collections import deque
8
+
9
+ from cfnlint.context import Context, Path
10
+ from cfnlint.context.conditions._conditions import Condition, Conditions
11
+
12
+
13
+ class TestCfnContext(unittest.TestCase):
14
+ def test_class(self):
15
+ context = Context(
16
+ conditions=Conditions.create_from_instance(
17
+ conditions={
18
+ "Foo": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
19
+ "Bar": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]},
20
+ },
21
+ rules={},
22
+ parameters={},
23
+ ),
24
+ )
25
+ self.assertEqual(context.regions, ["us-east-1"])
26
+ self.assertEqual(
27
+ context.conditions,
28
+ Conditions(
29
+ {
30
+ "Foo": Condition.create_from_instance(
31
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {}
32
+ ),
33
+ "Bar": Condition.create_from_instance(
34
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {}
35
+ ),
36
+ },
37
+ ),
38
+ )
39
+ self.assertEqual(context.path, Path())
40
+
41
+ # Test evolve
42
+ evolved = context.evolve(
43
+ regions=["us-west-2"],
44
+ conditions=context.conditions.evolve(
45
+ {"Foo": False},
46
+ ),
47
+ path=Path(path=deque([1])),
48
+ )
49
+ self.assertListEqual(evolved.regions, ["us-west-2"])
50
+ self.assertDictEqual(
51
+ evolved.conditions.status,
52
+ {
53
+ "Foo": False,
54
+ },
55
+ )
56
+ self.assertEqual(evolved.path.path, deque([1]))
57
+
58
+ evolved_again = evolved.evolve(
59
+ path=evolved.path.descend(path=2),
60
+ conditions=evolved.conditions.evolve(
61
+ {"Bar": True},
62
+ ),
63
+ )
64
+ self.assertListEqual(evolved_again.regions, ["us-west-2"])
65
+ self.assertDictEqual(
66
+ evolved_again.conditions.status, {"Foo": False, "Bar": True}
67
+ )
68
+ self.assertEqual(evolved_again.path.path, deque([1, 2]))
69
+ # no changes to the original
70
+ self.assertListEqual(context.regions, ["us-east-1"])
71
+ self.assertEqual(
72
+ context.conditions,
73
+ Conditions(
74
+ {
75
+ "Foo": Condition.create_from_instance(
76
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {}
77
+ ),
78
+ "Bar": Condition.create_from_instance(
79
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {}
80
+ ),
81
+ }
82
+ ),
83
+ )
84
+ self.assertEqual(context.path.path, deque())
85
+
86
+ no_path = context.evolve(regions=["us-east-2"])
87
+ self.assertListEqual(no_path.regions, ["us-east-2"])
88
+ self.assertEqual(
89
+ no_path.conditions,
90
+ Conditions(
91
+ {
92
+ "Foo": Condition.create_from_instance(
93
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}, {}
94
+ ),
95
+ "Bar": Condition.create_from_instance(
96
+ {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}, {}
97
+ ),
98
+ }
99
+ ),
100
+ )
101
+ self.assertEqual(no_path.path.path, deque())
102
+
103
+ with self.assertRaises(ValueError):
104
+ evolved_again.evolve(
105
+ conditions=evolved_again.conditions.evolve(
106
+ {"Foo": True},
107
+ ),
108
+ )
testbed/aws-cloudformation__cfn-lint/test/unit/module/context/test_create_context.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ SPDX-License-Identifier: MIT-0
4
+ """
5
+
6
+ from collections import namedtuple
7
+
8
+ import pytest
9
+
10
+ from cfnlint import Template
11
+ from cfnlint.context.context import create_context_for_template
12
+
13
+ _Counts = namedtuple("_Counts", ["resources", "parameters", "conditions", "mappings"])
14
+
15
+
16
+ @pytest.mark.parametrize(
17
+ "name,instance,counts",
18
+ [
19
+ (
20
+ "Valid template",
21
+ {
22
+ "Parameters": {
23
+ "Env": {
24
+ "Type": "String",
25
+ }
26
+ },
27
+ "Conditions": {
28
+ "IsUsEast1": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]}
29
+ },
30
+ "Mappings": {"Map": {"us-east-1": {"foo": "bar"}}},
31
+ "Resources": {
32
+ "Bucket": {
33
+ "Type": "AWS::S3::Bucket",
34
+ },
35
+ },
36
+ },
37
+ _Counts(resources=1, parameters=1, conditions=1, mappings=1),
38
+ ),
39
+ (
40
+ "Bad types in template",
41
+ {
42
+ "Parameters": [],
43
+ "Conditions": [],
44
+ "Mappings": [],
45
+ "Resources": [],
46
+ },
47
+ _Counts(resources=0, parameters=0, conditions=0, mappings=0),
48
+ ),
49
+ (
50
+ "Invalid type configurations",
51
+ {
52
+ "Parameters": {
53
+ "BusinessUnit": [],
54
+ "Env": {
55
+ "Type": "String",
56
+ },
57
+ },
58
+ "Mappings": {"AnotherMap": [], "Map": {"us-east-1": {"foo": "bar"}}},
59
+ "Resources": {
60
+ "Instance": [],
61
+ "Bucket": {
62
+ "Type": "AWS::S3::Bucket",
63
+ },
64
+ },
65
+ },
66
+ _Counts(resources=1, parameters=1, conditions=0, mappings=2),
67
+ ),
68
+ (
69
+ "Invalid mapping second key",
70
+ {
71
+ "Mappings": {
72
+ "BadKey": {
73
+ "Foo": [],
74
+ },
75
+ "Map": {"us-east-1": {"foo": "bar"}},
76
+ },
77
+ },
78
+ _Counts(resources=0, parameters=0, conditions=0, mappings=2),
79
+ ),
80
+ (
81
+ "Invalid mapping third key",
82
+ {
83
+ "Mappings": {
84
+ "BadKey": {
85
+ "Foo": {
86
+ "Bar": {},
87
+ },
88
+ },
89
+ "Map": {"us-east-1": {"foo": "bar"}},
90
+ },
91
+ },
92
+ _Counts(resources=0, parameters=0, conditions=0, mappings=2),
93
+ ),
94
+ ],
95
+ )
96
+ def test_create_context(name, instance, counts):
97
+ cfn = Template("", instance, ["us-east-1"])
98
+ context = create_context_for_template(cfn)
99
+
100
+ for i in counts._fields:
101
+ if i == "conditions":
102
+ assert len(context.conditions.conditions) == getattr(counts, i), (
103
+ f"Test {name} has {i} {len(getattr(context, i))} "
104
+ f"and expected {getattr(counts, i)}"
105
+ )
106
+ elif i == "mappings":
107
+ assert len(context.mappings.maps) == getattr(counts, i), (
108
+ f"Test {name} has {i} {len(context.mappings.maps)} "
109
+ f"and expected {getattr(counts, i)}"
110
+ )
111
+ else:
112
+ assert len(getattr(context, i)) == getattr(counts, i), (
113
+ f"Test {name} has {i} {len(getattr(context, i))} "
114
+ f"and expected {getattr(counts, i)}"
115
+ )