pulumi: Unable to unit test stacks which references Pulumi.Config

Unit tests written for stacks which use Pulumi.Config to read configuration values fail to execute as the config values are not available for the tests. Sample stack & its unit tests are available at : https://gist.github.com/svswaminathan/591254043500e1a3a041272a2ab17065

Running dotnet test throws the following error:

Pulumi.RunException : Running program 'C:\Samples\pulumi\pc-azure-csharp\bin\Debug\netcoreapp3.1\testhost.dll' failed with an unhandled exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Pulumi.Config+ConfigMissingException: Missing Required configuration variable 'project:resourceGroupName' please set a value using the command pulumi config set project:resourceGroupName <value> at Pulumi.Config.Require(String key) at MyStack..ctor() in C:\Samples\pulumi\pc-azure-csharp\MyStack.cs:line 11

Since Pulumi.Config is a sealed class, there is no possibility to mock it as well.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 36
  • Comments: 16 (3 by maintainers)

Most upvoted comments

In go there seems to be a way to do this without needing to muck with environment variables.

package example

import (
	"testing"
	"github.com/pulumi/pulumi/sdk/v2/go/common/resource"
	"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
	"github.com/stretchr/testify/assert"
)

type mocks int

func (mocks) NewResource(typeToken, name string, inputs resource.PropertyMap, provider, id string) (string, resource.PropertyMap, error) {
	return name + "_id", inputs, nil
}

func (mocks) Call(token string, args resource.PropertyMap, provider string) (resource.PropertyMap, error) {
	return args, nil
}


// Duplicate the pulumi.WithMocks() function with the additional configuration
// value of 'config'.
func WithMocksAndConfig(project, stack string, config map[string]string, mocks pulumi.MockResourceMonitor) pulumi.RunOption {
	return func(info *pulumi.RunInfo) {
		info.Project, info.Stack, info.Mocks, info.Config = project, stack, mocks, config
	}
}

func TestExample(t *testing.T) {
	config := map[string]string{
		"project:example.foo":  "goof",
		"project:example.bar":  "gold",
	}

	err := pulumi.RunErr(func(ctx *pulumi.Context) error {
		rv, err := Example(ctx, "hello, world")
		assert.NoError(t, err)
		assert.NotNil(t, rv)

		return nil
	}, WithMocksAndConfig("project", "stack", config, mocks(0)))
	assert.NoError(t, err)
}

Though better yet is to improve the WithMocks() function here like this:

func WithMocks(project, stack string, mocks MockResourceMonitor) RunOption {
	return func(info *RunInfo) {
		info.Project, info.Stack, info.Mocks = project, stack, mocks
	}
}

func WithMocksAndConfig(project, stack string,  config map[string]string, mocks MockResourceMonitor ) RunOption {
	return func(info *RunInfo) {
		info.Project, info.Stack, info.Mocks, info.Config = project, stack, mocks, config
	}
}

Hey whiteninja76, not sure if you’re still having an issue but I was able to Jest spyOn the config:

const config = new pulumi.Config();
jest
  .spyOn(config, 'requireSecret')
  .mockImplementation(() => 'fake_secret' as any);

If you’re not using Jest there may be something similar you could do.

Was able to work around this in typescript:

export class TestConfig extends Config {
  private configs?: Record<string, any>;
  public readonly name: string = "Fake-test-config";

  public setConfig(configs: Record<string, any>): Config {
    this.configs = configs;
    return this;
  }

  public get<K extends string = string>(
    key: string,
    opts?: StringConfigOptions<K>
  ): K | undefined {
    return this.configs![key] as K;
  }

  public getBoolean(key: string): boolean | undefined {
    return this.configs![key];
  }

  public getNumber(
    key: string,
    opts?: NumberConfigOptions
  ): number | undefined {
    return this.configs![key];
  }

  public getObject<T>(key: string): T | undefined {
    return this.configs![key];
  }

  public getSecret<K extends string = string>(
    key: string,
    opts?: StringConfigOptions<K>
  ): Output<K> | undefined {
    return this.configs![key];
  }

  public getSecretBoolean(key: string): Output<boolean> | undefined {
    return this.configs![key]
  }

  public getSecretNumber(
    key: string,
    opts?: NumberConfigOptions
  ): Output<number> | undefined {
    return this.configs![key]
  }

  public getSecretObject<T>(key: string): Output<T> | undefined {
    return this.configs![key]
  }

  public require<K extends string = string>(
    key: string,
    opts?: StringConfigOptions<K>
  ): K {
    return this.getRequired(key);
  }

  public requireBoolean(key: string): boolean {
    return this.getRequired(key);
  }

  public requireNumber(key: string, opts?: NumberConfigOptions): number {
    return this.getRequired(key);
  }

  public requireObject<T>(key: string): T {
    return this.getRequired(key);
  }

  public requireSecret<K extends string = string>(
    key: string,
    opts?: StringConfigOptions<K>
  ): Output<K> {
    return this.getRequiredOutput(key);
  }

  public requireSecretBoolean(key: string): Output<boolean> {
    return this.getRequiredOutput(key);
  }

  public requireSecretNumber(
    key: string,
    opts?: NumberConfigOptions
  ): Output<number> {
    return this.getRequiredOutput(key);
  }

  public requireSecretObject<T>(key: string): Output<T> {
    return this.getRequiredOutput(key);
  }

  private getRequired<T>(key: string): T {
    const result: T = this.configs![key];

    if (!result) {
      throw new Error(
        `key: ${key} missing from: ${util.inspect(this.configs)}`
      );
    }

    return result;
  }

  private getRequiredOutput<T>(key: string): Output<T> {
    return Output.create(null).apply(() => this.getRequired(key));
  }
}

and in tests:

new TestConfig().setConfig({})

It may not be ideal if you’re using ConfigOptions

@svswaminathan Currently, we don’t have API to mock config, and the actual configuration is taken from an environment variable PULUMI_CONFIG. So, if you have code like

new Config().Require("myvar");

You would need to pass a JSON value of the shape

export PULUMI_CONFIG='{ "project:myvar": "myvalue" }'

(example for macOS)

You should keep “project” because that’s the default namespace.

I understand this is less than ideal, so I’m open to suggestions for a first-class config API while unit testing.

My TypeScript workaround use a function for getting config and pulumi.runtime.setConfig.

// In pulumi program code

// Note that in real code, this fn is memoized
const getConfig = () => {
  const config = new pulumi.Config()
  const billingAccount = config.require('billingAccount')
  const orgId = config.require('orgId')
  return { billingAccount, orgId }
}

...

// All usage of config uses this function

// In beforeAll in test file

  pulumi.runtime.setConfig('project:orgId', '123456789012')
  pulumi.runtime.setConfig('project:billingAccount', '123456-123456-123456')

Accessing the config lazily via the function ensures that the pulumi.runtime.setConfig runs and sets config before the .require methods are called on the config.

In case anyone finds this interesting, this is what I ended up doing:

class MyMocks(pulumi.runtime.Mocks):
   def new_resource(self, args: MockResourceArgs) -> Tuple[Optional[str], dict]:
       return "", {}

   def call(self, args: MockCallArgs) -> Tuple[dict, Optional[List[Tuple[str, str]]]]:
       return {}, None


pulumi.runtime.set_mocks(MyMocks(), project="core-bitbucket")


@pytest.fixture
def mock_settings_env_vars() -> None:
   pulumi_config = {
       "core-bitbucket:bitbucket_username": "bitbucket_username",
       "core-bitbucket:bitbucket_app_password": "bitbucket_app_password",
       "core-bitbucket:data": json.dumps({
           "workspace": {
               "name": "test-workspace",
               "repositories": [
                   {
                       "name": "repository1",
                   },
                   {
                       "name": "repository2",
                   }
               ],
               "variables": [
                   {
                       "name": "TEST_ENV_VAR",
                       "value": "test_value",
                       "secured": False
                   }
               ]
           }
       })
   }

   with mock.patch.dict(os.environ, dict(PULUMI_CONFIG=json.dumps(pulumi_config))):
       yield

When attempting at the env var alternative + structured config:

     Error: Configuration 'product-infra:ecsCapacityGroupInstanceTypePriority' value '[object Object]' is not a valid JSON object

Just in case this is still relevant, or for people after me. I was having this exact same issue. The problem was that all objects that are not the main one, also need to be strings, not object. If you’re doing:

    process.env.PULUMI_CONFIG = JSON.stringify({
        "aws:region": "us-west-2",
        "extraconfiguration": {
            "things": "values",
            "morethings": "morevalues",
        }
    });

you could need to stringify that object as well:

    process.env.PULUMI_CONFIG = JSON.stringify({
        "aws:region": "us-west-2",
        "extraconfiguration": JSON.stringify({
            "things": "values",
            "morethings": "morevalues",
        })
    });

I was able to work around this one. A short Gist is pasted below. A working solution is condensed down to this code. Keep in mind that YamlDotNet is a requirement for this solution.

using System.IO;
using YamlDotNet.Serialization;

namespace Tests
{
    public class ConfigConverter
    {
        public string WriteAsJsonToText(string pulumiConfigAt, string configAttribute = "config")
        {
            var builder = new DeserializerBuilder();
            IDeserializer deserializer = builder.Build();
            using (var sr = new StreamReader(pulumiConfigAt))
            {
                var content = deserializer.Deserialize<dynamic>(sr);
                if (content != null)
                {
                    var serializer = new SerializerBuilder()
                        .JsonCompatible()
                        .Build();
                    using var memoryStream = new MemoryStream();
                    using (var streamWriter = new StreamWriter(memoryStream))
                    {
                        var config = content[configAttribute];
                        serializer.Serialize(streamWriter, config);
                        
                        streamWriter.Flush();
                        memoryStream.Position = 0;
                        using (var streamReader = new StreamReader(memoryStream))
                        {
                            return streamReader.ReadToEnd();
                        }
                    }
                }
            }

            return default;
        } 
    }
// Copy and paste from
    // https://github.com/pulumi/examples/blob/74db62a03d013c2854d2cf933c074ea0a3bbf69d/testing-unit-cs/Testing.cs
    /// <summary>
    /// Helper methods to streamlines unit testing experience.
    /// </summary>
    public static class Testing
    {
        /// <summary>
        /// Run the tests for a given stack type.
        /// </summary>
        public static Task<ImmutableArray<Resource>> RunAsync<T>() where T : Stack, new()
        {
            string projectName = "MY-PROJECT";
            string stackName = "prod";
            string configFile = $"Pulumi.{stackName}.yaml";
            
            var mocks = SetupMocks<T>();

            string currentDirectory = System.Environment.CurrentDirectory;
            
            string pulumiConfigAt = Path.GetFullPath(Path.Combine(currentDirectory, "..", "..", "..", "..", projectName, configFile));
            ConfigConverter fileConverter = new ConfigConverter();
            string configJsonAt = fileConverter.WriteAsJsonToText(pulumiConfigAt);
            System.Environment.SetEnvironmentVariable("PULUMI_CONFIG", configJsonAt);
            return Deployment.TestAsync<T>(mocks.Object, new TestOptions { IsPreview = false, ProjectName = projectName, StackName = stackName });
        }

        private static Mock<IMocks> SetupMocks<T>() where T : Stack, new()
        {
            var mocks = new Mock<IMocks>();
            mocks.Setup(m => m.NewResourceAsync(It.IsAny<string>(), It.IsAny<string>(),
                    It.IsAny<ImmutableDictionary<string, object>>(), It.IsAny<string>(), It.IsAny<string>()))
                .ReturnsAsync((string type, string name, ImmutableDictionary<string, object> inputs, string? provider,
                    string? id) => (name + "_id", inputs));
            mocks.Setup(m =>
                    m.CallAsync(It.IsAny<string>(), It.IsAny<ImmutableDictionary<string, object>>(), It.IsAny<string>()))
                .ReturnsAsync((string token, ImmutableDictionary<string, object> args, string? provider) => args);
            return mocks;
        }


        /// <summary>
        /// Extract the value from an output.
        /// </summary>
        public static Task<T> GetValueAsync<T>(this Output<T> output)
        {
            var tcs = new TaskCompletionSource<T>();
            output.Apply(v =>
            {
                tcs.SetResult(v);
                return v;
            });
            return tcs.Task;
        }   
    }
}