SERVER_SCRIPT <- normalizePath(file.path("helper", "server.R"), mustWork = TRUE) SE_ADDRESS <- list( cep = "01001000", logradouro = "Pra\u00e7a da S\u00e9", complemento = "lado \u00edmpar", unidade = "", bairro = "S\u00e9", localidade = "S\u00e3o Paulo", uf = "SP", estado = "S\u00e3o Paulo", regiao = "Sudeste", ibge = "3550308", gia = "1004", ddd = "11", siafi = "7107" ) AREAL_FAIXA <- list( localidade = "Areal", uf = "RJ", estado = "Rio de Janeiro", regiao = "Sudeste", ibge = "3300225", cep_ini = "25845001", cep_fim = "25849899", ceps = 118L ) CSV_HEADER <- paste0( "cep,logradouro,complemento,unidade,bairro,localidade,uf,estado,regiao,", "ibge,gia,ddd,siafi" ) json <- function(x) { as.character(jsonlite::toJSON(x, auto_unbox = TRUE)) } csv <- function(rows) { paste0(CSV_HEADER, "\n", paste(rows, collapse = "\n"), "\n") } response <- function(status, body, headers = list()) { list(status = status, body = body, headers = headers) } route <- function(match, ...) { list(match = match, responses = list(...)) } start_server <- function(routes) { directory <- tempfile("cepis-fake-server-") dir.create(directory) routes_path <- file.path(directory, "routes.rds") saveRDS(routes, routes_path) logfile <- file.path(directory, "requests.log") file.create(logfile) readyfile <- file.path(directory, "ready") system2( file.path(R.home("bin"), "Rscript"), shQuote(c(SERVER_SCRIPT, routes_path, logfile, readyfile)), wait = FALSE, stdout = file.path(directory, "stdout"), stderr = file.path(directory, "stderr") ) deadline <- Sys.time() + 30 while (!file.exists(readyfile) && Sys.time() < deadline) { Sys.sleep(0.02) } if (!file.exists(readyfile)) { stop( "the fake server did not start: ", paste(readLines(file.path(directory, "stderr"), warn = FALSE), collapse = " ") ) } port <- readLines(readyfile, warn = FALSE)[[1L]] list( url = paste0("http://127.0.0.1:", port), directory = directory, logfile = logfile ) } stop_server <- function(server) { try( curl::curl_fetch_memory(paste0(server$url, "/__shutdown__")), silent = TRUE ) unlink(server$directory, recursive = TRUE) } calls <- function(server, prefix = "") { lines <- readLines(server$logfile, warn = FALSE) sum(startsWith(lines, prefix)) } with_server <- function(routes, body) { server <- start_server(routes) on.exit(stop_server(server), add = TRUE) client <- cepis_client( base_url = server$url, timeout = 5, backoff_base = 0.001, backoff_max = 0.01 ) body(client, server) } caught <- function(expr) { tryCatch( { force(expr) NULL }, error = function(condition) condition ) } check <- function(label, condition) { if (!isTRUE(condition)) { stop("FAIL: ", label, call. = FALSE) } cat("ok - ", label, "\n", sep = "") invisible(TRUE) } check_condition <- function(label, expr, class) { condition <- caught(expr) check( label, inherits(condition, class) && inherits(condition, "cepis_error") ) invisible(condition) }