gpt4 book ai didi

Groovy HttpBuilder - 获取失败响应的正文

转载 作者:行者123 更新时间:2023-12-03 23:17:29 26 4
gpt4 key购买 nike

我正在尝试使用 Groovy HTTPBuilder 编写一个集成测试,该测试将验证正文中是否返回正确的错误消息以及 HTTP 409 状态消息。但是,我无法弄清楚如何在失败的情况下实际访问 HTTP 响应的正文。

http.request(ENV_URL, Method.POST, ContentType.TEXT) {
uri.path = "/curate/${id}/submit"
contentType = ContentType.JSON
response.failure = { failresp_inner ->
failresp = failresp_inner
}
}

then:
assert failresp.status == 409
// I would like something like
//assert failresp.data == "expected error message"

这是来自服务器的 HTTP 响应的样子:
2013-11-13 18:17:58,726 DEBUG  wire - << "HTTP/1.1 409 Conflict[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Date: Wed, 13 Nov 2013 23:17:58 GMT[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Content-Type: text/plain[\r][\n]"
2013-11-13 18:17:58,726 DEBUG wire - << "Transfer-Encoding: chunked[\r][\n]"
2013-11-13 18:17:58,727 DEBUG wire - << "[\r][\n]"
2013-11-13 18:17:58,728 DEBUG wire - << "E[\r][\n]"
2013-11-13 18:17:58,728 DEBUG wire - << "expected error message"
2013-11-13 18:17:58,728 DEBUG wire - << "[\r][\n]"
2013-11-13 18:17:58,728 DEBUG wire - << "0[\r][\n]"
2013-11-13 18:17:58,728 DEBUG wire - << "[\r][\n]"

最佳答案

我最近在尝试使用 Spock 对我的 REST 端点进行集成测试时遇到了这个问题。我使用 Sam 的回答作为灵感,并最终对其进行了改进,以便继续利用 HttpBuilder 提供的自动转换。折腾了一段时间后,我有了一个聪明的想法,就是将成功处理程序闭包分配给失败处理程序,以标准化行为,而不管返回什么状态代码。

client.handler.failure = client.handler.success

它的一个例子:
...

import static org.apache.http.HttpStatus.*

...

private RESTClient createClient(String username = null, String password = null) {
def client = new RESTClient(BASE_URL)
client.handler.failure = client.handler.success

if(username != null)
client.auth.basic(username, password)

return client
}

...

def unauthenticatedClient = createClient()
def userClient = createClient(USER_USERNAME, USER_PASSWORD)
def adminClient = createClient(ADMIN_USERNAME, ADMIN_PASSWORD)

...

def 'get account'() {
expect:
// unauthenticated tries to get user's account
unauthenticatedClient.get([path: "account/$USER_EMAIL"]).status == SC_UNAUTHENTICATED

// user gets user's account
with(userClient.get([path: "account/$USER_EMAIL"])) {
status == SC_OK
with(responseData) {
email == USER_EMAIL
...
}
}

// user tries to get user2's account
with(userClient.get([path: "account/$USER2_EMAIL"])) {
status == SC_FORBIDDEN
with(responseData) {
message.contains(USER_EMAIL)
message.contains(USER2_EMAIL)
...
}
}

// admin to get user's account
with(adminClient.get([path: "account/$USER_EMAIL"])) {
status == SC_OK
with(responseData) {
email == USER_EMAIL
...
}
}
}

关于Groovy HttpBuilder - 获取失败响应的正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19966548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com