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

huangapple go评论95阅读模式
英文:

How to Mock Pulumi Resources in Go Unit Tests?

问题

我有一个函数,它接受一个 AWS OpenIdConnectProvider Pulumi 资源作为输入,并创建一个带有附加的 AssumeRolePolicy 的 IAM 角色,其中包含来自该 OIDC 提供程序的信息。

问题是:我正在尝试为这个函数编写一个测试,并模拟一个 OIDC 提供程序作为函数调用的输入。我在如何正确模拟这个过程中遇到了困难,目前看起来模拟的数据并不像我期望的那样显示。

看起来我没有正确使用模拟,但我参考了这里的示例(https://github.com/pulumi/examples/blob/master/testing-unit-go/main_test.go)。

更多文档请参考这里(https://www.pulumi.com/docs/guides/testing/unit/)。

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 {

		// 获取模拟的 OIDC 提供程序,用作 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)

		// 检查1:Assume Role Policy 是否正确格式化
		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:*",
"system:serviceaccount:kube-system:cluster-autoscaler"
Test:       	TestCreateMyCustomRole

<details>
<summary>英文:</summary>
I have a function that takes an input of an AWS OpenIdConnectProvider Pulumi Resource and creates a IAM Role with an AssumeRolePolicy attached that contains info from that OIDC provider. 
**The Problem:** I am trying to write a test for this function and mock out a OIDC provider to feed in as input for the function call. I&#39;m having trouble understanding how to properly mock this so that the test output shows what I expect, currently it appears that the mocked data isn&#39;t coming up like I&#39;d expect. 
It seems like I&#39;m not using the mock correctly, but I went off the [example here](https://github.com/pulumi/examples/blob/master/testing-unit-go/main_test.go)
[Further Docs here](https://www.pulumi.com/docs/guides/testing/unit/)
```go
package myPkg
import (
&quot;github.com/pulumi/pulumi-aws/sdk/v5/go/aws/iam&quot;
&quot;github.com/pulumi/pulumi/sdk/v3/go/pulumi&quot;
)
func CreateMyCustomRole(ctx *pulumi.Context, name string, oidcProvider *iam.OpenIdConnectProvider, opts ...pulumi.ResourceOption) (*iam.Role, error) {
role := &amp;iam.Role{}
componentURN := fmt.Sprintf(&quot;%s-custom-role&quot;, name)
err := ctx.RegisterComponentResource(&quot;pkg:aws:MyCustomRole&quot;, componentURN, role, opts...)
if err != nil {
return nil, err
}
url := oidc.Url.ApplyT(func(s string) string {
return fmt.Sprint(strings.ReplaceAll(s, &quot;https://&quot;, &quot;&quot;), &quot;:sub&quot;)
}).(pulumi.StringOutput)
assumeRolePolicy := pulumi.Sprintf(`{
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [{
&quot;Effect&quot;: &quot;Allow&quot;,
&quot;Principal&quot;: { &quot;Federated&quot;: &quot;%s&quot; },
&quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,
&quot;Condition&quot;: {
&quot;StringEquals&quot;: {
&quot;%s&quot;: [
&quot;system:serviceaccount:kube-system:*&quot;,
&quot;system:serviceaccount:kube-system:cluster-autoscaler&quot;
]
}
}
}]
}`, oidcProvider.Arn, url)
roleURN := fmt.Sprintf(&quot;%s-custom-role&quot;, name)
role, err = iam.NewRole(ctx, roleURN, &amp;iam.RoleArgs{
Name:             pulumi.String(roleURN),
Description:      pulumi.String(&quot;Create Custom Role&quot;),
AssumeRolePolicy: assumeRolePolicy,
Tags:             pulumi.ToStringMap(map[string]string{&quot;project&quot;: &quot;test&quot;}),
})
if err != nil {
return nil, err
}
return role, nil
}
package myPkg

import (
	&quot;sync&quot;
	&quot;testing&quot;

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

type mocks int

func (mocks) NewResource(args pulumi.MockResourceArgs) (string, resource.PropertyMap, error) {
	return args.Name + &quot;_id&quot;, args.Inputs, nil
}

func (mocks) Call(args pulumi.MockCallArgs) (resource.PropertyMap, error) {
	outputs := map[string]interface{}{}
	if args.Token == &quot;aws:iam/getOpenidConnectProvider:getOpenidConnectProvider&quot; {
		outputs[&quot;arn&quot;] = &quot;arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc&quot;
		outputs[&quot;id&quot;] = &quot;abc&quot;
		outputs[&quot;url&quot;] = &quot;https://someurl&quot;
	}
	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, &quot;get-test-oidc-provider&quot;, pulumi.ID(&quot;abc&quot;), &amp;iam.OpenIdConnectProviderState{})
		assert.NoError(t, err)

		infra, err := CreateMyCustomRole(ctx, &quot;role1&quot;, 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, `{
			&quot;Version&quot;: &quot;2012-10-17&quot;,
			&quot;Statement&quot;: [{
				&quot;Effect&quot;: &quot;Allow&quot;,
				&quot;Principal&quot;: { &quot;Federated&quot;: &quot;arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc&quot; },
				&quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,
				&quot;Condition&quot;: {
					&quot;StringEquals&quot;: {
						&quot;someurl:sub&quot;: [
							&quot;system:serviceaccount:kube-system:*&quot;,
							&quot;system:serviceaccount:kube-system:cluster-autoscaler&quot;
						]
					}
            	}
			}]
		}`, assumeRolePolicy)

			wg.Done()
			return nil
		})

		wg.Wait()
		return nil
	}, pulumi.WithMocks(&quot;project&quot;, &quot;stack&quot;, mocks(0)))
	assert.NoError(t, err)
}

Output
    	            	Diff:
--- Expected
+++ Actual
@@ -4,3 +4,3 @@
&quot;Effect&quot;: &quot;Allow&quot;,
-				&quot;Principal&quot;: { &quot;Federated&quot;: &quot;arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc&quot; },
+				&quot;Principal&quot;: { &quot;Federated&quot;: &quot;&quot; },
&quot;Action&quot;: &quot;sts:AssumeRoleWithWebIdentity&quot;,
@@ -8,3 +8,3 @@
&quot;StringEquals&quot;: {
-						&quot;someurl:sub&quot;: [
+						&quot;:sub&quot;: [
&quot;system:serviceaccount:kube-system:*&quot;,
Test:       	TestCreateMyCustomRole

</details>
# 答案1
**得分**: 1
原来我在使用`NewResource`时弄错了。
当在测试函数中调用`GetOpenIdConnectProvider`时,它会读取一个资源并创建一个新的资源输出,从而触发对`mocks.NewResource`的调用。
修复的方法是在`NewResource`函数调用中为`GetOpenIdConnectProvider`返回的资源类型`openIdConnectProvider`定义一个if语句,并使用模拟的输出。
```go
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
}

在下面的代码片段中,我更改了assert,以便它失败并显示对NewResource进行的更改后的差异。

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

Turns out I was using the NewResource wrong.

When GetOpenIdConnectProvider is called in the test function it goes to read a resource and create a new resource output which triggers the call to mocks.NewResource

The fix was to instead define an if statement for the resource type returned by the GetOpenIdConnectProvider openIdConnectProviderin the NewResource function call with the mocked outputs.

func (mocks) NewResource(args pulumi.MockResourceArgs) (string, resource.PropertyMap, error) {
	pulumi.Printf(args.TypeToken)
	outputs := args.Inputs.Mappable()
	if args.TypeToken == &quot;aws:iam/openIdConnectProvider:OpenIdConnectProvider&quot; {
		outputs[&quot;arn&quot;] = &quot;arn:aws:iam::123:oidc-provider/oidc.eks.us-west-2.amazonaws.com/id/abc&quot;
		outputs[&quot;id&quot;] = &quot;abc&quot;
		outputs[&quot;url&quot;] = &quot;https://someurl&quot;
	}
	return args.Name + &quot;_id&quot;, resource.NewPropertyMapFromMap(outputs), nil
}

func (mocks) Call(args pulumi.MockCallArgs) (resource.PropertyMap, error) {
    outputs := map[string]interface{}{}
    return resource.NewPropertyMapFromMap(outputs), nil
}

Is this below code snippet I changed the assert so that it fails to show what the diff now looks like with the changes made to NewResource above

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

huangapple
  • 本文由 发表于 2023年4月14日 03:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76009185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定