Saturday, March 18, 2023

Can we write tests for the Pulumi language based usage?

 Yes, you can write tests for Pulumi code. Pulumi supports integration testing and unit testing, allowing you to validate and verify your Infrastructure as Code (IaC) before deploying it. You can write tests in the same language as your Pulumi code, like Python, TypeScript, or Go.


Here's an example of how to write unit tests for Pulumi code in Python:


First, make sure you have pulumi, pytest, and pulumi-aws (or other relevant pulumi provider) installed. You can install them using pip:


pip install pulumi pulumi-aws pytest


Create a simple Pulumi stack in a file called __main__.py:


import pulumi

import pulumi_aws as aws


# Create an AWS S3 bucket

bucket = aws.s3.Bucket('my-bucket')


# Export the bucket name

pulumi.export('bucket_name', bucket.id)


Create a test_infrastructure.py file for your unit tests:


import pulumi

import pulumi_aws as aws

from pulumi_aws import s3

from pulumi import ResourceOptions

import pytest

from unittest import mock


# Test for S3 bucket creation

def test_s3_bucket():

    # Mock the Pulumi runtime

    with mock.patch.object(pulumi.runtime, 'register_resource') as register_resource_mock:

        with mock.patch.object(pulumi.runtime, 'register_outputs') as register_outputs_mock:

            # Create the bucket

            from __main__ import bucket


            # Assert that the expected resource is registered

            register_resource_mock.assert_called_once_with(

                'aws:s3/bucket:Bucket',

                'my-bucket',

                {'acl': None, 'tags': None},

                None,

                False,

                ResourceOptions()

            )


            # Assert that the bucket name is registered as an output

            register_outputs_mock.assert_called_once_with({'bucket_name': pulumi.Output(bucket.id)})


Run your tests with pytest:


pytest


This is just a simple example. Depending on your use case and the complexity of your infrastructure, you may want to write more extensive tests or integration tests. Pulumi's testing guide provides more detailed information and examples for different languages and use cases: https://www.pulumi.com/docs/guides/testing/.