search
HomeBackend DevelopmentGolangHow to mock Pulumi resources in Go unit tests?

如何在 Go 单元测试中模拟 Pulumi 资源?

Question content

I have a function that takes input from the aws openidconnectprovider pulumi resource and creates an iam role and attaches an include from that oidc provider The assumerolepolicy of the supplier's information.

Question: I'm trying to write a test for this function and mock the oidc provider as input to the function call. I can't figure out how to simulate it correctly so that the test output shows what I expect, currently it seems the simulated data isn't coming out as I expect.

Looks like I'm not using mocking correctly, but I'm giving up on the example here

More documentation here

package mypkg

import (
   "github.com/pulumi/pulumi-aws/sdk/v5/go/aws/iam"
   "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)

func createmycustomrole(ctx *pulumi.context, name string, oidcprovider *iam.openidconnectprovider, opts ...pulumi.resourceoption) (*iam.role, error) {
    role := &iam.role{}

    componenturn := fmt.sprintf("%s-custom-role", name)

    err := ctx.registercomponentresource("pkg:aws:mycustomrole", componenturn, role, opts...)
    if err != nil {
        return nil, err
    }

    url := oidc.url.applyt(func(s string) string {
        return fmt.sprint(strings.replaceall(s, "https://", ""), ":sub")
    }).(pulumi.stringoutput)

    assumerolepolicy := pulumi.sprintf(`{
            "version": "2012-10-17",
            "statement": [{
                "effect": "allow",
                "principal": { "federated": "%s" },
                "action": "sts:assumerolewithwebidentity",
                "condition": {
                    "stringequals": {
                        "%s": [
                            "system:serviceaccount:kube-system:*",
                            "system:serviceaccount:kube-system:cluster-autoscaler"
                        ]
                    }
                }
            }]
        }`, oidcprovider.arn, url)

    roleurn := fmt.sprintf("%s-custom-role", name)

    role, err = iam.newrole(ctx, roleurn, &iam.roleargs{
            name:             pulumi.string(roleurn),
            description:      pulumi.string("create custom role"),
            assumerolepolicy: assumerolepolicy,
            tags:             pulumi.tostringmap(map[string]string{"project": "test"}),
        })
    if err != nil {
        return nil, err
    }

    return role, nil
}

package mypkg

import (
    "sync"
    "testing"

    "github.com/pulumi/pulumi-aws/sdk/v5/go/aws/iam"
    "github.com/pulumi/pulumi/sdk/v3/go/common/resource"
    "github.com/pulumi/pulumi/sdk/v3/go/pulumi"
    "github.com/stretchr/testify/assert"
)

type mocks int

func (mocks) newresource(args pulumi.mockresourceargs) (string, resource.propertymap, error) {
    return args.name + "_id", args.inputs, nil
}

func (mocks) call(args pulumi.mockcallargs) (resource.propertymap, error) {
    outputs := map[string]interface{}{}
    if args.token == "aws:iam/getopenidconnectprovider:getopenidconnectprovider" {
        outputs["arn"] = "arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc"
        outputs["id"] = "abc"
        outputs["url"] = "https://someurl"
    }
    return resource.newpropertymapfrommap(outputs), nil
}

func testcreatemycustomrole(t *testing.t) {
    err := pulumi.runerr(func(ctx *pulumi.context) error {

        // gets the mocked oidc provider to use as input for the createdefaultautoscalerrole
        oidc, err := iam.getopenidconnectprovider(ctx, "get-test-oidc-provider", pulumi.id("abc"), &iam.openidconnectproviderstate{})
        assert.noerror(t, err)

        infra, err := createmycustomrole(ctx, "role1", oidc})
        assert.noerror(t, err)

        var wg sync.waitgroup
        wg.add(1)

        // check 1: assume role policy is formatted correctly
        pulumi.all(infra.urn(), infra.assumerolepolicy).applyt(func(all []interface{}) error {
            urn := all[0].(pulumi.urn)
            assumerolepolicy := all[1].(string)

            assert.equal(t, `{
            "version": "2012-10-17",
            "statement": [{
                "effect": "allow",
                "principal": { "federated": "arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc" },
                "action": "sts:assumerolewithwebidentity",
                "condition": {
                    "stringequals": {
                        "someurl:sub": [
                            "system:serviceaccount:kube-system:*",
                            "system:serviceaccount:kube-system:cluster-autoscaler"
                        ]
                    }
                }
            }]
        }`, assumerolepolicy)

            wg.done()
            return nil
        })

        wg.wait()
        return nil
    }, pulumi.withmocks("project", "stack", mocks(0)))
    assert.noerror(t, err)
}

output
diff:
                        --- expected
                        +++ actual
                        @@ -4,3 +4,3 @@
                                        "effect": "allow",
                        -               "principal": { "federated": "arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc" },
                        +               "principal": { "federated": "" },
                                        "action": "sts:assumerolewithwebidentity",
                        @@ -8,3 +8,3 @@
                                            "stringequals": {
                        -                       "someurl:sub": [
                        +                       ":sub": [
                                                    "system:serviceaccount:kube-system:*",
        test:           testcreatemycustomrole

Correct answer


It turns out that I used newresource wrong.

When getopenidconnectprovider is called in a test function, it reads the resource and creates a new resource output, triggering a call to mocks.newresource

The fix is ​​to use mock output to define an if statement in the newresource function call for the resource type returned by getopenidconnectprovider openidconnectprovider.

func (mocks) newresource(args pulumi.mockresourceargs) (string, resource.propertymap, error) {
    pulumi.printf(args.typetoken)
    outputs := args.inputs.mappable()
    if args.typetoken == "aws:iam/openidconnectprovider:openidconnectprovider" {
        outputs["arn"] = "arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc"
        outputs["id"] = "abc"
        outputs["url"] = "https://someurl"
    }
    return args.name + "_id", resource.newpropertymapfrommap(outputs), nil
}

func (mocks) call(args pulumi.mockcallargs) (resource.propertymap, error) {
    outputs := map[string]interface{}{}
    return resource.newpropertymapfrommap(outputs), nil
}

The code snippet below is where I changed assert so that it doesn't show the difference now compared to the changes made to newresource above

Diff:
                            --- Expected
                             Actual
                            @@ -8,3 +8,3 @@
                                                "StringEquals": {
                            -                       "b:sub": [
                            +                       "someurl:sub": [
                                                        "system:serviceaccount:kube-system:*",

The above is the detailed content of How to mock Pulumi resources in Go unit tests?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
String Manipulation in Go: Mastering the 'strings' PackageString Manipulation in Go: Mastering the 'strings' PackageMay 14, 2025 am 12:19 AM

Mastering the strings package in Go language can improve text processing capabilities and development efficiency. 1) Use the Contains function to check substrings, 2) Use the Index function to find the substring position, 3) Join function efficiently splice string slices, 4) Replace function to replace substrings. Be careful to avoid common errors, such as not checking for empty strings and large string operation performance issues.

Go 'strings' package tips and tricksGo 'strings' package tips and tricksMay 14, 2025 am 12:18 AM

You should care about the strings package in Go because it simplifies string manipulation and makes the code clearer and more efficient. 1) Use strings.Join to efficiently splice strings; 2) Use strings.Fields to divide strings by blank characters; 3) Find substring positions through strings.Index and strings.LastIndex; 4) Use strings.ReplaceAll to replace strings; 5) Use strings.Builder to efficiently splice strings; 6) Always verify input to avoid unexpected results.

'strings' Package in Go: Your Go-To for String Operations'strings' Package in Go: Your Go-To for String OperationsMay 14, 2025 am 12:17 AM

ThestringspackageinGoisessentialforefficientstringmanipulation.1)Itofferssimpleyetpowerfulfunctionsfortaskslikecheckingsubstringsandjoiningstrings.2)IthandlesUnicodewell,withfunctionslikestrings.Fieldsforwhitespace-separatedvalues.3)Forperformance,st

Go bytes package vs strings package: Which should I use?Go bytes package vs strings package: Which should I use?May 14, 2025 am 12:12 AM

WhendecidingbetweenGo'sbytespackageandstringspackage,usebytes.Bufferforbinarydataandstrings.Builderforstringoperations.1)Usebytes.Bufferforworkingwithbyteslices,binarydata,appendingdifferentdatatypes,andwritingtoio.Writer.2)Usestrings.Builderforstrin

How to use the 'strings' package to manipulate strings in Go step by stepHow to use the 'strings' package to manipulate strings in Go step by stepMay 13, 2025 am 12:12 AM

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Go strings package: how to improve my code?Go strings package: how to improve my code?May 13, 2025 am 12:10 AM

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

What are the most useful functions in the GO bytes package?What are the most useful functions in the GO bytes package?May 13, 2025 am 12:09 AM

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Mastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMastering Binary Data Handling with Go's 'encoding/binary' Package: A Comprehensive GuideMay 13, 2025 am 12:07 AM

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools