R mock testing with locked namespaces - r

I'm struggling with creating some unit tests in R where I need to mock out functions like RCurl::getURL so they return canned output and don't required a network connection.
Here's an example:
library(mockthat)
test_that("API works", {
mock_response <- mockthat::mock('[{"foo":7}]')
mockthat::with_mock(
getURL=mock_response,
{
result <- myFunction()
})
...
This fails with the following error, but only when I run under devtools::check() or R CMD check (it succeeds under devtools::test()):
not ok 1 API works
Error: cannot change value of locked binding for 'getURL'
Backtrace:
1. mockthat::with_mock(...) test-yes.R:29:2
2. base::lapply(mocks, set_mock)
3. mockthat:::FUN(X[[i]], ...)
4. mockthat:::do_assign(mock$name, mock$new_value, mock$env)
5. base::assign(name, val, envir = env)
Is there something I can change to get this working, or a workaround I can use?
I'm using:
> packageVersion('mockthat')
[1] '0.2.6'
> cat(head(capture.output(sessionInfo()), 3), sep="\n")
R version 4.1.1 (2021-08-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 11.4
but the problem seems to also exist under testthat's mocking stuff (which is now deprecated so I don't want to use it anyway) and mockery too.
Apologies for not creating a proper reprex - I'm not sure how to demonstrate the problem without having a whole package structure.
[adapted from an issue reported at https://github.com/nbenn/mockthat/issues/6]

Related

Geomorph not functioning after update

I recently updated my MacBook air (2017) to the Mojave OS and proceeded to update my version of R and Rstudio. Unfortunately, ever since the 'plotTangentSpace' command no longer functions appropriately even when attempting to run the example 'plethodon' code from the Geomorph vingette, I always receive the following error in the output (bolded below):
data(plethodon)
Y.gpa<-gpagen(plethodon$land) #GPA-alignment
|====================================================================================| 100%
gp <- interaction(plethodon$species, plethodon$site)
plotTangentSpace(Y.gpa$coords, groups = gp)
Error in plotTangentSpace(Y.gpa$coords, groups = gp) :
unused arguments (Y.gpa$coords, groups = gp)
I have tried uninstalling and reinstalling R for a MacOS many times including versions 4.0.2, 3.6.3, 3.6.1, and 3.2.1. I have also uninstalled and reinstalled XQuartz several times.
If anyone has encountered a similar issue or has any other ideas I can try I would really appreciate the help. Thank you!
If you execute:
?plotTangentSpace
You should see that this is a deprecated function. That means you should not be using it. It says:
Notes for geomorph 3.3.0 and subsequent versions
I suspect you have not updated your copy of the vignette. There are instructions on the help page for an alternate approach. The example in the help page for the suggested function is:
data(plethspecies)
Y.gpa <- gpagen(plethspecies$land) #GPA-alignment
### Traditional PCA
PCA <- gm.prcomp(Y.gpa$coords)
summary(PCA)
plot(PCA, main = "PCA")
For the plethodon data they suggest:
PCA.w.phylo <- gm.prcomp(Y.gpa$coords, phy = plethspecies$phy)
summary(PCA.w.phylo)
plot(PCA.w.phylo, phylo = TRUE, main = "PCA.w.phylo")
So start a new session (to unload the currently loaded geomorph namespace, and execute this at the r session command line:
install.packages("geomorph")
You should be getting version 3.3.1 of the geomorph package.
I think I found the problem! In my case, the error was due to a old version of the package RRPP, which is required by Geomorph. After updating it, Geomorph is working perfectly! Hope this can be useful for you too.
I came across the same error but after updating the RRPP and rgl packages required for geomorph, the gm.prcomp() function worked for me. I hope this helps if you haven't figured it out already.

*platform-independent* language/locale settings?

tl;dr
Is it possible to change the LANGUAGE environment setting (or the LC_MESSAGES component of the locale) platform-independently, and if not (which is probably the case) to detect whether the value requested was in fact legal/took effect?
Context
One of my functions tried to detect the occurrence of a particular error by grep()ing the text of the error message. As previously pointed on an R mailing list (can't find the reference right now), this approach is fragile: the text of the message can change based on the setting of the LANGUAGE environment variable.
So I'm changing my code to not do that, but I'd like to add a regression test to the package that tests whether the problem occurs. And I'd like it to work (or at least not fail) across platforms.
As described e.g. in this question, I can use Sys.setenv(LANGUAGE=...) or Sys.setlocale("LC_MESSAGES",.) to change the message language. But this will only work if I guess the right LANGUAGE/LC_MESSAGES value, and it's available on the current system. (It seems that LANGUAGE is a language code, and LC_MESSAGES is a locale, and that the locale need not be installed if I just want to switch languages?)
Sys.getenv("LANGUAGE") ## [1] "en_CA:en"
test_msg <- function(msg,silent=FALSE) {
grepl(msg,try(x ,silent=silent))
}
test_msg("not found") ## TRUE ("object 'x' not found")
Sys.setenv(LANGUAGE="fr")
test_msg("introuvable")
## Erreur : objet 'x' introuvable
So far, so good. But resetting the LANGUAGE variable doesn't seem to work ...
Sys.setenv(LANGUAGE="en")
Sys.getenv("LANGUAGE")=="en" ## TRUE
test_msg("not found") ## FALSE ('introuvable')
Sys.setenv(LANGUAGE="en_CA:en")
test_msg("not found") ## FALSE ('introuvable')
Setting LC_MESSAGES to C seems more reliable ...
Sys.setlocale("LC_MESSAGES", "C")
test_msg("not found")
FWIW I've found that this sequence of commands actually seems to be unreliable, i.e. the same attempt to set the environment variable seems to work sometimes depending on what pissing around I've done previously ... I have to go back and keep starting with a clean session to get reproducible results ...
In any case, I know that if I were to try this on a computer without a French locale available, or where the locale/language name was different, that it wouldn't work. I'd like to be able to figure out whether the language setting has worked. I can use test_msg("introuvable") as brute force, but I'm hoping there's a more elegant option ...
relevant bits of sessionInfo():
R Under development (unstable) (2018-11-26 r75681)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 16.04.5 LTS
locale:
[1] LC_CTYPE=en_CA.UTF8 LC_NUMERIC=C
[3] LC_TIME=en_CA.UTF8 LC_COLLATE=en_CA.UTF8
[5] LC_MONETARY=en_CA.UTF8 LC_MESSAGES=en_CA.UTF8

How to call View() / utils::View() in a function as part of a package?

I am writing a function for a package that ends with a call to utils::View(). The aim of the function is to do some data wrangling and then open the dataset in the Rstudio data viewer with View(). If I define the function in the global environment it works fine. As an example (skipping the data wrangling part):
foo <- function(x) {
View(x)
}
foo(mtcars)
opens the dataset mtcars in the data viewer. However, once I put it in my r package and call the function as part of that package it does issue the following error:
"Error in .External2(C_dataviewer, x, title) : unable to start data viewer
In addition: Warning message:
In utils::View(mtcars) : unable to open display"
I have tried to use utils::View() or simply View(), without success. Also, I have tried it with XQuartz uninstalled and with XQuartz installed and couldn't make it work.
I am using Rstudio version 1.0.153 and
R version 3.4.1 (2017-06-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6
I am grateful for any hints on how to resolve this!
Try using View(df) instead utils::View(df)
or try restarting the session (Ctrl +shft +F10)
then again using View(df)
or use dpylr to convert it into a table then use glimpse
-----------------------Code-------------------------------------------
install.packages("dyplr")
dplyr::tbl_df(mtcars) #to convert data to table class
dplyr::glimpse(mtcars)

Travis builds fail on dplyr vector calls within vignette

When I push my package to travis the vignette checks fail. I'm aware I can skip it but it's bugging me.
I have identified at least one of the issues belongs to a specific call in my code.
The RMD chunk in question:
get_storm_data("fstadv", link = al.1998.charley %>% .$Link)
al.1998.charley:
al.1998.charley <- structure(list(Year = 1998,
Name = "TROPICAL STORM CHARLEY",
Basin = "AL",
Link = "http://www.nhc.noaa.gov/archive/1998/1998CHARLEYadv.html"),
class = "data.frame",
row.names = c(NA, -1L),
.Names = c("Year", "Name", "Basin", "Link"))
The link parameter is a character string sent to the function get_storm_data which does some web scraping.
The following three values are identical:
a <- al.1998.charley %>% .$Link
b <- al.1998.charley %>% `[[`('Link')
c <- "http://www.nhc.noaa.gov/archive/1998/1998CHARLEYadv.html"
identical(a, b)
[1] TRUE
identical(b, c)
[1] TRUE
However, only the value c passed to the link parameter will pass travis.
The travis error:
Building with: R CMD build
6.09s$ R CMD build .
* checking for file ‘./DESCRIPTION’ ... OK
* preparing ‘Hurricanes’:
* checking DESCRIPTION meta-information ... OK
* installing the package to build vignettes
* creating vignettes ... ERROR
Quitting from lines 86-87 (getting-started.Rmd)
Error: processing vignette 'getting-started.Rmd' failed with diagnostics:
is.character(url) is not TRUE
Execution halted
All of my previous attempts to resolve this can be found here, if necessary.
Edit
This vignette never caused issues before. Build 16 passed. Nothing was different in the vignette. I did git diff between that commit and HEAD to bring the branch to it's exact match (since original branch had since been deleted). Other than cosmetic differences in other files (spaces, newlines, etc.), it still failed.
This led me to believe it was an upgrade or change on travis' end. I read over the blog but saw no related changes between the last successful pass (Build 16) and current.
Final Edit
When I mentioned in the last edit the vignette had not changed since the last succesful build, I should have been more clear. That entire commit that passed in March would not pass today. I'm still not clear why.
I would like to point out for any newcomers: check the travis packages to make sure they match your system. R CMD build on my system passed with no issues. But some of my packages were outdated compared to travis'. Thanks to #jimhester (GitHub) for pointing that out.
Session Info
R version 3.4.0 (2017-04-21)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
_LC_CTYPE=en_US.UTF-8_, _LC_NUMERIC=C_, _LC_TIME=en_US.UTF-8_, _LC_COLLATE=en_US.UTF-8_, _LC_MONETARY=en_US.UTF-8_, _LC_MESSAGES=en_US.UTF-8_, _LC_PAPER=en_US.UTF-8_, _LC_NAME=C_, _LC_ADDRESS=C_, _LC_TELEPHONE=C_, _LC_MEASUREMENT=en_US.UTF-8_ and _LC_IDENTIFICATION=C_
attached base packages:
stats, graphics, grDevices, utils, datasets, methods and base
other attached packages:
Hurricanes(v.0.1.0), dplyr(v.0.5.0), purrr(v.0.2.2), readr(v.1.0.0), tidyr(v.0.6.1), tibble(v.1.2), ggplot2(v.2.2.1), tidyverse(v.1.0.0) and magrittr(v.1.5)
loaded via a namespace (and not attached):
Rcpp(v.0.12.7), digest(v.0.6.10), assertthat(v.0.1), R6(v.2.2.0), grid(v.3.4.0), plyr(v.1.8.4), DBI(v.0.5-1), gtable(v.0.2.0), scales(v.0.4.1), lazyeval(v.0.2.0), data.table(v.1.10.4), tools(v.3.4.0), pander(v.0.6.0), munsell(v.0.4.3), compiler(v.3.4.0) and colorspace(v.1.3-0)
Link in al.1998.charley is stored as a factor on Travis (perhaps you have set the stringsAsFactors option to FALSE somewhere locally?). httr won't coerce a factor vector to character, hence you get an error. Try wrapping as.character() around al.1998.charley %>% .$Link.

Fatal Error while using Rcpp in RStudio on Windows

I'm trying to use Rcpp on Windows in RStudio. I have R version 3.2.3 and I have installed the Rcpp package. The problem is that I am unable to call any functions defined through the CPP code. I tried the following (picked up from an example online).
body <- '
NumericVector xx(x);
return wrap( std::accumulate( xx.begin(), xx.end(), 0.0));'
add <- cxxfunction(signature(x = "numeric"), body, plugin = "Rcpp")
This gives the following warning, but completes execution successfully.
cygwin warning:
MS-DOS style path detected: C:/R/R-32~1.3/etc/x64/Makeconf
Preferred POSIX equivalent is: /cygdrive/c/R/R-32~1.3/etc/x64/Makeconf
CYGWIN environment variable option "nodosfilewarning" turns off this warning.
Consult the user's guide for more details about POSIX paths:
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
When I try to use the above function,
x <- 1
y <- 2
res <- add(c(x, y))
I get the following error :
R Session Aborted
R encountered a fatal error.
The session was terminated.
Any suggestions? This same 'Fatal Error' happens for any code that I run with Rcpp.
Try rebuilding locally, starting with Rcpp. This is valid code and will work (and the hundreds of unit tests stress may more than this). Sometimes the compiler or something else changes under you and this sort of thing happens. It is then useful to have an alternative build system -- eg via Travis at GitHub you get Linux for free.
Also, learning about Rcpp Attributes. Your example can be written as
R> library(Rcpp)
R> cppFunction("double adder(std::vector<double> x) { return std::accumulate(x.begin(), x.end(), 0.0); }")
R> adder(c(1,2))
[1] 3
R>
which is simpler. Works of course the same way with Rcpp::NumericVector.

Resources