Skip to content

Commit

Permalink
Add test for JSON parsing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
wkmor1 committed Jan 23, 2025
1 parent 1159243 commit 03cda62
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 5 deletions.
16 changes: 11 additions & 5 deletions R/api_get.R
Original file line number Diff line number Diff line change
Expand Up @@ -247,9 +247,17 @@ api_get <- function(obj) {

txt <- httr::content(resp, type = "text", encoding = "UTF-8")

valid <- jsonlite::validate(txt)
if (!jsonlite::validate(txt)) {

if (!identical(resp[["status_code"]], 200L) || !valid) {
obj <- NULL

err_msg <- paste0("API response parsing failed\n", txt)

stop(err_msg, call. = FALSE)

}

if (!identical(resp[["status_code"]], 200L)) {

parsed <- httr::content(resp)

Expand All @@ -259,9 +267,7 @@ api_get <- function(obj) {
"API request failed [",
resp[["status_code"]],
"]\n",
parsed[["message"]],
"\n",
txt
parsed[["message"]]
)

stop(err_msg, call. = FALSE)
Expand Down
47 changes: 47 additions & 0 deletions tests/testthat/test-finbif_taxa.R
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,50 @@ test_that("searching for taxa works", {
options(op)

})

test_that("invalid json triggers error", {

skip_on_cran()

op <- options()

f <- tempfile()

if (
requireNamespace("callr", quietly = TRUE) &&
requireNamespace("webfakes", quietly = TRUE)
) {

bg <- callr::r_bg(
function(file, version) {

app <- webfakes::new_app()

app[["get"]](
sprintf("/%s/taxa/search", version),
function(req, res) {
res[["send_json"]](text = "'invalid json]")
}
)

web <- webfakes::local_app_process(app)

cat(c(web[["url"]](), "."), file = file, sep = "\n")

Sys.sleep(60L)

},
list(file = f, version = getOption("finbif_api_version"))
)

while (!file.exists(f) || length(url <- readLines(f, warn = FALSE)) < 2L) {}

options(finbif_api_url = sub("/$", "", url[[1L]]), finbif_rate_limit = Inf)

expect_error(finbif_taxa("Invalid JSON"), "API response parsing failed")

}

options(op)

})

0 comments on commit 03cda62

Please sign in to comment.