"httptest2" 是专门设计用于测试 "httr2" 请求的:
httptest2
is specifically designed to test httr2
requests:
该软件包有助于编写使用 httr2
的软件包的测试。
不幸的是,
gh
使用 httr
:
Imports:
cli (>= 3.0.1),
gitcreds,
httr (>= 1.2),
ini,
jsonlite
这意味着你不能直接使用
httptest2
和
gh
。
但是,通过使用
gh
源代码,你可以提取由
gh
发送到
httr
的
GET
请求的参数:
gh_get <- function(endpoint, ..., per_page = NULL, .token = NULL, .destfile = NULL,
.overwrite = FALSE, .api_url = NULL, .method = "GET",
.limit = NULL, .accept = "application/vnd.github.v3+json",
.send_headers = NULL, .progress = TRUE, .params = list()) {
params <- c(list(...), .params)
params <- gh:::drop_named_nulls(params)
if (is.null(per_page)) {
if (!is.null(.limit)) {
per_page <- max(min(.limit, 100), 1)
}
}
if (!is.null(per_page)) {
params <- c(params, list(per_page = per_page))
}
req <- gh:::gh_build_request(
endpoint = endpoint, params = params,
token = .token, destfile = .destfile,
overwrite = .overwrite, accept = .accept,
send_headers = .send_headers,
api_url = .api_url, method = .method
)
req
}
req <- gh_get("GET /repos/r-lib/gh")
req
这样做可以使用你提供的示例,使用
httr2
发送相同的请求:
library(httr2)
resp_httr2 <- request(base_url=req$url) %>%
req_perform() %>%
resp_body_json()
如果您主要关注的是 JSON 内容,结果是相同的,只是属性不同:
resp_gh <- gh::gh("GET /repos/r-lib/gh")
all.equal(resp_gh,resp_httr2,check.attributes=FALSE)
如果你想使用
httptest2
,切换到
httr2
会起作用:
with_mock_dir("gh", {
test_that("api works", {
resp <- request(base_url=req$url) %>%
req_perform() %>%
resp_body_json()
expect_equal(resp$full_name,"r-lib/gh")})
})
离线测试现在可行,因为
httptest2
创建了
gh\api.github.com
目录。