Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 36 ยท Testing and Policy

Unit Testing Pulumi Programs with Mocks

Unit test Pulumi infrastructure code without a cloud: pulumi.runtime.setMocks, newResource and call mocks, testing outputs, tags and security rules, and keeping tests fast.

Infrastructure code is code, so it deserves tests. The cheapest, fastest tests are unit tests: they run your Pulumi program with a fake engine, so no cloud is contacted, nothing is created and a run takes milliseconds. They are perfect for rules such as "every bucket is private", "prod has at least two instances" or "this component names its children correctly".

Pulumi provides this through mocks. You replace the engine with two functions: one that answers "create this resource" and one that answers "call this provider function". The real SDKs cannot run on this site, so the test code below is read-only. The runnable stand-in implements a tiny mock engine and test runner so you can practice the pattern in the browser or on Piston.

The mocking API

In TypeScript, tests install mocks before importing the program:

TypeScript
import * as pulumi from "@pulumi/pulumi";
import { describe, it, before } from "node:test";
import assert from "node:assert/strict";

pulumi.runtime.setMocks(
  {
    newResource(args: pulumi.runtime.MockResourceArgs): { id: string; state: Record<string, any> } {
      // args.type, args.name, args.inputs
      return {
        id: `${args.name}-id`,
        state: {
          ...args.inputs,
          arn: `arn:aws:mock:::${args.name}`,
        },
      };
    },
    call(args: pulumi.runtime.MockCallArgs): Record<string, any> {
      if (args.token === "aws:index/getAvailabilityZones:getAvailabilityZones") {
        return { names: ["eu-central-1a", "eu-central-1b"] };
      }
      return args.inputs;
    },
  },
  "shop",   // project name
  "test",   // stack name
  false     // dry run (true behaves like preview)
);

describe("infrastructure", () => {
  let infra: typeof import("./index");

  before(async () => {
    infra = await import("./index");     // program imported AFTER setMocks
  });

  it("makes the bucket private", async () => {
    const acl = await promiseOf(infra.bucket.acl);
    assert.equal(acl, "private");
  });
});

function promiseOf<T>(output: pulumi.Output<T>): Promise<T> {
  return new Promise((resolve) => output.apply(resolve));
}

Key points:

  • newResource returns the resource's id and its state (the outputs). Returning args.inputs as state makes most outputs match what the program asked for; add computed fields (ARN, endpoint) when the program uses them.
  • call answers provider function calls such as getAvailabilityZones or getCallerIdentity. Unmocked calls that return nothing may break code that reads their results, so return fixtures.
  • Outputs are asynchronous. Convert them to promises with output.apply(resolve) (or use pulumi.all) before asserting.
  • Import the program inside a before hook, after setMocks, because resources are created on import.

In Python the equivalents are pulumi.runtime.set_mocks(MyMocks(), preview=False) with new_resource and call methods, and in Go pulumi.WithMocks. The same ideas apply.

What to test

Good unit tests check rules, not implementation details:

  1. Security: no public buckets, no 0.0.0.0/0 on port 22, encryption enabled.
  2. Policy of naming and tagging: every resource has owner and environment tags.
  3. Defaults and validation of your components: invalid inputs throw clear errors.
  4. Branching on config: prod creates a replica; dev does not.
  5. Wiring: a function's role has the policy that grants only the queue it reads.

Avoid asserting the exact number of properties or snapshot-testing the entire program; those tests break on every harmless refactor.

Stand-in: a mock engine and tests

The code below builds a small engine with newResource mocking, a "program" function and tests that collect created resources. It uses only Node's assert.

Node.js Stand-in: unit testing a program with a fake engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test fails deliberately so you can read a failure. Fix it by changing the expected count to 1 and watch all four pass.

Making outputs testable

Asserting on outputs needs a small helper in the real SDK, because outputs are resolved asynchronously:

TypeScript
export function promiseOf<T>(output: pulumi.Output<T>): Promise<T> {
  return new Promise((resolve) => output.apply(resolve));
}

it("blocks public ACLs", async () => {
  const blocked = await promiseOf(infra.publicAccessBlock.blockPublicAcls);
  assert.equal(blocked, true);
});

For several outputs use pulumi.all([a, b]).apply(([x, y]) => ...) and assert inside, resolving with a result you check afterwards. If an assertion throws inside apply, wrap it so the failure reaches the test runner (for example by rejecting a promise).

Pitfalls

  • Importing the program before setMocks. Resources are created at import; your mocks would never be used, and the real engine would try to start.
  • Forgetting to return state. If the mock returns only an id, outputs such as arn are undefined and dependent code breaks in confusing ways.
  • Testing the mocks. If your assertion only checks values the mock echoed back, it proves nothing. Assert on rules that your program logic enforces.
  • Slow tests. Unit tests should not call the network. If a call sneaks through, you forgot to mock a function.
  • Over-specified tests. Test behavior (private, tagged, count) rather than every property.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the newResource mock return?

    The mock supplies the id and the outputs (state) the program will see for that resource.
  2. 2. Why must the program be imported after setMocks?

    Pulumi programs create resources at import time. Without mocks installed first, the real engine would be used.
  3. 3. How do you assert on an Output<string> in a test?

    Outputs resolve asynchronously, so resolve them with apply (or pulumi.all) before asserting.
  4. 4. Which is the best unit test for infrastructure?

    Rule-based tests stay valid across refactors; snapshots and property counts break on harmless changes.

Summary

  • Unit tests run the program against mocks (setMocks), so they are fast and need no cloud.
  • Mock newResource (id and state) and call (provider functions) and import the program afterwards.
  • Convert outputs to promises before asserting.
  • Test rules: security, tags, defaults, branching and wiring, not incidental details.
  • Keep tests offline; anything slower belongs to integration tests.

Next: Integration Testing and Ephemeral Stacks