Metadata-Version: 2.1
Name: aws-cdk.assertions
Version: 1.125.0
Summary: An assertion library for use with CDK Apps
Home-page: https://github.com/aws/aws-cdk
Author: Amazon Web Services
License: Apache-2.0
Project-URL: Source, https://github.com/aws/aws-cdk.git
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Typing :: Typed
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved
Classifier: Framework :: AWS CDK
Classifier: Framework :: AWS CDK :: 1
Requires-Python: >=3.6
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE

# Assertions

<!--BEGIN STABILITY BANNER-->---


![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> The APIs of higher level constructs in this module are experimental and under active development.
> They are subject to non-backward compatible changes or removal in any future version. These are
> not subject to the [Semantic Versioning](https://semver.org/) model and breaking changes will be
> announced in the release notes. This means that while you may use them, you may need to update
> your source code when upgrading to a newer version of this package.

---
<!--END STABILITY BANNER-->

Functions for writing test asserting against CDK applications, with focus on CloudFormation templates.

The `Template` class includes a set of methods for writing assertions against CloudFormation templates. Use one of the `Template.fromXxx()` static methods to create an instance of this class.

To create `Template` from CDK stack, start off with:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
from aws_cdk.core import Stack
from aws_cdk.assertions import Template

stack = Stack(...)
assert = Template.from_stack(stack)
```

Alternatively, assertions can be run on an existing CloudFormation template -

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
template = fs.read_file_sync("/path/to/template/file")
assert = Template.from_string(template)
```

## Full Template Match

The simplest assertion would be to assert that the template matches a given
template.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.template_matches(
    Resources={
        "Type": "Foo::Bar",
        "Properties": {
            "Baz": "Qux"
        }
    }
)
```

The `Template` class also supports [snapshot
testing](https://jestjs.io/docs/snapshot-testing) using jest.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# using jest
expect(Template.from_stack(stack)).to_match_snapshot()
```

For non-javascript languages, the `toJSON()` can be called to get an in-memory object
of the template.

## Counting Resources

This module allows asserting the number of resources of a specific type found
in a template.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.resource_count_is("Foo::Bar", 2)
```

## Resource Matching & Retrieval

Beyond resource counting, the module also allows asserting that a resource with
specific properties are present.

The following code asserts that the `Properties` section of a resource of type
`Foo::Bar` contains the specified properties -

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.has_resource_properties("Foo::Bar",
    Foo="Bar",
    Baz=5,
    Qux=["Waldo", "Fred"]
)
```

Alternatively, if you would like to assert the entire resource definition, you
can use the `hasResource()` API.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.has_resource("Foo::Bar",
    Properties={"Foo": "Bar"},
    DependsOn=["Waldo", "Fred"]
)
```

Beyond assertions, the module provides APIs to retrieve matching resources.
The `findResources()` API is complementary to the `hasResource()` API, except,
instead of asserting its presence, it returns the set of matching resources.

By default, the `hasResource()` and `hasResourceProperties()` APIs perform deep
partial object matching. This behavior can be configured using matchers.
See subsequent section on [special matchers](#special-matchers).

## Output and Mapping sections

The module allows you to assert that the CloudFormation template contains an Output
that matches specific properties. The following code asserts that a template contains
an Output with a `logicalId` of `Foo` and the specified properties -

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.has_output("Foo",
    Value="Bar",
    Export={"Name": "ExportBaz"}
)
```

If you want to match against all Outputs in the template, use `*` as the `logicalId`.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
assert.has_output("*",
    Value="Bar",
    Export={"Name": "ExportBaz"}
)
```

`findOutputs()` will return a set of outputs that match the `logicalId` and `props`,
and you can use the `'*'` special case as well.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
result = assert.find_outputs("*",
    Value="Fred"
)
expect(result.Foo).to_equal({"Value": "Fred", "Description": "FooFred"})
expect(result.Bar).to_equal({"Value": "Fred", "Description": "BarFred"})
```

The APIs `hasMapping()` and `findMappings()` provide similar functionalities.

## Special Matchers

The expectation provided to the `hasXXX()` and `findXXX()` methods, besides
carrying literal values, as seen in the above examples, also accept special
matchers.

They are available as part of the `Match` class.

### Object Matchers

The `Match.objectLike()` API can be used to assert that the target is a superset
object of the provided pattern.
This API will perform a deep partial match on the target.
Deep partial matching is where objects are matched partially recursively. At each
level, the list of keys in the target is a subset of the provided pattern.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": "Flob",
#           "Bob": "Cat"
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.object_like(
        Wobble="Flob"
    )
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.object_like(
        Brew="Coffee"
    )
)
```

The `Match.objectEquals()` API can be used to assert a target as a deep exact
match.

### Presence and Absence

The `Match.absentProperty()` matcher can be used to specify that a specific
property should not exist on the target. This can be used within `Match.objectLike()`
or outside of any matchers.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": "Flob",
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.object_like(
        Bob=Match.absent_property()
    )
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.object_like(
        Wobble=Match.absent_property()
    )
)
```

The `Match.anyValue()` matcher can be used to specify that a specific value should be found
at the location. This matcher will fail if when the target location has null-ish values
(i.e., `null` or `undefined`).

This matcher can be combined with any of the other matchers.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": {
#           "Wobble": ["Flob", "Flib"],
#         }
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred={
        "Wobble": [Match.any_value(), "Flip"]
    }
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred={
        "Wimble": Match.any_value()
    }
)
```

### Array Matchers

The `Match.arrayWith()` API can be used to assert that the target is equal to or a subset
of the provided pattern array.
This API will perform subset match on the target.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"]
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.array_with(["Flob"])
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar", Match.object_like(
    Fred=Match.array_with(["Wobble"])
));
```

*Note:* The list of items in the pattern array should be in order as they appear in the
target array. Out of order will be recorded as a match failure.

Alternatively, the `Match.arrayEquals()` API can be used to assert that the target is
exactly equal to the pattern array.

### Not Matcher

The not matcher inverts the search pattern and matches all patterns in the path that does
not match the pattern specified.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"]
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Fred=Match.not(["Flob"])
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar", Match.object_like(
    Fred=Match.not(["Flob", "Cat"])
));
```

### Serialized JSON

Often, we find that some CloudFormation Resource types declare properties as a string,
but actually expect JSON serialized as a string.
For example, the [`BuildSpec` property of `AWS::CodeBuild::Project`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-buildspec),
the [`Definition` property of `AWS::StepFunctions::StateMachine`](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html#cfn-stepfunctions-statemachine-definition),
to name a couple.

The `Match.serializedJson()` matcher allows deep matching within a stringified JSON.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Baz": "{ \"Fred\": [\"Waldo\", \"Willow\"] }"
#       }
#     }
#   }
# }

# The following will NOT throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Baz=Match.serialized_json(
        Fred=Match.array_with(["Waldo"])
    )
)

# The following will throw an assertion error
assert.has_resource_properties("Foo::Bar",
    Baz=Match.serialized_json(
        Fred=["Waldo", "Johnny"]
    )
)
```

## Capturing Values

This matcher APIs documented above allow capturing values in the matching entry
(Resource, Output, Mapping, etc.). The following code captures a string from a
matching resource.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Given a template -
# {
#   "Resources": {
#     "MyBar": {
#       "Type": "Foo::Bar",
#       "Properties": {
#         "Fred": ["Flob", "Cat"],
#         "Waldo": ["Qix", "Qux"],
#       }
#     }
#   }
# }

fred_capture = Capture()
waldo_capture = Capture()
assert.has_resource_properties("Foo::Bar",
    Fred=fred_capture,
    Waldo=["Qix", waldo_capture]
)

fred_capture.as_array()# returns ["Flob", "Cat"]
waldo_capture.as_string()
```

## Strongly typed languages

Some of the APIs documented above, such as `templateMatches()` and
`hasResourceProperties()` accept fluently an arbitrary JSON (like) structure
its parameter.
This fluency is available only in dynamically typed languages like javascript
and Python.

For strongly typed languages, like Java, you can achieve similar fluency using
any popular JSON deserializer. The following Java example uses `Gson` -

```java
// In Java, using text blocks and Gson
import com.google.gson.Gson;

String json = """
  {
    "Foo": "Bar",
    "Baz": 5,
    "Qux": [ "Waldo", "Fred" ],
  } """;

Map expected = new Gson().fromJson(json, Map.class);
assert.hasResourceProperties("Foo::Bar", expected);
```


