From 03cda62531c06ffbbe7a81c051e8213c65698fed Mon Sep 17 00:00:00 2001 From: wkmor1 Date: Thu, 23 Jan 2025 12:35:12 +0200 Subject: [PATCH] Add test for JSON parsing errors --- R/api_get.R | 16 +++++++---- tests/testthat/test-finbif_taxa.R | 47 +++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/R/api_get.R b/R/api_get.R index 04af5eb8..bd879421 100644 --- a/R/api_get.R +++ b/R/api_get.R @@ -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) @@ -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) diff --git a/tests/testthat/test-finbif_taxa.R b/tests/testthat/test-finbif_taxa.R index 9bc7344b..d3c9e36a 100644 --- a/tests/testthat/test-finbif_taxa.R +++ b/tests/testthat/test-finbif_taxa.R @@ -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) + +})