Is it possible to invoke the debugger in RStudio when running testthat tests? I haven't been able to find a setup that allows this (various combinations of "use devtools package functions if available" in the settings, hitting the "Test Package" option in the "Build -> More" menu, running test() in the console, putting in browser() calls, etc.) but haven't found a way yet.
I also find myself getting lost a lot when testing, unsure whether the code being run has been installed in the system libraries (by doing 'Build & Reload'), or is being run in situ from the local R directory, or what - sometimes RStudio complains that a breakpoint can't be set until the package is rebuilt (so I suspect the former) or doesn't (so I suspect the latter). Not sure if this issue is closely related or not to my main question.
Without finding a way to drop into the debugger, I end up pasting test code into the console & working in a very ad-hoc fashion, and basically shooting my TDD habits in the foot. So any advice would be appreciated - if it's not possible to invoke the debugger, any suggested workarounds?
I'm running RStudio version 0.99.447 on OS X, in local mode, with R 3.2.1.
Edit - I'd also love to know more background about the options, e.g. "option X will never support debugging, because it's running in a forked process, try this other option Y instead."
Update - having had no responses here, I also asked at https://support.rstudio.com/hc/communities/public/questions/204779797-Debugging-testthat-tests-in-RStudio (where I also haven't had any responses).
The following works for me:
Insert a call to browser() somewhere within the testthat unit tests.
Run devtools::test() from the RStudio console (instead of using the "Test Package" menu item from the UI)
Then, when the test runner hits the browser() invocation, you should be able to use the environment browser and step through the code.
I haven't found a way to get testthat to stop at breakpoints, but inserting browser() invocations is a pretty close substitute.
To be absolutely sure that you're starting from a consistent state when it comes to loading packages, you can close RStudio, re-open it, run "Clean and rebuild", and then devtools::test()
Lastly, if you're working within an RStudio package, you may want to check out the following advice from RStudio support:
In order to debug effectively in your package, you’ll also want to ensure that your package is compiled with the --with-keep.source option. This option is the default for new packages in RStudio; if you need to set it manually, it can be found in Tools -> Project Options -> Build Tools.
If you want to use editor breakpoints from RStudio in order to debug unit tests, you can do it by working around testthat. As Hadley said in a Github issue, testthat usually runs in a separate session from RStudio, so it won't ever be able to use editor breakpoints. However, the tests, themselves, are function calls with two arguments, a description and code. You can read these and run them with a little code.
testf_trace <- function(filename, match) {
env <- new.env()
test_that <- function(desc, code) {
if (length(grep(match, desc)) > 0) {
eval(substitute(code), env)
}
}
env$test_that <- test_that
source(filename, env)
}
If you have a test that reads test_that("invariant is true", { f(3) == 6 }), then you can test this by running testf_trace(filename, "is true").
If you're unsure where a function is defined, and hence whether the breakpoint will work, you can find out by typing the name of the function at the console. The last line or two will tell you in which environment the function is defined, if it was defined in an environment other than .Global.
Related
I am running Red Hat Enterprise Linux (RHEL) 8.5 with Linux kernel 4.18 and Gnome 3.32.2. In this system, I've got R 4.1.2 compiled with the tool asdf with shared libraries enabled. On top of that, I installed RStudio 2021.09.01-372 from an RPM from the official RStudio website.
When I start Rstudio, the first line of output after the usual R startup is an error:
Error in tools::startDynamicHelp() : internet routines cannot be loaded
I am unable to figure out what's causing this error, and with it I can't run things like refresh CRAN or update packages. But if I start a pure R session from the terminal (instead of Rstudio) this error does not occur.
Some things I tried:
Install the krb5 and libssh2 packages on my host system: Didn't help.
Starting a "pure" R session (both with and without the --vanilla argument) from the Terminal tab within Rstudio also gives this error. If I try to run update.packages() from this session, it pops up a window to select a CRAN mirror then fails with the following:
Warning: failed to download mirrors file (internet routines cannot be loaded); using local file '/home/[my username]/.asdf/installs/R/4.1.2/lib64/R/doc/CRAN_mirrors.csv'
Warning: unable to access index for repository https://cloud.r-project.org/src/contrib:
internet routines cannot be loaded
Warning message:
In download.file(url, destfile = f, quiet = TRUE) :
unable to load shared object '/home/penyuan/.asdf/installs/R/4.1.2/lib64/R/modules//internet.so':
/lib64/libssh.so.4: undefined symbol: EVP_KDF_ctrl, version OPENSSL_1_1_1b
But like I said, the strange thing is if I start an R session outside of Rstudio, these errors don't happen.
Within RStudio, the only workaround I can find is to run this command upon startup (suggested in this thread):
options(download.file.method="wget")
Once this is done, everything else seems to work, such as package updates.
However, I don't want to manually do this every time I start RStudio. So I tried to put it into ~/.Rprofile including a test print() as follows:
print("This is `~/.Rprofile`")
options(download.file.method="wget")
When I open RStudio, I can see the output from the print() call, but the options() command is not run because the original error shows up again. I still have to manually enter options(download.file.method="wget") every time.
I also tried to fold everything into a .First function in ~/.Rprofile as follows:
.First <- function() {
options(download.file.method="wget")
print("This is the `.First` function in `~/.Rprofile`")
}
Unfortunately, same result as before: print()'s output is seen, but options() is not run.
I also made sure that my ~/.Rprofile includes a trailing newline as discussed here. But this didn't help.
The above are the steps I've tried so far.
Why does this error only occur when running RStudio or a terminal within Rstudio? Why doesn't it happen if I start R from a terminal outside of Rstudio?
Is there a way to solve the problem so that the error doesn't happen in the first place? If it can't be solved, how do I set up my ~/.Rprofile so that options(download.file.method="wget") will be run?
Thank you.
I wanted to make internally sharing/locally launching a shiny app developed with the {golem} framework a little more robust.
Hence, I used the renv package and installed the shiny app as a local package into a project folder.
I proceeded as follows (thanks #Kat for the suggestion):
initialize renv using renv::init(bare = TRUE)
renv::install("my_local_package")
renv::snapshot(type = "all")
renv::isolate()
Writing a launch file consisting of:
library(golempackage)
renv::restore()
golempackage::run_app(options = list(launch.browser = TRUE))
Share folder.
However, when launching the shiny app on a different computer (or a docker testing environment), I get the following error caused by the package bslib. Same happens when I delete my cache:
An error has occurred!
File attachments must exist: 'C:/Users/XYZ/AppData/Local/R/cache/R/renv/cache/v5/.../bslib/lib/bs3/assets/fonts'
Note: this error even occurs if I set the cache to be project-local and share it inside the project folder.
However, now the error message does not reference the global but the project-local cache. Unfortunately still as an absolute path which throws an error for other users.
This is all super weird and I have not the slightest idea why this occurs.
I would like to avoid removing bslib.
As far as I can see, the error is coming from the sass package, e.g.
https://github.com/rstudio/sass/blob/f7a954027447dd0b9826ec01c7084c89a6e64fcc/R/layers.R#L442-L443
While I don't know exactly know what's going on, you could probably use the R debugger to check why that's failing. (Does the referenced folder exist in both cases? Are you expecting renv to be using the cache in the second case?)
Typically, when starting up an renv project, one gets a message that looks something like this:
* Project '~/path/to/project' loaded. [renv 0.10.0]
I am trying to suppress this message, particularly when non-interactively running a script from this project.
Checking the package help, I noted ?config i.e. User-Level Configuration of renv. Specifically, I found synchronized.check, of which the document states is for controlling how renv lockfile synchronization is checked (this is also outputted to the console). However, I couldn't find how to control the main startup message. I also checked the ?settings but found nothing relevant either.
I've tried fiddling with options and Sys.setenv without luck so far.
So, is it possible to suppress the message, seeing that the renv script activate.R controls how the package itself is loaded?
You are correct that there isn't a specific documented way to configure this in renv. For now, you can set:
options(renv.verbose = FALSE)
before renv is loaded. (You may want to turn it back to TRUE if you want renv to display other messages as part of its normal work.)
You can suppress library startup messages with suppressPackageStartupMessages, e.g.
suppressPackageStartupMessages(library(igraph))
There is also suppressMessages for arbitrary function calls.
When running R CMD check I get the following note:
checking for future file timestamps ... NOTE
unable to verify current time
I have seen this discussed here, but I am not sure which files it is checking for timestamps, so I'm not sure which files I should look at. This happens locally on my windows and remotely on different systems (using github actions).
Take a look at https://svn.r-project.org/R/trunk/src/library/tools/R/check.R
The check command relies on an external web resource:
now <- tryCatch({
foo <- suppressWarnings(readLines("http://worldclockapi.com/api/json/utc/now",
warn = FALSE))
This resource http://worldclockapi.com/ is currently not available.
Hence the following happens (see same package source):
if (is.na(now)) {
any <- TRUE
noteLog(Log, "unable to verify current time")
See also references:
https://community.rstudio.com/t/r-devel-r-cmd-check-failing-because-of-time-unable-to-verify-current-time/25589
So, unfortunately this requires a fix in the check function by the R development team ... or the web-resource coming online again.
To add to qasta's answer, you can silence this check by setting the _R_CHECK_SYSTEM_CLOCK_ environment variable to zero e.g Sys.setenv('_R_CHECK_SYSTEM_CLOCK_' = 0)
To silence this in a persistent manner, you can set this environment variable on R startup. One way to do so is through the .Renviron file, in the following manner:
install.packages("usethis") (If not installed already)
usethis::edit_r_environ()
Add _R_CHECK_SYSTEM_CLOCK_=0 to the file
Save, close file, restart R
When I download files (Windows 7) using
tryCatch(download.file(paste0(url_bv,arq), paste0(dir_bv,arq))
,error=function(cond) message(paste('erro:',arq,'não encontrado'))
,warning=function(cond) message(paste('warning:',arq,'não encontrado')))
I can´t delete files, getting the msg in the question title.
If I just do
download.file(paste0(url_bv,arq), paste0(dir_bv,arq))
there is no problem.
How can I release the folder/file in R?
I think this is likely a bug in R (windows version). I can faithfully reproduce it in R-3.2.5 (win10_64). I suggest you file a bug report (read R FAQ 9.2 for clear direction).
I tried it with several variations:
different url schemes ("http://" and "https://")
different download.file(..., method=...) options ("wininet", "internal", and "auto" all behaved in this manner; "libcurl" did not, but it merely downloaded the 404.html without telling me there was a problem)
triggers whenever warning=... or condition=... clauses are given to tryCatch and something weird happens in expr
does not trigger with error=... or finally=... arguments
32bit and 64bit variants
not in RStudio
as R --vanilla
All attempted on ubuntu-14.04 (R-3.2.3-64bit) as well, it would not trigger.