FDS
FDS

Reputation: 43

Terraform Custom Provider Use Factories to Test

I’m creating a new Provider, but i have some doubts in provider Factories.

I’m following terraform-provider-scaffolding so in provider_test.go i have the following:

var providerFactories = map[string]func() (*schema.Provider, error){
    "acdcn": func() (*schema.Provider, error) {
        return New("dev")(), nil
    },
}

Then in resource test file i would like access to Provider to be able to use my api client to delete the created resource. I’m trying the following:

provider, err := providerFactories["acdcn"]()

apiClient := provider.Meta().(*client.Client)

But the provider.Meta() is always nil. How i can access to my api client configured in provider?

The Test works well, the resource is created, but i’m unable to destroy the resource inside function configured in CheckDestroy.

EDIT: I notice that i misunderstood the meaning of CheckDestroy key. The test automatically runs the delete resource operation. So that solves my problem. But i maintain the question, how can i access to my api client?

Thanks

Upvotes: 0

Views: 388

Answers (1)

FDS
FDS

Reputation: 43

The Solution that i got from Hashicorp Github:

// This provider can be used in testing code for API calls without requiring
// the use of saving and referencing specific ProviderFactories instances.
//
// PreCheck(t) must be called before using this provider instance.
var testAccProvider *schema.Provider = New("test")

Then the TestCase.PreCheck function can be used to configure that separate instance of the provider, e.g.

// Updating provider_test.go
func testAccPreCheck(t *testing.T) {
    err := testAccProvider.Configure(context.Background(), terraform.NewResourceConfigRaw(nil))

    if err != nil {
        t.Fatal(err)
    }
}

Acceptance test code can then reference the provider client: testAccProvider.Meta().(*ExampleClient) (type asserted to the correct type for your provider).

For more information: Github Issue

Upvotes: 0

Related Questions