登录
首页 >  Golang >  Go问答

在 Go 中如何处理 Pact 返回的错误请求 (400, 500)?

来源:stackoverflow

时间:2024-03-20 19:15:34 225浏览 收藏

在 Go 中使用 Pact 时,对于不存在的端点状态,StateHandlers 无法直接更改响应。相反,它们通过修改提供者的内部状态来设置测试的初始条件。在测试执行期间,提供者将执行其常规代码并根据设置的状态做出响应。例如,对于不存在的产品状态,StateHandler 将更新数据库或配置存根以反映该状态。

问题内容

我正在公司中采用 pact,但在 golang 上,我们在基本情况下遇到了障碍,即消费者对于一个端点有 2 个状态:

  • given(“存在 id 1 的产品”)。
  • given(“id 2 的产品不存在”)。

我们的麻烦在于不存在的情况。

消费者

mockprovider.addinteraction().
            given("the product with id 66 doesn't exists").
            uponreceiving("a request product 66").
            withrequest(http.methodget, s("/api/v1/product/66")).
            willrespondwith(http.statusnotfound).

提供商

func TestContract(t *testing.T) {

    SetLogLevel("TRACE")
    verifier := HTTPVerifier{}

    err := verifier.VerifyProvider(t, VerifyRequest{
        ProviderBaseURL:            "http://localhost:8080",
        Provider:                   "ms.pact-provider-example-for-go",
        ProviderVersion:            "example",                                            // os.Getenv("APP_SHA"),
        BrokerURL:                  "https://…", // os.Getenv("PACT_BROKER_BASE_URL"),
        PublishVerificationResults: false,
        StateHandlers: StateHandlers{
            "A product with id 1 exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {
                …
                return response, nil
            },
            "A product with id 2 doesn't exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {
                // ???
            },
        },
    })

    require.NoError(t, err)
}

问题

由于 providerstatev3response 是一个地图接口,我们如何返回错误的请求响应?


正确答案


statehandlers 不存在直接更改响应(这可能会影响测试的有效性),它们的存在是为了修改当前测试的提供程序的内部状态。使用状态名称(以及可选的参数)来确定应配置什么状态。

当测试执行时,提供者应该在该状态下执行其通常的代码,并做出相应的响应。

StateHandlers: StateHandlers{
            "A product with id 1 exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {
                // modify internal state of the provider, so that product with ID 1 exists in the database
                return response, nil
            },
            "A product with id 2 doesn't exists": func(setup bool, s ProviderStateV3) (ProviderStateV3Response, error) {
                // modify internal state of the provider, so that product with ID 2 does not exist in the database
            },
        },

存储库中有示例,例如 https://github.com/pact-foundation/pact-go/blob/master/examples/mux/provider/user_service_test.go#L94-L120

状态是抽象的 - 它并不暗示状态是如何配置的。它可以通过更新数据库、配置存根等多种方式实现状态转换。

今天关于《在 Go 中如何处理 Pact 返回的错误请求 (400, 500)?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>