Unit Testing
Pulumi programs are authored in a general-purpose language like TypeScript, Python, Go, or C#. The full power of each language is available, including access to tools and libraries for that runtime, including testing frameworks.
When running an update, your Pulumi program talks to the Pulumi CLI to orchestrate the deployment. The idea of unit tests is to cut this communication channel and replace the engine with mocks. The mocks respond to the commands from within the same OS process and return dummy data for each call that your Pulumi program makes.
Because mocks don't execute any real work, unit tests run very fast. Also, they can be made deterministic because tests don't depend on the behavior of any external system.
Get Started
Unit tests are supported in all existing Pulumi runtimes: Node.js, Python, Go, and .NET.
Let's build a sample test suite. The example uses AWS resources, but the same capabilities and workflow apply to any Pulumi provider. To follow along, complete the Get Started with AWS guide to set up a basic Pulumi program in your language of choice.
Sample Program
Throughout this guide, we are testing a program that creates a simple AWS EC2-based webserver. We want to develop unit tests to ensure:
- Instances have a Name tag.
- Instances must not use an inline
userDatascript—we must use a virtual machine image. - Instances must not have SSH open to the Internet.
Our starting code is loosely based on the aws-js-webserver example:
Choose the language below to adjust the contents of this guide. Your choice is applied throughout the guide.
index.ts:
import * as aws from "@pulumi/aws";
export const group = new aws.ec2.SecurityGroup("web-secgrp", {
ingress: [
{ protocol: "tcp", fromPort: 22, toPort: 22, cidrBlocks: ["0.0.0.0/0"] },
{ protocol: "tcp", fromPort: 80, toPort: 80, cidrBlocks: ["0.0.0.0/0"] },
],
});
const userData = `#!/bin/bash echo "Hello, World!" > index.html nohup python -m SimpleHTTPServer 80 &`;
export const server = new aws.ec2.Instance("web-server-www", {
instanceType: "t2.micro",
securityGroups: [ group.name ], // reference the group object above
ami: "ami-c55673a0", // AMI for us-east-2 (Ohio)
userData: userData, // start a simple webserver
});This basic Pulumi program allocates a security group and an instance. Notice, however, that we are violating all three of the rules stated above—let's write some tests!
Install the unit testing framework
You are free to use your favorite frameworks and libraries for writing unit tests and assertions.
This guide uses Mocha as the testing framework. Install Mocha to your development environment.
Then, install additional NPM modules to your program:
npm install mocha @types/mocha ts-nodeAdd Mocks
Let's add the following code to mock the external calls to the Pulumi CLI.
ec2tests.ts:
import * as pulumi from "@pulumi/pulumi";
pulumi.runtime.setMocks({
newResource: function(args: pulumi.runtime.MockResourceArgs): {id: string, state: any} {
return {
id: args.inputs.name + "_id",
state: args.inputs,
};
},
call: function(args: MockCallArgs) {
return args.inputs;
},
});The definition of the mocks interface is available at the runtime API reference page.
Write the Tests
The overall structure and scaffolding of our tests will look like any ordinary Mocha testing:
ec2tests.ts:
import * as pulumi from "@pulumi/pulumi";
import "mocha";
pulumi.runtime.setMocks({
// ... mocks as shown above
});
describe("Infrastructure", function() {
let infra: typeof import("../index");
before(async function() {
// It's important to import the program _after_ the mocks are defined.
infra = await import("../index");
})
describe("#server", function() {
// TODO(check 1): Instances have a Name tag.
// TODO(check 2): Instances must not use an inline userData script.
});
describe("#group", function() {
// TODO(check 3): Instances must not have SSH open to the Internet.
});
});Now let's implement our first test: ensuring that instances have a Name tag. To verify this we need to grab hold of the EC2 instance object, and check the relevant property:
// check 1: Instances have a Name tag.
it("must have a name tag", function(done) {
pulumi.all([infra.server.urn, infra.server.tags]).apply(([urn, tags]) => {
if (!tags || !tags["Name"]) {
done(new Error(`Missing a name tag on server ${urn}`));
} else {
done();
}
});
});This looks like a normal test, with a few noteworthy pieces:
- Since we're querying resource state without doing a deployment, there are many properties whose values will be undefined. This includes any output properties computed by your cloud provider that you did not explicitly return from the mocks. That's fine for these tests—we're checking for valid inputs anyway.
- Because all Pulumi resource properties are outputs—since many of them are computed asynchronously—we need to use the
applymethod to get access to the values. - Finally, since these outputs are resolved asynchronously, we need to use the framework's built-in asynchronous test capability.
After we've gotten through that setup, we get access to the raw inputs as plain values. The tags property is a map, so we make sure it is (1) defined, and (2) not missing an entry for the Name key. This is very basic, but we can check anything!
Now let's write our second check to assert that userdata property is empty:
// check 2: Instances must not use an inline userData script.
it("must not use userData (use an AMI instead)", function(done) {
pulumi.all([infra.server.urn, infra.server.userData]).apply(([urn, userData]) => {
if (userData) {
done(new Error(`Illegal use of userData on server ${urn}`));
} else {
done();
}
});
});And finally, let's write our third check. It’s a bit more complex because we're searching for ingress rules associated with a security group—of which there may be many—and CIDR blocks within those ingress rules—of which there may also be many. But it's still several lines of code:
// check 3: Instances must not have SSH open to the Internet.
it("must not open port 22 (SSH) to the Internet", function(done) {
pulumi.all([infra.group.urn, infra.group.ingress]).apply(([ urn, ingress ]) => {
if (ingress.find(rule =>
rule.fromPort === 22 && (rule.cidrBlocks || []).find(block => block === "0.0.0.0/0"))) {
done(new Error(`Illegal SSH port 22 open to the Internet (CIDR 0.0.0.0/0) on group ${urn}`));
} else {
done();
}
});
});That's it—now let's run the tests.
Run the Tests
The command line to run your Mocha tests would therefore be:
$ mocha -r ts-node/register ec2tests.tsRunning this will tell us that we have three failing tests, as we had planned.
Infrastructure
#server
1) must have a name tag
2) must not use userData (use an AMI instead)
#group
3) must not open port 22 (SSH) to the Internet
0 passing (454ms)
3 failingLet's fix our program to comply:
index.ts:
import * as aws from "@pulumi/aws";
export const group = new aws.ec2.SecurityGroup("web-secgrp", {
ingress: [
{ protocol: "tcp", fromPort: 80, toPort: 80, cidrBlocks: ["0.0.0.0/0"] },
],
});
export const server = new aws.ec2.Instance("web-server-www", {
instanceType: "t2.micro",
securityGroups: [ group.name ], // reference the group object above
ami: "ami-c55673a0", // AMI for us-east-2 (Ohio)
tags: { Name: "www-server" }, // name tag
});And then rerun our tests:
Infrastructure
#server
✓ must have a name tag
✓ must not use userData (use an AMI instead)
#group
✓ must not open port 22 (SSH) to the Internet
3 passing (454ms)All the tests passed!
Full Example
The full code for this guide is available in the examples repository: Unit Tests in TypeScript.