content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Get the http interactions of the current cassette #' #' @export #' @return object of class `HTTPInteractionList` if there is a current #' cassette in use, or `NullList` if no cassette in use #' @examples \dontrun{ #' vcr_configure(dir = tempdir()) #' insert_cassette("foo_bar") #' webmockr::webmockr_allow_net_connect() #' library(crul) #' cli <- crul::HttpClient$new("https://eu.httpbin.org/get") #' one <- cli$get(query = list(a = 5)) #' z <- http_interactions() #' z #' z$interactions #' z$used_interactions #' # on eject, request written to the cassette #' eject_cassette("foo_bar") #' #' # insert cassette again #' insert_cassette("foo_bar") #' # now interactions will be present #' z <- http_interactions() #' z$interactions #' z$used_interactions #' invisible(cli$get(query = list(a = 5))) #' z$used_interactions #' #' # cleanup #' unlink(file.path(tempdir(), "foo_bar.yml")) #' } http_interactions <- function() { trycurr <- tryCatch(current_cassette(), error = function(e) e) if (!inherits(trycurr, "error")) return(trycurr$http_interactions_) NullList$new() }
/scratch/gouwar.j/cran-all/cranData/vcr/R/http_interactions.R
vcr__env <- new.env() #' Insert a cassette to record HTTP requests #' #' @export #' @inheritParams use_cassette #' @inheritSection use_cassette Cassette options #' @inherit check_cassette_names details #' @seealso [use_cassette()], [eject_cassette()] #' @return an object of class `Cassette` #' @examples \dontrun{ #' library(vcr) #' library(crul) #' vcr_configure(dir = tempdir()) #' webmockr::webmockr_allow_net_connect() #' #' (x <- insert_cassette(name = "leo5")) #' current_cassette() #' x$new_recorded_interactions #' x$previously_recorded_interactions() #' cli <- crul::HttpClient$new(url = "https://httpbin.org") #' cli$get("get") #' x$new_recorded_interactions # 1 interaction #' x$previously_recorded_interactions() # empty #' webmockr::stub_registry() # not empty #' # very important when using inject_cassette: eject when done #' x$eject() # same as eject_cassette("leo5") #' x$new_recorded_interactions # same, 1 interaction #' x$previously_recorded_interactions() # now not empty #' ## stub_registry now empty, eject() calls webmockr::disable(), which #' ## calls the disable method for each of crul and httr adadapters, #' ## which calls webmockr's remove_stubs() method for each adapter #' webmockr::stub_registry() #' #' # cleanup #' unlink(file.path(tempdir(), "leo5.yml")) #' } insert_cassette <- function(name, record = NULL, match_requests_on = NULL, update_content_length_header = FALSE, allow_playback_repeats = FALSE, serialize_with = NULL, persist_with = NULL, preserve_exact_body_bytes = NULL, re_record_interval = NULL, clean_outdated_http_interactions = NULL) { check_cassette_name(name) vcr_env_handle() if (turned_on()) { if ( any( name %in% names(cassettes_session()) ) ) { stop(sprintf("There is already a cassette with the same name: %s", name), "\n see ?eject_cassette") } # enable webmockr webmockr::enable(quiet=vcr_c$quiet) sup_mssg(vcr_c$quiet, webmockr::webmockr_allow_net_connect()) # record cassete name for use in logging, etc. vcr__env$current_cassette <- name # make cassette tmp <- Cassette$new(name, record = record %||% vcr_c$record, match_requests_on = match_requests_on %||% vcr_c$match_requests_on, update_content_length_header = update_content_length_header, allow_playback_repeats = allow_playback_repeats, serialize_with = serialize_with %||% vcr_c$serialize_with, persist_with = persist_with %||% vcr_c$persist_with, preserve_exact_body_bytes = preserve_exact_body_bytes %||% vcr_c$preserve_exact_body_bytes, re_record_interval = re_record_interval %||% vcr_c$re_record_interval, clean_outdated_http_interactions = clean_outdated_http_interactions %||% vcr_c$clean_outdated_http_interactions, tag = NULL, tags = NULL, allow_unused_http_interactions = NULL, exclusive = NULL ) return(tmp) } else if (!light_switch$ignore_cassettes) { message <- "vcr is turned off. You must turn it on before you can insert a cassette. Or you can set ignore_cassettes=TRUE option to completely ignore cassette insertions." stop(message) } else { # vcr is turned off and `ignore_cassettes=TRUE`, returns NULL return(NULL) } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/insert_cassette.R
#' Turn vcr on and off, check on/off status, and turn off for a given http call #' #' @export #' @name lightswitch #' @param ... Any block of code to run, presumably an http request #' @param ignore_cassettes (logical) Controls what happens when a cassette is #' inserted while vcr is turned off. If `TRUE` is passed, the cassette #' insertion will be ignored; otherwise an error will be raised. #' Default: `FALSE` #' @includeRmd man/rmdhunks/lightswitch.Rmd #' @examples \dontrun{ #' vcr_configure(dir = tempdir()) #' #' turn_on() #' turned_on() #' turn_off() #' #' # turn off for duration of a block #' library(crul) #' turned_off({ #' res <- HttpClient$new(url = "https://eu.httpbin.org/get")$get() #' }) #' res #' #' # turn completely off #' turn_off() #' library(webmockr) #' crul::mock() #' # HttpClient$new(url = "https://eu.httpbin.org/get")$get(verbose = TRUE) #' turn_on() #' } turned_off <- function(..., ignore_cassettes = FALSE) { turn_off(ignore_cassettes = ignore_cassettes) on.exit(turn_on()) force(...) } #' @rdname lightswitch #' @export turn_on <- function() { light_switch$turned_off <- FALSE } #' @rdname lightswitch #' @export turned_on <- function() { !light_switch$turned_off } #' @export #' @rdname lightswitch turn_off <- function(ignore_cassettes = FALSE) { cassette <- tryCatch(current_cassette(), error = function(e) e) if (!inherits(cassette, "error")) { if (length(cassette) != 0) { stop( sprintf( "A vcr cassette is currently in use: %s.\n You must eject it before you can turn vcr off", cassette$name), call. = FALSE) } } light_switch$ignore_cassettes <- ignore_cassettes message("vcr turned off; see ?turn_on to turn vcr back on") light_switch$turned_off <- TRUE } # environment variable handlers vcr_env_mssg <- "invalid option for env var: '%s'; see ?vcr::lightswitch" vcr_env_handle <- function() { vcr_env_turn_off() vcr_env_turned_off() vcr_env_ignore_cassettes() } catch_error <- function(x) tryCatch(x, error = function(e) e) vcr_env_var_check <- function(x, var) { if (!inherits(x, "logical") || length(x) != 1 || all(is.na(x))) stop(sprintf(vcr_env_mssg, var), call. = FALSE) } vcr_env_turn_off <- function() { var <- "VCR_TURN_OFF" x <- Sys.getenv(var, "") if (x != "") { x <- as.logical(x) vcr_env_var_check(x, var) light_switch$ignore_cassettes <- x light_switch$turned_off <- x } } vcr_env_turned_off <- function() { var <- "VCR_TURNED_OFF" x <- Sys.getenv(var, "") if (x != "") { x <- as.logical(x) vcr_env_var_check(x, var) light_switch$turned_off <- x } } vcr_env_ignore_cassettes <- function() { var <- "VCR_IGNORE_CASSETTES" x <- Sys.getenv(var, "") if (x != "") { x <- as.logical(x) vcr_env_var_check(x, var) light_switch$ignore_cassettes <- x } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/lightswitch.R
vcr_log_env <- new.env() #' vcr log file setup #' #' @export #' @name vcr_logging #' @keywords internal #' @param file (character) a file path, required #' @param message (character) a message to log #' @param overwrite (logical) whether or not to overwrite the file at #' 'file' if it already exists. Default: `TRUE` #' @param include_date (logical) include date and time in each log entry. #' Default: `FALSE` #' @examples #' # user workflow #' vcr_configuration() #' logfile <- file.path(tempdir(), "vcr.log") #' vcr_configure(dir = tempdir(), log = TRUE, log_opts = list(file = logfile)) #' #' readLines(logfile) # empty #' #' # log messages #' vcr_log_info("hello world!") #' readLines(logfile) #' vcr_log_info("foo bar") #' readLines(logfile) #' ## many messages #' vcr_log_info(c("brown cow", "blue horse")) #' readLines(logfile) #' vcr_log_info(c("brown cow", "blue horse", "green goat")) #' readLines(logfile) #' #' # standalone workflow #' # set a file to log to #' vcr_log_file((f <- tempfile())) #' readLines(f) # empty #' #' # log messages #' vcr_log_info("hello world!") #' readLines(logfile) #' vcr_log_info("foo bar") #' readLines(logfile) #' #' # cleanup #' unlink(f) #' unlink(logfile) # FIXME: add # indentation = ' ' * indentation_level #' @export #' @rdname vcr_logging vcr_log_file <- function(file, overwrite = TRUE) { assert(file, 'character') assert(overwrite, 'logical') if (file != "console") { if (!file.exists(file)) { file.create(file) } else if (file.exists(file) && overwrite) { file.remove(file) file.create(file) } else { stop('file exists and overwrite=FALSE') } } # save file name vcr_log_env$file <- file return(TRUE) } #' @export #' @rdname vcr_logging vcr_log_info <- function(message, include_date = TRUE) { if (include_date) message <- paste(as.character(Sys.time()), "-", message) message <- paste(make_prefix(), "-", message) vcr_log_write(message) } make_prefix <- function() { sprintf("[%s: '%s']", vcr_c$log_opts$log_prefix, vcr__env$current_cassette %||% "<none>") } vcr_log_write <- function(message) { if (vcr_c$log) { if (is.null(vcr_log_env$file)) { stop("no connection set up to write to, see ?vcr_logging") } if (vcr_log_env$file == "console") { cat(message, sep = "\n", append = TRUE) } else { cat(message, sep = "\n", file = vcr_log_env$file, append = TRUE) } } } trailing_newline <- function(str) { if (grepl("\n$", str)) str else paste0(str, "\n") }
/scratch/gouwar.j/cran-all/cranData/vcr/R/logger.R
get_method <- function(x) { x <- as.character(x) tmp <- grep( "(get)$|(post)$|(put)$|(delete)$|(options)$|(patch)$|(head)$", tolower(x), value = TRUE) tmp <- sub("httr::", "", tmp) if (length(tmp) == 0) NULL else tmp } is_url <- function(x) { grepl( "https?://", x, ignore.case = TRUE) || grepl("localhost:[0-9]{4}", x, ignore.case = TRUE ) } get_uri <- function(x) { x <- as.character(x) tmp <- x[vapply(x, is_url, logical(1))] if (length(tmp) == 0) NULL else tmp } get_host <- function(x) { eval(parse(text = x))(x)$hostname } get_path <- function(x) { eval(parse(text = vcr_c$uri_parser))(x)$path } get_query <- function(x) { if ("query" %in% names(x)) { x[["query"]] } else { NULL } } parseurl <- function(x) { tmp <- urltools::url_parse(x) tmp <- as.list(tmp) if (!is.na(tmp$parameter)) { tmp$parameter <- sapply(strsplit(tmp$parameter, "&")[[1]], function(z) { zz <- strsplit(z, split = "=")[[1]] as.list(stats::setNames(zz[2], zz[1])) }, USE.NAMES = FALSE) } tmp }
/scratch/gouwar.j/cran-all/cranData/vcr/R/match_helpers.R
vcr_c <- NULL # nocov start VCRHooks <- NULL request_matchers <- NULL request_ignorer <- NULL cassette_serializers <- NULL cassette_persisters <- NULL light_switch <- NULL vcr_cassettes <- NULL initialize_ivars <- function() { light_switch <<- new.env() light_switch$turned_off <<- FALSE light_switch$ignore_cassettes <<- FALSE vcr_c$cassettes <<- list() vcr_c$linked_context <<- NULL request_matchers <<- RequestMatcherRegistry$new() request_ignorer <<- RequestIgnorer$new() cassette_serializers <<- Serializers$new() cassette_persisters <<- Persisters$new() } .onLoad <- function(libname, pkgname){ # initialize vcr config object vcr_c <<- VCRConfig$new() # initialize hooks VCRHooks <<- Hooks$new() # initialize bucket of cassettes in session vcr_cassettes <<- new.env() # lots of things initialize_ivars() } # nocov end
/scratch/gouwar.j/cran-all/cranData/vcr/R/onLoad.R
# vcr_configure(dir = tempdir()) # # (yy <- FileSystem$new(file_name = "file4014931b21b.yml")) # yy$set_cassette(content = "hello world!") # # # is empty? # yy$is_empty() # # # get cassette # yy$get_cassette(file_name = "file4014931b21b.yml") # # # clenaup # unlink(file.path(tempdir(), "file4014931b21b.yml")) #' @title File system persister #' @description The only built-in cassette persister. Persists cassettes #' to the file system. #' @keywords internal #' @details #' \strong{Private Methods} #' \describe{ #' \item{\code{storage_location()}}{ #' Get storage location #' } #' \item{\code{absolute_path_to_file()}}{ #' Get absolute path to the `storage_location` #' } #' } FileSystem <- R6::R6Class("FileSystem", public = list( #' @field file_name (character) the file name, not whole path file_name = NULL, #' @field write_fxn (character) fxn to use for writing to disk write_fxn = NULL, #' @field content (character) content to record to a cassette content = NULL, #' @field path (character) storage directory for cassettes path = NULL, #' @field write2disk (character) write to disk or make a new FileSystem write2disk = FALSE, #' @description Create a new `FileSystem` object #' @param file_name (character) the file name, not whole path #' @param write_fxn (character) fxn to use for writing to disk #' @param content (character) content to record to a cassette #' @param path (character) storage directory for cassettes #' @param write2disk (logical) write to disk or just make a new FileSystem #' object. Default: `FALSE` #' @return A new `FileSystem` object initialize = function(file_name = NULL, write_fxn = NULL, content = NULL, path = NULL, write2disk = FALSE) { self$file_name <- file_name self$content <- content self$write_fxn <- write_fxn self$write2disk <- write2disk self$path <- if (is.null(path)) cassette_path() else path # write to disk if (self$write2disk) self$write_fxn(self$content, self$path) }, #' @description Gets the cassette for the given storage key (file name) #' @param file_name (character) the file name, not whole path #' @return named list, from `yaml::yaml.load_file` get_cassette = function(file_name = NULL) { file_name <- if (is.null(file_name)) self$file_name else file_name if (is.null(file_name)) stop('No file name provided', call. = FALSE) path <- private$absolute_path_to_file(self$path, file_name) if (!file.exists(path)) stop("File doesn't exist", call. = FALSE) yaml::yaml.load_file(path) }, #' @description Checks if a cassette is empty or not #' @return logical is_empty = function() { if (is.null(self$file_name)) stop('No file name provided', call. = FALSE) path <- private$absolute_path_to_file(self$path, self$file_name) if (!file.exists(path)) return(TRUE) if (is.null(yaml::yaml.load_file(path))) { return(TRUE) } else { return(FALSE) } }, #' @description Sets the cassette for the given storage key (file name) #' @param file_name (character) the file name, not whole path #' @param content (character) content to record to a cassette #' @return no return; writes to disk set_cassette = function(file_name = NULL, content) { file_name <- if (is.null(file_name)) self$file_name else file_name if (is.null(file_name)) stop('No file name provided', call. = FALSE) path <- private$absolute_path_to_file(self$path, file_name) directory <- dirname(path) if (!file.exists(directory)) { dir.create(directory, recursive = TRUE, showWarnings = TRUE) } cat(yaml::as.yaml(content), file = path) } ), private = list( storage_location = function() { self$path }, absolute_path_to_file = function(x, y) { if (is.null(self$path)) { NULL } else { path.expand(file.path(x, y)) } } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/persisters-file.R
#' @title Cassette persisters #' @description Keeps track of the cassette persisters in a hash-like object #' @export #' @keywords internal #' @details There's only one option: `FileSystem` #' \strong{Private Methods} #' \describe{ #' \item{\code{persister_get()}}{ #' Gets and sets a named persister #' } #' } #' @examples #' (aa <- Persisters$new()) #' aa$name #' aa$persisters #' yaml_serializer <- aa$persisters$new() #' yaml_serializer Persisters <- R6::R6Class( "Persisters", public = list( #' @field persisters (list) internal use, holds persister object persisters = list(), #' @field name (character) name = "FileSystem", #' @description Create a new `Persisters` object #' @param persisters (list) a list #' @param name (character) Persister name, only option right now #' is "FileSystem" #' @return A new `Persisters` object initialize = function(persisters = list(), name = "FileSystem") { self$persisters <- persisters self$name <- name private$persister_get() } ), private = list( # Gets and sets a named persister persister_get = function() { if (!self$name %in% 'FileSystem') { stop(sprintf("The requested VCR cassette persister (%s) is not registered.", self$name), call. = FALSE) } self$persisters <- switch(self$name, FileSystem = FileSystem) } ) ) #' @rdname Persisters persister_fetch <- function(x = "FileSystem", file_name) { per <- Persisters$new(name = x) per <- per$persisters per$new(file_name = file_name) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/persisters.R
#' @export print.cassette <- function(x, ...){ cat(paste0("<cassette> ", x$name), sep = "\n") cat(paste0(" Recorded at: ", if (!is.null(x$recorded_at)) x$recorded_at), sep = "\n") cat(paste0(" Recorded with: ", if (!is.null(x$recorded_at)) x$recorded_with), sep = "\n") }
/scratch/gouwar.j/cran-all/cranData/vcr/R/print_cassette.R
#' Are real http connections allowed? #' #' @export #' @return boolean, `TRUE` if real HTTP requests allowed; `FALSE` if not #' @examples #' real_http_connections_allowed() real_http_connections_allowed <- function() { trycurr <- tryCatch(current_cassette(), error = function(e) e) if (!inherits(trycurr, c("error", "list"))) return(current_cassette()$recording()) if (identical(trycurr, list())) return(FALSE) !(vcr_c$allow_http_connections_when_no_cassette || !turned_on()) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/real_connections.R
#' vcr recording options #' #' @includeRmd man/rmdhunks/record-modes.Rmd #' #' @name recording NULL
/scratch/gouwar.j/cran-all/cranData/vcr/R/recording.R
#' @title The request of an HTTPInteraction #' @description object that handled all aspects of a request #' @export #' @keywords internal #' @examples #' url <- "https://eu.httpbin.org/post" #' body <- list(foo = "bar") #' headers <- list( #' `User-Agent` = "libcurl/7.54.0 r-curl/3.2 crul/0.5.2", #' `Accept-Encoding` = "gzip, deflate", #' Accept = "application/json, text/xml, application/xml, */*" #' ) #' #' (x <- Request$new("POST", url, body, headers)) #' x$body #' x$method #' x$uri #' x$host #' x$path #' x$headers #' h <- x$to_hash() #' x$from_hash(h) Request <- R6::R6Class( 'Request', public = list( #' @field method (character) http method method = NULL, #' @field uri (character) a uri uri = NULL, #' @field scheme (character) scheme (http or https) scheme = NULL, #' @field host (character) host (e.g., stuff.org) host = NULL, #' @field path (character) path (e.g., foo/bar) path = NULL, #' @field query (character) query params, named list query = NULL, #' @field body (character) named list body = NULL, #' @field headers (character) named list headers = NULL, #' @field skip_port_stripping (logical) whether to strip thhe port skip_port_stripping = FALSE, #' @field hash (character) a named list - internal use hash = NULL, #' @field opts (character) options - internal use opts = NULL, #' @field disk (logical) xx disk = NULL, #' @field fields (various) request body details fields = NULL, #' @field output (various) request output details, disk, memory, etc output = NULL, #' @description Create a new `Request` object #' @param method (character) the HTTP method (i.e. head, options, get, #' post, put, patch or delete) #' @param uri (character) request URI #' @param body (character) request body #' @param headers (named list) request headers #' @param opts (named list) options internal use #' @param disk (boolean), is body a file on disk #' @param fields (various) post fields #' @param output (various) output details #' @return A new `Request` object initialize = function(method, uri, body, headers, opts, disk, fields, output) { if (!missing(method)) self$method <- tolower(method) if (!missing(body)) { if (inherits(body, "list")) { body <- paste(names(body), body, sep = "=", collapse = ",") } self$body <- body } if (!missing(headers)) self$headers <- headers if (!missing(uri)) { if (!self$skip_port_stripping) { self$uri <- private$without_standard_port(uri) } else { self$uri <- uri } # parse URI to get host and path tmp <- eval(parse(text = vcr_c$uri_parser))(self$uri) self$scheme <- tmp$scheme self$host <- tmp$domain self$path <- tmp$path self$query <- tmp$parameter } if (!missing(opts)) self$opts <- opts if (!missing(disk)) self$disk <- disk if (!missing(fields)) self$fields <- fields if (!missing(output)) self$output <- output }, #' @description Convert the request to a list #' @return list to_hash = function() { self$hash <- list( method = self$method, uri = self$uri, body = serializable_body(self$body, self$opts$preserve_exact_body_bytes %||% FALSE), headers = self$headers, disk = self$disk ) return(self$hash) }, #' @description Convert the request to a list #' @param hash a list #' @return a new `Request` object from_hash = function(hash) { Request$new( method = hash[['method']], uri = hash[['uri']], # body = hash[['body']], body = body_from(hash[['body']]), headers = hash[['headers']], disk = hash[['disk']] ) } ), private = list( without_standard_port = function(uri) { if (is.null(uri)) return(uri) u <- private$parsed_uri(uri) if (paste0(u$scheme, if (is.na(u$port)) NULL else u$port) %in% c('http', 'https/443')) { return(uri) } u$port <- NA return(urltools::url_compose(u)) }, parsed_uri = function(uri) { urltools::url_parse(uri) } ) ) serializable_body <- function(x, preserve_exact_body_bytes = FALSE) { if (is.null(x)) return(x) if (preserve_exact_body_bytes) { if (can_charToRaw(x)) { tmp <- base64enc::base64encode(charToRaw(x)) base64 <- TRUE } else { tmp <- x base64 <- FALSE } structure(tmp, base64 = base64) } else { x } } body_from <- function(x) { if (is.null(x)) x <- "" if ( (!is.null(attr(x, "base64")) && attr(x, "base64")) # (!is.null(attr(x, "base64")) && attr(x, "base64")) || all(is_base64(x)) ) { b64dec <- base64enc::base64decode(x) b64dec_r2c <- tryCatch(rawToChar(b64dec), error = function(e) e) if (inherits(b64dec_r2c, "error")) { # probably is binary (e.g., pdf), so can't be converted to char. b64dec } else { # probably was originally character data, so # can convert to character from binary b64dec_r2c } } else { x # try_encode_string(x, Encoding_safe(x)) } } try_encoding <- function(x) { if (missing(x)) stop("'x' is missing") z <- tryCatch(Encoding(x), error = function(e) e) if (inherits(z, "error")) "ASCII-8BIT" else z } is_base64 <- function(x, cassette) { if (!is.list(x)) { if ("base64" %in% names(attributes(x))) { return(attr(x, 'base64')) } return(FALSE) } # new base64 setup where it is stored in "base64_string" hasb64str <- "base64_string" %in% names(x) if (hasb64str) return(TRUE) if ( cassette$preserve_exact_body_bytes && "string" %in% names(x) ) { # old base64 setup where it was stored in "string" message("re-record cassettes using 'preserve_exact_body_bytes = TRUE'") return(TRUE) } else { # not using base64 return(FALSE) } } Encoding_safe <- function(x) { tryenc <- tryCatch(Encoding(x), error = function(e) e) if (inherits(tryenc, "error")) "unknown" else tryenc } b64_pattern <- "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$" try_encode_string <- function(string, encoding) { ## FIXME, this function doesn't do anything #return string if encoding.nil? || string.encoding.name == encoding # if (is.null(encoding) || ) return(string) # ASCII-8BIT just means binary, so encoding to it is nonsensical # and yet "\u00f6".encode("ASCII-8BIT") raises an error. # Instead, we'll force encode it (essentially just tagging it as binary) # return string.force_encoding(encoding) if encoding == "ASCII-8BIT" if (encoding == "ASCII-8BIT") return(string) return(string) # FIXME - Encoding() doesn't seem to fail with non-sensical # --- find something better #res <- tryCatch(Encoding(string) <- encoding, error = function(e) e) #string.encode(encoding) # rescue EncodingError => e # struct_type = name.split('::').last.downcase # warn "VCR: got `#{e.class.name}: #{e.message}` while trying to encode the #{string.encoding.name} " + # "#{struct_type} body to the original body encoding (#{encoding}). Consider using the " + # "`:preserve_exact_body_bytes` option to work around this." # return(string) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_class.R
#' @title RequestHandlerCrul #' @description Methods for the crul package, building on [RequestHandler] #' @export #' @examples \dontrun{ #' vcr_configure( #' dir = tempdir(), #' record = "once" #' ) #' #' data(crul_request) #' crul_request$url$handle <- curl::new_handle() #' crul_request #' x <- RequestHandlerCrul$new(crul_request) #' # x$handle() #' #' # body matching #' library(vcr) #' library(crul) #' vcr_configure(dir = tempdir(), log = TRUE, #' log_opts = list(file = file.path(tempdir(), "vcr.log"))) #' cli <- HttpClient$new(url = "https://httpbin.org") #' #' ## testing, same uri and method, changed body in 2nd block #' use_cassette(name = "apple7", { #' resp <- cli$post("post", body = list(foo = "bar")) #' }, match_requests_on = c("method", "uri", "body")) #' ## should error, b/c record="once" #' if (interactive()) { #' use_cassette(name = "apple7", { #' resp <- cli$post("post", body = list(foo = "bar")) #' resp2 <- cli$post("post", body = list(hello = "world")) #' }, match_requests_on = c("method", "uri", "body")) #' } #' cas <- insert_cassette(name = "apple7", #' match_requests_on = c("method", "uri", "body")) #' resp2 <- cli$post("post", body = list(foo = "bar")) #' eject_cassette("apple7") #' #' ## testing, same body, changed method in 2nd block #' if (interactive()) { #' use_cassette(name = "apple8", { #' x <- cli$post("post", body = list(hello = "world")) #' }, match_requests_on = c("method", "body")) #' use_cassette(name = "apple8", { #' x <- cli$get("post", body = list(hello = "world")) #' }, match_requests_on = c("method", "body")) #' } #' #' ## testing, same body, changed uri in 2nd block #' # use_cassette(name = "apple9", { #' # x <- cli$post("post", body = list(hello = "world")) #' # w <- cli$post("get", body = list(hello = "world")) #' # }, match_requests_on = c("method", "body")) #' # use_cassette(name = "apple9", { #' # NOTHING HERE #' # }, match_requests_on = c("method", "body")) #' # unlink(file.path(vcr_configuration()$dir, "apple9.yml")) #' } RequestHandlerCrul <- R6::R6Class( 'RequestHandlerCrul', inherit = RequestHandler, private = list( response_for = function(x) { VcrResponse$new(x$status_http(), x$response_headers, x$parse("UTF-8"), x$response_headers$status, super$cassette$cassette_opts) }, on_ignored_request = function(request) { tmp2 <- webmockr::webmockr_crul_fetch(self$request_original) response <- webmockr::build_crul_response(self$request_original, tmp2) return(response) }, on_stubbed_by_vcr_request = function(request) { # return stubbed vcr response - no real response to do serialize_to_crul(request, super$get_stubbed_response(request)) }, on_recordable_request = function(request) { tmp2 <- webmockr::webmockr_crul_fetch(self$request_original) response <- webmockr::build_crul_response(self$request_original, tmp2) self$vcr_response <- private$response_for(response) cas <- tryCatch(current_cassette(), error = function(e) e) if (inherits(cas, "error")) stop("no cassette in use") cas$record_http_interaction(response) return(response) } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_handler-crul.R
#' @title RequestHandlerHttr #' @description Methods for the httr package, building on [RequestHandler] #' @export #' @param request The request from an object of class `HttpInteraction` #' @examples \dontrun{ #' vcr_configure( #' dir = tempdir(), #' record = "once" #' ) #' #' # GET request #' library(httr) #' load("~/httr_req.rda") #' req #' x <- RequestHandlerHttr$new(req) #' # x$handle() #' #' # POST request #' library(httr) #' webmockr::httr_mock() #' mydir <- file.path(tempdir(), "testing_httr") #' invisible(vcr_configure(dir = mydir)) #' use_cassette(name = "testing2", { #' res <- POST("https://httpbin.org/post", body = list(foo = "bar")) #' }, match_requests_on = c("method", "uri", "body")) #' #' load("~/httr_req_post.rda") #' insert_cassette("testing3") #' httr_req_post #' x <- RequestHandlerHttr$new(httr_req_post) #' x #' # x$handle() #' self=x #' #' } RequestHandlerHttr <- R6::R6Class( "RequestHandlerHttr", inherit = RequestHandler, public = list( #' @description Create a new `RequestHandlerHttr` object #' @param request The request from an object of class `HttpInteraction` #' @return A new `RequestHandlerHttr` object initialize = function(request) { self$request_original <- request self$request <- { Request$new(request$method, request$url, webmockr::pluck_body(request), request$headers, fields = request$fields, output = request$output) } self$cassette <- tryCatch(current_cassette(), error = function(e) e) } ), private = list( # make a `vcr` response response_for = function(x) { VcrResponse$new( c(list(status_code = x$status_code), httr::http_status(x)), x$headers, httr::content(x, encoding = "UTF-8"), x$all_headers[[1]]$version, super$cassette$cassette_opts ) }, # these will replace those in on_ignored_request = function(request) { # perform and return REAL http response # * make real request # * run through response_for() to make vcr response, store vcr response # * give back real response # real request webmockr::httr_mock(FALSE) on.exit(webmockr::httr_mock(TRUE), add = TRUE) tmp2 <- eval(parse(text = paste0("httr::", request$method))) ( request$url, body = webmockr::pluck_body(request), do.call(httr::config, request$options), httr::add_headers(request$headers) ) # run through response_for() self$vcr_response <- private$response_for(tmp2) # return real response return(response) }, on_stubbed_by_vcr_request = function(request) { # return stubbed vcr response - no real response to do serialize_to_httr(request, super$get_stubbed_response(request)) }, on_recordable_request = function(request) { # do real request - then stub response - then return stubbed vcr response # - this may need to be called from webmockr httradapter? # real request webmockr::httr_mock(FALSE) on.exit(webmockr::httr_mock(TRUE), add = TRUE) tmp2 <- eval(parse(text = paste0("httr::", self$request_original$method))) ( self$request_original$url, body = webmockr::pluck_body(self$request_original), do.call(httr::config, self$request_original$options), httr::add_headers(self$request_original$headers), if (!is.null(self$request_original$output$path)) httr::write_disk(self$request_original$output$path, TRUE) ) response <- webmockr::build_httr_response(self$request_original, tmp2) # make vcr response | then record interaction self$vcr_response <- private$response_for(response) cas <- tryCatch(current_cassette(), error = function(e) e) if (inherits(cas, "error")) stop("no cassette in use") cas$record_http_interaction(response) # return real response return(response) } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_handler-httr.R
#' @title RequestHandler #' @description Base handler for http requests, deciding whether a #' request is stubbed, to be ignored, recordable, or unhandled #' @export #' @details #' \strong{Private Methods} #' \describe{ #' \item{\code{request_type(request)}}{ #' Get the request type #' } #' \item{\code{externally_stubbed()}}{ #' just returns FALSE #' } #' \item{\code{should_ignore()}}{ #' should we ignore the request, depends on request ignorer #' infrastructure that's not working yet #' } #' \item{\code{has_response_stub()}}{ #' Check if there is a matching response stub in the #' http interaction list #' } #' \item{\code{get_stubbed_response()}}{ #' Check for a response and get it #' } #' \item{\code{request_summary(request)}}{ #' get a request summary #' } #' \item{\code{on_externally_stubbed_request(request)}}{ #' on externally stubbed request do nothing #' } #' \item{\code{on_ignored_request(request)}}{ #' on ignored request, do something #' } #' \item{\code{on_recordable_request(request)}}{ #' on recordable request, record the request #' } #' \item{\code{on_unhandled_request(request)}}{ #' on unhandled request, run UnhandledHTTPRequestError #' } #' } #' @examples \dontrun{ #' # record mode: once #' vcr_configure( #' dir = tempdir(), #' record = "once" #' ) #' #' data(crul_request) #' crul_request$url$handle <- curl::new_handle() #' crul_request #' x <- RequestHandler$new(crul_request) #' # x$handle() #' #' # record mode: none #' vcr_configure( #' dir = tempdir(), #' record = "none" #' ) #' data(crul_request) #' crul_request$url$handle <- curl::new_handle() #' crul_request #' insert_cassette("testing_record_mode_none", record = "none") #' #file.path(vcr_c$dir, "testing_record_mode_none.yml") #' x <- RequestHandlerCrul$new(crul_request) #' # x$handle() #' crul_request$url$url <- "https://api.crossref.org/works/10.1039/c8sm90002g/" #' crul_request$url$handle <- curl::new_handle() #' z <- RequestHandlerCrul$new(crul_request) #' # z$handle() #' eject_cassette("testing_record_mode_none") #' } RequestHandler <- R6::R6Class( 'RequestHandler', public = list( #' @field request_original original, before any modification request_original = NULL, #' @field request the request, after any modification request = NULL, #' @field vcr_response holds [VcrResponse] object vcr_response = NULL, #' @field stubbed_response the stubbed response stubbed_response = NULL, #' @field cassette the cassette holder cassette = NULL, #' @description Create a new `RequestHandler` object #' @param request The request from an object of class `HttpInteraction` #' @return A new `RequestHandler` object initialize = function(request) { self$request_original <- request self$request <- { Request$new(request$method, request$url$url %||% request$url, webmockr::pluck_body(request) %||% "", request$headers, disk = !is.null(request$output$path)) } self$cassette <- tryCatch(current_cassette(), error = function(e) e) }, #' @description Handle the request (`request` given in `$initialize()`) #' @return handles a request, outcomes vary handle = function() { vcr_log_info(sprintf("Handling request: %s (disabled: %s)", private$request_summary(self$request), private$is_disabled()), vcr_c$log_opts$date) req_type <- private$request_type() req_type_fun <- sprintf("private$on_%s_request", req_type) vcr_log_info(sprintf("Identified request type: (%s) for %s", req_type, private$request_summary(self$request)), vcr_c$log_opts$date) eval(parse(text = req_type_fun))(self$request) } ), private = list( request_summary = function(request) { request_matchers <- if ( !inherits(self$cassette, c("error", "list")) && !is.null(self$cassette) ) { self$cassette$match_requests_on } else { vcr_c$match_requests_on } request_summary(Request$new()$from_hash(request), request_matchers) }, request_type = function() { if (private$externally_stubbed()) { # FIXME: not quite sure what externally_stubbed is meant for # perhaps we can get rid of it here if only applicable in Ruby # cat("request_type: is externally stubbed", "\n") "externally_stubbed" } else if (private$should_ignore(self$request)) { # cat("request_type: is ignored", "\n") "ignored" } else if (private$has_response_stub(self$request)) { # cat("request_type: is stubbed_by_vcr", "\n") "stubbed_by_vcr" } else if (real_http_connections_allowed()) { # cat("request_type: is recordable", "\n") "recordable" } else { # cat("request_type: is unhandled", "\n") "unhandled" } }, # request type helpers externally_stubbed = function() FALSE, should_ignore = function(request) { request_ignorer$should_be_ignored(request) }, has_response_stub = function(request) { hi <- http_interactions() if (length(hi$interactions) == 0) return(FALSE) hi$has_interaction_matching(request) }, is_disabled = function(adapter = "crul") !webmockr::enabled(adapter), # get stubbed response get_stubbed_response = function(request) { self$stubbed_response <- http_interactions()$response_for(request) self$stubbed_response }, ##################################################################### ### various on* methods, some global for any adapter, ### and some may be specific to an adapter ### - all fxns take `request` param for consistentcy, even if they dont use it ##### so we can "monkey patch" these in each HTTP client adapter by ##### reassigning some of these functions with ones specific to the HTTP client on_externally_stubbed_request = function(request) NULL, on_ignored_request = function(request) { # perform and return REAL http response # reassign per adapter }, on_stubbed_by_vcr_request = function(request) { # return stubbed vcr response - no real response to do # reassign per adapter }, on_recordable_request = function(request) { # do real request - then stub response - then return stubbed vcr response # - this may need to be called from webmockr cruladapter? # reassign per adapter }, on_unhandled_request = function(request) { err <- UnhandledHTTPRequestError$new(request) err$run() } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_handler.R
# (x <- RequestIgnorer$new()) # x$LOCALHOST_ALIASES # x$ignored_hosts # x$ignore_hosts(hosts = "google.com") # x$ignored_hosts # x$ignore_localhost() # x$ignored_hosts # x$ignore_localhost_value('127.0.0.1') # x$ignored_hosts #' @title Request ignorer #' @description request ignorer methods #' @keywords internal RequestIgnorer <- R6::R6Class( "RequestIgnorer", public = list( #' @field LOCALHOST_ALIASES A constant with values: 'localhost', '127.0.0.1', #' and '0.0.0.0' LOCALHOST_ALIASES = c('localhost', '127.0.0.1', '0.0.0.0'), #' @field ignored_hosts vector of ignored host URI's ignored_hosts = list(), #' @description Create a new `RequestIgnorer` object #' @return A new `RequestIgnorer` object initialize = function() { private$ignored_hosts_init() self$ignore_request() }, #' @description Will ignore any request for which the given function #' returns `TRUE` #' @return no return; defines request ignorer hook ignore_request = function() { fun <- function(x) { if (is.null(self$ignored_hosts$bucket)) return(FALSE) host <- parseurl(x$uri)$domain %||% NULL if (is.null(host)) return(FALSE) # update ignored hosts if any found in configuration if (!is.null(vcr_c$ignore_hosts)) self$ignore_hosts(vcr_c$ignore_hosts) if (vcr_c$ignore_localhost) self$ignore_localhost() self$ignored_hosts$includes(host) } VCRHooks$define_hook(hook_type = "ignore_request", fun = fun) }, #' @description ignore all localhost values (localhost, 127.0.0.1, 0.0.0.0) #' @return no return; sets to ignore all localhost aliases ignore_localhost = function() { self$ignored_hosts$merge(self$LOCALHOST_ALIASES) }, #' @description ignore a specific named localhost #' @param value (character) A localhost value to ignore, e.g., 'localhost' #' @return no return; defines request ignorer hook ignore_localhost_value = function(value) { self$ignore_hosts(value) }, #' @description ignore any named host #' @param hosts (character) vector of hosts to ignore #' @return no return; adds host to ignore ignore_hosts = function(hosts) { # self$ignored_hosts <- c(self$ignored_hosts, hosts) self$ignored_hosts$merge(hosts) }, #' @description method to determine whether to ignore a request #' @param request request to ignore #' @return no return; defines request ignorer hook should_be_ignored = function(request) { if (missing(request)) stop("'request' can not be missing") VCRHooks$invoke_hook(hook_type = "ignore_request", args = request) } ), private = list( # Initialize an empty ignored hosts object on package load ignored_hosts_init = function() { self$ignored_hosts <- EnvHash$new() } ) ) # @param fun A function, of the form: coming... EnvHash <- R6::R6Class( "EnvHash", public = list( bucket = c(), print = function(...) { bucks <- self$bucket if (length(bucks) == 0) "" else bucks cat("<ignored hosts>", sep = "\n") cat(paste0(" ", paste0(bucks, collapse = ", ")), sep = "\n") invisible(self) }, merge = function(vals) { self$bucket <- unique(c(self$bucket, vals)) }, includes = function(name) { name %in% self$bucket }, reject = function(fun) { self$bucket <- Filter(Negate(fun), self$bucket) } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_ignorer.R
#' @title RequestMatcherRegistry #' @description handles request matchers #' @export #' @examples \dontrun{ #' (x <- RequestMatcherRegistry$new()) #' x$default_matchers #' x$registry #' } RequestMatcherRegistry <- R6::R6Class( 'RequestMatcherRegistry', public = list( #' @field registry initialze registry list with a request, or leave empty registry = NULL, #' @field default_matchers request matchers to use. default: method, uri default_matchers = NULL, #' @description Create a new RequestMatcherRegistry object #' @param registry initialze registry list with a request, or leave empty #' @param default_matchers request matchers to use. default: method, uri #' @return A new `RequestMatcherRegistry` object initialize = function(registry = list(), default_matchers = list('method', 'uri')) { self$registry <- registry self$default_matchers <- default_matchers self$register_built_ins() }, #' @description Register a custom matcher #' @param name matcher name #' @param func function that describes a matcher, should return #' a single boolean #' @return no return; registers the matcher register = function(name, func) { if (name %in% self$registry) { warning( sprintf("There is already a vcr request matcher registered for %s. Overriding it.", name) ) } self$registry[[name]] <- Matcher$new(func = func) }, #' @description Register all built in matchers #' @return no return; registers all built in matchers #' @note r1=from new request; r2=from recorded interaction register_built_ins = function() { self$register("method", function(r1, r2) r1$method == r2$method) self$register("uri", function(r1, r2) identical( curl::curl_unescape(query_params_remove_str(r1$uri)), curl::curl_unescape(r2$uri)) ) self$register("body", function(r1, r2) identical(r1$body, r2$body)) self$register('headers', function(r1, r2) identical(r1$headers, r2$headers)) self$register("host", function(r1, r2) identical(r1$host, r2$host)) self$register("path", function(r1, r2) identical(sub("/$", "", r1$path), sub("/$", "", r2$path))) self$register("query", function(r1, r2) identical(curl::curl_unescape(r1$query), curl::curl_unescape(r2$query))) self$try_to_register_body_as_json() }, #' @description Try to register body as JSON #' @param r1,r2 [Request] class objects #' @return no return; registers the matcher try_to_register_body_as_json = function(r1, r2) { if (!requireNamespace("jsonlite", quietly = TRUE)) { stop("please install jsonlite", call. = FALSE) } self$register("body_as_json", function(r1, r2) { tc <- tryCatch( identical(jsonlite::fromJSON(r1$body), jsonlite::fromJSON(r2$body)), error = function(e) e ) if (inherits(tc, "error")) FALSE else tc }) } ) ) # generate matcher functions Matcher <- R6::R6Class( 'Matcher', public = list( func = NULL, initialize = function(func) self$func <- func, matches = function(...) self$func(...) ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_matcher_registry.R
#' vcr request matching #' #' There are a number of options, some of which are on by default, some of #' which can be used together, and some alone. #' #' @includeRmd man/rmdhunks/request-matching-vignette.Rmd #' #' @name request-matching NULL
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_matching.R
#' request and response summary methods #' #' @export #' @name request_response #' @keywords internal #' @param request a [Request] object #' @param request_matchers (character) a vector of matchers. #' Default: `""` #' @param response a [VcrResponse] object #' @return character string, of either request or response #' @details By default, method and uri are included #' in the request summary - if body and/or headers are #' specified in `request_matchers`, then they are also #' included #' #' HTTP status code and response body are included in the #' response summary. The response body is truncated to a #' max of 80 characters #' #' In `response_summary()` we use [gsub] with `useBytes=TRUE` to avoid #' problems sometimes seen with multibyte strings - this shouldn't affect #' your data/etc. as this is only for printing a summary of the response #' @examples #' # request #' url <- "https://httpbin.org" #' body <- list(foo = "bar") #' headers <- list( #' `User-Agent` = "r-curl/3.2", #' `Accept-Encoding` = "gzip, deflate", #' Accept = "application/json" #' ) #' #' (x <- Request$new("POST", url, body, headers)) #' request_summary(request = x) #' request_summary(request = x, c('method', 'uri')) #' request_summary(request = x, c('method', 'uri', 'body')) #' request_summary(request = x, c('method', 'uri', 'headers')) #' request_summary(request = x, c('method', 'uri', 'body', 'headers')) #' #' # response #' status <- list(status_code = 200, message = "OK", #' explanation = "Request fulfilled, document follows") #' headers <- list( #' status = "HTTP/1.1 200 OK", #' connection = "keep-alive", #' date = "Tue, 24 Apr 2018 04:46:56 GMT" #' ) #' response_body <- #' "{\"args\": {\"q\": \"stuff\"}, \"headers\": {\"Accept\": \"text/html\"}}\n" #' (x <- VcrResponse$new(status, headers, #' response_body, "HTTP/1.1 200 OK")) #' response_summary(x) #' #' ## with binary body #' # path <- "tests/testthat/png_eg.rda" #' # load(path) #' # (x <- VcrResponse$new(status, headers, png_eg, "HTTP/1.1 200 OK")) #' # response_summary(x) request_summary <- function(request, request_matchers = "") { stopifnot(inherits(request, "Request")) stopifnot(inherits(request_matchers, "character")) atts <- c(request$method, request$uri) if ("body" %in% request_matchers) { atts <- c(atts, substring(request$body, 0, 80)) } if ("headers" %in% request_matchers) { atts <- c(atts, request$headers) } paste0(atts, collapse = " ") } #' @export #' @rdname request_response response_summary <- function(response) { stopifnot(inherits(response, "VcrResponse")) if (inherits(response$status, c("list", "http_code"))) { ss <- response$status$status_code } else if (inherits(response$status, c("character", "integer", "numeric"))) { ss <- response$status } else { ss <- NULL } # if body is raw, state that it's raw resp <- if (is.raw(response$body)) "<raw>" else response$body # construct summary # note: gsub changes a string to UTF-8, useBytes seems to avoid doing this # & avoids multibyte string errors sprintf("%s %s", ss %||% '???', substring(gsub("\n", " ", resp, useBytes = TRUE), 1, 80)) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/request_response.R
#' @title The response of an HTTPInteraction #' @description Custom vcr http response object #' @export #' @keywords internal #' @examples \dontrun{ #' vcr_configure(dir = tempdir()) #' #' # basic example of VcrResponse use #' url <- "https://google.com" #' (cli <- crul::HttpClient$new(url = url)) #' (res <- cli$get("get", query = list(q = "stuff"))) #' (x <- VcrResponse$new(res$status_http(), res$response_headers, #' res$parse("UTF-8"), res$response_headers$status)) #' x$body #' x$status #' x$headers #' x$http_version #' x$to_hash() #' x$from_hash(x$to_hash()) #' #' # update content length header #' ## example 1 #' ### content-length header present, but no change #' url <- "https://fishbase.ropensci.org" #' cli <- crul::HttpClient$new(url = url, headers = list(`Accept-Encoding` = '*')) #' res <- cli$get("species/34") #' x <- VcrResponse$new(res$status_http(), res$response_headers, #' res$parse("UTF-8"), res$response_headers$status) #' x$headers$`content-length` #' x$update_content_length_header() #' x$headers$`content-length` #' #' ## example 2 #' ### no content-length header b/c a transfer-encoding header is included #' ### and no content-length header allowed if transfer-encoding header #' ### used (via rfc7230) #' url <- "https://google.com" #' cli <- crul::HttpClient$new(url = url) #' res <- cli$get() #' x <- VcrResponse$new(res$status_http(), res$response_headers, #' rawToChar(res$content), res$response_headers$status) #' x$headers$`content-length` # = NULL #' x$update_content_length_header() # no change, b/c header doesn't exist #' x$headers$`content-length` # = NULL #' #' ## example 3 #' ### content-length header present, and does change #' body <- " Hello World " #' x <- VcrResponse$new(200, list('content-length'=nchar(body)), #' body, "HTTP/2") #' x$headers$`content-length` # = 13 #' x$body <- gsub("^\\s|\\s$", "", x$body) #' x$headers$`content-length` # = 13 #' x$update_content_length_header() #' x$headers$`content-length` # = 11 #' #' # check if body is compressed #' url <- "https://fishbase.ropensci.org" #' (cli <- crul::HttpClient$new(url = url)) #' (res <- cli$get("species/3")) #' res$response_headers #' (x <- VcrResponse$new(res$status_http(), res$response_headers, #' res$parse("UTF-8"), res$response_headers$status)) #' x$content_encoding() #' x$is_compressed() #' #' # with disk #' url <- "https://google.com" #' (cli <- crul::HttpClient$new(url = url)) #' f <- tempfile() #' (res <- cli$get("get", query = list(q = "stuff"), disk = f)) #' (x <- VcrResponse$new(res$status_http(), res$response_headers, #' f, res$response_headers$status, disk = TRUE)) #' } VcrResponse <- R6::R6Class( "VcrResponse", public = list( #' @field status the status of the response status = NULL, #' @field headers the response headers headers = NULL, #' @field body the response body body = NULL, #' @field http_version the HTTP version http_version = NULL, #' @field opts a list opts = NULL, #' @field adapter_metadata Additional metadata used by a specific VCR adapter adapter_metadata = NULL, #' @field hash a list hash = NULL, #' @field disk a boolean disk = NULL, #' @description Create a new VcrResponse object #' @param status the status of the response #' @param headers the response headers #' @param body the response body #' @param http_version the HTTP version #' @param opts a list #' @param adapter_metadata Additional metadata used by a specific VCR adapter #' @param disk boolean, is body a file on disk #' @return A new `VcrResponse` object initialize = function(status, headers, body, http_version, opts, adapter_metadata = NULL, disk) { if (!missing(status)) self$status <- status if (!missing(headers)) self$headers <- headers if (!missing(body)) { if (inherits(body, "list")) { body <- paste(names(body), body, sep = "=", collapse = ",") } # self$body <- if (is.character(body)) enc2utf8(body) else body self$body <- body } if (!missing(http_version)) { self$http_version <- extract_http_version(http_version) } if (!missing(opts)) self$opts <- opts if (!missing(adapter_metadata)) self$adapter_metadata <- adapter_metadata if (!missing(disk)) self$disk <- disk }, #' @description print method for the `VcrResponse` class #' @param x self #' @param ... ignored print = function(x, ...) cat("<VcrResponse> ", sep = "\n"), #' @description Create a hash #' @return a list to_hash = function() { self$hash <- list( status = self$status, headers = self$headers, body = serializable_body(self$body, self$opts$preserve_exact_body_bytes %||% FALSE), http_version = self$http_version, disk = self$disk ) return(self$hash) }, #' @description Get a hash back to an R list #' @param hash a list #' @return an `VcrResponse` object from_hash = function(hash) { VcrResponse$new( hash[["status"]], hash[["headers"]], # hash[["body"]], body_from(hash[["body"]]), hash[["http_version"]], hash[["adapater_metadata"]], hash[["disk"]] ) }, #' @description Updates the Content-Length response header so that #' it is accurate for the response body #' @return no return; modifies the content length header update_content_length_header = function() { if (!is.null(self$get_header("content-length"))) { len <- 0 if (length(self$body) > 0 && nchar(self$body) > 0) { len <- as.character(nchar(self$body)) } self$edit_header("content-length", len) } }, #' @description Get a header by name #' @param key (character) header name to get #' @return the header value (if it exists) get_header = function(key) { self$headers[[key]] }, #' @description Edit a header #' @param key (character) header name to edit #' @param value (character) new value to assign #' @return no return; modifies the header in place edit_header = function(key, value = NULL) { self$headers[[key]] <- value }, #' @description Delete a header #' @param key (character) header name to delete #' @return no return; the header is deleted if it exists delete_header = function(key) { self$headers[key] <- NULL }, #' @description Get the content-encoding header value #' @return (character) the content-encoding value content_encoding = function() { self$get_header("content-encoding")[1] }, #' @description Checks if the encoding is one of "gzip" or "deflate" #' @return logical is_compressed = function() { self$content_encoding() %in% c("gzip", "deflate") } ) ) extract_http_version <- function(x) { if (!is.character(x)) return(x) if (grepl("HTTP/[0-9]\\.?", x)) { strsplit(stract(x, "HTTP/[12]\\.?([0-9])?"), "/")[[1]][2] %||% "" } else { return(x) } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/response_class.R
# generate actual crul response serialize_to_crul <- function(request, response) { # request req <- webmockr::RequestSignature$new( method = request$method, uri = request$uri, options = list( body = request$body %||% NULL, headers = request$headers %||% NULL, proxies = NULL, auth = NULL, disk = response$disk ) ) # response resp <- webmockr::Response$new() resp$set_url(request$uri) bod <- response$body resp$set_body(if ("string" %in% names(bod)) bod$string else bod, response$disk %||% FALSE) resp$set_request_headers(request$headers, capitalize = FALSE) resp$set_response_headers(response$headers, capitalize = FALSE) # resp$set_status(status = response$status %||% 200) resp$set_status(status = response$status$status_code %||% 200) # generate crul response webmockr::build_crul_response(req, resp) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/serialize_to_crul.R
disk_true <- function(x) { if (is.null(x)) return(FALSE) assert(x, "logical") return(x) } # generate actual httr response serialize_to_httr <- function(request, response) { # request req <- webmockr::RequestSignature$new( method = request$method, uri = request$uri, options = list( body = request$body %||% NULL, headers = request$headers %||% NULL, proxies = NULL, auth = NULL, disk = response$disk, fields = request$fields %||% NULL, output = request$output %||% NULL ) ) # response resp <- webmockr::Response$new() resp$set_url(request$uri) # in vcr >= v0.4, "disk" is in the response, but in older versions # its missing - use response$body if disk is not present response_body <- response$body if ("disk" %in% names(response) && disk_true(response$disk)) { response_body <- if (response$disk) { structure(response$body, class = "path") } else { response$body } } resp$set_body(response_body, response$disk %||% FALSE) resp$set_request_headers(request$headers, capitalize = FALSE) resp$set_response_headers(response$headers, capitalize = FALSE) resp$set_status(status = response$status$status_code %||% 200) # generate httr response webmockr::build_httr_response(as_httr_request(req), resp) } keep_last <- function(...) { x <- c(...) x[!duplicated(names(x), fromLast = TRUE)] } httr_ops <- function(method, w) { # if (!length(w)) return(w) if (tolower(method) == "get") w$httpget <- TRUE if (tolower(method) == "post") w$post <- TRUE if (!tolower(method) %in% c("get", "post")) w$customrequest <- toupper(method) return(w) } as_httr_request <- function(x) { structure(list(method = toupper(x$method), url = x$url$url, headers = keep_last(x$headers), fields = x$fields, options = httr_ops(x$method, compact(keep_last(x$options))), auth_token = x$auth, output = x$output), class = "request") }
/scratch/gouwar.j/cran-all/cranData/vcr/R/serialize_to_httr.R
#' Serializer class - base class for JSON/YAML serializers #' @keywords internal Serializer <- R6::R6Class("Serializer", public = list( #' @field file_extension (character) A file extension file_extension = NULL, #' @field path (character) full path to the yaml file path = NULL, #' @description Create a new YAML object #' @param file_extension (character) A file extension #' @param path (character) path to the cassette, excluding the cassette #' directory and the file extension #' @return A new `YAML` object initialize = function(file_extension = NULL, path = NULL) { self$file_extension <- file_extension if (is.null(path)) { self$path <- paste0(cassette_path(), "/", basename(tempfile()), self$file_extension) } else { self$path <- paste0(cassette_path(), "/", path, self$file_extension) } }, #' @description Serializes a hash - REPLACED BY YAML/JSON METHODS #' @param x (list) the object to serialize #' @param path (character) the file path #' @param bytes (logical) whether to preserve exact body bytes or not #' @return (character) the YAML or JSON string to write to disk serialize = function(x, path, bytes) {}, #' @description Serializes a file - REPLACED BY YAML/JSON METHODS deserialize = function() {} ), private = list( strip_newlines = function(x) { if (!inherits(x, "character")) return(x) gsub("[\r\n]", "", x) }, process_body = function(x, cassette) { if (is.null(x)) { return(list()) } else { # check for base64 encoding x$http_interactions <- lapply(x$http_interactions, function(z) { if (is_base64(z$response$body, cassette)) { # string or base64_string? str_slots <- c('string', 'base64_string') slot <- str_slots[str_slots %in% names(z$response$body)] # if character and newlines detected, remove newlines z$response$body[[slot]] <- private$strip_newlines(z$response$body[[slot]]) b64dec <- base64enc::base64decode(z$response$body[[slot]]) b64dec_r2c <- tryCatch(rawToChar(b64dec), error = function(e) e) z$response$body[[slot]] <- if (inherits(b64dec_r2c, "error")) { # probably is binary (e.g., pdf), so can't be converted to char. b64dec } else { # probably was originally character data, so # can convert to character from binary b64dec_r2c } # set encoding to empty string, we're ignoring it for now z$response$body$encoding <- "" } return(z) }) return(x) } } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/serializer.R
# ww <- JSON$new(path = "stuff3") # ww # ww$file_extension # fun <- ww$serialize() # fun(list(http_interactions = list(response = list(body = "bar"))), # path = ww$path, bytes = FALSE) # ww$deserialize() #' @title The JSON serializer #' @description class with methods for serializing via \pkg{jsonlite} #' @keywords internal JSON <- R6::R6Class("JSON", inherit = Serializer, public = list( #' @description Create a new `JSON` object #' @param path (character) full path to the yaml file #' @return A new `JSON` object initialize = function(path = NULL) { super$initialize(".json", path) }, #' @description Serializes the given hash using internal fxn write_json #' @param x (list) the object to serialize #' @param path (character) the file path #' @param bytes (logical) whether to preserve exact body bytes or not #' @return (character) the json string to write to disk serialize = function(x, path, bytes) { function(x, path, bytes) { write_json(x, path, bytes) } }, #' @description Deserializes the content at the file path using #' jsonlite::fromJSON #' @param cassette the current cassette object so it's properties can #' be retrieved #' @return (list) the deserialized object, an R list deserialize = function(cassette) { str <- sensitive_put_back(readLines(self$path)) tmp <- jsonlite::fromJSON(str, FALSE) tmp <- query_params_put_back(tmp) private$process_body(tmp, cassette) } ) )
/scratch/gouwar.j/cran-all/cranData/vcr/R/serializers-json.R
# yy <- YAML$new(path = "stuff2") # yy # yy$file_extension # fun <- yy$serialize() # fun(list(http_interactions = list(response = list(body = "bar"))), # path = yy$path, bytes = FALSE) # yy$deserialize() # } #' @title The YAML serializer #' @description class with methods for serializing via the \pkg{yaml} package #' @keywords internal YAML <- R6::R6Class("YAML", inherit = Serializer, public = list( #' @description Create a new YAML object #' @param path (character) path to the cassette, excluding the cassette #' directory and the file extension #' @return A new `YAML` object initialize = function(path = NULL) { super$initialize(".yml", path) }, #' @description Serializes the given hash using internal fxn write_yaml #' @param x (list) the object to serialize #' @param path (character) the file path #' @param bytes (logical) whether to preserve exact body bytes or not #' @return (character) the YAML string to write to disk serialize = function(x, path, bytes) { #write_yaml(x, self$path) function(x, path, bytes) { write_yaml(x, path, bytes) } }, #' @description Deserializes the content at the path using #' yaml::yaml.load_file #' @param cassette the current cassette object so it's properties can #' be retrieved #' @return (list) the deserialized object, an R list deserialize = function(cassette) { tmp <- yaml_load_desecret(self$path) private$process_body(tmp, cassette) } ) ) yaml_load_desecret <- function(path) { str <- sensitive_put_back(readLines(path, encoding = "UTF-8")) tmp <- yaml::yaml.load(str) tmp <- query_params_put_back(tmp) tmp }
/scratch/gouwar.j/cran-all/cranData/vcr/R/serializers-yaml.R
#' @title Cassette serializers #' @description Keeps track of the cassette serializers in a hash-like object #' @export #' @keywords internal #' @details #' \strong{Private Methods} #' \describe{ #' \item{\code{serialize_get()}}{ #' Gets a named serializer. This is also run on `Serializers$new()` #' } #' } #' @examples \dontrun{ #' (aa <- Serializers$new()) #' aa$name #' aa$serializers #' yaml_serializer <- aa$serializers$new() #' yaml_serializer #' #' x <- Serializers$new(name = "json") #' x$serializers$new() #' json_serializer <- x$serializers$new() #' json_serializer #' } Serializers <- R6::R6Class( "Serializers", public = list( #' @field serializers (list) list of serializer names serializers = list(), #' @field name (character) Name of a serializer. "yaml" (default) or "json" name = "yaml", #' @description Create a new Serializers object #' @param serializers (list) list of serializer names #' @param name (character) Name of a serializer. "yaml" (default) or "json" #' @return A new `Serializers` object initialize = function(serializers = list(), name = "yaml") { self$serializers <- serializers self$name <- name private$serialize_get() } ), private = list( serialize_get = function() { self$serializers <- switch(self$name, yaml = YAML, json = JSON, stop(sprintf( "The requested vcr cassette serializer (%s) is not registered.", self$name), call. = FALSE) ) } ) ) #' @export #' @rdname Serializers serializer_fetch <- function(x = "yaml", name) { ser <- Serializers$new(name = x) ser <- ser$serializers ser$new(path = name) } check_serializer <- function(x) { if (!x %in% c("yaml", "json")) { mssg <- sprintf( "The requested vcr cassette serializer (%s) is not registered.", x) stop(mssg, call. = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/serializers.R
#' Skip tests if vcr is off #' #' Custom testthat skipper to skip tests if vcr is turned off via the #' environment variable `VCR_TURN_OFF`. #' #' @details This might be useful if your test will fail with real requests: #' when the cassette was e.g. edited (a real request produced a 200 status code #' but you made it a 502 status code for testing the behavior of your code #' when the API errors) #' or if the tests are very specific (e.g. testing a date was correctly parsed, #' but making a real request would produce a different date). #' #' @return Nothing, skip test. #' @export #' #' @seealso [turn_off()] skip_if_vcr_off <- function() { if (!requireNamespace("testthat", quietly = TRUE)) { stop( paste0( "This function is meant to be used within testthat tests.", "Please install testthat." ) ) } if ( nzchar(Sys.getenv("VCR_TURN_OFF")) && as.logical(Sys.getenv("VCR_TURN_OFF")) ) { testthat::skip("Not run when vcr is off") } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/skip-vcr-off.R
#' split string every N characters #' @param str (character) a string #' @param length (integer) number of characters to split by #' @examples \dontrun{ #' str = "XOVEWVJIEWNIGOIWENVOIWEWVWEW" #' str_splitter(str, 5) #' str_splitter(str, 5L) #' } str_splitter <- function(str, length) { gsub(sprintf("(.{%s})", length), "\\1 ", str) }
/scratch/gouwar.j/cran-all/cranData/vcr/R/split_string.R
#' Use a cassette to record HTTP requests #' #' @export #' @inherit check_cassette_names details #' @param name The name of the cassette. vcr will check this to ensure it #' is a valid file name. Not allowed: spaces, file extensions, control #' characters (e.g., `\n`), illegal characters ('/', '?', '<', '>', '\\', ':', #' '*', '|', and '\"'), dots alone (e.g., '.', '..'), Windows reserved #' words (e.g., 'com1'), trailing dots (can cause problems on Windows), #' names longer than 255 characters. See section "Cassette names" #' @param ... a block of code containing one or more requests (required). Use #' curly braces to encapsulate multi-line code blocks. If you can't pass a code #' block use [insert_cassette()] instead. #' @param record The record mode (default: `"once"`). See [recording] for a #' complete list of the different recording modes. #' @param match_requests_on List of request matchers #' to use to determine what recorded HTTP interaction to replay. Defaults to #' `["method", "uri"]`. The built-in matchers are "method", "uri", "host", #' "path", "headers", "body" and "query" #' @param update_content_length_header (logical) Whether or #' not to overwrite the `Content-Length` header of the responses to #' match the length of the response body. Default: `FALSE` #' @param allow_playback_repeats (logical) Whether or not to #' allow a single HTTP interaction to be played back multiple times. #' Default: `FALSE`. #' @param serialize_with (character) Which serializer to use. #' Valid values are "yaml" (default) and "json". Note that you can have #' multiple cassettes with the same name as long as they use different #' serializers; so if you only want one cassette for a given cassette name, #' make sure to not switch serializers, or clean up files you no longer need. #' @param persist_with (character) Which cassette persister to #' use. Default: "file_system". You can also register and use a #' custom persister. #' @param preserve_exact_body_bytes (logical) Whether or not #' to base64 encode the bytes of the requests and responses for #' this cassette when serializing it. See also `preserve_exact_body_bytes` #' in [vcr_configure()]. Default: `FALSE` #' @param re_record_interval (integer) How frequently (in seconds) the #' cassette should be re-recorded. default: `NULL` (not re-recorded) #' @param clean_outdated_http_interactions (logical) Should outdated #' interactions be recorded back to file? default: `FALSE` #' #' @details A run down of the family of top level \pkg{vcr} functions #' #' - `use_cassette` Initializes a cassette. Returns the inserted #' cassette. #' - `insert_cassette` Internally used within `use_cassette` #' - `eject_cassette` ejects the current cassette. The cassette #' will no longer be used. In addition, any newly recorded HTTP interactions #' will be written to disk. #' #' @section Cassette options: #' #' Default values for arguments controlling cassette behavior are #' inherited from vcr's global configuration. See [`vcr_configure()`] for a #' complete list of options and their default settings. You can override these #' options for a specific cassette by changing an argument's value to something #' other than `NULL` when calling either `insert_cassette()` or #' `use_cassette()`. #' #' @section Behavior: #' This function handles a few different scenarios: #' #' - when everything runs smoothly, and we return a `Cassette` class object #' so you can inspect the cassette, and the cassette is ejected #' - when there is an invalid parameter input on cassette creation, #' we fail with a useful message, we don't return a cassette, and the #' cassette is ejected #' - when there is an error in calling your passed in code block, #' we return with a useful message, and since we use `on.exit()` #' the cassette is still ejected even though there was an error, #' but you don't get an object back #' - whenever an empty cassette (a yml/json file) is found, we delete it #' before returning from the `use_cassette()` function call. we achieve #' this via use of `on.exit()` so an empty cassette is deleted even #' if there was an error in the code block you passed in #' #' @section Cassettes on disk: #' Note that _"eject"_ only means that the R session cassette is no longer #' in use. If any interactions were recorded to disk, then there is a file #' on disk with those interactions. #' #' @section Using with tests (specifically \pkg{testthat}): #' There's a few ways to get correct line numbers for failed tests and #' one way to not get correct line numbers: #' #' *Correct*: Either wrap your `test_that()` block inside your `use_cassette()` #' block, OR if you put your `use_cassette()` block inside your `test_that()` #' block put your `testthat` expectations outside of the `use_cassette()` #' block. #' #' *Incorrect*: By wrapping the `use_cassette()` block inside your #' `test_that()` block with your \pkg{testthat} expectations inside the #' `use_cassette()` block, you'll only get the line number that the #' `use_cassette()` block starts on. #' #' @return an object of class `Cassette` #' #' @seealso [insert_cassette()], [eject_cassette()] #' @examples \dontrun{ #' library(vcr) #' library(crul) #' vcr_configure(dir = tempdir()) #' #' use_cassette(name = "apple7", { #' cli <- HttpClient$new(url = "https://httpbin.org") #' resp <- cli$get("get") #' }) #' readLines(file.path(tempdir(), "apple7.yml")) #' #' # preserve exact body bytes - records in base64 encoding #' use_cassette("things4", { #' cli <- crul::HttpClient$new(url = "https://httpbin.org") #' bbb <- cli$get("get") #' }, preserve_exact_body_bytes = TRUE) #' ## see the body string value in the output here #' readLines(file.path(tempdir(), "things4.yml")) #' #' # cleanup #' unlink(file.path(tempdir(), c("things4.yml", "apple7.yml"))) #' #' #' # with httr #' library(vcr) #' library(httr) #' vcr_configure(dir = tempdir(), log = TRUE, log_opts = list(file = file.path(tempdir(), "vcr.log"))) #' #' use_cassette(name = "stuff350", { #' res <- GET("https://httpbin.org/get") #' }) #' readLines(file.path(tempdir(), "stuff350.yml")) #' #' use_cassette(name = "catfact456", { #' res <- GET("https://catfact.ninja/fact") #' }) #' #' # record mode: none #' library(crul) #' vcr_configure(dir = tempdir()) #' #' ## make a connection first #' conn <- crul::HttpClient$new("https://eu.httpbin.org") #' ## this errors because 'none' disallows any new requests #' # use_cassette("none_eg", (res2 <- conn$get("get")), record = "none") #' ## first use record mode 'once' to record to a cassette #' one <- use_cassette("none_eg", (res <- conn$get("get")), record = "once") #' one; res #' ## then use record mode 'none' to see it's behavior #' two <- use_cassette("none_eg", (res2 <- conn$get("get")), record = "none") #' two; res2 #' } use_cassette <- function(name, ..., record = NULL, match_requests_on = NULL, update_content_length_header = FALSE, allow_playback_repeats = FALSE, serialize_with = NULL, persist_with = NULL, preserve_exact_body_bytes = NULL, re_record_interval = NULL, clean_outdated_http_interactions = NULL) { cassette <- insert_cassette(name, record = record, match_requests_on = match_requests_on, update_content_length_header = update_content_length_header, allow_playback_repeats = allow_playback_repeats, serialize_with = serialize_with, persist_with = persist_with, preserve_exact_body_bytes = preserve_exact_body_bytes, re_record_interval = re_record_interval, clean_outdated_http_interactions = clean_outdated_http_interactions ) if (is.null(cassette)) { force(...) return(NULL) } on.exit(cassette$eject()) cassette$call_block(...) return(cassette) } check_empty_cassette <- function(cas) { if (!any(nzchar(readLines(cas$file())))) { warning(empty_cassette_message, call. = FALSE) } }
/scratch/gouwar.j/cran-all/cranData/vcr/R/use_cassette.R
#' vcr: Record HTTP Calls to Disk #' #' \pkg{vcr} records test suite 'HTTP' requests and replay them during #' future runs. #' #' Check out the [http testing book](https://books.ropensci.org/http-testing/) #' for a lot more documentation on `vcr`, `webmockr`, and `crul` #' #' @section Backstory: #' A Ruby gem of the same name (`VCR`, <https://github.com/vcr/vcr>) was #' created many years ago and is the original. Ports in many languages #' have been done. Check out that GitHub repo for all the details on #' how the canonical version works. #' #' @section Main functions: #' The [use_cassette] function is most likely what you'll want to use. It #' sets the cassette you want to record to, inserts the cassette, and then #' ejects the cassette, recording the interactions to the cassette. #' #' Instead, you can use [insert_cassette], but then you have to make sure #' to use [eject_cassette]. #' #' @section vcr configuration: #' [vcr_configure] is the function to use to set R session wide settings. #' See it's manual file for help. #' #' @section Record modes: #' See [recording] for help on record modes. #' #' @section Request matching: #' See [request-matching] for help on the many request matching options. #' #' @importFrom R6 R6Class #' @importFrom utils getParseData #' @importFrom yaml yaml.load yaml.load_file as.yaml #' @importFrom base64enc base64decode base64encode #' @importFrom urltools url_parse url_compose #' @importFrom crul HttpClient mock #' @importFrom httr http_status content #' @importFrom webmockr pluck_body #' @author Scott Chamberlain #' @docType package #' @aliases vcr-package #' @name vcr NULL #' An HTTP request as prepared by the \pkg{crul} package #' #' The object is a list, and is the object that is passed on to #' \pkg{webmockr} and \pkg{vcr} instead of routing through #' \pkg{crul} as normal. Used in examples/tests. #' #' @format A list #' @name crul_request #' @docType data #' @keywords data NULL
/scratch/gouwar.j/cran-all/cranData/vcr/R/vcr-package.R
vcr_text <- list( test_all = "library(\"testthat\") test_check(\"%s\")\n", config = "library(\"vcr\") # *Required* as vcr is set up on loading invisible(vcr::vcr_configure( dir = vcr::vcr_test_path(\"fixtures\") ))\nvcr::check_cassette_names()\n", example_test = "# EXAMPLE VCR USAGE: RUN AND DELETE ME foo <- function() crul::ok('https://httpbin.org/get') test_that(\"foo works\", { vcr::use_cassette(\"testing\", { x <- foo() }) expect_true(x) })\n", learn_more = "Learn more about `vcr`: https://books.ropensci.org/http-testing", gitattributes = "* text=auto tests/fixtures/**/* -diff\n" ) vcr_cat_line <- function(txt) { bullet <- crayon::green(cli::symbol$tick) cli::cat_line(paste(bullet, txt, " ")) } vcr_cat_info <- function(txt) { bullet <- cli::symbol$circle_filled cli::cat_line(paste(bullet, txt, " ")) } pkg_name <- function(dir) { desc_path <- file.path(dir, "DESCRIPTION") if (!file.exists(desc_path)) { stop("'DESCRIPTION' not found; are you sure it's an R package?") } data.frame(read.dcf(desc_path), stringsAsFactors = FALSE)[["Package"]] } suggest_vcr <- function(dir, verbose = TRUE, version = "*") { if (verbose) vcr_cat_line(sprintf("Adding %s to %s field in DESCRIPTION", crayon::blue("vcr"), crayon::red("Suggests"))) desc::desc_set_dep("vcr", "Suggests", file = dir, version = version) invisible() } test_r_file_exists <- function(dir) { ff <- setdiff( list.files(file.path(dir, "tests"), full.names=TRUE, pattern = ".R|.r"), list.dirs(file.path(dir, "tests"), recursive=FALSE)) if (length(ff) == 0) return(FALSE) any( vapply(ff, function(z) { any(grepl("test_check", readLines(z))) }, logical(1)) ) } #' Setup vcr for a package #' #' @export #' @param dir (character) path to package root. default's to #' current directory #' @param verbose (logical) print progress messages. default: `TRUE` #' @return only messages about progress, returns invisible() #' @details Sets a mimimum vcr version, which is usually the latest #' (stable) version on CRAN. You can of course easily remove or change #' the version requirement yourself after running this function. use_vcr <- function(dir = ".", verbose = TRUE) { assert(dir, "character") stopifnot(length(dir) == 1) if (!dir.exists(dir)) stop("'dir' does not exist") invisible(lapply(c("desc", "cli", "crayon"), check_for_a_pkg)) pkg <- pkg_name(dir) if (verbose) vcr_cat_info(paste0("Using package: ", crayon::blue(pkg))) # note: assuming fixtures directory if (verbose) vcr_cat_info(paste0("assuming fixtures at: ", crayon::blue("tests/fixtures"))) # add vcr to Suggests in DESCRIPTION file suggest_vcr(dir, verbose, ">= 0.6.0") # add tests/testthat.R if not present if (!dir.exists(file.path(dir, "tests/testthat"))) { if (verbose) vcr_cat_line(paste0("Creating directory: ", file.path(dir, "tests/testthat"))) dir.create(file.path(dir, "tests/testthat"), recursive = TRUE) } if (verbose) vcr_cat_info("Looking for testthat.R file or similar") tall <- file.path(dir, "tests/testthat.R") if (!test_r_file_exists(dir)) { if (verbose) vcr_cat_line(paste0(crayon::blue("tests/testthat.R:" ), " added")) file.create(tall, showWarnings = FALSE) cat(sprintf(vcr_text$test_all, pkg), file = tall, append = TRUE) } else { if (verbose) vcr_cat_info(paste0(crayon::blue("tests/testthat.R (or similar):" ), " exists")) } # add helper-pkgname.R to tests/testthat/ rel_hf <- "tests/testthat/helper-vcr.R" abs_hf <- file.path(dir, rel_hf) if (!file.exists(abs_hf)) { file.create(abs_hf, showWarnings = FALSE) } if (!any(grepl("vcr_configure", readLines(abs_hf)))) { if (verbose) vcr_cat_line(paste0("Adding vcr config to ", crayon::blue(rel_hf))) cat(vcr_text$config, file = abs_hf, append = TRUE) } else { if (verbose) vcr_cat_info(paste0("vcr config appears to be already setup in ", crayon::blue(rel_hf))) } # add dummy test file with example of use_cassette() if (verbose) vcr_cat_line(paste0("Adding example test file ", crayon::blue("tests/testthat/test-vcr_example.R"))) dummyfile <- file.path(dir, "tests/testthat/test-vcr_example.R") cat(vcr_text$example_test, file = dummyfile) # add .gitattributes file gitattsfile <- file.path(dir, ".gitattributes") if (!file.exists(gitattsfile)) { if (verbose) vcr_cat_line(paste0(crayon::blue(".gitattributes:" ), " added")) cat(vcr_text$gitattributes, file = gitattsfile) } else { if (verbose) vcr_cat_info(paste0(crayon::blue(".gitattributes:" ), " exists")) txt <- readLines(gitattsfile) if ( any(grepl("tests\\/fixtures\\/\\*\\*\\/\\* -diff", txt)) && any(grepl("* text=auto", txt)) ) { if (verbose) vcr_cat_info( paste0(crayon::blue(".gitattributes"), " already setup to ignore cassette diffs")) } else { if (verbose) vcr_cat_info(sprintf("appending lines to %s to ignore cassette diffs", crayon::blue(".gitattributes"))) cat(vcr_text$gitattributes, file = gitattsfile, append = TRUE) } } # done if (verbose) vcr_cat_info(vcr_text$learn_more) invisible() }
/scratch/gouwar.j/cran-all/cranData/vcr/R/vcr_setup.R
#' Locate file in tests directory #' #' This function, similar to `testthat::test_path()`, is designed to work both #' interactively and during tests, locating files in the `tests/` directory. #' #' @note `vcr_test_path()` assumes you are using testthat for your unit tests. #' #' @param ... Character vectors giving path component. each character string #' gets added on to the path, e.g., `vcr_test_path("a", "b")` becomes #' `tests/a/b` relative to the root of the package. #' #' @return A character vector giving the path #' @export #' @examples #' if (interactive()) { #' vcr_test_path("fixtures") #' } vcr_test_path <- function(...) { if (missing(...)) stop("Please provide a directory name.") if (any(!nzchar(...))) stop("Please use non empty path elements.") # dirname () moves up one level from testthat dir root <- dirname(rprojroot::find_testthat_root_file()) path <- file.path(root, ...) if (!dir.exists(path)){ message("could not find ", path, "; creating it") dir.create(path) } path }
/scratch/gouwar.j/cran-all/cranData/vcr/R/vcr_test_path.R
write_yaml <- function(x, file, bytes) { write_header(file) lapply(x, write_interactions, file = file, bytes = bytes) } write_json <- function(x, file, bytes) { lapply(x, write_interactions_json, file = file, bytes = bytes) } write_header <- function(file) { cat("http_interactions:", sep = "\n", file = file) } # dedup header keys so we have unique yaml keys # (x <- list(b = "foo", c = list(a = 5, a = 6))) # (x <- list(b = "foo", a = 5)) # (x <- list(b = "foo", a = 5, a = 6)) # dedup_keys(x) dedup_keys <- function(x) { if (length(x) == 0 || is.null(x)) return(x) nms <- names(x) # if repeats, collapse dups under single name if (length(unique(nms)) != length(nms)) { x <- split(x, nms) for (i in seq_along(x)) { if (length(x[[i]]) > 1) { x[[i]] <- unlist(unname(x[[i]])) } else { x[[i]] <- unlist(unname(x[[i]])) } } } return(x) } str_breaks <- function(x) { z <- str_splitter(x, 80L) paste0(z, collapse = "\n") } prep_interaction <- function(x, file, bytes) { assert(x, c("list", "HTTPInteraction")) assert(file, "character") if (is.raw(x$response$body)) bytes <- TRUE body <- if (bytes || is.raw(x$response$body)) { bd <- get_body(x$response$body) if (!is.raw(bd)) bd <- charToRaw(bd) tmp <- base64enc::base64encode(bd) str_breaks(tmp) } else { get_body(x$response$body) } if (length(body) == 0 || !nzchar(body)) body <- "" res = list( list( request = list( method = x$request$method, uri = x$request$uri, body = list( encoding = "", string = get_body(x$request$body) ), headers = dedup_keys(x$request$headers) ), response = list( status = x$response$status, headers = dedup_keys(x$response$headers), body = list( encoding = "", file = x$response$disk, string = body ) ), recorded_at = paste0(format(Sys.time(), tz = "GMT"), " GMT"), recorded_with = pkg_versions() ) ) if (bytes) { str_index <- which(grepl("string", names(res[[1]]$response$body))) names(res[[1]]$response$body)[str_index] <- "base64_string" } return(res) } # param x: a list with "request" and "response" slots # param file: a file path # param bytes: logical, whether to preserve exact bytes or not write_interactions <- function(x, file, bytes) { z <- prep_interaction(x, file, bytes) z <- headers_remove(z) z <- query_params_remove(z) tmp <- yaml::as.yaml(z) tmp <- sensitive_remove(tmp) cat(tmp, file = file, append = TRUE) } write_interactions_json <- function(x, file, bytes) { z <- prep_interaction(x, file, bytes) z <- headers_remove(z) z <- query_params_remove(z) # combine with existing data on same file, if any on_disk <- invisible(tryCatch(jsonlite::fromJSON(file, FALSE), error = function(e) e)) if (!inherits(on_disk, "error") && is.list(on_disk)) { z <- c(on_disk$http_interactions, z) } tmp <- jsonlite::toJSON( list(http_interactions = z), auto_unbox = TRUE, pretty = vcr_c$json_pretty) tmp <- sensitive_remove(tmp) cat(paste0(tmp, "\n"), file = file) } pkg_versions <- function() { paste( paste0("vcr/", utils::packageVersion("vcr")), paste0("webmockr/", utils::packageVersion("webmockr")), sep = ", " ) } get_body <- function(x) { if (is.null(x)) '' else x } encoding_guess <- function(x, bytes = FALSE, force_guess = FALSE) { if (bytes && !force_guess) return("ASCII-8BIT") enc <- try_encoding(x) if (enc == "unknown") { message("encoding couldn't be detected; assuming UTF-8") } return("UTF-8") }
/scratch/gouwar.j/cran-all/cranData/vcr/R/write.R
pluck <- function(x, name, type) { if (missing(type)) { lapply(x, "[[", name) } else { vapply(x, "[[", name, FUN.VALUE = type) } } last <- function(x) { if (length(x) == 0) { return(list()) } else { x[length(x)][1] } } errmssg <- "use_cassette requires a block.\nIf you cannot wrap your code in a block, use\ninsert_cassette / eject_cassette instead." compact <- function(x) Filter(Negate(is.null), x) `%||%` <- function(x, y) { if (missing(x) || is.null(x) || all(nchar(x) == 0) || length(x) == 0) y else x } `%try%` <- function(x, y) { z <- tryCatch(x, error = function(e) e) if (inherits(z, "error")) y else x } stract <- function(str, pattern) regmatches(str, regexpr(pattern, str)) assert <- function(x, y) { if (!is.null(x)) { if (!inherits(x, y)) { stop(deparse(substitute(x)), " must be of class ", paste0(y, collapse = ", "), call. = FALSE) } } invisible(x) } merge_list <- function(x, y, ...) { if (length(x) == 0) return(y) if (length(y) == 0) return(x) z <- match(names(y), names(x)) z <- is.na(z) if (any(z)) { x[names(y)[which(z)]] = y[which(z)] } x } check_for_a_pkg <- function(x) { if (!requireNamespace(x, quietly = TRUE)) { stop("Please install ", x, call. = FALSE) } else { invisible(TRUE) } } has_internet <- function() { z <- try(suppressWarnings(readLines('https://www.google.com', n = 1)), silent = TRUE) !inherits(z, "try-error") } can_rawToChar <- function(x) { z <- tryCatch(rawToChar(x), error = function(e) e) return(!inherits(z, "error")) } can_charToRaw <- function(x) { z <- tryCatch(charToRaw(x), error = function(e) e) return(!inherits(z, "error")) } stp <- function(...) stop(..., call. = FALSE) check_cassette_name <- function(x) { if (grepl("\\s", x)) stp("no spaces allowed in cassette names") if (grepl("\\.yml$|\\.yaml$", x)) stp("don't include a cassette path extension") # the below adapted from fs::path_sanitize, which adapted # from the npm package sanitize-filename illegal <- "[/\\?<>\\:*|\":]" control <- "[[:cntrl:]]" reserved <- "^[.]+$" windows_reserved <- "^(con|prn|aux|nul|com[0-9]|lpt[0-9])([.].*)?$" windows_trailing <- "[. ]+$" if (grepl(illegal, x)) stp("none of the following characters allowed in cassette ", "names: (/, ?, <, >, \\, :, *, |, and \")") if (grepl(control, x)) stp("no control characters allowed in cassette names") if (grepl(reserved, x)) stp("cassette names can not be simply ., .., etc.") if (grepl(windows_reserved, x)) stp("cassette names can not have reserved windows strings") if (grepl(windows_trailing, x)) stp("cassette names can not have a trailing .") if (nchar(x) > 255) stp("cassette name can not be > 255 characters") } check_request_matchers <- function(x) { mro <- c("method", "uri", "headers", "host", "path", "body", "query") if (!all(x %in% mro)) { stop("1 or more 'match_requests_on' values (", paste0(x, collapse = ", "), ") is not in the allowed set: ", paste0(mro, collapse = ", "), call. = FALSE) } x } check_record_mode <- function(x) { stopifnot(length(x) == 1, is.character(x)) recmodes <- c("none", "once", "new_episodes", "all") if (!x %in% recmodes) { stop("'record' value of '", x, "' is not in the allowed set: ", paste0(recmodes, collapse = ", "), call. = FALSE) } x } sup_cond <- function(quiet, fun, cond = suppressMessages) { if (quiet) cond(fun) else force(fun) } sup_mssg <- function(quiet, fun) sup_cond(quiet, fun) sup_warn <- function(quiet, fun) sup_cond(quiet, fun, suppressWarnings)
/scratch/gouwar.j/cran-all/cranData/vcr/R/zzz.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(vcr)
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/cassette-manual-editing.R
--- title: "Why and how to edit your vcr cassettes?" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{5. cassette manual editing} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/cassette-editing-vignette.Rmd', eval=TRUE} ``` ## Conclusion In this vignette we saw why and how to edit your vcr cassettes. We also presented approaches that use webmockr instead of vcr for mocking API responses. We mentioned editing cassettes by hand but you could also write a script using the `yaml` or `jsonlite` package to edit your YAML/JSON cassettes programmatically.
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/cassette-manual-editing.Rmd
## ----echo=FALSE--------------------------------------------------------------- knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ## ----------------------------------------------------------------------------- # library("vcr") ## ----------------------------------------------------------------------------- library("vcr") ## ----------------------------------------------------------------------------- vcr_config_defaults() ## ----------------------------------------------------------------------------- vcr_configure( dir = "foobar/vcr_cassettes" ) ## ----------------------------------------------------------------------------- vcr_configure( dir = "foobar/vcr_cassettes", record = "all" ) ## ----------------------------------------------------------------------------- vcr_configure_reset() ## ----------------------------------------------------------------------------- vcr_configure(dir = "new/path") ## ----------------------------------------------------------------------------- vcr_configure(record = "new_episodes") ## ----------------------------------------------------------------------------- vcr_configure(match_requests_on = c('query', 'headers')) ## ----------------------------------------------------------------------------- vcr_configure(allow_unused_http_interactions = FALSE) ## ----------------------------------------------------------------------------- vcr_configure(serialize_with = "yaml") ## ----------------------------------------------------------------------------- vcr_configure(persist_with = "FileSystem") ## ----------------------------------------------------------------------------- vcr_configure(ignore_hosts = "google.com") ## ----------------------------------------------------------------------------- vcr_configure(ignore_localhost = TRUE) ## ----eval=FALSE--------------------------------------------------------------- # vcr_configure(ignore_hosts = "google.com") # use_cassette("foo_bar", { # crul::HttpClient$new("https://httpbin.org/get")$get() # crul::HttpClient$new("https://google.com")$get() # }) ## ----------------------------------------------------------------------------- vcr_configure(uri_parser = "urltools::url_parse") ## ----------------------------------------------------------------------------- vcr_configure(preserve_exact_body_bytes = TRUE)
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/configuration.R
--- title: "Configure vcr" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{2. vcr configuration} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ``` vcr configuration ================= `vcr` configuration ```{r} library("vcr") ``` ```{r child='../man/rmdhunks/configuration-vignette.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/configuration.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(vcr)
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/debugging.R
--- title: "Debugging your tests that use vcr" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{4. vcr tests debugging} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/debugging-vignette.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/debugging.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/design.R
--- title: "Design of vcr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Design of vcr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r child='../man/rmdhunks/vcr-design.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/design.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(vcr)
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/internals.R
--- title: "How vcr works, in a lot of details" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{internals} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/internals-vignette.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/internals.Rmd
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ## ----setup-------------------------------------------------------------------- library(vcr) ## ----------------------------------------------------------------------------- library(vcr) turn_on() turned_on() turn_off() turned_on() ## ---- echo=FALSE-------------------------------------------------------------- vcr::turn_on()
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/lightswitch.R
--- title: "Turning vcr on and off" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{Turning vcr on and off} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/lightswitch.Rmd', eval=TRUE} ``` ```{r, echo=FALSE} vcr::turn_on() ```
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/lightswitch.Rmd
## ----echo=FALSE--------------------------------------------------------------- knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE )
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/record-modes.R
--- title: "Record modes" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{vcr record modes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r child='../man/rmdhunks/record-modes.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/record-modes.Rmd
## ----echo=FALSE--------------------------------------------------------------- knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ## ----------------------------------------------------------------------------- library(vcr) ## ----echo=FALSE, eval=FALSE--------------------------------------------------- # unlink(file.path(cassette_path(), "foo_bar.yml")) ## ----eval = FALSE------------------------------------------------------------- # use_cassette(name = "foo_bar", { # cli$post("post", body = list(a = 5)) # }, # match_requests_on = c('method', 'headers', 'body') # ) ## ----echo=FALSE, eval=FALSE--------------------------------------------------- # unlink(file.path(cassette_path(), "foo_bar.yml")) ## ----echo=FALSE, eval=FALSE--------------------------------------------------- # unlink(file.path(cassette_path(), "nothing_new.yml")) ## ----eval = FALSE------------------------------------------------------------- # library(crul) # library(vcr) # cli <- crul::HttpClient$new("https://httpbin.org/get", # headers = list(foo = "bar")) # use_cassette(name = "nothing_new", { # one <- cli$get() # }, # match_requests_on = 'headers' # ) # cli$headers$foo <- "stuff" # use_cassette(name = "nothing_new", { # two <- cli$get() # }, # match_requests_on = 'headers' # ) # one$request_headers # two$request_headers ## ----echo=FALSE, eval=FALSE--------------------------------------------------- # unlink(file.path(cassette_path(), "nothing_new.yml"))
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/request_matching.R
--- title: "Configure vcr request matching" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{3. request matching} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r child='../man/rmdhunks/request-matching-vignette.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/request_matching.Rmd
## ----echo=FALSE--------------------------------------------------------------- knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ## ----eval=FALSE--------------------------------------------------------------- # install.packages("vcr") ## ----eval=FALSE--------------------------------------------------------------- # remotes::install_github("ropensci/vcr") ## ----------------------------------------------------------------------------- # library("vcr") ## ---- echo=FALSE, message=FALSE----------------------------------------------- library("vcr") ## ----echo=FALSE, results='hide', eval=identical(Sys.getenv("IN_PKGDOWN"), "true")---- # suppressPackageStartupMessages(require(vcr, quietly = TRUE)) # unlink(file.path(cassette_path(), "helloworld.yml")) # vcr_configure(dir = tempdir()) ## ---- eval=identical(Sys.getenv("IN_PKGDOWN"), "true")------------------------ # library(vcr) # library(crul) # # cli <- crul::HttpClient$new(url = "https://eu.httpbin.org") # system.time( # use_cassette(name = "helloworld", { # cli$get("get") # }) # ) ## ---- eval=identical(Sys.getenv("IN_PKGDOWN"), "true")------------------------ # system.time( # use_cassette(name = "helloworld", { # cli$get("get") # }) # ) ## ----echo=FALSE, eval=identical(Sys.getenv("IN_PKGDOWN"), "true")------------- # unlink(file.path(cassette_path(), "helloworld.yml")) ## ---- echo = FALSE, results='asis', collapse=TRUE----------------------------- defaults <- rev(vcr_config_defaults()) defaults[unlist(lapply(defaults, is.character))] <- paste0('"', defaults[unlist(lapply(defaults, is.character))], '"') cat(sprintf("* %s = `%s`\n", names(defaults), defaults)) ## ----------------------------------------------------------------------------- vcr_configuration() ## ----echo=FALSE--------------------------------------------------------------- unlink(file.path(cassette_path(), "one.yml")) ## ----eval = FALSE------------------------------------------------------------- # use_cassette(name = "one", { # cli$post("post", body = list(a = 5)) # }, # match_requests_on = c('method', 'headers', 'body') # )
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/vcr.R
--- title: "Introduction to vcr" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{1. vcr introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ``` vcr introduction ================ `vcr` is an R port of the Ruby gem [VCR](https://github.com/vcr/vcr) (i.e., a translation, there's no Ruby here :)) `vcr` helps you stub and record HTTP requests so you don't have to repeat HTTP requests. The main use case is for unit tests, but you can use it outside of the unit test use case. `vcr` works with the `crul` and `httr` HTTP request packages. Check out the [HTTP testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`, and other packages. ## Elevator pitch ```{r child='../man/rmdhunks/elevator-pitch.Rmd', eval=TRUE} ``` ## Installation CRAN ```{r eval=FALSE} install.packages("vcr") ``` Development version ```{r eval=FALSE} remotes::install_github("ropensci/vcr") ``` ```{r} library("vcr") ``` ## Getting Started ```{r child='../man/rmdhunks/setup.Rmd', eval=TRUE} ``` ## Basic usage ```{r child='../man/rmdhunks/basic-usage.Rmd', eval=TRUE} ``` ## Terminology ```{r child='../man/rmdhunks/glossary.Rmd', eval=TRUE} ``` ## Workflows ```{r child='../man/rmdhunks/workflows.Rmd', eval=TRUE} ``` ## Configuration ```{r child='../man/rmdhunks/configuration.Rmd', eval=TRUE} ``` ## Matching/Matchers ```{r child='../man/rmdhunks/matching.Rmd', eval=TRUE} ``` ## Note about missing features ```{r child='../man/rmdhunks/missing-features.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/vcr.Rmd
## ----echo=FALSE--------------------------------------------------------------- knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ## ----setup-------------------------------------------------------------------- library("vcr") ## ----------------------------------------------------------------------------- tmpdir <- tempdir() vcr_configure( dir = file.path(tmpdir, "fixtures"), write_disk_path = file.path(tmpdir, "files") ) ## ----------------------------------------------------------------------------- library(crul) ## make a temp file f <- tempfile(fileext = ".json") ## make a request cas <- use_cassette("test_write_to_disk", { out <- HttpClient$new("https://httpbin.org/get")$get(disk = f) }) file.exists(out$content) out$parse() ## ----echo=FALSE--------------------------------------------------------------- invisible(vcr_configure_reset())
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/write-to-disk.R
--- title: "Mocking writing to disk" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{Writing to disk} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r setup} library("vcr") ``` ```{r child='../man/rmdhunks/write-to-disk.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/inst/doc/write-to-disk.Rmd
```{r, echo=FALSE, message=FALSE} library("vcr") ``` ### In tests In your tests, for whichever tests you want to use `vcr`, wrap them in a `vcr::use_cassette()` call like: ```r library(testthat) vcr::use_cassette("rl_citation", { test_that("my test", { aa <- rl_citation() expect_is(aa, "character") expect_match(aa, "IUCN") expect_match(aa, "www.iucnredlist.org") }) }) ``` OR put the `vcr::use_cassette()` block on the inside, but put `testthat` expectations outside of the `vcr::use_cassette()` block: ```r library(testthat) test_that("my test", { vcr::use_cassette("rl_citation", { aa <- rl_citation() }) expect_is(aa, "character") expect_match(aa, "IUCN") expect_match(aa, "www.iucnredlist.org") }) ``` Don't wrap the `use_cassette()` block inside your `test_that()` block with `testthat` expectations inside the `use_cassette()` block, as you'll only get the line number that the `use_cassette()` block starts on on failures. The first time you run the tests, a "cassette" i.e. a file with recorded HTTP interactions, is created at `tests/fixtures/rl_citation.yml`. The times after that, the cassette will be used. If you change your code and more HTTP interactions are needed in the code wrapped by `vcr::use_cassette("rl_citation"`, delete `tests/fixtures/rl_citation.yml` and run the tests again for re-recording the cassette. ### Outside of tests If you want to get a feel for how vcr works, although you don't need too. ```{r echo=FALSE, results='hide', eval=identical(Sys.getenv("IN_PKGDOWN"), "true")} suppressPackageStartupMessages(require(vcr, quietly = TRUE)) unlink(file.path(cassette_path(), "helloworld.yml")) vcr_configure(dir = tempdir()) ``` ```{r, eval=identical(Sys.getenv("IN_PKGDOWN"), "true")} library(vcr) library(crul) cli <- crul::HttpClient$new(url = "https://eu.httpbin.org") system.time( use_cassette(name = "helloworld", { cli$get("get") }) ) ``` The request gets recorded, and all subsequent requests of the same form used the cached HTTP response, and so are much faster ```{r, eval=identical(Sys.getenv("IN_PKGDOWN"), "true")} system.time( use_cassette(name = "helloworld", { cli$get("get") }) ) ``` ```{r echo=FALSE, eval=identical(Sys.getenv("IN_PKGDOWN"), "true")} unlink(file.path(cassette_path(), "helloworld.yml")) ``` Importantly, your unit test deals with the same inputs and the same outputs - but behind the scenes you use a cached HTTP response - thus, your tests run faster. The cached response looks something like (condensed for brevity): ```yaml http_interactions: - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '200' message: OK explanation: Request fulfilled, document follows headers: status: HTTP/1.1 200 OK connection: keep-alive body: encoding: UTF-8 string: "{\n \"args\": {}, \n \"headers\": {\n \"Accept\": \"application/json, text/xml, application/xml, */*\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"libcurl/7.54.0 r-curl/3.2 crul/0.5.2\"\n }, \n \"origin\": \"111.222.333.444\", \n \"url\": \"https://eu.httpbin.org/get\"\n}\n" recorded_at: 2018-04-03 22:55:02 GMT recorded_with: vcr/0.1.0, webmockr/0.2.4, crul/0.5.2 ``` All components of both the request and response are preserved, so that the HTTP client (in this case `crul`) can reconstruct its own response just as it would if it wasn't using `vcr`. ### Less basic usage For tweaking things to your needs, make sure to read the docs about [configuration](https://docs.ropensci.org/vcr/articles/configuration.html) (e.g., where are the fixtures saved? can they be re-recorded automatically regulary?) and [request matching](https://docs.ropensci.org/vcr/articles/request_matching.html) (how does vcr match a request to a recorded interaction?)
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/basic-usage.Rmd
## Why edit cassettes? By design vcr is very good at recording HTTP interactions that actually took place. Now sometimes when testing/demo-ing your package you will want to use _fake_ HTTP interactions. For instance: * What happens if the web API returns a 503 code? Is there an informative error? * What happens if it returns a 503 and then a 200 code? Does the retry work? * What if the API returns too much data for even simple queries and you want to make your cassettes smaller? In all these cases, you can edit your cassettes as long as you are aware of the risks! ## Risks related to cassette editing * If you use a vcr cassette where you replace a 200 code with a 503 code, and vcr is turned off, the test will fail because the API will probably not return an error. Use `vcr::skip_if_vcr_off()`. * If you edit cassettes by hand you can't re-record them easily, you'd need to re-record them then re-apply your edits. Therefore you'll need to develop a good workflow. ## Example 1: test using an edited cassette with a 503 First, write your test e.g. ```r vcr::use_cassette("api-error", { testhat("Errors are handled well", { vcr::skip_if_vcr_off() expect_error(call_my_api()), "error message") }) }) ``` Then run your tests a first time. 1. It will fail 2. It will have created a cassette under `tests/fixtures/api-error.yml` that looks something like ```yaml http_interactions: - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '200' message: OK explanation: Request fulfilled, document follows headers: status: HTTP/1.1 200 OK connection: keep-alive body: encoding: UTF-8 string: "{\n \"args\": {}, \n \"headers\": {\n \"Accept\": \"application/json, text/xml, application/xml, */*\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"libcurl/7.54.0 r-curl/3.2 crul/0.5.2\"\n }, \n \"origin\": \"111.222.333.444\", \n \"url\": \"https://eu.httpbin.org/get\"\n}\n" recorded_at: 2018-04-03 22:55:02 GMT recorded_with: vcr/0.1.0, webmockr/0.2.4, crul/0.5.2 ``` You can edit to (new status code) ```yaml http_interactions: - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '503' ``` And run your test again, it should pass! Note the use of `vcr::skip_if_vcr_off()`: if vcr is turned off, there is a real API request and most probably this request won't get a 503 as a status code. ### The same thing with webmockr The advantage of the approach involving editing cassettes is that you only learn one thing, which is vcr. Now, by using the webmockr directly in your tests, you can also test for the behavior of your package in case of errors. Below we assume `api_url()` returns the URL `call_my_api()` calls. ```r testhat("Errors are handled well", { webmockr::enable() stub <- webmockr::stub_request("get", api_url()) webmockr::to_return(stub, status = 503) expect_error(call_my_api()), "error message") webmockr::disable() }) ``` A big pro of this approach is that it works even when vcr is turned off. A con is that it's quite different from the vcr syntax. ## Example 2: test using an edited cassette with a 503 then a 200 Here we assume your package contains some sort of [retry](https://blog.r-hub.io/2020/04/07/retry-wheel/). First, write your test e.g. ```r vcr::use_cassette("api-error", { testhat("Errors are handled well", { vcr::skip_if_vcr_off() expect_message(thing <- call_my_api()), "retry message") expect_s4_class(thing, "data.frame") }) }) ``` Then run your tests a first time. 1. It will fail 2. It will have created a cassette under `tests/fixtures/api-error.yml` that looks something like ```yaml http_interactions: - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '200' message: OK explanation: Request fulfilled, document follows headers: status: HTTP/1.1 200 OK connection: keep-alive body: encoding: UTF-8 string: "{\n \"args\": {}, \n \"headers\": {\n \"Accept\": \"application/json, text/xml, application/xml, */*\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"libcurl/7.54.0 r-curl/3.2 crul/0.5.2\"\n }, \n \"origin\": \"111.222.333.444\", \n \"url\": \"https://eu.httpbin.org/get\"\n}\n" recorded_at: 2018-04-03 22:55:02 GMT recorded_with: vcr/0.1.0, webmockr/0.2.4, crul/0.5.2 ``` You can duplicate the HTTP interaction, and make the first one return a 503 status code. vcr will first use the first interaction, then the second one, when making the same request. ```yaml http_interactions: - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '503' - request: method: get uri: https://eu.httpbin.org/get body: encoding: '' string: '' headers: User-Agent: libcurl/7.54.0 r-curl/3.2 crul/0.5.2 response: status: status_code: '200' message: OK explanation: Request fulfilled, document follows headers: status: HTTP/1.1 200 OK connection: keep-alive body: encoding: UTF-8 string: "{\n \"args\": {}, \n \"headers\": {\n \"Accept\": \"application/json, text/xml, application/xml, */*\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"libcurl/7.54.0 r-curl/3.2 crul/0.5.2\"\n }, \n \"origin\": \"111.222.333.444\", \n \"url\": \"https://eu.httpbin.org/get\"\n}\n" recorded_at: 2018-04-03 22:55:02 GMT recorded_with: vcr/0.1.0, webmockr/0.2.4, crul/0.5.2 ``` And run your test again, it should pass! Note the use of `vcr::skip_if_vcr_off()`: if vcr is turned off, there is a real API request and most probably this request won't get a 503 as a status code. ### The same thing with webmockr The advantage of the approach involving editing cassettes is that you only learn one thing, which is vcr. Now, by using the webmockr directly in your tests, you can also test for the behavior of your package in case of errors. Below we assume `api_url()` returns the URL `call_my_api()` calls. ```r testhat("Errors are handled well", { webmockr::enable() stub <- webmockr::stub_request("get", api_url()) stub %>% to_return(status = 503) %>% to_return(status = 200, body = "{\n \"args\": {}, \n \"headers\": {\n \"Accept\": \"application/json, text/xml, application/xml, */*\", \n \"Accept-Encoding\": \"gzip, deflate\", \n \"Connection\": \"close\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"libcurl/7.54.0 r-curl/3.2 crul/0.5.2\"\n }, \n \"origin\": \"111.222.333.444\", \n \"url\": \"https://eu.httpbin.org/get\"\n}\n", headers = list(b = 6)) expect_message(thing <- call_my_api()), "retry message") expect_s4_class(thing, "data.frame") webmockr::disable() }) ``` The pro of this approach is the elegance of the stubbing, with the two different responses. Each webmockr function like `to_return()` even has an argument `times` indicating the number of times the given response should be returned. The con is that on top of being different from vcr, in this case where we also needed a good response in the end (the one with a 200 code, and an actual body), writing the mock is much more cumbersome than just recording a vcr cassette.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/cassette-editing-vignette.Rmd
Cassette names: - Should be meaningful so that it is obvious to you what test/function they relate to. Meaningful names are important so that you can quickly determine to what test file or test block a cassette belongs. Note that vcr cannot check that your cassette names are meaningful. - Should not be duplicated. Duplicated cassette names would lead to a test using the wrong cassette. - Should not have spaces. Spaces can lead to problems in using file paths. - Should not include a file extension. vcr handles file extensions for the user. - Should not have illegal characters that can lead to problems in using file paths: `/`, `?`, `<`, `>`, `\\`, `:`, `*`, `|`, and `\"` - Should not have control characters, e.g., `\n` - Should not have just dots, e.g., `.` or `..` - Should not have Windows reserved words, e.g., `com1` - Should not have trailing dots - Should not be longer than 255 characters `vcr::check_cassette_names()` is meant to be run during your tests, from a [`helper-*.R` file](https://testthat.r-lib.org/reference/test_dir.html#special-files) inside the `tests/testthat` directory. It only checks that cassette names are not duplicated. Note that if you do need to have duplicated cassette names you can do so by using the `allowed_duplicates` parameter in `check_cassette_names()`. A helper function `check_cassette_names()` runs inside [insert_cassette()] that checks that cassettes do not have: spaces, file extensions, unaccepted characters (slashes).
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/cassette-names.Rmd
```{r} library("vcr") ``` You can also get the default configuration variables via `vcr_config_defaults()` ```{r} vcr_config_defaults() ``` These defaults are set when you load `vcr` - you can override any of them as described below. ## Set configuration variables Use `vcr_configure()` to set configuration variables. For example, set a single variable: ```{r} vcr_configure( dir = "foobar/vcr_cassettes" ) ``` Or many at once: ```{r} vcr_configure( dir = "foobar/vcr_cassettes", record = "all" ) ``` ## Re-set to defaults ```{r} vcr_configure_reset() ``` ## Details on some of the config options ### dir Directory where cassettes are stored ```{r} vcr_configure(dir = "new/path") ``` ### record The record mode One of: 'all', 'none', 'new_episodes', 'once'. See `?recording` for info on the options ```{r} vcr_configure(record = "new_episodes") ``` ### match_requests_on Customize how `vcr` matches requests ```{r} vcr_configure(match_requests_on = c('query', 'headers')) ``` ### allow_unused_http_interactions Allow HTTP connections when no cassette Default is `TRUE`, and thus does not error when http interactions are unused. You can set to `FALSE` in which case vcr errors when a cassette is ejected and not all http interactions have been used. ```{r} vcr_configure(allow_unused_http_interactions = FALSE) ``` ### serialize_with Which serializer to use: "yaml" or "json". Note that you can have multiple cassettes with the same name as long as they use different serializers; so if you only want one cassette for a given cassette name, make sure to not switch serializers, or clean up files you no longer need. ```{r} vcr_configure(serialize_with = "yaml") ``` ### persist_with Which persister to use. Right now only option is "FileSystem" ```{r} vcr_configure(persist_with = "FileSystem") ``` ### ignoring some requests **ignore_hosts** Specify particular hosts to ignore. By ignore, we mean that real HTTP requests to the ignored host will be allowed to occur, while all others will not. ```{r} vcr_configure(ignore_hosts = "google.com") ``` **ignore_localhost** Ignore all localhost requests ```{r} vcr_configure(ignore_localhost = TRUE) ``` **ignore_request** THIS DOESN'T WORK YET **How to ignore requests** For ignoring requests, you can for example, have real http requests go through (ignored by `vcr`) while other requests are handled by `vcr`. For example, let's say you want requests to `google.com` to be ignored: ```{r eval=FALSE} vcr_configure(ignore_hosts = "google.com") use_cassette("foo_bar", { crul::HttpClient$new("https://httpbin.org/get")$get() crul::HttpClient$new("https://google.com")$get() }) ``` The request to httpbin.org will be handled by `vcr`, a cassette created for the request/response to that url, while the google.com request will be ignored and not cached at all. Note: ignoring requests only works for the `crul` package for now; it should work for `httr` in a later `vcr` version. ### uri_parse Which uri parser to use By default we use `crul::url_parse`, but you can use a different one. Remember to pass in the function quoted, and namespaced. ```{r} vcr_configure(uri_parser = "urltools::url_parse") ``` ### preserve_exact_body_bytes Some HTTP servers are not well-behaved and respond with invalid data. Set `preserve_exact_body_bytes` to `TRUE` to base64 encode the result body in order to preserve the bytes exactly as-is. `vcr` does not do this by default, since base64-encoding the string removes the human readability of the cassette. ```{r} vcr_configure(preserve_exact_body_bytes = TRUE) ``` ### filter_sensitive_data A named list of values to replace. Sometimes your package or script is working with sensitive tokens/keys, which you do not want to accidentally share with the world. Before recording (writing to a cassette) we do the replacement and then when reading from the cassette we do the reverse replacement to get back to the real data. ```r vcr_configure( filter_sensitive_data = list("<some_api_key>" = Sys.getenv('MY_API_KEY')) ) ``` Before recording to disk, the env var `MY_API_KEY` is retrieved from your machine, and we find instances of it, and replace with `<some_api_key>`. When replaying to create the HTTP response object we put the real value of the env var back in place. To target specific request or response headers see `filter_request_headers` and `filter_response_headers`. ### filter_request_headers Expects a character vector or a named list. If a character vector, or any unnamed element in a list, the request header is removed before being written to the cassette. If a named list is passed, the name is the header and the value is the value with which to replace the real value. A request header you set to remove or replace is only removed/replaced from the cassette, and any requests using a cassette, but will still be in your crul or httr response objects on a real request that creates the cassette. Examples: ```r vcr_configure( filter_request_headers = "Authorization" ) vcr_configure( filter_request_headers = c("Authorization", "User-Agent") ) vcr_configure( filter_request_headers = list(Authorization = "<<<not-my-bearer-token>>>") ) ``` ### filter_response_headers Expects a character vector or a named list. If a character vector, or any unnamed element in a list, the response header is removed before being written to the cassette. If a named list is passed, the name is the header and the value is the value with which to replace the real value. A response header you set to remove or replace is only removed/replaced from the cassette, and any requests using a cassette, but will still be in your crul or httr response objects on a real request that creates the cassette. Examples: ```r vcr_configure( filter_response_headers = "server" ) vcr_configure( filter_response_headers = c("server", "date") ) vcr_configure( filter_response_headers = list(server = "fake-server") ) ``` ### filter_query_parameters Expects a character vector or a named list. If a character vector, or any unnamed element in a list, the query parameter is removed (both parameter name and value) before being written to the cassette. If a named list is passed, the name is the query parameter name and the value is the value with which to replace the real value. A response header you set to remove or replace is only removed/replaced from the cassette, and any requests using a cassette, but will still be in your crul or httr response objects on a real request that creates the cassette. Beware of your `match_requests_on` option when using this filter. If you filter out a query parameter it's probably a bad idea to match on `query` given that there is no way for vcr to restore the exact http request from your cassette after one or more query parameters is removed or changed. One way you could filter a query parameter and still match on query or at least on the complete uri is to use replacement behavior (a named list), but instead of `list(a="b")` use two values `list(a=c("b","c"))`, where "c" is the string to be stored in the cassette. You could of course replace those values with values from environment variables so that you obscure the real values if your code is public. Examples: ```r # completely drop parameter "user" vcr_configure( filter_query_parameters = "user" ) # completely drop parameters "user" and "api_key" vcr_configure( filter_query_parameters = c("user", "api_key") ) # replace the value of parameter "api_key" with "fake-api-key" # NOTE: in this case there's no way to put back any value on # subsequent requests, so we have to match by dropping this # parameter value before comparing URIs vcr_configure( filter_query_parameters = list(api_key = "fake-api-key") ) # replace the value found at Sys.getenv("MY_API_KEY") of parameter # "api_key" with the value "foo". When using a cassette on subsequent # requests, we can replace "foo" with the value at Sys.getenv("MY_API_KEY") # before doing the URI comparison vcr_configure( filter_query_parameters = list(api_key = c(Sys.getenv("MY_API_KEY"), "foo")) ) ```
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/configuration-vignette.Rmd
See also the [configuration vignette](https://docs.ropensci.org/vcr/articles/configuration.html). We set the following defaults: ```{r, echo = FALSE, results='asis', collapse=TRUE} defaults <- rev(vcr_config_defaults()) defaults[unlist(lapply(defaults, is.character))] <- paste0('"', defaults[unlist(lapply(defaults, is.character))], '"') cat(sprintf("* %s = `%s`\n", names(defaults), defaults)) ``` You can get the defaults programmatically with ```r vcr_config_defaults() ``` You can change all the above defaults with `vcr_configure()`: ```r vcr_configure() ``` Calling `vcr_configuration()` gives you some of the more important configuration parameters in a nice tidy print out ```{r} vcr_configuration() ``` <!-- `use_cassette()` is an easier approach. An alternative is to use `insert_cassett()` + `eject_cassette()`. `use_cassette()` does both insert and eject operations for you, but you can instead do them manually by using the above functions. You do have to eject the cassette after using insert. --> For more details refer to the [configuration vignette](https://docs.ropensci.org/vcr/articles/configuration.html)
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/configuration.Rmd
Sometimes your tests using a vcr cassette will fail and you will want to debug them. ## An HTTP request has been made that vcr does not know how to handle If you get an error starting with "An HTTP request has been made that vcr does not know how to handle:" when running your tests, it means that the code in your test makes an HTTP request for which there is no matching information in the cassette you are using. You might have added a request, or changed one slightly. The easy fix is: delete the cassette and re-run the test to re-record the cassette. Run the test a second time to ensure all is well. If not, escalate to the next paragraph. Maybe you didn't actually want to change the request you are making. Make sure the requests do not contain something random, or something related to e.g. what time it is now, in the URI (`http://foo.com?time=13`). To make sure things are not varying, you might want to use mocking (of e.g. a function returning the current time), setting a random seed, using [`withr`](https://withr.r-lib.org/) (for e.g. setting an option to a certain value in your test). ### Actual debugging Ideally you will want to run the code of the tests as if it were run inside tests, in particular, using the same vcr cassette. ### Prepare your debugging environment You will first need to load either the vcr helper `tests/testthat/helper-vcr.R` (e.g. via `devtools::load_all()`) or source the vcr setup file `tests/testthat/setup-vcr.R` i.e. the file with these lines (and maybe others) ```r library("vcr") invisible(vcr::vcr_configure( dir = vcr::vcr_test_path("fixtures"), filter_sensitive_data = list("<<github_api_token>>" = Sys.getenv('GITHUB_PAT')) )) vcr::check_cassette_names() ``` If instead of `vcr::vcr_test_path("fixtures")` you see `"../fixtures"`, replace `"../fixtures"` with `vcr::vcr_test_path("fixtures")`, as `vcr::vcr_test_path()` is a function that is meant to help exactly what you will want: have the path to `tests/fixtures/` work from tests and from the root (which is where you will be running the code to debug it). So that is one step (loading the vcr helper or sourcing the vcr setup file), or maybe two (if you also had to replace `"../fixtures"` with `vcr::vcr_test_path("fixtures")`). ### Debugging itself Now look at the test whose code you are trying to debug e.g. ```r foo <- function() crul::ok('https://httpbin.org/get') test_that("foo works", { vcr::use_cassette("testing", { x <- foo() }) expect_true(x) }) ``` If you want to run the code as if you were in the test, ```r foo <- function() crul::ok('https://httpbin.org/get') vcr::insert_cassette("testing") # it will be created if needed x <- foo() x # further interactive debugging and fixes vcr::eject_cassette("testing") ``` ### Logging You can use vcr's built in logging to help in your debugging process. To configure logging, use the `vcr_configure()` function, and set `log=TRUE` and set options for logging on the `log_opts` parameter as a named list. See `?vcr_configure` for details. Here, we are setting our log file to be a temporary file that will be cleaned up at the end of the R session. Here, the file extension is `.log`, but the file extension does not matter. ```r vcr::vcr_configure( dir = vcr::vcr_test_path("fixtures"), log = TRUE, log_opts = list(file = file.path(tempdir(), "vcr.log")) ) ``` With `log=TRUE` you can continue with debugging. Open the log file you set in a text editor or other location; or examine in your shell/terminal. As an example, after running the block above ```r foo <- function() crul::ok('https://httpbin.org/get') test_that("foo works", { vcr::use_cassette("testing", { x <- foo() }) expect_true(x) }) ``` If we open the log file we'll see the logs for each step vcr takes in handling an HTTP request. The logs have information on what cassette was used, what exact time it was recorded, what matchers were in use, the cassette options, and how a request is handled. ``` [Cassette: 'testing'] - 2020-11-24 16:05:17 - Init. HTTPInteractionList w/ request matchers [method, uri] & 0 interaction(s): { } [Cassette: 'testing'] - 2020-11-24 16:05:17 - Initialized with options: {name: testing, record: once, serialize_with: yaml, persist_with: FileSystem, match_requests_on: c("method", "uri"), update_content_length_header: FALSE, allow_playback_repeats: FALSE, preserve_exact_body_bytes: FALSE} [Cassette: 'testing'] - 2020-11-24 16:05:17 - Handling request: head https://httpbin.org/get (disabled: FALSE) [Cassette: 'testing'] - 2020-11-24 16:05:17 - Identified request type: (recordable) for head https://httpbin.org/get [Cassette: 'testing'] - 2020-11-24 16:05:17 - Recorded HTTP interaction: head https://httpbin.org/get => 200 ``` Logging isn't meant to be turned on all the time - rather only for debugging/informational purposes. ### Return to normal development Make sure you ejected the cassette you were using! Unless your vcr helper/setup file tweaked more things than you would like, you do not even need to re-start R, but you could, just to be on the safe side.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/debugging-vignette.Rmd
* **Setup vcr for your package with `vcr::use_vcr()`** * Tweak the configuration to protect your secrets * **Sprinkle your tests with `vcr::use_cassette()` to save HTTP interactions to disk in "cassettes" files** * If you want to test for package behavior when the API returns e.g. a 404 or 503 code, edit the cassettes, or use [webmockr](https://docs.ropensci.org/webmockr/) Now your tests can work without any internet connection! [Demo of adding vcr testing to an R package](https://github.com/ropensci-books/exemplighratia/pull/2/files), [corresponding narrative](https://books.ropensci.org/http-testing/vcr.html).
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/elevator-pitch.Rmd
* _vcr_: the name comes from the idea that we want to record something and play it back later, like a vcr * _cassette_: A _thing_ to record HTTP interactions to. Right now the only option is the file system (writing to files), but in the future could be other things, e.g. a key-value store like Redis * _fixture_: A fixture is something used to consistently test a piece of software. In this case, a cassette (just defined above) is a fixture - used in unit tests. If you use our setup function `vcr_setup()` the default directory created to hold cassettes is called `fixtures/` as a signal as to what the folder contains. * Persisters: how to save requests - currently only option is the file system * _serialize_: translating data into a format that can be stored; here, translate HTTP request and response data into a representation on disk to read back later * Serializers: how to serialize the HTTP response - currently only option is YAML; other options in the future could include e.g. JSON * _insert cassette_: create a cassette (all HTTP interactions will be recorded to this cassette) * _eject cassette_: eject the cassette (no longer recording to that cassette) * _replay_: refers to using a cached result of an http request that was recorded earlier
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/glossary.Rmd
**The steps** 1. Use either `vcr::use_cassette()` or `vcr::insert_cassette()` a. If you use `vcr::insert_cassette()`, make sure to run `vcr::eject_cassette()` when you're done to stop recording 2. When you first run a request with `vcr` there's no cached data to use, so we allow HTTP requests until your request is done. 3. Before we run the real HTTP request, we "stub" the request with `webmockr` so that future requests will match the stub. This stub is an R6 class with details of the interaction (request + response), but is not on disk. 4. After the stub is made, we run the real HTTP request. 5. We then disallow HTTP requests so that if the request is done again we use the cached response 6. The last thing we do is write the HTTP interaction to disk in a mostly human readable form. When you run that request again using `vcr::use_cassette()` or `vcr::insert_cassette()`: * We use `webmockr` to match the request to cached requests, and since we stubbed the request the first time we used the cached response. Of course if you do a different request, even slightly (but depending on which matching format you decided to use), then the request will have no matching stub and no cached response, and then a real HTTP request is done - we then cache it, then subsequent requests will pull from that cached response. `webmockr` has adapters for each R client (crul and httr) - so that we actually intercept HTTP requests when `webmockr` is loaded and the user turns it on. So, `webmockr` doesn't actually require an internet or localhost connection at all, but can do its thing just fine by matching on whatever the user requests to match on. In fact, `webmockr` doesn't allow real HTTP requests by default, but can be toggled off of course. The main use case we are going for in `vcr` is to deal with real HTTP requests and responses, so we allow real HTTP requests when we need to, and turn it off when we don't. This gives us a very flexible and powerful framework where we can support `webmockr` and `vcr` integration for any number of R clients for HTTP requests and support many different formats serialized to disk.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/internals-vignette.Rmd
Sometimes you may need to turn off `vcr`, either for individual function calls, individual test blocks, whole test files, or for the entire package. The following attempts to break down all the options. `vcr` has the following four exported functions: - `turned_off()` - Turns vcr off for the duration of a code block - `turn_off()` - Turns vcr off completely, so that it no longer handles every HTTP request - `turn_on()` - turns vcr on; the opposite of `turn_off()` - `turned_on()` - Asks if vcr is turned on, returns a boolean Instead of using the above four functions, you could use environment variables to achieve the same thing. This way you could enable/disable `vcr` in non-interactive environments such as continuous integration, Docker containers, or running R non-interactively from the command line. The full set of environment variables `vcr` uses, all of which accept only `TRUE` or `FALSE`: - `VCR_TURN_OFF`: turn off vcr altogether; set to `TRUE` to skip any vcr usage; default: `FALSE` - `VCR_TURNED_OFF`: set the `turned_off` internal package setting; this does not turn off vcr completely as does `VCR_TURN_OFF` does, but rather is looked at together with `VCR_IGNORE_CASSETTES` - `VCR_IGNORE_CASSETTES`: set the `ignore_cassettes` internal package setting; this is looked at together with `VCR_TURNED_OFF` ## turned_off {#turned-off} `turned_off()` lets you temporarily make a real HTTP request without completely turning `vcr` off, unloading it, etc. What happens internally is we turn off `vcr`, run your code block, then on exit turn `vcr` back on - such that `vcr` is only turned off for the duration of your code block. Even if your code block errors, `vcr` will be turned back on due to use of `on.exit(turn_on())` ```r library(vcr) library(crul) turned_off({ con <- HttpClient$new(url = "https://httpbin.org/get") con$get() }) ``` ```r #> <crul response> #> url: https://httpbin.org/get #> request_headers: #> User-Agent: libcurl/7.54.0 r-curl/4.3 crul/0.9.0 #> Accept-Encoding: gzip, deflate #> Accept: application/json, text/xml, application/xml, */* #> response_headers: #> status: HTTP/1.1 200 OK #> date: Fri, 14 Feb 2020 19:44:46 GMT #> content-type: application/json #> content-length: 365 #> connection: keep-alive #> server: gunicorn/19.9.0 #> access-control-allow-origin: * #> access-control-allow-credentials: true #> status: 200 ``` ## turn_off/turn_on {#turn-off-on} `turn_off()` is different from `turned_off()` in that `turn_off()` is not aimed at a single call block, but rather it turns `vcr` off for the entire package. `turn_off()` does check first before turning `vcr` off that there is not currently a cassette in use. `turn_off()` is meant to make R ignore `vcr::insert_cassette()` and `vcr::use_cassette()` blocks in your test suite - letting the code in the block run as if they were not wrapped in `vcr` code - so that all you have to do to run your tests with cached requests/responses AND with real HTTP requests is toggle a single R function or environment variable. ```r library(vcr) vcr_configure(dir = tempdir()) # real HTTP request works - vcr is not engaged here crul::HttpClient$new(url = "https://eu.httpbin.org/get")$get() # wrap HTTP request in use_cassette() - vcr is engaged here use_cassette("foo_bar", { crul::HttpClient$new(url = "https://eu.httpbin.org/get")$get() }) # turn off & ignore cassettes - use_cassette is ignored, real HTTP request made turn_off(ignore_cassettes = TRUE) use_cassette("foo_bar", { crul::HttpClient$new(url = "https://eu.httpbin.org/get")$get() }) # if you turn off and don't ignore cassettes, error thrown turn_off(ignore_cassettes = FALSE) use_cassette("foo_bar", { res2=crul::HttpClient$new(url = "https://eu.httpbin.org/get")$get() }) # vcr back on - now use_cassette behaves as before turn_on() use_cassette("foo_bar3", { res2=crul::HttpClient$new(url = "https://eu.httpbin.org/get")$get() }) ``` ## turned_on {#turned-on} `turned_on()` does what it says on the tin - it tells you if `vcr` is turned on or not. ```{r} library(vcr) turn_on() turned_on() turn_off() turned_on() ``` ## Environment variables {#lightswitch-env-vars} The `VCR_TURN_OFF` environment variable can be used within R or on the command line to turn off `vcr`. For example, you can run tests for a package that uses `vcr`, but ignore any `use_cassette`/`insert_cassette` usage, by running this on the command line in the root of your package: ``` VCR_TURN_OFF=true Rscript -e "devtools::test()" ``` Or, similarly within R: ```r Sys.setenv(VCR_TURN_OFF = TRUE) devtools::test() ``` The `VCR_TURNED_OFF` and `VCR_IGNORE_CASSETTES` environment variables can be used in combination to achieve the same thing as `VCR_TURN_OFF`: ``` VCR_TURNED_OFF=true VCR_IGNORE_CASSETTES=true Rscript -e "devtools::test()" ```
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/lightswitch.Rmd
`vcr` looks for similarity in your HTTP requests to cached requests. You can set what is examined about the request with one or more of the following options: * `body` * `headers` * `host` * `method` * `path` * `query` * `uri` By default, we use `method` (HTTP method, e.g., `GET`) and `uri` (test for exact match against URI, e.g., `http://foo.com`). You can set your own options by tweaking the `match_requests_on` parameter: ```{r echo=FALSE} unlink(file.path(cassette_path(), "one.yml")) ``` ```{r eval = FALSE} use_cassette(name = "one", { cli$post("post", body = list(a = 5)) }, match_requests_on = c('method', 'headers', 'body') ) ``` For more details refer to the [request matching vignette](https://docs.ropensci.org/vcr/articles/request_matching.html).
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/matching.Rmd
There's a number of features in this package that are not yet supported, but for which their parameters are found in the package. We've tried to make sure the parameters that are ignored are marked as such. Keep an eye out for package updates for changes in these parameters, and/or let us know you want it and we can move it up in the priority list.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/missing-features.Rmd
Record modes dictate under what circumstances http requests/responses are recorded to cassettes (disk). Set the recording mode with the parameter `record` in the `use_cassette()` and `insert_cassette()` functions. ## once The `once` record mode will: - Replay previously recorded interactions. - Record new interactions if there is no cassette file. - Cause an error to be raised for new requests if there is a cassette file. It is similar to the `new_episodes` record mode, but will prevent new, unexpected requests from being made (i.e. because the request URI changed or whatever). `once` is the default record mode, used when you do not set one. ## none The `none` record mode will: - Replay previously recorded interactions. - Cause an error to be raised for any new requests. This is useful when your code makes potentially dangerous HTTP requests. The `none` record mode guarantees that no new HTTP requests will be made. ## new_episodes The `new_episodes` record mode will: - Record new interactions. - Replay previously recorded interactions. It is similar to the `once` record mode, but will **always** record new interactions, even if you have an existing recorded one that is similar (but not identical, based on the `match_request_on` option). ## all The `all` record mode will: - Record new interactions. - Never replay previously recorded interactions. This can be temporarily used to force vcr to re-record a cassette (i.e. to ensure the responses are not out of date) or can be used when you simply want to log all HTTP requests.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/record-modes.Rmd
To match previously recorded requests, `vcr` has to try to match new HTTP requests to a previously recorded one. By default, we match on HTTP method (e.g., `GET`) and URI (e.g., `http://foo.com`), following Ruby's VCR gem. You can customize how we match requests with one or more of the following options, some of which are on by default, some of which can be used together, and some alone. * `method`: Use the **method** request matcher to match requests on the HTTP method (i.e. GET, POST, PUT, DELETE, etc). You will generally want to use this matcher. The **method** matcher is used (along with the **uri** matcher) by default if you do not specify how requests should match. * `uri`: Use the **uri** request matcher to match requests on the request URI. The **uri** matcher is used (along with the **method** matcher) by default if you do not specify how requests should match. * `host`: Use the **host** request matcher to match requests on the request host. You can use this (alone, or in combination with **path**) as an alternative to **uri** so that non-deterministic portions of the URI are not considered as part of the request matching. * `path`: Use the **path** request matcher to match requests on the path portion of the request URI. You can use this (alone, or in combination with **host**) as an alternative to **uri** so that non-deterministic portions of the URI * `query`: Use the **query** request matcher to match requests on the query string portion of the request URI. You can use this (alone, or in combination with others) as an alternative to **uri** so that non-deterministic portions of the URI are not considered as part of the request matching. * `body`: Use the **body** request matcher to match requests on the request body. * `headers`: Use the **headers** request matcher to match requests on the request headers. You can set your own options by tweaking the `match_requests_on` parameter in `use_cassette()`: ```{r} library(vcr) ``` ```{r echo=FALSE, eval=FALSE} unlink(file.path(cassette_path(), "foo_bar.yml")) ``` ```{r eval = FALSE} use_cassette(name = "foo_bar", { cli$post("post", body = list(a = 5)) }, match_requests_on = c('method', 'headers', 'body') ) ``` ```{r echo=FALSE, eval=FALSE} unlink(file.path(cassette_path(), "foo_bar.yml")) ``` ## Matching ### headers ```{r echo=FALSE, eval=FALSE} unlink(file.path(cassette_path(), "nothing_new.yml")) ``` ```{r eval = FALSE} library(crul) library(vcr) cli <- crul::HttpClient$new("https://httpbin.org/get", headers = list(foo = "bar")) use_cassette(name = "nothing_new", { one <- cli$get() }, match_requests_on = 'headers' ) cli$headers$foo <- "stuff" use_cassette(name = "nothing_new", { two <- cli$get() }, match_requests_on = 'headers' ) one$request_headers two$request_headers ``` ```{r echo=FALSE, eval=FALSE} unlink(file.path(cassette_path(), "nothing_new.yml")) ```
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/request-matching-vignette.Rmd
The docs assume you are using testthat for your unit tests. ### `use_vcr` You can then set up your package to use `vcr` with: ```r vcr::use_vcr() ``` This will: * put `vcr` into the `DESCRIPTION` * check that `testthat` is setup * setup `testthat` if not * set the recorded cassettes to be saved in and sourced from `tests/fixtures` * setup a config file for `vcr` * add an example test file for `vcr` * make a `.gitattributes` file with settings for `vcr` * make a `./tests/testthat/helper-vcr.R` file What you will see in the R console: ``` ◉ Using package: vcr.example ◉ assuming fixtures at: tests/fixtures ✓ Adding vcr to Suggests field in DESCRIPTION ✓ Creating directory: ./tests/testthat ◉ Looking for testthat.R file or similar ✓ tests/testthat.R: added ✓ Adding vcr config to tests/testthat/helper-vcr.example.R ✓ Adding example test file tests/testthat/test-vcr_example.R ✓ .gitattributes: added ◉ Learn more about `vcr`: https://books.ropensci.org/http-testing/ ``` ### Protecting secrets Secrets often turn up in API work. A common example is an API key. `vcr` saves responses from APIs as YAML files, and this will include your secrets unless you indicate to `vcr` what they are and how to protect them. The `vcr_configure` function has the `filter_sensitive_data` argument function for just this situation. The `filter_sensitive_data` argument takes a named list where the _name_ of the list is the string that will be used in the recorded cassettes _instead of_ the secret, which is the list _item_. `vcr` will manage the replacement of that for you, so all you need to do is to edit your [`helper-vcr.R` file](https://testthat.r-lib.org/reference/test_dir.html#special-files) like this: ```r library("vcr") # *Required* as vcr is set up on loading invisible(vcr::vcr_configure( dir = "../fixtures" )) vcr::check_cassette_names() ``` Use the `filter_sensitive_data` argument in the `vcr_configure` function to show `vcr` how to keep your secret. The best way to store secret information is to have it in a `.Renviron` file. Assuming that that is already in place, supply a named list to the `filter_sensitive_data` argument. ```r library("vcr") invisible(vcr::vcr_configure( filter_sensitive_data = list("<<<my_api_key>>>" = Sys.getenv('APIKEY')), # add this dir = "../fixtures" )) vcr::check_cassette_names() ``` Notice we wrote `Sys.getenv('APIKEY')` and not the API key directly, otherwise you'd have written your API key to a file that might end up in a public repo. The will get your secret information from the environment, and make sure that whenever `vcr` records a new cassette, it will replace the secret information with `<<<my_api_key>>>`. You can find out more about this in the [HTTP testing book](https://books.ropensci.org/http-testing/) chapter on security. The addition of the line above will instruct `vcr` to replace any string in cassettes it records that are equivalent to your string which is stored as the `APIKEY` environmental variable with the masking string `<<<my_api_key>>>`. In practice, you might get a `YAML` that looks a little like this: ```yaml http_interactions: - request: method: post ... headers: Accept: application/json, text/xml, application/xml, */* Content-Type: application/json api-key: <<<my_api_key>>> ... ``` Here, my `APIKEY` environmental variable would have been stored as the `api-key` value, but `vcr` has realised this and recorded the string `<<<my_api_key>>>` instead. Once the cassette is recorded, `vcr` no longer needs the API key as no real requests will be made. Furthermore, as by default requests matching does not include the API key, things will work. **Now, how to ensure tests work in the absence of a real API key?** E.g. to have tests pass on continuous integration for external pull requests to your code repository. * vcr does not need an actual API key for requests once the cassettes are created, as no real requests will be made. * you still need to fool your _package_ into believing there is an API key as it will construct requests with it. So add the following lines to a testthat setup file (e.g. `tests/testthat/helper-vcr.R`) ```r if (!nzchar(Sys.getenv("APIKEY"))) { Sys.setenv("APIKEY" = "foobar") } ``` #### Using an `.Renviron` A simple way to manage local environmental variables is to use an [`.Renviron` file](https://rstats.wtf/r-startup.html#renviron). Your `.Renviron` file might look like this: ```sh APIKEY="mytotallysecretkey" ``` You can have this set at a project or user level, and `usethis` has the [`usethis::edit_r_environ()`](https://usethis.r-lib.org/reference/edit.html) function to help edit the file.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/setup.Rmd
This section explains `vcr`'s internal design and architecture. ### Where vcr comes from and why R6 `vcr` was "ported" from the Ruby gem (aka, library) of the same name[^1]. Because it was ported from Ruby, an object-oriented programming language I thought it would be easier to use an object system in R that most closely resemble that used in Ruby (at least in my opinion). This thinking lead to choosing [R6][]. The exported functions users interact with are not R6 classes, but are rather normal R functions. However, most of the internal code in the package uses R6. Thus, familiarity with R6 is important for people that may want to contribute to `vcr`, but not required at all for `vcr` users. ### Principles #### An easy to use interface hides complexity As described above, `vcr` uses R6 internally, but users interact with normal R functions. Internal functions that are quite complicated are largely R6 while exported, simpler functions users interact with are normal R functions. #### Class/function names are inherited from Ruby vcr Since R `vcr` was ported from Ruby, we kept most of the names of functions/classes and variables. So if you're wondering about why a function, class, or variable has a particular name, its derivation can not be found out in this package, for the most part that is. #### Hooks into HTTP clients Perhaps the most fundamental thing about that this package work is how it knows what HTTP requests are being made. This stumped me for quite a long time. When looking at Ruby vcr, at first I thought it must be "listening" for HTTP requests somehow. Then I found out about [monkey patching][mp]; that's how it's achieved in Ruby. That is, the Ruby vcr package literally overrides certain methods in Ruby HTTP clients, hijacking internals of the HTTP clients. However, monkey patching is not allowed in R. Thus, in R we have to somehow have "hooks" into HTTP clients in R. Fortunately, Scott is the maintainer of one of the HTTP clients, `crul`, so was able to quickly create a hook. Very fortunately, there was already a hook mechanism in the `httr` package. The actual hooks are not in `vcr`, but in `webmockr`. `vcr` depends on `webmockr` for hooking into HTTP clients `httr` and `crul`. ### Internal classes An overview of some of the more important aspects of vcr. #### Configuration An internal object (`vcr_c`) is created when `vcr` is loaded with the default vcr configuration options inside of an R6 class `VCRConfig` - see <https://github.com/ropensci/vcr/blob/main/R/onLoad.R>. This class is keeps track of default and user specified configuration options. You can access `vcr_c` using triple namespace `:::`, though it is not intended for general use. Whenever you make calls to `vcr_configure()` or other configuration functions, `vcr_c` is affected. #### Cassette class `Cassette` is an R6 class that handles internals/state for each cassette. Each time you run `use_cassette()` this class is used. The class has quite a few methods in it, so there's a lot going on in the class. Ideally the class would be separated into subclasses to handle similar sets of logic, but there's not an easy way to do that with R6. Of note in `Cassette` is that when called, within the `initialize()` call `webmockr` is used to create webmockr stubs. #### How HTTP requests are handled Within `webmockr`, there are calls to the vcr class `RequestHandler`, which has child classes `RequestHandlerCrul` and `RequestHandlerHttr` for `crul` and `httr`, respectively. These classes determine what to do with each HTTP request. The options for each HTTP request include: - **Ignored** You can ignore HTTP requests under certain rules using the configuration options `ignore_hosts` and `ignore_localhost` - **Stubbed by vcr** This is an HTTP request for which a match is found in the cassette defined in the `use_cassette()`/`insert_cassette()` call. In this case the matching request/response from the cassette is returned with no real HTTP request allowed. - **Recordable** This is an HTTP request for which no match is found in the cassette defined in the `use_cassette()`/`insert_cassette()` call. In this case a real HTTP request is allowed, and the request/response is recorded to the cassette. - **Unhandled** This is a group of cases, all of which cause an error to be thrown with a message trying to help the user figure out how to fix the problem. If you use [vcr logging][logging] you'll see these categories in your logs. #### Serializers Serializers handle in what format cassettes are written to files on disk. The current options are YAML (default) and JSON. YAML was implemented first in `vcr` because that's the default option in Ruby vcr. An R6 class `Serializer` is the parent class for all serializer types; `YAML` and `JSON` are both R6 classes that inherit from `Serializer`. Both `YAML` and `JSON` define just two methods: `serialize()` and `deserialize()` for converting R structures to yaml or json, and converting yaml or json back to R structures, respectively. ### Environments #### Logging An internal environment (`vcr_log_env`) is used when you use logging. At this point it only keeps track of one variable - `file` - to be able to refer to what file is used for logging across many classes/functions that need to write to the log file. #### A bit of housekeeping Another internal environment (`vcr__env`) is used to keep track of a few items, including the current cassette in use, and the last vcr error. #### Lightswitch Another internal environment (`light_switch`) is used to keep track of users turning on and off `vcr`. See `?lightswitch`. [^1]: The first version of Ruby's vcr was released in February 2010 https://rubygems.org/gems/vcr/versions/0.1.0. Ruby vcr source code: https://github.com/vcr/vcr/ [R6]: https://adv-r.hadley.nz/r6.html [mp]: https://en.wikipedia.org/wiki/Monkey_patch [logging]: https://docs.ropensci.org/vcr/articles/debugging.html?q=logging#logging-1
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/vcr-design.Rmd
### vcr for tests * See [usage section](#usage) * When running tests or checks of your whole package, note that some users have found different results with `devtools::check()` vs. `devtools::test()`. It's not clear why this would make a difference. Do let us know if you run into this problem. ### vcr in your R project You can use `vcr` in any R project as well. * Load `vcr` in your project * Similar to the above example, use `use_cassette` to run code that does HTTP requests. * The first time a real request is done, and after that the cached response will be used.
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/workflows.Rmd
If you have http requests for which you write the response to disk, then use `vcr_configure()` to set the `write_disk_path` option. See more about the write_disk_path configuration option in `vignette("configuration", package = "vcr")`. Here, we create a temporary directory, then set the fixtures ```{r} tmpdir <- tempdir() vcr_configure( dir = file.path(tmpdir, "fixtures"), write_disk_path = file.path(tmpdir, "files") ) ``` Then pass a file path (that doesn't exist yet) to crul's `disk` parameter. `vcr` will take care of handling writing the response to that file in addition to the cassette. ```{r} library(crul) ## make a temp file f <- tempfile(fileext = ".json") ## make a request cas <- use_cassette("test_write_to_disk", { out <- HttpClient$new("https://httpbin.org/get")$get(disk = f) }) file.exists(out$content) out$parse() ``` This also works with `httr`. The only difference is that you write to disk with a function `httr::write_disk(path)` rather than a parameter. Note that when you write to disk when using `vcr`, the cassette is slightly changed. Instead of holding the http response body itself, the cassette has the file path with the response body. ```yaml http_interactions: - request: method: get uri: https://httpbin.org/get response: headers: status: HTTP/1.1 200 OK access-control-allow-credentials: 'true' body: encoding: UTF-8 file: yes string: /private/var/folders/fc/n7g_vrvn0sx_st0p8lxb3ts40000gn/T/Rtmp5W4olr/files/file177e2e5d97ec.json ``` And the file has the response body that otherwise would have been in the `string` yaml field above: ```json { "args": {}, "headers": { "Accept": "application/json, text/xml, application/xml, */*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "libcurl/7.54.0 r-curl/4.3 crul/0.9.0" }, "origin": "24.21.229.59, 24.21.229.59", "url": "https://httpbin.org/get" } ``` ```{r echo=FALSE} invisible(vcr_configure_reset()) ```
/scratch/gouwar.j/cran-all/cranData/vcr/man/rmdhunks/write-to-disk.Rmd
--- title: "Why and how to edit your vcr cassettes?" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{5. cassette manual editing} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/cassette-editing-vignette.Rmd', eval=TRUE} ``` ## Conclusion In this vignette we saw why and how to edit your vcr cassettes. We also presented approaches that use webmockr instead of vcr for mocking API responses. We mentioned editing cassettes by hand but you could also write a script using the `yaml` or `jsonlite` package to edit your YAML/JSON cassettes programmatically.
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/cassette-manual-editing.Rmd
--- title: "Configure vcr" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{2. vcr configuration} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ``` vcr configuration ================= `vcr` configuration ```{r} library("vcr") ``` ```{r child='../man/rmdhunks/configuration-vignette.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/configuration.Rmd
--- title: "Debugging your tests that use vcr" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{4. vcr tests debugging} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/debugging-vignette.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/debugging.Rmd
--- title: "Design of vcr" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Design of vcr} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r child='../man/rmdhunks/vcr-design.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/design.Rmd
--- title: "How vcr works, in a lot of details" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{internals} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/internals-vignette.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/internals.Rmd
--- title: "Turning vcr on and off" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{Turning vcr on and off} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` ```{r setup} library(vcr) ``` ```{r child='../man/rmdhunks/lightswitch.Rmd', eval=TRUE} ``` ```{r, echo=FALSE} vcr::turn_on() ```
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/lightswitch.Rmd
--- title: "Record modes" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{vcr record modes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r child='../man/rmdhunks/record-modes.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/record-modes.Rmd
--- title: "Configure vcr request matching" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{3. request matching} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r child='../man/rmdhunks/request-matching-vignette.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/request_matching.Rmd
--- title: "Introduction to vcr" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{1. vcr introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE, eval = FALSE ) ``` vcr introduction ================ `vcr` is an R port of the Ruby gem [VCR](https://github.com/vcr/vcr) (i.e., a translation, there's no Ruby here :)) `vcr` helps you stub and record HTTP requests so you don't have to repeat HTTP requests. The main use case is for unit tests, but you can use it outside of the unit test use case. `vcr` works with the `crul` and `httr` HTTP request packages. Check out the [HTTP testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`, and other packages. ## Elevator pitch ```{r child='../man/rmdhunks/elevator-pitch.Rmd', eval=TRUE} ``` ## Installation CRAN ```{r eval=FALSE} install.packages("vcr") ``` Development version ```{r eval=FALSE} remotes::install_github("ropensci/vcr") ``` ```{r} library("vcr") ``` ## Getting Started ```{r child='../man/rmdhunks/setup.Rmd', eval=TRUE} ``` ## Basic usage ```{r child='../man/rmdhunks/basic-usage.Rmd', eval=TRUE} ``` ## Terminology ```{r child='../man/rmdhunks/glossary.Rmd', eval=TRUE} ``` ## Workflows ```{r child='../man/rmdhunks/workflows.Rmd', eval=TRUE} ``` ## Configuration ```{r child='../man/rmdhunks/configuration.Rmd', eval=TRUE} ``` ## Matching/Matchers ```{r child='../man/rmdhunks/matching.Rmd', eval=TRUE} ``` ## Note about missing features ```{r child='../man/rmdhunks/missing-features.Rmd', eval=TRUE} ```
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/vcr.Rmd
--- title: "Mocking writing to disk" author: "Scott Chamberlain" date: "`r Sys.Date()`" output: html_document: toc: true toc_float: true theme: readable vignette: > %\VignetteIndexEntry{Writing to disk} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r echo=FALSE} knitr::opts_chunk$set( comment = "#>", collapse = TRUE, warning = FALSE, message = FALSE ) ``` Request matching ================ ```{r setup} library("vcr") ``` ```{r child='../man/rmdhunks/write-to-disk.Rmd', eval=TRUE} ``` ## More documentation Check out the [http testing book](https://books.ropensci.org/http-testing/) for a lot more documentation on `vcr`, `webmockr`, and `crul`
/scratch/gouwar.j/cran-all/cranData/vcr/vignettes/write-to-disk.Rmd
replace_from <- function(what, pkg, to = topenv(caller_env())) { if (what %in% getNamespaceExports(pkg)) { env <- ns_env(pkg) } else { env <- to } env_get(env, what, inherit = TRUE) } # nocov start # Useful for micro-optimising default arguments requiring evaluation, # such as `param = c("foo", "bar")`. Buys about 0.6us on my desktop. fn_inline_formals <- function(fn, names) { stopifnot(typeof(fn) == "closure") fmls <- formals(fn) fmls[names] <- lapply(fmls[names], eval) formals(fn) <- fmls fn } # nocov end
/scratch/gouwar.j/cran-all/cranData/vctrs/R/aaa.R
#' Lazy character vector #' #' `new_lazy_character()` takes a function with no arguments which must return #' a character vector of arbitrary length. The function will be evaluated #' exactly once whenever any properties of the character vector are required #' (including the length or any vector elements). #' #' A "real" production level implementation might work more like #' `carrier::crate()`, where the function is isolated and users must explicitly #' provide any data required to evaluate the function, since the time of #' evaluation is unknown. #' #' As of June 2023, running `x <- new_lazy_character(~ c("x", "y"))` in the #' RStudio console will call the ALTREP length method, which materializes the #' object. Doing this in a terminal session running R does not, so it is an #' RStudio issue. This doesn't affect tests run within a `test_that()` block. #' #' @param fn A function with no arguments returning a character vector. #' #' @noRd new_lazy_character <- function(fn) { fn <- as_function(fn) .Call(ffi_altrep_new_lazy_character, fn) } lazy_character_is_materialized <- function(x) { .Call(ffi_altrep_lazy_character_is_materialized, x) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/altrep-lazy-character.R
is_altrep <- function(x) { .Call(vctrs_is_altrep, x) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/altrep.R
#' Arithmetic operations #' #' This generic provides a common double dispatch mechanism for all infix #' operators (`+`, `-`, `/`, `*`, `^`, `%%`, `%/%`, `!`, `&`, `|`). It is used #' to power the default arithmetic and boolean operators for [vctr]s objects, #' overcoming the limitations of the base [Ops] generic. #' #' `vec_arith_base()` is provided as a convenience for writing methods. It #' recycles `x` and `y` to common length then calls the base operator with the #' underlying [vec_data()]. #' #' `vec_arith()` is also used in `diff.vctrs_vctr()` method via `-`. #' #' @param op An arithmetic operator as a string #' @param x,y A pair of vectors. For `!`, unary `+` and unary `-`, `y` will be #' a sentinel object of class `MISSING`, as created by `MISSING()`. #' @inheritParams rlang::args_dots_empty #' #' @seealso [stop_incompatible_op()] for signalling that an arithmetic #' operation is not permitted/supported. #' @seealso See [vec_math()] for the equivalent for the unary mathematical #' functions. #' @export #' @keywords internal #' @examples #' d <- as.Date("2018-01-01") #' dt <- as.POSIXct("2018-01-02 12:00") #' t <- as.difftime(12, unit = "hours") #' #' vec_arith("-", dt, 1) #' vec_arith("-", dt, t) #' vec_arith("-", dt, d) #' #' vec_arith("+", dt, 86400) #' vec_arith("+", dt, t) #' vec_arith("+", t, t) #' #' vec_arith("/", t, t) #' vec_arith("/", t, 2) #' #' vec_arith("*", t, 2) vec_arith <- function(op, x, y, ...) { check_dots_empty0(...) UseMethod("vec_arith", x) } #' @export #' @rdname vec_arith vec_arith.default <- function(op, x, y, ...) { stop_incompatible_op(op, x, y) } # Atomic vectors ---------------------------------------------------------- #' @rdname vec_arith #' @export vec_arith.logical #' @method vec_arith logical #' @export vec_arith.logical <- function(op, x, y, ...) UseMethod("vec_arith.logical", y) #' @method vec_arith.logical default #' @export vec_arith.logical.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y) #' @method vec_arith.logical logical #' @export vec_arith.logical.logical <- function(op, x, y, ...) vec_arith_base(op, x, y) #' @method vec_arith.logical numeric #' @export vec_arith.logical.numeric <- function(op, x, y, ...) vec_arith_base(op, x, y) #' @rdname vec_arith #' @export vec_arith.numeric #' @method vec_arith numeric #' @export vec_arith.numeric <- function(op, x, y, ...) UseMethod("vec_arith.numeric", y) #' @method vec_arith.numeric default #' @export vec_arith.numeric.default <- function(op, x, y, ...) stop_incompatible_op(op, x, y) #' @method vec_arith.numeric logical #' @export vec_arith.numeric.logical <- function(op, x, y, ...) vec_arith_base(op, x, y) #' @method vec_arith.numeric numeric #' @export vec_arith.numeric.numeric <- function(op, x, y, ...) vec_arith_base(op, x, y) # Helpers ----------------------------------------------------------------- #' @export #' @rdname vec_arith vec_arith_base <- function(op, x, y) { args <- vec_recycle_common(x, y) op_fn <- getExportedValue("base", op) op_fn(vec_data(args[[1L]]), vec_data(args[[2L]])) } #' @export #' @rdname vec_arith MISSING <- function() { structure(list(), class = "MISSING") }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/arith.R
#' Assert an argument has known prototype and/or size #' #' @description #' `r lifecycle::badge("questioning")` #' #' * `vec_is()` is a predicate that checks if its input is a vector that #' conforms to a prototype and/or a size. #' #' * `vec_assert()` throws an error when the input is not a vector or #' doesn't conform. #' #' @inheritSection vector-checks Vectors and scalars #' #' @section Error types: #' #' `vec_is()` never throws. #' `vec_assert()` throws the following errors: #' #' * If the input is not a vector, an error of class #' `"vctrs_error_scalar_type"` is raised. #' #' * If the prototype doesn't match, an error of class #' `"vctrs_error_assert_ptype"` is raised. #' #' * If the size doesn't match, an error of class #' `"vctrs_error_assert_size"` is raised. #' #' Both errors inherit from `"vctrs_error_assert"`. #' #' @section Lifecycle: #' #' Both `vec_is()` and `vec_assert()` are questioning because their `ptype` #' arguments have semantics that are challenging to define clearly and are #' rarely useful. #' #' - Use [obj_is_vector()] or [obj_check_vector()] for vector checks #' #' - Use [vec_check_size()] for size checks #' #' - Use [vec_cast()], [inherits()], or simple type predicates like #' [rlang::is_logical()] for specific type checks #' #' @inheritParams rlang::args_error_context #' #' @param x A vector argument to check. #' @param ptype Prototype to compare against. If the prototype has a #' class, its [vec_ptype()] is compared to that of `x` with #' `identical()`. Otherwise, its [typeof()] is compared to that of #' `x` with `==`. #' @param size A single integer size against which to compare. #' @param arg Name of argument being checked. This is used in error #' messages. The label of the expression passed as `x` is taken as #' default. #' #' @return `vec_is()` returns `TRUE` or `FALSE`. `vec_assert()` either #' throws a typed error (see section on error types) or returns `x`, #' invisibly. #' @keywords internal #' @export vec_assert <- function(x, ptype = NULL, size = NULL, arg = caller_arg(x), call = caller_env()) { if (!obj_is_vector(x)) { stop_scalar_type(x, arg, call = call) } if (!is_null(ptype)) { ptype <- vec_ptype(ptype) x_type <- vec_ptype_finalise(vec_ptype(x)) if (!is_same_type(x_type, ptype)) { msg <- vec_assert_type_explain(x_type, ptype, arg) abort( msg, class = c("vctrs_error_assert_ptype", "vctrs_error_assert"), required = ptype, actual = x_type, call = call ) } } if (!is_null(size)) { size <- vec_cast(size, integer(), x_arg = "size") n_size <- length(size) if (n_size != 1L) { abort(glue::glue("`size` must be length 1, not length {n_size}.")) } x_size <- vec_size(x) if (!identical(x_size, size)) { stop_assert_size( x_size, size, arg, call = call ) } } invisible(x) } # Also thrown from C stop_assert_size <- function(actual, required, arg, call = caller_env()) { if (!nzchar(arg)) { arg <- "Input" } else { arg <- glue::backtick(arg) } message <- glue::glue("{arg} must have size {required}, not size {actual}.") stop_assert( message, class = "vctrs_error_assert_size", actual = actual, required = required, call = call ) } stop_assert <- function(message = NULL, class = NULL, ..., call = caller_env()) { stop_vctrs( message, class = c(class, "vctrs_error_assert"), ..., call = call ) } #' @rdname vec_assert #' @export vec_is <- function(x, ptype = NULL, size = NULL) { if (!obj_is_vector(x)) { return(FALSE) } if (!is_null(ptype)) { ptype <- vec_ptype(ptype) x_type <- vec_ptype_finalise(vec_ptype(x)) if (!is_same_type(x_type, ptype)) { return(FALSE) } } if (!is_null(size)) { size <- vec_recycle(vec_cast(size, integer()), 1L) x_size <- vec_size(x) if (!identical(x_size, size)) { return(FALSE) } } TRUE } #' Vector checks #' #' @description #' #' - `obj_is_vector()` tests if `x` is considered a vector in the vctrs sense. #' See _Vectors and scalars_ below for the exact details. #' #' - `obj_check_vector()` uses `obj_is_vector()` and throws a standardized and #' informative error if it returns `FALSE`. #' #' - `vec_check_size()` tests if `x` has size `size`, and throws an informative #' error if it doesn't. #' #' @inheritParams rlang::args_dots_empty #' @inheritParams rlang::args_error_context #' #' @param x For `obj_*()` functions, an object. For `vec_*()` functions, a #' vector. #' #' @param size The size to check for. #' #' @returns #' - `obj_is_vector()` returns a single `TRUE` or `FALSE`. #' #' - `obj_check_vector()` returns `NULL` invisibly, or errors. #' #' - `vec_check_size()` returns `NULL` invisibly, or errors. #' #' @section Vectors and scalars: #' #' Informally, a vector is a collection that makes sense to use as column in a #' data frame. The following rules define whether or not `x` is considered a #' vector. #' #' If no [vec_proxy()] method has been registered, `x` is a vector if: #' #' - The [base type][typeof] of the object is atomic: `"logical"`, `"integer"`, #' `"double"`, `"complex"`, `"character"`, or `"raw"`. #' #' - `x` is a list, as defined by [obj_is_list()]. #' #' - `x` is a [data.frame]. #' #' If a `vec_proxy()` method has been registered, `x` is a vector if: #' #' - The proxy satisfies one of the above conditions. #' #' - The base type of the proxy is `"list"`, regardless of its class. S3 lists #' are thus treated as scalars unless they implement a `vec_proxy()` method. #' #' Otherwise an object is treated as scalar and cannot be used as a vector. #' In particular: #' #' - `NULL` is not a vector. #' #' - S3 lists like `lm` objects are treated as scalars by default. #' #' - Objects of type [expression] are not treated as vectors. #' #' @section Technical limitations: #' #' - Support for S4 vectors is currently limited to objects that inherit from an #' atomic type. #' #' - Subclasses of [data.frame] that *append* their class to the back of the #' `"class"` attribute are not treated as vectors. If you inherit from an S3 #' class, always prepend your class to the front of the `"class"` attribute #' for correct dispatch. This matches our general principle of allowing #' subclasses but not mixins. #' #' @name vector-checks #' @examples #' obj_is_vector(1) #' #' # Data frames are vectors #' obj_is_vector(data_frame()) #' #' # Bare lists are vectors #' obj_is_vector(list()) #' #' # S3 lists are vectors if they explicitly inherit from `"list"` #' x <- structure(list(), class = c("my_list", "list")) #' obj_is_list(x) #' obj_is_vector(x) #' #' # But if they don't explicitly inherit from `"list"`, they aren't #' # automatically considered to be vectors. Instead, vctrs considers this #' # to be a scalar object, like a linear model returned from `lm()`. #' y <- structure(list(), class = "my_list") #' obj_is_list(y) #' obj_is_vector(y) #' #' # `obj_check_vector()` throws an informative error if the input #' # isn't a vector #' try(obj_check_vector(y)) #' #' # `vec_check_size()` throws an informative error if the size of the #' # input doesn't match `size` #' vec_check_size(1:5, size = 5) #' try(vec_check_size(1:5, size = 4)) NULL #' @export #' @rdname vector-checks obj_is_vector <- function(x) { .Call(ffi_obj_is_vector, x) } #' @export #' @rdname vector-checks obj_check_vector <- function(x, ..., arg = caller_arg(x), call = caller_env()) { check_dots_empty0(...) invisible(.Call(ffi_obj_check_vector, x, environment())) } #' @export #' @rdname vector-checks vec_check_size <- function(x, size, ..., arg = caller_arg(x), call = caller_env()) { check_dots_empty0(...) invisible(.Call(ffi_vec_check_size, x, size, environment())) } #' List checks #' #' @description #' - `obj_is_list()` tests if `x` is considered a list in the vctrs sense. It #' returns `TRUE` if: #' - `x` is a bare list with no class. #' - `x` is a list explicitly inheriting from `"list"`. #' #' - `list_all_vectors()` takes a list and returns `TRUE` if all elements of #' that list are vectors. #' #' - `list_all_size()` takes a list and returns `TRUE` if all elements of that #' list have the same `size`. #' #' - `obj_check_list()`, `list_check_all_vectors()`, and `list_check_all_size()` #' use the above functions, but throw a standardized and informative error if #' they return `FALSE`. #' #' @inheritParams rlang::args_error_context #' @inheritParams rlang::args_dots_empty #' #' @param x For `vec_*()` functions, an object. For `list_*()` functions, a #' list. #' #' @param size The size to check each element for. #' #' @details #' Notably, data frames and S3 record style classes like POSIXlt are not #' considered lists. #' #' @seealso [list_sizes()] #' @export #' @examples #' obj_is_list(list()) #' obj_is_list(list_of(1)) #' obj_is_list(data.frame()) #' #' list_all_vectors(list(1, mtcars)) #' list_all_vectors(list(1, environment())) #' #' list_all_size(list(1:2, 2:3), 2) #' list_all_size(list(1:2, 2:4), 2) #' #' # `list_`-prefixed functions assume a list: #' try(list_all_vectors(environment())) obj_is_list <- function(x) { .Call(ffi_obj_is_list, x) } #' @rdname obj_is_list #' @export obj_check_list <- function(x, ..., arg = caller_arg(x), call = caller_env()) { check_dots_empty0(...) invisible(.Call(ffi_check_list, x, environment())) } #' @rdname obj_is_list #' @export list_all_vectors <- function(x) { .Call(ffi_list_all_vectors, x, environment()) } #' @rdname obj_is_list #' @export list_check_all_vectors <- function(x, ..., arg = caller_arg(x), call = caller_env()) { check_dots_empty0(...) invisible(.Call(ffi_list_check_all_vectors, x, environment())) } #' @rdname obj_is_list #' @export list_all_size <- function(x, size) { .Call(ffi_list_all_size, x, size, environment()) } #' @rdname obj_is_list #' @export list_check_all_size <- function(x, size, ..., arg = caller_arg(x), call = caller_env()) { check_dots_empty0(...) invisible(.Call(ffi_list_check_all_size, x, size, environment())) } # Called from C stop_non_list_type <- function(x, arg, call) { if (nzchar(arg)) { arg <- cli::format_inline("{.arg {arg}}") } else { arg <- "Input" } cli::cli_abort( "{arg} must be a list, not {obj_type_friendly(x)}.", call = call ) } is_same_type <- function(x, ptype) { if (is_partial(ptype)) { env <- environment() ptype <- tryCatch( vctrs_error_incompatible_type = function(...) return_from(env, FALSE), vec_ptype_common(x, ptype) ) } x <- vec_slice(x, integer()) ptype <- vec_slice(ptype, integer()) # FIXME: Remove row names for matrices and arrays, and handle empty # but existing dimnames x <- vec_set_names(x, NULL) ptype <- vec_set_names(ptype, NULL) identical(x, ptype) } vec_assert_type_explain <- function(x, type, arg) { arg <- str_backtick(arg) x <- paste0("<", vec_ptype_full(x), ">") type <- paste0("<", vec_ptype_full(type), ">") intro <- paste0(arg, " must be a vector with type") intro <- layout_type(intro, type) outro <- paste0("Instead, it has type") outro <- layout_type(outro, x) paste_line( !!!intro, if (str_is_multiline(intro)) "", !!!outro ) } layout_type <- function(start, type) { if (str_is_multiline(type)) { paste_line( paste0(start, ":"), "", paste0(" ", indent(type, 2)) ) } else { paste0(start, " ", type, ".") } }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/assert.R
#' Combine many data frames into one data frame #' #' This pair of functions binds together data frames (and vectors), either #' row-wise or column-wise. Row-binding creates a data frame with common type #' across all arguments. Column-binding creates a data frame with common length #' across all arguments. #' #' @section Invariants: #' #' All inputs are first converted to a data frame. The conversion for #' 1d vectors depends on the direction of binding: #' #' * For `vec_rbind()`, each element of the vector becomes a column in #' a single row. #' * For `vec_cbind()`, each element of the vector becomes a row in a #' single column. #' #' Once the inputs have all become data frames, the following #' invariants are observed for row-binding: #' #' * `vec_size(vec_rbind(x, y)) == vec_size(x) + vec_size(y)` #' * `vec_ptype(vec_rbind(x, y)) = vec_ptype_common(x, y)` #' #' Note that if an input is an empty vector, it is first converted to #' a 1-row data frame with 0 columns. Despite being empty, its #' effective size for the total number of rows is 1. #' #' For column-binding, the following invariants apply: #' #' * `vec_size(vec_cbind(x, y)) == vec_size_common(x, y)` #' * `vec_ptype(vec_cbind(x, y)) == vec_cbind(vec_ptype(x), vec_ptype(x))` #' #' @inheritParams vec_c #' @inheritParams rlang::args_error_context #' #' @param ... Data frames or vectors. #' #' When the inputs are named: #' * `vec_rbind()` assigns names to row names unless `.names_to` is #' supplied. In that case the names are assigned in the column #' defined by `.names_to`. #' * `vec_cbind()` creates packed data frame columns with named #' inputs. #' #' `NULL` inputs are silently ignored. Empty (e.g. zero row) inputs #' will not appear in the output, but will affect the derived `.ptype`. #' @param .names_to #' This controls what to do with input names supplied in `...`. #' * By default, input names are [zapped][rlang::zap]. #' #' * If a string, specifies a column where the input names will be #' copied. These names are often useful to identify rows with #' their original input. If a column name is supplied and `...` is #' not named, an integer column is used instead. #' #' * If `NULL`, the input names are used as row names. #' @param .name_repair One of `"unique"`, `"universal"`, `"check_unique"`, #' `"unique_quiet"`, or `"universal_quiet"`. See [vec_as_names()] for the #' meaning of these options. #' #' With `vec_rbind()`, the repair function is applied to all inputs #' separately. This is because `vec_rbind()` needs to align their #' columns before binding the rows, and thus needs all inputs to #' have unique names. On the other hand, `vec_cbind()` applies the #' repair function after all inputs have been concatenated together #' in a final data frame. Hence `vec_cbind()` allows the more #' permissive minimal names repair. #' #' @return A data frame, or subclass of data frame. #' #' If `...` is a mix of different data frame subclasses, `vec_ptype2()` #' will be used to determine the output type. For `vec_rbind()`, this #' will determine the type of the container and the type of each column; #' for `vec_cbind()` it only determines the type of the output container. #' If there are no non-`NULL` inputs, the result will be `data.frame()`. #' #' @section Dependencies: #' #' ## vctrs dependencies #' #' - [vec_cast_common()] #' - [vec_proxy()] #' - [vec_init()] #' - [vec_assign()] #' - [vec_restore()] #' #' #' ## base dependencies of `vec_rbind()` #' #' - [base::c()] #' #' If columns to combine inherit from a common class, #' `vec_rbind()` falls back to `base::c()` if there exists a `c()` #' method implemented for this class hierarchy. #' #' @seealso [vec_c()] for combining 1d vectors. #' @examples #' # row binding ----------------------------------------- #' #' # common columns are coerced to common class #' vec_rbind( #' data.frame(x = 1), #' data.frame(x = FALSE) #' ) #' #' # unique columns are filled with NAs #' vec_rbind( #' data.frame(x = 1), #' data.frame(y = "x") #' ) #' #' # null inputs are ignored #' vec_rbind( #' data.frame(x = 1), #' NULL, #' data.frame(x = 2) #' ) #' #' # bare vectors are treated as rows #' vec_rbind( #' c(x = 1, y = 2), #' c(x = 3) #' ) #' #' # default names will be supplied if arguments are not named #' vec_rbind( #' 1:2, #' 1:3, #' 1:4 #' ) #' #' # column binding -------------------------------------- #' #' # each input is recycled to have common length #' vec_cbind( #' data.frame(x = 1), #' data.frame(y = 1:3) #' ) #' #' # bare vectors are treated as columns #' vec_cbind( #' data.frame(x = 1), #' y = letters[1:3] #' ) #' #' # if you supply a named data frame, it is packed in a single column #' data <- vec_cbind( #' x = data.frame(a = 1, b = 2), #' y = 1 #' ) #' data #' #' # Packed data frames are nested in a single column. This makes it #' # possible to access it through a single name: #' data$x #' #' # since the base print method is suboptimal with packed data #' # frames, it is recommended to use tibble to work with these: #' if (rlang::is_installed("tibble")) { #' vec_cbind(x = tibble::tibble(a = 1, b = 2), y = 1) #' } #' #' # duplicate names are flagged #' vec_cbind(x = 1, x = 2) #' #' @name vec_bind NULL #' @export #' @param .name_spec A name specification (as documented in [vec_c()]) #' for combining the outer inputs names in `...` and the inner row #' names of the inputs. This only has an effect when `.names_to` is #' set to `NULL`, which causes the input names to be assigned as row #' names. #' @rdname vec_bind vec_rbind <- function(..., .ptype = NULL, .names_to = rlang::zap(), .name_repair = c("unique", "universal", "check_unique", "unique_quiet", "universal_quiet"), .name_spec = NULL, .error_call = current_env()) { .External2(ffi_rbind, .ptype, .names_to, .name_repair, .name_spec) } vec_rbind <- fn_inline_formals(vec_rbind, ".name_repair") #' @export #' @rdname vec_bind #' @param .size If, `NULL`, the default, will determine the number of rows in #' `vec_cbind()` output by using the tidyverse [recycling #' rules][theory-faq-recycling]. #' #' Alternatively, specify the desired number of rows, and any inputs of length #' 1 will be recycled appropriately. vec_cbind <- function(..., .ptype = NULL, .size = NULL, .name_repair = c("unique", "universal", "check_unique", "minimal", "unique_quiet", "universal_quiet"), .error_call = current_env()) { .External2(ffi_cbind, .ptype, .size, .name_repair) } vec_cbind <- fn_inline_formals(vec_cbind, ".name_repair") as_df_row <- function(x, quiet = FALSE) { .Call(ffi_as_df_row, x, quiet, environment()) } as_df_col <- function(x, outer_name) { .Call(ffi_as_df_col, x, outer_name, environment()) } #' Frame prototype #' #' @description #' #' `r lifecycle::badge("experimental")` #' #' This is an experimental generic that returns zero-columns variants #' of a data frame. It is needed for [vec_cbind()], to work around the #' lack of colwise primitives in vctrs. Expect changes. #' #' @param x A data frame. #' @inheritParams rlang::args_dots_empty #' #' @keywords internal #' @export vec_cbind_frame_ptype <- function(x, ...) { UseMethod("vec_cbind_frame_ptype") } #' @export vec_cbind_frame_ptype.default <- function(x, ...) { x[0] } #' @export vec_cbind_frame_ptype.sf <- function(x, ...) { data.frame() }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/bind.R
#' Combine many vectors into one vector #' #' Combine all arguments into a new vector of common type. #' #' @section Invariants: #' * `vec_size(vec_c(x, y)) == vec_size(x) + vec_size(y)` #' * `vec_ptype(vec_c(x, y)) == vec_ptype_common(x, y)`. #' #' @section Dependencies: #' #' ## vctrs dependencies #' #' - [vec_cast_common()] with fallback #' - [vec_proxy()] #' - [vec_restore()] #' #' #' ## base dependencies #' #' - [base::c()] #' #' If inputs inherit from a common class hierarchy, `vec_c()` falls #' back to `base::c()` if there exists a `c()` method implemented for #' this class hierarchy. #' #' @inheritParams rlang::args_error_context #' @inheritParams vec_ptype_show #' @inheritParams name_spec #' @inheritParams vec_as_names #' #' @param ... Vectors to coerce. #' @param .name_repair How to repair names, see `repair` options in #' [vec_as_names()]. #' @return A vector with class given by `.ptype`, and length equal to the #' sum of the `vec_size()` of the contents of `...`. #' #' The vector will have names if the individual components have names #' (inner names) or if the arguments are named (outer names). If both #' inner and outer names are present, an error is thrown unless a #' `.name_spec` is provided. #' #' @seealso [vec_cbind()]/[vec_rbind()] for combining data frames by rows #' or columns. #' @export #' @examples #' vec_c(FALSE, 1L, 1.5) #' #' # Date/times -------------------------- #' c(Sys.Date(), Sys.time()) #' c(Sys.time(), Sys.Date()) #' #' vec_c(Sys.Date(), Sys.time()) #' vec_c(Sys.time(), Sys.Date()) #' #' # Factors ----------------------------- #' c(factor("a"), factor("b")) #' vec_c(factor("a"), factor("b")) #' #' #' # By default, named inputs must be length 1: #' vec_c(name = 1) #' try(vec_c(name = 1:3)) #' #' # Pass a name specification to work around this: #' vec_c(name = 1:3, .name_spec = "{outer}_{inner}") #' #' # See `?name_spec` for more examples of name specifications. vec_c <- function(..., .ptype = NULL, .name_spec = NULL, .name_repair = c("minimal", "unique", "check_unique", "universal", "unique_quiet", "universal_quiet"), .error_arg = "", .error_call = current_env()) { .External2(ffi_vec_c, .ptype, .name_spec, .name_repair) } vec_c <- fn_inline_formals(vec_c, ".name_repair") base_c <- function(xs) { # Dispatch in the base namespace which inherits from the global env exec("c", !!!xs, .env = ns_env("base")) } base_c_invoke <- function(xs) { local_options("vctrs:::base_c_in_progress" = TRUE) # Remove all `NULL` arguments which prevent dispatch if in first # position and might not be handled correctly by methods xs <- compact(xs) unspecified <- map_lgl(xs, fallback_is_unspecified) if (!any(unspecified)) { return(base_c(xs)) } # First concatenate without the unspecified chunks. This way the # `c()` method doesn't need to handle unspecified inputs correctly, # and we're guaranteed to dispatch on the correct class even if the # first input is unspecified. out <- base_c(xs[!unspecified]) # Create index vector with `NA` locations for unspecified chunks locs <- c_locs(xs) locs[unspecified] <- map(locs[unspecified], rep_along, na_int) locs[!unspecified] <- c_locs(xs[!unspecified]) locs <- vec_c(!!!locs, .ptype = int()) # Expand the concatenated vector with unspecified chunks out[locs] } # FIXME: Should be unnecessary in the future. We currently attach an # attribute to unspecified columns initialised in `df_cast()`. We # can't use an unspecified vector because we (unnecessarily but for # convenience) go through `vec_assign()` before falling back in # `vec_rbind()`. fallback_is_unspecified <- function(x) { is_unspecified(x) || is_true(attr(x, "vctrs:::unspecified")) } c_locs <- function(xs) { locs <- reduce(lengths(xs), .init = list(0), function(output, input) { n <- last(last(output)) c(output, list(seq(n + 1, n + input))) }) locs[-1] }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/c.R
#' Cast a vector to a specified type #' #' @description #' #' `vec_cast()` provides directional conversions from one type of #' vector to another. Along with [vec_ptype2()], this generic forms #' the foundation of type coercions in vctrs. #' #' @includeRmd man/faq/developer/links-coercion.Rmd #' #' @inheritParams rlang::args_error_context #' @param x Vectors to cast. #' @param ... For `vec_cast_common()`, vectors to cast. For #' `vec_cast()`, `vec_cast_default()`, and `vec_restore()`, these #' dots are only for future extensions and should be empty. #' @param to,.to Type to cast to. If `NULL`, `x` will be returned as is. #' @param x_arg Argument name for `x`, used in error messages to #' inform the user about the locations of incompatible types #' (see [stop_incompatible_type()]). #' @param to_arg Argument name `to` used in error messages to #' inform the user about the locations of incompatible types #' (see [stop_incompatible_type()]). #' @return A vector the same length as `x` with the same type as `to`, #' or an error if the cast is not possible. An error is generated if #' information is lost when casting between compatible types (i.e. when #' there is no 1-to-1 mapping for a specific value). #' #' @section Dependencies of `vec_cast_common()`: #' #' ## vctrs dependencies #' #' - [vec_ptype2()] #' - [vec_cast()] #' #' #' ## base dependencies #' #' Some functions enable a base-class fallback for #' `vec_cast_common()`. In that case the inputs are deemed compatible #' when they have the same [base type][base::typeof] and inherit from #' the same base class. #' #' @seealso Call [stop_incompatible_cast()] when you determine from the #' attributes that an input can't be cast to the target type. #' @export #' @examples #' # x is a double, but no information is lost #' vec_cast(1, integer()) #' #' # When information is lost the cast fails #' try(vec_cast(c(1, 1.5), integer())) #' try(vec_cast(c(1, 2), logical())) #' #' # You can suppress this error and get the partial results #' allow_lossy_cast(vec_cast(c(1, 1.5), integer())) #' allow_lossy_cast(vec_cast(c(1, 2), logical())) #' #' # By default this suppress all lossy cast errors without #' # distinction, but you can be specific about what cast is allowed #' # by supplying prototypes #' allow_lossy_cast(vec_cast(c(1, 1.5), integer()), to_ptype = integer()) #' try(allow_lossy_cast(vec_cast(c(1, 2), logical()), to_ptype = integer())) #' #' # No sensible coercion is possible so an error is generated #' try(vec_cast(1.5, factor("a"))) #' #' # Cast to common type #' vec_cast_common(factor("a"), factor(c("a", "b"))) vec_cast <- function(x, to, ..., x_arg = caller_arg(x), to_arg = "", call = caller_env()) { if (!missing(...)) { check_ptype2_dots_empty(...) } return(.Call(ffi_cast, x, to, environment())) UseMethod("vec_cast", to) } vec_cast_dispatch <- function(x, to, ..., x_arg = "", to_arg = "") { UseMethod("vec_cast", to) } vec_cast_dispatch_native <- function(x, to, ..., x_arg = "", to_arg = "", call = caller_env()) { .Call( ffi_cast_dispatch_native, x, to, match_fallback_opts(...), x_arg, to_arg, environment() ) } #' @export #' @rdname vec_cast vec_cast_common <- function(..., .to = NULL, .arg = "", .call = caller_env()) { .External2(ffi_cast_common, .to) } vec_cast_common_opts <- function(..., .to = NULL, .opts = fallback_opts(), .arg = "", .call = caller_env()) { .External2(ffi_cast_common_opts, .to, .opts) } vec_cast_common_params <- function(..., .to = NULL, .s3_fallback = NULL, .arg = "", .call = caller_env()) { opts <- fallback_opts( s3_fallback = .s3_fallback ) vec_cast_common_opts( ..., .to = .to, .opts = opts, .arg = .arg, .call = .call ) } vec_cast_common_fallback <- function(..., .to = NULL, .arg = "", .call = caller_env()) { vec_cast_common_opts( ..., .to = .to, .opts = full_fallback_opts(), .arg = .arg, .call = .call ) } #' @rdname vec_default_ptype2 #' @inheritParams vec_cast #' @export vec_default_cast <- function(x, to, ..., x_arg = "", to_arg = "", call = caller_env()) { if (is_asis(x)) { return(vec_cast_from_asis( x, to, x_arg = x_arg, to_arg = to_arg, call = call )) } if (is_asis(to)) { return(vec_cast_to_asis( x, to, x_arg = x_arg, to_arg = to_arg, call = call )) } if (inherits(to, "vctrs_vctr") && !inherits(to, c("vctrs_rcrd", "vctrs_list_of"))) { return(vctr_cast( x, to, x_arg = x_arg, to_arg = to_arg, call = call )) } opts <- match_fallback_opts(...) if (is_common_class_fallback(to) && length(common_class_suffix(x, to))) { return(x) } # Data frames have special bare class and same type fallbacks if (is.data.frame(x) && is.data.frame(to)) { out <- df_cast_opts( x, to, ..., opts = opts, x_arg = x_arg, to_arg = to_arg, call = call ) # Same-type fallback for data frames. If attributes of the empty # data frames are congruent, just reproduce these attributes. This # eschews any constraints on rows and cols that `[` and `[<-` # methods might have. If that is a problem, the class needs to # implement vctrs methods. if (identical(non_df_attrib(x), non_df_attrib(to))) { attributes(out) <- c(df_attrib(out), non_df_attrib(to)) return(out) } # Bare-class fallback for data frames. # FIXME: Should we only allow it when target is a bare df? if (inherits(to, "tbl_df")) { out <- df_as_tibble(out) } return(out) } if (is_same_type(x, to)) { return(x) } withRestarts( stop_incompatible_cast( x, to, x_arg = x_arg, to_arg = to_arg, `vctrs:::from_dispatch` = match_from_dispatch(...), call = call ), vctrs_restart_cast = function(out) { out } ) } is_bare_df <- function(x) { inherits_only(x, "data.frame") || inherits_only(x, c("tbl_df", "tbl", "data.frame")) } is_informative_error_vctrs_error_cast_lossy <- function(x, ...) { FALSE }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/cast.R
# proxies ----------------------------------------------------------------- #' Comparison and order proxy #' #' @description #' `vec_proxy_compare()` and `vec_proxy_order()` return proxy objects, i.e. #' an atomic vector or data frame of atomic vectors. #' #' For [`vctrs_vctr`][vctr] objects: #' #' - `vec_proxy_compare()` determines the behavior of `<`, `>`, `>=` #' and `<=` (via [vec_compare()]); and [min()], [max()], [median()], and #' [quantile()]. #' #' - `vec_proxy_order()` determines the behavior of `order()` and `sort()` #' (via `xtfrm()`). #' #' @details #' The default method of `vec_proxy_compare()` assumes that all classes built #' on top of atomic vectors or records are comparable. Internally the default #' calls [vec_proxy_equal()]. If your class is not comparable, you will need #' to provide a `vec_proxy_compare()` method that throws an error. #' #' The behavior of `vec_proxy_order()` is identical to `vec_proxy_compare()`, #' with the exception of lists. Lists are not comparable, as comparing #' elements of different types is undefined. However, to allow ordering of #' data frames containing list-columns, the ordering proxy of a list is #' generated as an integer vector that can be used to order list elements #' by first appearance. #' #' If a class implements a `vec_proxy_compare()` method, it usually doesn't need #' to provide a `vec_proxy_order()` method, because the latter is implemented #' by forwarding to `vec_proxy_compare()` by default. Classes inheriting from #' list are an exception: due to the default `vec_proxy_order()` implementation, #' `vec_proxy_compare()` and `vec_proxy_order()` should be provided for such #' classes (with identical implementations) to avoid mismatches between #' comparison and sorting. #' #' @inheritSection vec_proxy_equal Data frames #' #' @param x A vector x. #' @inheritParams rlang::args_dots_empty #' @return A 1d atomic vector or a data frame. #' #' @section Dependencies: #' - [vec_proxy_equal()] called by default in `vec_proxy_compare()` #' - [vec_proxy_compare()] called by default in `vec_proxy_order()` #' #' @keywords internal #' @export #' @examples #' # Lists are not comparable #' x <- list(1:2, 1, 1:2, 3) #' try(vec_compare(x, x)) #' #' # But lists are orderable by first appearance to allow for #' # ordering data frames with list-cols #' df <- new_data_frame(list(x = x)) #' vec_sort(df) vec_proxy_compare <- function(x, ...) { check_dots_empty0(...) return(.Call(vctrs_proxy_compare, x)) UseMethod("vec_proxy_compare") } #' @export vec_proxy_compare.default <- function(x, ...) { stop_native_implementation("vec_proxy_compare.default") } #' @rdname vec_proxy_compare #' @export vec_proxy_order <- function(x, ...) { check_dots_empty0(...) return(.Call(vctrs_proxy_order, x)) UseMethod("vec_proxy_order") } #' @export vec_proxy_order.default <- function(x, ...) { stop_native_implementation("vec_proxy_order.default") } # compare ----------------------------------------------------------------- #' Compare two vectors #' #' @section S3 dispatch: #' `vec_compare()` is not generic for performance; instead it uses #' [vec_proxy_compare()] to create a proxy that is used in the comparison. #' #' @param x,y Vectors with compatible types and lengths. #' @param na_equal Should `NA` values be considered equal? #' @param .ptype Override to optionally specify common type #' @return An integer vector with values -1 for `x < y`, 0 if `x == y`, #' and 1 if `x > y`. If `na_equal` is `FALSE`, the result will be `NA` #' if either `x` or `y` is `NA`. #' #' @section Dependencies: #' - [vec_cast_common()] with fallback #' - [vec_recycle_common()] #' - [vec_proxy_compare()] #' #' @export #' @examples #' vec_compare(c(TRUE, FALSE, NA), FALSE) #' vec_compare(c(TRUE, FALSE, NA), FALSE, na_equal = TRUE) #' #' vec_compare(1:10, 5) #' vec_compare(runif(10), 0.5) #' vec_compare(letters[1:10], "d") #' #' df <- data.frame(x = c(1, 1, 1, 2), y = c(0, 1, 2, 1)) #' vec_compare(df, data.frame(x = 1, y = 1)) vec_compare <- function(x, y, na_equal = FALSE, .ptype = NULL) { obj_check_vector(x) obj_check_vector(y) check_bool(na_equal) args <- vec_recycle_common(x, y) args <- vec_cast_common_params(!!!args, .to = .ptype) .Call(ffi_vec_compare, vec_proxy_compare(args[[1]]), vec_proxy_compare(args[[2]]), na_equal) } # Helpers ----------------------------------------------------------------- # Used for testing cmp <- function(x, y) (x > y) - (x < y)
/scratch/gouwar.j/cran-all/cranData/vctrs/R/compare.R
#' Complete #' #' @description #' `vec_detect_complete()` detects "complete" observations. An observation is #' considered complete if it is non-missing. For most vectors, this implies that #' `vec_detect_complete(x) == !vec_detect_missing(x)`. #' #' For data frames and matrices, a row is only considered complete if all #' elements of that row are non-missing. To compare, `!vec_detect_missing(x)` #' detects rows that are partially complete (they have at least one non-missing #' value). #' #' @details #' A [record][new_rcrd] type vector is similar to a data frame, and is only #' considered complete if all fields are non-missing. #' #' @param x A vector #' #' @return #' A logical vector with the same size as `x`. #' #' @seealso [stats::complete.cases()] #' @export #' @examples #' x <- c(1, 2, NA, 4, NA) #' #' # For most vectors, this is identical to `!vec_detect_missing(x)` #' vec_detect_complete(x) #' !vec_detect_missing(x) #' #' df <- data_frame( #' x = x, #' y = c("a", "b", NA, "d", "e") #' ) #' #' # This returns `TRUE` where all elements of the row are non-missing. #' # Compare that with `!vec_detect_missing()`, which detects rows that have at #' # least one non-missing value. #' df2 <- df #' df2$all_non_missing <- vec_detect_complete(df) #' df2$any_non_missing <- !vec_detect_missing(df) #' df2 vec_detect_complete <- function(x) { .Call(vctrs_detect_complete, x) } vec_slice_complete <- function(x) { .Call(vctrs_slice_complete, x) } vec_locate_complete <- function(x) { .Call(vctrs_locate_complete, x) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/complete.R
#' Custom conditions for vctrs package #' #' These functions are called for their side effect of raising #' errors and warnings. #' These conditions have custom classes and structures to make #' testing easier. #' #' @inheritParams rlang::args_error_context #' @param x,y,to Vectors #' @param ...,class Only use these fields when creating a subclass. #' @param x_arg,y_arg,to_arg Argument names for `x`, `y`, and `to`. Used in #' error messages to inform the user about the locations of incompatible #' types. #' @param action An option to customize the incompatible type message depending #' on the context. Errors thrown from [vec_ptype2()] use `"combine"` and #' those thrown from [vec_cast()] use `"convert"`. #' @param details Any additional human readable details. #' @param message An overriding message for the error. `details` and #' `message` are mutually exclusive, supplying both is an error. #' #' @examples #' #' # Most of the time, `maybe_lossy_cast()` returns its input normally: #' maybe_lossy_cast( #' c("foo", "bar"), #' NA, #' "", #' lossy = c(FALSE, FALSE), #' x_arg = "", #' to_arg = "" #' ) #' #' # If `lossy` has any `TRUE`, an error is thrown: #' try(maybe_lossy_cast( #' c("foo", "bar"), #' NA, #' "", #' lossy = c(FALSE, TRUE), #' x_arg = "", #' to_arg = "" #' )) #' #' # Unless lossy casts are allowed: #' allow_lossy_cast( #' maybe_lossy_cast( #' c("foo", "bar"), #' NA, #' "", #' lossy = c(FALSE, TRUE), #' x_arg = "", #' to_arg = "" #' ) #' ) #' #' @keywords internal #' @name vctrs-conditions NULL stop_vctrs <- function(message = NULL, class = NULL, ..., call = caller_env()) { abort( message, class = c(class, "vctrs_error"), ..., call = call ) } warn_vctrs <- function(message = NULL, class = NULL, ..., call = caller_env()) { warn( message, class = c(class, "vctrs_warning"), ..., call = call ) } stop_incompatible <- function(x, y, ..., details = NULL, message = NULL, class = NULL, call = caller_env()) { stop_vctrs( message, class = c(class, "vctrs_error_incompatible"), x = x, y = y, details = details, ..., call = call ) } #' @return #' `stop_incompatible_*()` unconditionally raise an error of class #' `"vctrs_error_incompatible_*"` and `"vctrs_error_incompatible"`. #' #' @rdname vctrs-conditions #' @export stop_incompatible_type <- function(x, y, ..., x_arg, y_arg, action = c("combine", "convert"), details = NULL, message = NULL, class = NULL, call = caller_env()) { obj_check_vector(x, arg = x_arg) obj_check_vector(y, arg = y_arg) action <- arg_match(action) message <- cnd_type_message( x, y, x_arg, y_arg, details, action, message, from_dispatch = match_from_dispatch(...) ) subclass <- switch( action, combine = "vctrs_error_ptype2", convert = "vctrs_error_cast" ) stop_incompatible( x, y, x_arg = x_arg, y_arg = y_arg, details = details, ..., message = message, class = c(class, subclass, "vctrs_error_incompatible_type"), call = call ) } #' @rdname vctrs-conditions #' @export stop_incompatible_cast <- function(x, to, ..., x_arg, to_arg, details = NULL, message = NULL, class = NULL, call = caller_env()) { stop_incompatible_type( x = x, y = to, to = to, ..., x_arg = x_arg, y_arg = to_arg, to_arg = to_arg, action = "convert", details = details, message = message, class = class, call = call ) } stop_incompatible_shape <- function(x, y, x_size, y_size, axis, x_arg, y_arg, call = caller_env()) { details <- format_error_bullets(c( x = glue::glue("Incompatible sizes {x_size} and {y_size} along axis {axis}.") )) stop_incompatible_type( x, y, x_arg = x_arg, y_arg = y_arg, details = details, call = call ) } type_actions <- c( "combine", "convert" ) cnd_type_separator <- function(action) { if (identical(action, "combine")) { "and" } else if (identical(action, "convert")) { "to" } else { abort("Internal error: Unknown `action`.") } } cnd_type_message <- function(x, y, x_arg, y_arg, details, action, message, from_dispatch = FALSE, fallback = NULL) { if (!is_null(message)) { if (!is_null(details)) { abort("Can't supply both `message` and `details`.") } return(message) } x_arg <- arg_as_string(x_arg) y_arg <- arg_as_string(y_arg) if (nzchar(x_arg)) { x_name <- paste0(" `", x_arg, "` ") } else { x_name <- " " } if (nzchar(y_arg)) { y_name <- paste0(" `", y_arg, "` ") } else { y_name <- " " } separator <- cnd_type_separator(action) if (is.data.frame(x) && is.data.frame(y)) { if (vec_is_coercible(new_data_frame(x), new_data_frame(y))) { x_type <- cnd_type_message_df_label(x) y_type <- cnd_type_message_df_label(y) } else { x_type <- vec_ptype_full(x) y_type <- vec_ptype_full(y) } } else { x_type <- cnd_type_message_type_label(x) y_type <- cnd_type_message_type_label(y) } converting <- action == "convert" # If we are here directly from dispatch, this means there is no # ptype2 method implemented and the is-same-class fallback has # failed because of diverging attributes. The author of the class # should implement a ptype2 method as documented in the FAQ # indicated below. if (from_dispatch && !converting && identical(class(x)[[1]], class(y)[[1]])) { details <- c(incompatible_attrib_bullets(), details) details <- format_error_bullets(details) } if (is_null(fallback)) { end <- "." } else { end <- glue::glue("; falling back to {fallback}.") } if (converting && nzchar(y_arg)) { header <- glue::glue("Can't convert{x_name}<{x_type}> to match type of{y_name}<{y_type}>{end}") } else { header <- glue::glue("Can't {action}{x_name}<{x_type}> {separator}{y_name}<{y_type}>{end}") } paste_line(header, details) } cnd_type_message_type_label <- function(x) { if (is.data.frame(x)) { class(x)[[1]] } else { vec_ptype_full(x) } } incompatible_attrib_bullets <- function() { c( x = "Some attributes are incompatible.", i = "The author of the class should implement vctrs methods.", i = "See <https://vctrs.r-lib.org/reference/faq-error-incompatible-attributes.html>." ) } cnd_type_message_df_label <- function(x) { x <- class(x)[[1]] if (identical(x, "tbl_df")) { "tibble" } else { x } } #' @rdname vctrs-conditions #' @export stop_incompatible_op <- function(op, x, y, details = NULL, ..., message = NULL, class = NULL, call = caller_env()) { message <- message %||% glue_lines( "<{vec_ptype_full(x)}> {op} <{vec_ptype_full(y)}> is not permitted", details ) stop_incompatible( x, y, op = op, details = details, ..., message = message, class = c(class, "vctrs_error_incompatible_op"), call = call ) } #' @rdname vctrs-conditions #' @export stop_incompatible_size <- function(x, y, x_size, y_size, ..., x_arg, y_arg, details = NULL, message = NULL, class = NULL, call = caller_env()) { stop_incompatible( x, y, x_size = x_size, y_size = y_size, ..., x_arg = x_arg, y_arg = y_arg, details = details, message = message, class = c(class, "vctrs_error_incompatible_size"), call = call ) } #' @export cnd_header.vctrs_error_incompatible_size <- function(cnd, ...) { if (is_string(cnd$message) && nzchar(cnd$message)) { return(cnd$message) } x_size <- vec_cast(cnd$x_size, int()) y_size <- vec_cast(cnd$y_size, int()) stopifnot( length(x_size) == 1, length(y_size) == 1 ) x_arg <- arg_as_string(cnd$x_arg) y_arg <- arg_as_string(cnd$y_arg) if (nzchar(x_arg)) { x_tag <- glue::glue("`{x_arg}` (size {x_size})") } else { x_tag <- glue::glue("input of size {x_size}") } if (nzchar(y_arg)) { y_tag <- glue::glue("to match `{y_arg}` (size {y_size})") } else { y_tag <- glue::glue("to size {y_size}") } glue::glue("Can't recycle {x_tag} {y_tag}.") } #' @export cnd_body.vctrs_error_incompatible_size <- function(cnd, ...) { cnd$details } #' Lossy cast error #' #' @description #' #' `r lifecycle::badge("experimental")` #' #' By default, lossy casts are an error. Use `allow_lossy_cast()` to #' silence these errors and continue with the partial results. In this #' case the lost values are typically set to `NA` or to a lower value #' resolution, depending on the type of cast. #' #' Lossy cast errors are thrown by `maybe_lossy_cast()`. Unlike #' functions prefixed with `stop_`, `maybe_lossy_cast()` usually #' returns a result. If a lossy cast is detected, it throws an error, #' unless it's been wrapped in `allow_lossy_cast()`. In that case, it #' returns the result silently. #' #' @inheritParams stop_incompatible_cast #' @inheritParams vec_cast #' @inheritParams rlang::args_error_context #' @param result The result of a potentially lossy cast. #' @param to Type to cast to. #' @param lossy A logical vector indicating which elements of `result` #' were lossy. #' #' Can also be a single `TRUE`, but note that `locations` picks up #' locations from this vector by default. In this case, supply your #' own location vector, possibly empty. #' @param loss_type The kind of lossy cast to be mentioned in error #' messages. Can be loss of precision (for instance from double to #' integer) or loss of generality (from character to factor). #' @param locations An optional integer vector giving the #' locations where `x` lost information. #' @param .deprecation If `TRUE`, the error is downgraded to a #' deprecation warning. This is useful for transitioning your class #' to a stricter conversion scheme. The warning advises your users #' to wrap their code with `allow_lossy_cast()`. #' @keywords internal #' @export maybe_lossy_cast <- function(result, x, to, lossy = NULL, locations = NULL, ..., loss_type = c("precision", "generality"), x_arg, to_arg, call = caller_env(), details = NULL, message = NULL, class = NULL, .deprecation = FALSE) { if (!any(lossy)) { return(result) } if (.deprecation) { maybe_warn_deprecated_lossy_cast(x, to, loss_type, x_arg, to_arg) return(result) } locations <- locations %||% which(lossy) withRestarts( vctrs_restart_error_cast_lossy = function() result, stop_lossy_cast( x = x, to = to, result = result, locations = locations, ..., loss_type = loss_type, x_arg = x_arg, to_arg = to_arg, details = details, message = message, class = class, call = call ) ) } stop_lossy_cast <- function(x, to, result, locations = NULL, ..., loss_type, x_arg, to_arg, details = NULL, message = NULL, class = NULL, call = caller_env()) { stop_incompatible_cast( x = x, to = to, result = result, locations = locations, ..., loss_type = loss_type, x_arg = x_arg, to_arg = to_arg, details = details, class = c(class, "vctrs_error_cast_lossy"), call = call ) } #' @export cnd_header.vctrs_error_cast_lossy <- function(cnd, ...) { x_label <- format_arg_label(vec_ptype_full(cnd$x), cnd$x_arg) to_label <- format_arg_label(vec_ptype_full(cnd$y), cnd$y_arg) loss_type <- loss_type(cnd$loss_type) glue::glue("Can't convert from {x_label} to {to_label} due to loss of {loss_type}.") } #' @export cnd_body.vctrs_error_cast_lossy <- function(cnd, ...) { if (length(cnd$locations)) { format_error_bullets(inline_list("Locations: ", cnd$locations)) } else { character() } } loss_type <- function(x) { stopifnot( is_character(x), all(x %in% c("precision", "generality")) ) x[[1]] } # Used in maybe_warn_deprecated_lossy_cast() new_error_cast_lossy <- function(x, to, loss_type, x_arg = "", to_arg = "") { error_cnd( c("vctrs_error_cast_lossy", "vctrs_error_incompatible_type"), x = x, y = to, loss_type = loss_type, x_arg = x_arg, y_arg = to_arg ) } #' @rdname vctrs-conditions #' @param x_ptype,to_ptype Suppress only the casting errors where `x` #' or `to` match these [prototypes][vec_ptype]. #' @export allow_lossy_cast <- function(expr, x_ptype = NULL, to_ptype = NULL) { withCallingHandlers( vctrs_error_cast_lossy = function(err) { if (!is_null(x_ptype) && !vec_is(err$x, x_ptype)) { return() } if (!is_null(to_ptype) && !vec_is(err$y, to_ptype)) { return() } invokeRestart("vctrs_restart_error_cast_lossy") }, expr ) } maybe_warn_deprecated_lossy_cast <- function(x, to, loss_type, x_arg, to_arg, user_env = caller_env(2)) { # Returns `TRUE` if `allow_lossy_cast()` is on the stack and accepts # to handle the condition handled <- withRestarts( vctrs_restart_error_cast_lossy = function() TRUE, { # Signal fully formed condition but strip the error classes in # case someone is catching: This is not an abortive condition. cnd <- new_error_cast_lossy( x, to, loss_type = loss_type, x_arg = x_arg, to_arg = to_arg ) class(cnd) <- setdiff(class(cnd), c("error", "rlang_error")) signalCondition(cnd) FALSE } ) if (handled) { return(invisible()) } from <- format_arg_label(vec_ptype_abbr(x), x_arg) to <- format_arg_label(vec_ptype_abbr(to), to_arg) lifecycle::deprecate_warn( when = "0.2.0", what = I("Coercion with lossy casts"), with = "allow_lossy_cast()", details = paste0( glue::glue("We detected a lossy transformation from { from } to { to }. "), "The result will contain lower-resolution values or missing values. ", "To suppress this warning, wrap your code with `allow_lossy_cast()`." ), always = TRUE, user_env = user_env ) invisible() } stop_unsupported <- function(x, method, call = caller_env()) { msg <- glue::glue("`{method}.{class(x)[[1]]}()` not supported.") stop_vctrs( "vctrs_error_unsupported", message = msg, x = x, method = method, call = call ) } stop_unimplemented <- function(x, method, call = caller_env()) { msg <- glue::glue("`{method}.{class(x)[[1]]}()` not implemented.") stop_vctrs( "vctrs_error_unimplemented", message = msg, x = x, method = method, call = call ) } stop_scalar_type <- function(x, arg = NULL, call = caller_env()) { if (is_null(arg) || !nzchar(arg)) { arg <- "Input" } else { arg <- glue::backtick(arg) } msg <- glue::glue("{arg} must be a vector, not {obj_type_friendly(x)}.") stop_vctrs( msg, "vctrs_error_scalar_type", actual = x, call = call ) } stop_corrupt_factor_levels <- function(x, arg = "x", call = caller_env()) { msg <- glue::glue("`{arg}` is a corrupt factor with non-character levels") abort(msg, call = call) } stop_corrupt_ordered_levels <- function(x, arg = "x", call = caller_env()) { msg <- glue::glue("`{arg}` is a corrupt ordered factor with non-character levels") abort(msg, call = call) } stop_recycle_incompatible_size <- function(x_size, size, x_arg = "x", call = caller_env()) { stop_vctrs( x_size = x_size, y_size = size, x_arg = x_arg, # FIXME: tibble is the only package that uses `vctrs_error_recycle_incompatible_size` class = c("vctrs_error_incompatible_size", "vctrs_error_recycle_incompatible_size"), call = call ) } # Names ------------------------------------------------------------------- stop_names <- function(class = NULL, ..., call = caller_env()) { stop_vctrs( class = c(class, "vctrs_error_names"), ..., call = call ) } stop_names_cannot_be_empty <- function(names, call = caller_env()) { stop_names( class = "vctrs_error_names_cannot_be_empty", names = names, call = call ) } #' @export cnd_header.vctrs_error_names_cannot_be_empty <- function(cnd, ...) { "Names can't be empty." } #' @export cnd_body.vctrs_error_names_cannot_be_empty <- function(cnd, ...) { locations <- detect_empty_names(cnd$names) if (length(locations) == 1) { bullet <- glue::glue("Empty name found at location {locations}.") } else { bullet <- glue::glue("Empty names found at locations {ensure_full_stop(enumerate(locations))}") } bullet <- c(x = bullet) format_error_bullets(bullet) } stop_names_cannot_be_dot_dot <- function(names, call = caller_env()) { stop_names( class = "vctrs_error_names_cannot_be_dot_dot", names = names, call = call ) } #' @export cnd_header.vctrs_error_names_cannot_be_dot_dot <- function(cnd, ...) { "Names can't be of the form `...` or `..j`." } #' @export cnd_body.vctrs_error_names_cannot_be_dot_dot <- function(cnd, ...) { names <- cnd$names locations <- detect_dot_dot(names) names <- names[locations] split <- vec_group_loc(names) info <- map2_chr(split$key, split$loc, make_names_loc_bullet) header <- "These names are invalid:" header <- c(x = header) header <- format_error_bullets(header) message <- bullets(info, header = header) message <- indent(message, 2) message } stop_names_must_be_unique <- function(names, arg = "", call = caller_env()) { stop_names( class = "vctrs_error_names_must_be_unique", arg = arg, names = names, call = call ) } #' @export cnd_header.vctrs_error_names_must_be_unique <- function(cnd, ...) { "Names must be unique." } #' @export cnd_body.vctrs_error_names_must_be_unique <- function(cnd, ...) { names <- cnd$names dups <- vec_group_loc(names) dup_indicator <- map_lgl(dups$loc, function(x) length(x) != 1L) dups <- vec_slice(dups, dup_indicator) header <- "These names are duplicated:" header <- c(x = header) header <- format_error_bullets(header) info <- map2_chr(dups$key, dups$loc, make_names_loc_bullet) message <- bullets(info, header = header) message <- indent(message, 2) arg <- arg_as_string(cnd$arg) if (arg != "") { hint <- c(i = glue::glue("Use argument `{cnd$arg}` to specify repair strategy.")) message <- c(message, format_error_bullets(hint)) } message } make_names_loc_bullet <- function(x, loc) { if (length(loc) == 1) { glue::glue("{glue::double_quote(x)} at location {loc}.") } else { glue::glue("{glue::double_quote(x)} at locations {ensure_full_stop(enumerate(loc))}") } } enumerate <- function(x, max = 5L, allow_empty = FALSE) { n <- length(x) if (n == 0L && !allow_empty) { abort("Internal error: Enumeration can't be empty.") } if (n > max) { paste0(glue::glue_collapse(x[seq2(1, max)], ", "), ", etc.") } else { if (n == 2) { last <- " and " } else { last <- ", and " } glue::glue_collapse(x, ", ", last = last) } } ensure_full_stop <- function(x) { n <- nchar(x) if (substr(x, n, n) == ".") { x } else { paste0(x, ".") } } stop_native_implementation <- function(fn) { cli::cli_abort( c( "{.fn {fn}} is implemented at C level.", " " = "This R function is purely indicative and should never be called." ), .internal = TRUE ) } # Helpers ----------------------------------------------------------------- glue_lines <- function(..., env = parent.frame()) { out <- map_chr(chr(...), glue::glue, .envir = env) paste(out, collapse = "\n") } format_arg_label <- function(type, arg = "") { type <- paste0("<", type, ">") if (nzchar(arg)) { paste0("`", arg, "` ", type) } else { type } } arg_as_string <- function(arg) { if (is_null(arg)) { "" } else if (is_string(arg)) { arg } else { as_label(arg) } } append_arg <- function(x, arg) { if (is_null(arg)) { return(x) } arg <- arg_as_string(arg) if (nzchar(arg)) { glue::glue("{x} `{arg}`") } else { x } }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/conditions.R
#' Count unique values in a vector #' #' Count the number of unique values in a vector. `vec_count()` has two #' important differences to `table()`: it returns a data frame, and when #' given multiple inputs (as a data frame), it only counts combinations that #' appear in the input. #' #' @param x A vector (including a data frame). #' @param sort One of "count", "key", "location", or "none". #' * "count", the default, puts most frequent values at top #' * "key", orders by the output key column (i.e. unique values of `x`) #' * "location", orders by location where key first seen. This is useful #' if you want to match the counts up to other unique/duplicated functions. #' * "none", leaves unordered. This is not guaranteed to produce the same #' ordering across R sessions, but is the fastest method. #' @return A data frame with columns `key` (same type as `x`) and #' `count` (an integer vector). #' #' @section Dependencies: #' - [vec_proxy_equal()] #' - [vec_slice()] #' - [vec_order()] #' @export #' @examples #' vec_count(mtcars$vs) #' vec_count(iris$Species) #' #' # If you count a data frame you'll get a data frame #' # column in the output #' str(vec_count(mtcars[c("vs", "am")])) #' #' # Sorting --------------------------------------- #' #' x <- letters[rpois(100, 6)] #' # default is to sort by frequency #' vec_count(x) #' #' # by can sort by key #' vec_count(x, sort = "key") #' #' # or location of first value #' vec_count(x, sort = "location") #' head(x) #' #' # or not at all #' vec_count(x, sort = "none") vec_count <- function(x, sort = c("count", "key", "location", "none")) { sort <- arg_match0(sort, c("count", "key", "location", "none")) # Returns info pair giving index of first occurrence value and count info <- vec_count_impl(x) # Sorting based on rearranging `info` if (sort == "location") { loc <- vec_order(info$loc) info <- vec_slice(info, loc) } else if (sort == "count") { # Order by descending count, but ascending original location. # This retains stable ordering in case of ties in the `count`. # Need `vec_order_radix()` to handle different `direction`s. loc <- vec_order_radix(info[c("count", "loc")], direction = c("desc", "asc")) info <- vec_slice(info, loc) } out <- data_frame( key = vec_slice(x, info$loc), count = info$count ) # Sorting based on rearranging `out` if (sort == "key") { loc <- vec_order(out$key) out <- vec_slice(out, loc) } out } vec_count_impl <- function(x) { .Call(vctrs_count, x) } # Duplicates -------------------------------------------------------------- #' Find duplicated values #' #' * `vec_duplicate_any()`: detects the presence of duplicated values, #' similar to [anyDuplicated()]. #' * `vec_duplicate_detect()`: returns a logical vector describing if each #' element of the vector is duplicated elsewhere. Unlike [duplicated()], it #' reports all duplicated values, not just the second and subsequent #' repetitions. #' * `vec_duplicate_id()`: returns an integer vector giving the location of #' the first occurrence of the value. #' #' @section Missing values: #' In most cases, missing values are not considered to be equal, i.e. #' `NA == NA` is not `TRUE`. This behaviour would be unappealing here, #' so these functions consider all `NAs` to be equal. (Similarly, #' all `NaN` are also considered to be equal.) #' #' @param x A vector (including a data frame). #' @return #' * `vec_duplicate_any()`: a logical vector of length 1. #' * `vec_duplicate_detect()`: a logical vector the same length as `x`. #' * `vec_duplicate_id()`: an integer vector the same length as `x`. #' #' @section Dependencies: #' - [vec_proxy_equal()] #' #' @seealso [vec_unique()] for functions that work with the dual of duplicated #' values: unique values. #' @name vec_duplicate #' @examples #' vec_duplicate_any(1:10) #' vec_duplicate_any(c(1, 1:10)) #' #' x <- c(10, 10, 20, 30, 30, 40) #' vec_duplicate_detect(x) #' # Note that `duplicated()` doesn't consider the first instance to #' # be a duplicate #' duplicated(x) #' #' # Identify elements of a vector by the location of the first element that #' # they're equal to: #' vec_duplicate_id(x) #' # Location of the unique values: #' vec_unique_loc(x) #' # Equivalent to `duplicated()`: #' vec_duplicate_id(x) == seq_along(x) NULL #' @rdname vec_duplicate #' @export vec_duplicate_any <- function(x) { .Call(vctrs_duplicated_any, x) } #' @rdname vec_duplicate #' @export vec_duplicate_detect <- function(x) { .Call(vctrs_duplicated, x) } #' @rdname vec_duplicate #' @export vec_duplicate_id <- function(x) { .Call(vctrs_id, x) } # Unique values ----------------------------------------------------------- #' Find and count unique values #' #' * `vec_unique()`: the unique values. Equivalent to [unique()]. #' * `vec_unique_loc()`: the locations of the unique values. #' * `vec_unique_count()`: the number of unique values. #' #' @inherit vec_duplicate sections #' @param x A vector (including a data frame). #' @return #' * `vec_unique()`: a vector the same type as `x` containing only unique #' values. #' * `vec_unique_loc()`: an integer vector, giving locations of unique values. #' * `vec_unique_count()`: an integer vector of length 1, giving the #' number of unique values. #' @seealso [vec_duplicate] for functions that work with the dual of #' unique values: duplicated values. #' #' @section Dependencies: #' - [vec_proxy_equal()] #' #' @export #' @examples #' x <- rpois(100, 8) #' vec_unique(x) #' vec_unique_loc(x) #' vec_unique_count(x) #' #' # `vec_unique()` returns values in the order that encounters them #' # use sort = "location" to match to the result of `vec_count()` #' head(vec_unique(x)) #' head(vec_count(x, sort = "location")) #' #' # Normally missing values are not considered to be equal #' NA == NA #' #' # But they are for the purposes of considering uniqueness #' vec_unique(c(NA, NA, NA, NA, 1, 2, 1)) vec_unique <- function(x) { vec_slice(x, vec_unique_loc(x)) } #' @rdname vec_unique #' @export vec_unique_loc <- function(x) { .Call(vctrs_unique_loc, x) } #' @rdname vec_unique #' @export vec_unique_count <- function(x) { .Call(vctrs_n_distinct, x) } # Matching ---------------------------------------------------------------- #' Find matching observations across vectors #' #' `vec_in()` returns a logical vector based on whether `needle` is found in #' haystack. `vec_match()` returns an integer vector giving location of #' `needle` in `haystack`, or `NA` if it's not found. #' #' `vec_in()` is equivalent to [%in%]; `vec_match()` is equivalent to `match()`. #' #' @section Missing values: #' In most cases places in R, missing values are not considered to be equal, #' i.e. `NA == NA` is not `TRUE`. The exception is in matching functions #' like [match()] and [merge()], where an `NA` will match another `NA`. #' By `vec_match()` and `vec_in()` will match `NA`s; but you can control #' this behaviour with the `na_equal` argument. #' #' @param needles,haystack Vector of `needles` to search for in vector haystack. #' `haystack` should usually be unique; if not `vec_match()` will only #' return the location of the first match. #' #' `needles` and `haystack` are coerced to the same type prior to #' comparison. #' @inheritParams rlang::args_dots_empty #' @param na_equal If `TRUE`, missing values in `needles` can be #' matched to missing values in `haystack`. If `FALSE`, they #' propagate, missing values in `needles` are represented as `NA` in #' the return value. #' @param needles_arg,haystack_arg Argument tags for `needles` and #' `haystack` used in error messages. #' @return A vector the same length as `needles`. `vec_in()` returns a #' logical vector; `vec_match()` returns an integer vector. #' #' @section Dependencies: #' - [vec_cast_common()] with fallback #' - [vec_proxy_equal()] #' #' @export #' @examples #' hadley <- strsplit("hadley", "")[[1]] #' vec_match(hadley, letters) #' #' vowels <- c("a", "e", "i", "o", "u") #' vec_match(hadley, vowels) #' vec_in(hadley, vowels) #' #' # Only the first index of duplicates is returned #' vec_match(c("a", "b"), c("a", "b", "a", "b")) vec_match <- function(needles, haystack, ..., na_equal = TRUE, needles_arg = "", haystack_arg = "") { check_dots_empty0(...) .Call(vctrs_match, needles, haystack, na_equal, environment()) } #' @export #' @rdname vec_match vec_in <- function(needles, haystack, ..., na_equal = TRUE, needles_arg = "", haystack_arg = "") { check_dots_empty0(...) .Call(vctrs_in, needles, haystack, na_equal, environment()) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/dictionary.R
#' Actual vector dimensions #' #' @description #' * `vec_dim_n()` gives the dimensionality (i.e. number of dimensions) #' * `vec_dim()` returns the size of each dimension #' #' These functions access the raw `"dim"` attribute of the object #' and do not dispatch over the [dim()] generic. #' #' @details #' Unlike base R, we treat vectors with `NULL` dimensions as 1d. This #' simplifies the type system by eliding a special case. Compared to the base R #' equivalent, `vec_dim()` returns [length()], not `NULL`, when `x` is 1d. #' #' @seealso #' [dim2()], a variant of [dim()] that returns [length()] if an object #' doesn't have dimensions. #' #' @param x A vector #' @noRd #' @examples #' # Compared to base R #' x <- 1:5 #' dim(x) #' vec_dim(x) NULL # FIXME: Should `vec_dim()` return the size instead of the length? vec_dim <- function(x) { .Call(vctrs_dim, x) } vec_dim_n <- function(x) { .Call(vctrs_dim_n, x) } has_dim <- function(x) { .Call(vctrs_has_dim, x) } #' Perceived vector dimensions #' #' @description #' `dim2()` is a variant of [dim()] that returns [vec_size()] if an object #' doesn't have dimensions. #' #' @details #' Unlike base R, we treat vectors with `NULL` dimensions as 1d. This #' simplifies the type system by eliding a special case. Compared to the base R #' equivalent, `dim2()` returns [length()], not `NULL`, when `x` is 1d. #' #' @seealso #' [vec_dim()], a variant that never dispatches over the [dim()] generic. #' #' @param x A vector #' @noRd #' @examples #' # Compared to base R #' x <- 1:5 #' dim(x) #' vec_dim(x) dim2 <- function(x) { dim(x) %||% length(x) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/dim.R
#' Drop empty elements from a list #' #' `list_drop_empty()` removes empty elements from a list. This includes `NULL` #' elements along with empty vectors, like `integer(0)`. This is equivalent to, #' but faster than, `vec_slice(x, list_sizes(x) != 0L)`. #' #' @section Dependencies: #' - [vec_slice()] #' #' @param x A list. #' #' @export #' @examples #' x <- list(1, NULL, integer(), 2) #' list_drop_empty(x) list_drop_empty <- function(x) { .Call(vctrs_list_drop_empty, x) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/empty.R
#' Equality proxy #' #' Returns a proxy object (i.e. an atomic vector or data frame of atomic #' vectors). For [vctr]s, this determines the behaviour of `==` and #' `!=` (via [vec_equal()]); [unique()], [duplicated()] (via #' [vec_unique()] and [vec_duplicate_detect()]); [is.na()] and [anyNA()] #' (via [vec_detect_missing()]). #' #' The default method calls [vec_proxy()], as the default underlying #' vector data should be equal-able in most cases. If your class is #' not equal-able, provide a `vec_proxy_equal()` method that throws an #' error. #' #' @section Data frames: #' If the proxy for `x` is a data frame, the proxy function is automatically #' recursively applied on all columns as well. After applying the proxy #' recursively, if there are any data frame columns present in the proxy, then #' they are unpacked. Finally, if the resulting data frame only has a single #' column, then it is unwrapped and a vector is returned as the proxy. #' #' @param x A vector x. #' @inheritParams rlang::args_dots_empty #' #' @return A 1d atomic vector or a data frame. #' @keywords internal #' #' @section Dependencies: #' - [vec_proxy()] called by default #' #' @export vec_proxy_equal <- function(x, ...) { check_dots_empty0(...) return(.Call(vctrs_proxy_equal, x)) UseMethod("vec_proxy_equal") } #' @export vec_proxy_equal.default <- function(x, ...) { stop_native_implementation("vec_proxy_equal.default") } #' Equality #' #' `vec_equal()` tests if two vectors are equal. #' #' @inheritParams vec_compare #' @return A logical vector the same size as the common size of `x` and `y`. #' Will only contain `NA`s if `na_equal` is `FALSE`. #' #' @section Dependencies: #' - [vec_cast_common()] with fallback #' - [vec_recycle_common()] #' - [vec_proxy_equal()] #' #' @seealso [vec_detect_missing()] #' #' @export #' @examples #' vec_equal(c(TRUE, FALSE, NA), FALSE) #' vec_equal(c(TRUE, FALSE, NA), FALSE, na_equal = TRUE) #' #' vec_equal(5, 1:10) #' vec_equal("d", letters[1:10]) #' #' df <- data.frame(x = c(1, 1, 2, 1), y = c(1, 2, 1, NA)) #' vec_equal(df, data.frame(x = 1, y = 2)) vec_equal <- function(x, y, na_equal = FALSE, .ptype = NULL) { check_bool(na_equal) args <- vec_recycle_common(x, y) args <- vec_cast_common_params(!!!args, .to = .ptype) .Call(vctrs_equal, args[[1]], args[[2]], na_equal) } obj_equal <- function(x, y) { .Call(vctrs_equal_object, x, y) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/equal.R
#' Create a data frame from all combinations of the inputs #' #' @description #' `vec_expand_grid()` creates a new data frame by creating a grid of all #' possible combinations of the input vectors. It is inspired by #' [expand.grid()]. Compared with `expand.grid()`, it: #' #' - Produces sorted output by default by varying the first column the slowest, #' rather than the fastest. Control this with `.vary`. #' #' - Never converts strings to factors. #' #' - Does not add additional attributes. #' #' - Drops `NULL` inputs. #' #' - Can expand any vector type, including data frames and [records][new_rcrd]. #' #' @details #' If any input is empty (i.e. size 0), then the result will have 0 rows. #' #' If no inputs are provided, the result is a 1 row data frame with 0 columns. #' This is consistent with the fact that `prod()` with no inputs returns `1`. #' #' @inheritParams rlang::args_error_context #' @inheritParams df_list #' #' @param ... Name-value pairs. The name will become the column name in the #' resulting data frame. #' #' @param .vary One of: #' #' - `"slowest"` to vary the first column slowest. This produces sorted #' output and is generally the most useful. #' #' - `"fastest"` to vary the first column fastest. This matches the behavior #' of [expand.grid()]. #' #' @returns #' A data frame with as many columns as there are inputs in `...` and as many #' rows as the [prod()] of the sizes of the inputs. #' #' @export #' @examples #' vec_expand_grid(x = 1:2, y = 1:3) #' #' # Use `.vary` to match `expand.grid()`: #' vec_expand_grid(x = 1:2, y = 1:3, .vary = "fastest") #' #' # Can also expand data frames #' vec_expand_grid( #' x = data_frame(a = 1:2, b = 3:4), #' y = 1:4 #' ) vec_expand_grid <- function(..., .vary = "slowest", .name_repair = "check_unique", .error_call = current_env()) { .vary <- arg_match0( arg = .vary, values = c("slowest", "fastest"), error_call = .error_call ) .Call(ffi_vec_expand_grid, list2(...), .vary, .name_repair, environment()) }
/scratch/gouwar.j/cran-all/cranData/vctrs/R/expand.R
#' FAQ - Is my class compatible with vctrs? #' #' @includeRmd man/faq/developer/reference-compatibility.Rmd description #' #' @name reference-faq-compatibility NULL #' FAQ - How does coercion work in vctrs? #' #' @includeRmd man/faq/developer/theory-coercion.Rmd description #' #' @name theory-faq-coercion NULL # Also see the `redirects:` section in `_pkgdown.yml` # for `vector_recycling_rules.html` #' FAQ - How does recycling work in vctrs and the tidyverse? #' #' @includeRmd man/faq/developer/theory-recycling.Rmd description #' #' @name theory-faq-recycling #' @aliases vector_recycling_rules NULL #' FAQ - How to implement ptype2 and cast methods? #' #' @includeRmd man/faq/developer/howto-coercion.Rmd description #' #' @name howto-faq-coercion NULL #' FAQ - How to implement ptype2 and cast methods? (Data frames) #' #' @includeRmd man/faq/developer/howto-coercion-data-frame.Rmd description #' #' @name howto-faq-coercion-data-frame NULL #' FAQ - Why isn't my class treated as a vector? #' #' @includeRmd man/faq/developer/howto-faq-fix-scalar-type-error.Rmd description #' #' @name howto-faq-fix-scalar-type-error NULL
/scratch/gouwar.j/cran-all/cranData/vctrs/R/faq-developer.R
#' Internal FAQ - `vec_ptype2()`, `NULL`, and unspecified vectors #' #' @includeRmd man/faq/internal/ptype2-identity.Rmd description #' #' @name internal-faq-ptype2-identity NULL
/scratch/gouwar.j/cran-all/cranData/vctrs/R/faq-internal.R