quick question about unit testing at AWS using Gol...
# golang
p
quick question about unit testing at AWS using Golang: • taken -> https://www.pulumi.com/docs/iac/concepts/testing/unit/ I was trying to understand how unit testing applied in Pulumi, here is the code example:
main.go
file:
Copy code
func createInfrastructure(ctx *pulumi.Context) (*infrastructure, error) {
  // actual code is here which creates infrastructure
}
main_test.go
file:
Copy code
import (
	"<http://github.com/pulumi/pulumi/sdk/v3/go/common/resource|github.com/pulumi/pulumi/sdk/v3/go/common/resource>"
	"<http://github.com/pulumi/pulumi/sdk/v3/go/pulumi|github.com/pulumi/pulumi/sdk/v3/go/pulumi>"
)

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) {
	return args.Args, nil
}

// AND TEST FUNCTION

func TestInfrastructure(t *testing.T) {
	err := pulumi.RunErr(func(ctx *pulumi.Context) error {
		infra, err := createInfrastructure(ctx)
		assert.NoError(t, err)

		var wg sync.WaitGroup
		wg.Add(3)

		// TODO(check 1): Instances have a Name tag.
		// TODO(check 2): Instances must not use an inline userData script.
		// TODO(check 3): Instances must not have SSH open to the Internet.

		wg.Wait()
		return nil
	}, pulumi.WithMocks("project", "stack", mocks(0)))
	assert.NoError(t, err)
}
And last an example for TODO(check 1)
Copy code
// check 1: Instances have a Name tag.
pulumi.All(infra.server.URN(), infra.server.Tags).ApplyT(func(all []interface{}) error {
	urn := all[0].(pulumi.URN)
	tags := all[1].(map[string]string)

	assert.Containsf(t, tags, "Name", "missing a Name tag on server %v", urn)
	wg.Done()
	return nil
})
So my question here is, I would expect that inside
TestInfrastructure
function, we are somehow not calling actual
createInfrastructure
function so we don't wait for apicalls to finish, Actually I would expect we call it but I would expect we are using some sort of dependency injection approach with an interface and passing mock interface instead I couldn't understand how we are using mock API under the hood?
@victorious-church-57397 maybe you have some ideas šŸ™‚
f
there's a few golang things going on here - main things imo to notice are
type mocks int
(defining the mock impl, which ends up as a
MockResourceMonitor
interface)
func (mocks)
(defining the receiver as the mock)
pulumi.RunErr
and
pulumi.WithMocks("project", "stack", mocks(0))
(running a
pulumi up
using the mock)