R语言 如何使用testthat将系统变量或包选项传递给测试

2g32fytz  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(151)

我有一个普通结构化的R项目,其中的test文件夹包含我所有的单元测试,用testthat实现。

library(testthat)
library(MyPackage)
test_check("MyPackage")

现在,测试中使用的一些功能需要设置Sys.env。为了避免在每个测试文件中手动设置它,我的期望是,当在test_check("MyPackage")命令之前放置适当的行时,所有后续测试都可以查询系统变量。示例:

library(testthat)
library(MyPackage)
Sys.setenv("test123" = "test")
test_check("MyPackage")

在特定的测试文件中:

testthat::test_that("test os for testing", {
  print(Sys.getenv("test123"))
  os <- Sys.info()["sysname"]
  testthat::expect_true(os %in% c("Windows", "Linux"))
})

当点击 “Test Package” 时,我看到print(Sys.getenv("test123"))的输出是""。所以我猜环境被重置了。还有其他方法吗?

lo8azlld

lo8azlld1#

我无法用一个简单的测试包重现报告的行为,运行R 4.3.0和testthat3.1.7。你的问题可能会被关闭,但我还是会分享这个包……

$ R CMD build addOne
$ R CMD check addOne_0.0-0.tar.gz
* checking tests ...
  Running ‘testthat.R’
 OK

DESCRIPTION

Package: addOne
Version: 0.0-0
License: GPL (>= 2)
Description: A (one paragraph) description of what
  the package does and why it may be useful.
Title: My First Collection of Functions
Author: Mikael Jagan [aut, cre]
Maintainer: Mikael Jagan <Mikael.Jagan@some.domain.net>
Suggests: testthat
Config/testthat/edition: 3

NAMESPACE

export(addOne)

R/addOne.R

addOne <- function(x) as.double(x) + 1

man/addOne.Rd

\name{addOne}
\alias{addOne}
\title{Add one to a number}
\description{Adds one to a number.}
\usage{addOne(x)}
\arguments{
\item{x}{A number.}
}
\examples{
stopifnot(identical(addOne(0), 1))
}

tests/testthat.R

library(testthat)
library(addOne)
Sys.setenv(SOMEVAR = "someval")
stopifnot(identical(Sys.getenv("SOMEVAR"), "someval"))
test_check("addOne")

tests/testthat/test-addOne.R

stopifnot(identical(Sys.getenv("SOMEVAR"), "someval"))
test_that("zzz", expect_identical(Sys.getenv("SOMEVAR"), "someval"))

相关问题