简体   繁体   English

如何使用 testthat 测试作为包一部分的独立 R 脚本

[英]How to test standalone R scripts which are part of a package using testthat

I am building a R package, RE and I would like to package a standalone script with it to be placed in RE/exec/wrapper.R .我正在构建一个 R 包, RE ,我想打包一个独立的脚本,将它放在RE/exec/wrapper.R 中 I have written a test function for testthat which works just fine when run from the command line using devtools::test("RE") , but fails when run using devtools::check("RE") .我为testthat编写了一个测试函数,它在使用devtools::test("RE")从命令行运行时工作正常,但在使用devtools::check("RE")运行时失败。

The relevant code portion that fails is:失败的相关代码部分是:

cmd <- "Rscript \"C:\\RE\\exec\\wrapper.R\" base print \"{\\\"x\\\": 2}\""
rv <- system(cmd, intern = FALSE, ignore.stderr = FALSE, show.output.on.console = FALSE)

When run as part of "test" everything runs fine and system returns 0 as it should.当作为“测试”的一部分运行时,一切运行良好, system按原样返回0 When run as part of "check", system gives out the error message given below and returns 1 .当作为“检查”的一部分运行时, system给出下面给出的错误消息并返回1

Error in file(filename, "r", encoding = encoding) : cannot open the connection
Calls: local ... eval.parent -> eval -> eval -> eval -> eval -> source -> file
In addition: Warning message:
In file(filename, "r", encoding = encoding) : cannot open file 'startup.Rs': No such file or directory
Execution halted

I have:我有:

  1. Checked that the file exists (it does in both cases)检查文件是否存在(在两种情况下都存在)
  2. Tried tryCatch .试过tryCatch No error are caught, and system just returns a 1没有捕获到错误, system只返回1

This makes me think that it is an issue with system and R CMD CHECK .这让我认为这是systemR CMD CHECK

The answer is in https://github.com/r-lib/testthat/issues/144 .答案在https://github.com/r-lib/testthat/issues/144 中 The environment variable R_TESTS must be unset via Sys.setenv("R_TESTS" = "") in the top level test script ( package_root/tests/testthat.R ), or system will not run correctly when called from R CMD CHECK .环境变量R_TESTS必须通过顶层测试脚本 ( package_root/tests/testthat.R ) 中的Sys.setenv("R_TESTS" = "")取消设置,否则从R CMD CHECK调用时system将无法正确运行。 I am leaving the question up, because it took me several hours of experimenting and searching before stumbling on the answer.我将这个问题搁置一旁,因为在绊倒答案之前,我花了几个小时的时间进行试验和搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM