【问题标题】:How can I test validation functionality in a terraform provider如何在 terraform 提供程序中测试验证功能
【发布时间】:2021-10-17 02:57:30
【问题描述】:

我已经为需要在自定义 terraform 提供程序中验证的字段编写了一些更复杂的验证逻辑。当然,我可以测试这些是单元测试,但这还不够;如果我忘记实际应用验证器,为什么?

所以,我需要实际使用 terraform config 并让提供者执行这是正常、自然的事情。

基本上,我预计它会出错。该文档似乎表明我应该对输出进行正则表达式匹配。但这不可能是正确的;看起来超级脆。谁能告诉我这是怎么做到的?

func TestValidation(t *testing.T) {
    const userBasic = `
        resource "my_user" "dude" {
            name    = "the.dude%d"
            password = "Password1" // needs a special char to pass
            email   = "the.dude%d@domain.com"
            groups  = [ "readers" ]
        }
    `
    rgx, _ := regexp.Compile("abc")
    resource.UnitTest(t, resource.TestCase{
        Providers:    testAccProviders,
        Steps: []resource.TestStep{
            {
                Config: userBasic,
                ExpectError: rgx,
            },
        },
    })
}

这段代码显然不起作用。而且,很多研究都没有给出答案。

【问题讨论】:

  • 完全不相关,但你知道在测试中你可以使用regexp.MustCompile,它返回一个正则表达式或恐慌,而不是regexp.Compile,它返回一个错误。
  • 感谢您的意见

标签: go terraform terraform-provider


【解决方案1】:

由于 sdk 版本 2.3.0 您可以在 resource.TestCase 上设置 ErrorCheck 函数以提供更复杂的错误验证。

例如:

resource.UnitTest(t, resource.TestCase{
    Providers:  testAccProviders,
    ErrorCheck: func(err error) error {
        if err == nil {
            return errors.New("expected error but got none")
        }

        // your validation code here

        // some simple example with string matching
        if strings.Contains(err.Error(), "your expected error message blah") {
           return nil
        }

        // return original error if no match
        return err
    },
    Steps: []resource.TestStep{
        {
            Config: userBasic,
        },
    },
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2012-09-04
    • 1970-01-01
    • 2020-05-16
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多