【问题标题】:Terraform Custom Provider Use Factories to TestTerraform 自定义提供程序使用工厂进行测试
【发布时间】:2022-01-01 22:21:42
【问题描述】:

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

我正在关注 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 客户端?

谢谢

【问题讨论】:

    标签: terraform terraform-provider


    【解决方案1】:

    我从 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 Issue

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 2020-07-08
      • 2013-01-24
      • 2019-11-23
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多