Explain pulumi mock for AWS SecurityGroup.TypeScript
Mocking is a handy technique to simulate the behavior of real objects and test the way these objects operate in different scenarios, especially those in which we prefer not to engage real objects. The primary use of mocking in Pulumi is for unit testing.
In the context of Pulumi AWS Security Group, you can create a unit test that will mock the Security Group creation, rather than actually performing any operations on AWS.
To mock the
aws.ec2.SecurityGroupresource, we need to use
pulumi.runtime.setMocks()to define the behavior when Pulumi interacts with the AWS provider. With this, we can define what we expect to be returned when a Security Group is created by using
aws.ec2.SecurityGroup.get(). When our test runs, Pulumi will interact with the mocked response, and not with AWS itself, thus allowing you to test your infrastructure code without any cost or side-effects.
Take a look at the following TypeScript program as an example.
MyMocksclass is used to handle calls to create new resources and provider functions. When a new resource is created (
new aws.ec2.SecurityGroup), the
newResourcefunction is called. We define what we want to be returned in the mock response. In this case, we're returning a urn and id.
When we run our test, Pulumi interacts with this mocked provider, instead of the real AWS.
This way, we're able to confirm that our
aws.ec2.SecurityGroupis correctly instantiated and that we're able to access its properties.
Note that you need to install necessary packages for this test to work:
@pulumi/aws, and testing/dev packages:
This test can be executed using the mocha test runner by running
mocha -r ts-node/register <path-to-test-file>.
Contributing extensively to this approach lets you confirm that your infrastructure code works as expected before it's deployed, saving you time, and avoiding unexpected surprises.
Remember to check out the
aws.ec2.SecurityGroupresource documentation for information about its functionalities and usage.