0

我正在创建一个新的提供者,但我对提供者工厂有一些疑问。

我正在关注 terraform-provider-scaffolding 所以在 provider_test.go 我有以下内容:

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

然后在资源测试文件中,我希望访问 Provider 能够使用我的 api 客户端删除创建的资源。我正在尝试以下操作:

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

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

但是 provider.Meta() 总是为零。我如何访问在提供程序中配置的我的 api 客户端?

测试运行良好,资源已创建,但我无法销毁 CheckDestroy 中配置的函数内部资源。

编辑:我注意到我误解了 CheckDestroy 键的含义。测试自动运行删除资源操作。这样就解决了我的问题。但我坚持这个问题,我怎样才能访问我的 api 客户端?

谢谢

4

1 回答 1

0

我从 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")

然后可以使用 TestCase.PreCheck 函数来配置提供者的单独实例,例如

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

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

然后验收测试代码可以引用提供者客户端:testAccProvider.Meta().(*ExampleClient)(类型断言为您的提供者的正确类型)。

更多信息:Github 问题

于 2021-11-26T11:10:46.883 回答