How to mock Pulumi resources in Go unit tests?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goisidealforbeginnersandsuitableforcloudandnetworkservicesduetoitssimplicity,efficiency,andconcurrencyfeatures.1)InstallGofromtheofficialwebsiteandverifywith'goversion'.2)Createandrunyourfirstprogramwith'gorunhello.go'.3)Exploreconcurrencyusinggorout

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
