Unit Testing Pulumi Programs
Pulumi programs are authored in a general-purpose language like TypeScript, Python, Go, .NET, or Java. The full power of that language is available to you, including its tooling, libraries, and 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 answer those commands from within the same OS process, returning placeholder data for each call your program makes.
Because mocks don't do any real work, unit tests run fast. They're also deterministic, since nothing about them depends on the behavior of an external system.
Get started
This guide builds a sample test suite against AWS resources, but the same capabilities and workflow apply to any Pulumi provider. To follow along, complete the get-started guide to set up a Pulumi program in the language of your choice.
Unit tests are supported in every general-purpose Pulumi language runtime.
Sample program
Throughout this guide, you'll test a program that creates an AWS EC2 web server. The tests check that:
- Instances have a
Nametag. - Instances must not use an inline
userDatascript. They must use a virtual machine image instead. - Instances must not have SSH open to the internet.
INFO
Mock-based unit testing needs a general-purpose language runtime, so for declarative Pulumi programs written in YAML or HCL, see integration testing instead.
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 python3 -m http.server 80 &`;
// Look up the latest Amazon Linux 2023 AMI.
const ami = aws.ec2.getAmiOutput({
owners: ["amazon"],
mostRecent: true,
filters: [{ name: "name", values: ["al2023-ami-2023.*-x86_64"] }],
});
export const server = new aws.ec2.Instance("web-server-www", {
instanceType: "t2.micro",
securityGroups: [group.name], // reference the group object above
ami: ami.id,
userData: userData, // start a simple web server
});The program allocates a security group and an instance, and it looks the instance's AMI up with getAmi rather than hard-coding one. It also breaks all three of those rules, and the tests you write next catch each one.
Install the unit testing framework
Use whichever test framework and assertion library you prefer.
This guide uses Mocha as the test framework, run through tsx so that it executes your TypeScript directly. Install both as development dependencies of your program:
npm install --save-dev mocha @types/mocha tsxAdd the mocks
Mocks stand in for the Pulumi CLI, answering your program from inside the same process. They have two handlers: newResource for each resource your program registers, and call for each provider function it invokes, which includes the sample program's AMI lookup.
Here is the whole file, followed by a breakdown of each handler.
ec2tests.ts
import * as pulumi from "@pulumi/pulumi";
pulumi.runtime.setMocks({
newResource: function(args: pulumi.runtime.MockResourceArgs): {id: string, state: any} {
switch (args.type) {
case "aws:ec2/securityGroup:SecurityGroup":
return {
id: "sg-12345678",
state: {
...args.inputs,
// Mock output properties that may be used in tests
arn: "arn:aws:ec2:us-west-2:123456789012:security-group/sg-12345678",
name: args.inputs.name || args.name + "-sg",
},
};
case "aws:ec2/instance:Instance":
return {
id: "i-1234567890abcdef0",
state: {
...args.inputs,
// Mock output properties that may be used in tests
arn: "arn:aws:ec2:us-west-2:123456789012:instance/i-1234567890abcdef0",
instanceState: "running",
primaryNetworkInterfaceId: "eni-12345678",
privateDns: "ip-10-0-1-17.ec2.internal",
publicDns: "ec2-203-0-113-12.compute-1.amazonaws.com",
publicIp: "203.0.113.12",
},
};
default:
return {
id: args.inputs.name + "_id",
state: {
...args.inputs,
},
};
}
},
call: function(args: pulumi.runtime.MockCallArgs) {
switch (args.token) {
case "aws:ec2/getAmi:getAmi":
return {
id: "ami-0eb1f3cdeeb8eed2a",
architecture: "x86_64",
};
default:
return args.inputs;
}
},
},
"project", // Project name. Mocked resources get it in their URNs.
"stack", // Stack name. Also part of the URN.
false, // Sets the flag `dryRun`, which indicates if pulumi is running in preview mode.
);The full mocks interface is defined on the Node.js runtime API reference page.
Mocking resources
newResource is handed one resource registration at a time, and returns the ID and state the engine would have returned. Two kinds of property pass through it:
- Input properties, such as
tags,userData, andingress, are set by your program and arrive on the mock's arguments. Returning them unchanged is usually what you want. - Output properties, such as
arn,publicIp, andinstanceState, are computed by the cloud provider. The mock has to return them explicitly, or they come back undefined.
The tests later in this guide read both kinds, which is why the mock branches on the resource type: each type needs its own set of output properties.
Mocking provider functions
Provider functions, such as aws.ec2.getAmi or aws.getAvailabilityZones, don't create anything. They query the provider, so the mocks answer them in call rather than in newResource. Mocking one pins the value the lookup returns, which is what keeps a test that depends on a live cloud query deterministic.
Each function is identified by a token of the form <package>:<module>/<function>:<function>, so getAmi in the AWS provider's ec2 module is aws:ec2/getAmi:getAmi. You'll find the token for any function on its page in the Pulumi Registry, and in the provider's schema. Match on it to decide what to return.
The call handler also receives the arguments the program passed to the function, in args.inputs in TypeScript (args.args in Python and Java, args.Args in Go and C#), so a single mock can answer different queries with different results. A test that exercises both an Amazon Linux lookup and an Ubuntu one can return a different AMI for each, keyed on the filters the program supplied.
The snippets below come from a compact, self-contained project rather than from the web server this guide builds, so that the mock and the assertion it enables sit side by side.
Match on the token in call, and fall through to the default for every other function:
pulumi.runtime.setMocks({
newResource: function(args: pulumi.runtime.MockResourceArgs): {id: string, state: any} {
return {
id: args.name + "_id",
state: args.inputs,
};
},
call: function(args: pulumi.runtime.MockCallArgs) {
switch (args.token) {
case "aws:ec2/getAmi:getAmi":
return {
id: "ami-0eb1f3cdeeb8eed2a",
architecture: "x86_64",
};
default:
return args.inputs;
}
},
}, "project", "stack", false); // Project and stack names, plus dryRun; the names show up in mocked URNs.The test can then assert that the mocked value reached the resource that consumed it:
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() {
it("must use the AMI returned by the getAmi lookup", function(done) {
pulumi.all([infra.server.urn, infra.server.ami]).apply(([urn, ami]) => {
if (ami !== "ami-0eb1f3cdeeb8eed2a") {
done(new Error(`Unexpected AMI ${ami} on server ${urn}`));
} else {
done();
}
});
});
});
});The mock only needs the fields your test actually reads. Anything you leave out comes back empty, exactly as it does for an unmocked resource output.
These five projects, one per language, are runnable and run in this site's CI. They live under static/programs, named unit-testing-function-mock-<language>.
Mocking stack references
If your program uses StackReference to read outputs from another stack, you need to handle them in your mocks. When a StackReference resource is created, the mock's newResource function receives it with type pulumi:pulumi:StackReference. You can return mock outputs that simulate the referenced stack's outputs.
pulumi.runtime.setMocks({
newResource: function(args: pulumi.runtime.MockResourceArgs): {id: string, state: any} {
// Handle StackReference resources
if (args.type === "pulumi:pulumi:StackReference") {
return {
id: args.inputs.name + "_id",
state: {
...args.inputs,
outputs: {
// Mock the outputs from the referenced stack
vpcId: "vpc-12345678",
subnetIds: ["subnet-11111111", "subnet-22222222"],
clusterName: "my-cluster",
},
},
};
}
// Handle all other resources
return {
id: args.inputs.name + "_id",
state: args.inputs,
};
},
call: function(args: pulumi.runtime.MockCallArgs) {
return args.inputs;
},
});In your program, you can then use a StackReference as usual:
// Example: Program that reads from a StackReference
const networkStack = new pulumi.StackReference("organization/network/prod");
const vpcId = networkStack.getOutput("vpcId");
// In tests, vpcId will resolve to "vpc-12345678" based on the mock aboveThis approach lets you test how your program uses outputs from other stacks without needing those stacks to actually exist. You can mock different scenarios by returning different outputs in your test setup.
Write the tests
The structure and scaffolding look like any ordinary Mocha test:
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 implement the first check: instances have a Name tag. Take hold of the EC2 instance object and inspect the 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:
- The test queries resource state without running a deployment, so many properties are undefined. That includes every output property your cloud provider computes and the mocks don't return explicitly. These checks only read inputs, so none of that matters here.
- Every Pulumi resource property is an output, because so many of them are computed asynchronously. Reach the underlying values with
apply(see theGetValueAsyncfunction inTesting.cs). - Since outputs resolve asynchronously, the test relies on the framework's built-in support for asynchronous tests.
Past that setup, the raw inputs are available as plain values. The tags property is a map, so the check confirms that it's defined and that it holds an entry for the Name key. That's a small assertion, but the same approach reaches any property on any resource.
The second check asserts that the 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();
}
});
});The third check takes a few more lines, because a security group may carry many ingress rules, and each of those rules may carry many CIDR blocks. The test walks all of them:
// 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 all three checks. Now run the tests.
Run the tests
Run the Mocha tests with:
npx mocha --require tsx ec2tests.tsAll three tests fail, exactly as 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 failingNow fix the program so that it complies:
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"] },
],
});
// Look up the latest Amazon Linux 2023 AMI.
const ami = aws.ec2.getAmiOutput({
owners: ["amazon"],
mostRecent: true,
filters: [{ name: "name", values: ["al2023-ami-2023.*-x86_64"] }],
});
export const server = new aws.ec2.Instance("web-server-www", {
instanceType: "t2.micro",
securityGroups: [ group.name ], // reference the group object above
ami: ami.id,
tags: { Name: "webserver" }, // name tag
});Then rerun the 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 (108ms)All three tests pass.
Limitations
When using mocks for unit testing, it's important to understand that the mock server does not implement the full Pulumi engine. This means certain features that rely on the engine's deployment orchestration will not execute during mock-based tests.
Lifecycle hooks and transforms
Lifecycle hooks and resource transforms are not executed in mock tests. While your program can register hooks and transforms with the mock server, they will not actually run during test execution.
This limitation exists because implementing full hook and transform support would require reimplementing significant portions of the Pulumi engine in each language SDK. Since mocks are designed to run fast and deterministically without external dependencies, this trade-off is intentional.
If your program uses lifecycle hooks or transforms, structure your tests to work around this limitation:
- Test the logic separately: Extract the logic from hooks and transforms into standalone functions that can be unit tested independently.
- Mock the expected outcomes: Configure your mocks to return resource state that reflects what would happen after hooks or transforms execute.
- Use integration tests: For end-to-end validation of hook and transform behavior, use integration tests that deploy actual resources to a testing environment.
For example, if you have a transform that adds default tags to all resources, your mock's newResource function can return resource state that already includes those tags, simulating the transform's effect without actually executing it.
Full example
The full code for this guide is available in the examples repository: Unit Tests in TypeScript.
Learn more
- Integration testing deploys real resources and checks them end to end, which is where lifecycle hooks, transforms, and anything else the mock server doesn't implement belong.
- Inputs and outputs explains why resource properties resolve asynchronously, and how
applyreaches their values. - Pulumi Policies enforces rules like the three in this guide across every stack in your organization, rather than one program at a time.