调用选项具有不同的副作用,具体取决于调用方式

问题描述

我想要一个函数来设置 repospktType 选项

不知何故,调用 options() 似乎具有不同的副作用,具体取决于调用方式 - 我想了解其原因。

这是 set_options() 的单元测试:

set_options <- function(
  repos = c(RSPM = "https://packagemanager.rstudio.com/all/__linux__/focal/latest"),pkgType = "binary"
) {
  options(
    repos = repos,pkgType = pkgType
  )
}

library(testthat)

test_that("Set options",{
  actual <- set_options()
  print(actual)

  expected <- list(
    repos = c(RSPM = "https://packagemanager.rstudio.com/all/__linux__/focal/latest"),pkgType = "binary"
  )

  expect_identical(actual,expected)

  expect_identical(getoption("repos"),expected$repos)
  expect_identical(getoption("pkgType"),expected$pkgType)
})

以交互方式执行代码或通过 source("path/to/file.R") 获取代码时,它可以正常工作:

source("tests/testthat/test-options.R")
# $repos
#                                                           RSPM 
# "https://packagemanager.rstudio.com/all/__linux__/focal/latest" 
#
# $pkgType
# [1] "binary"
#
# Test passed ?

但是,当我通过 devtools::test() 运行测试时,我得到以下结果:

[...]
⠏ |   0       | options                                                                 $repos
CRAN 
"@CRAN@" 

$pkgType
[1] "source"

x |   2 1     | options [0.2 s]                                                         
────────────────────────────────────────────────────────────────────────────────────────
Failure (test-options.R:22:3): Set options
`actual` (`actual`) not identical to `expected` (`expected`).

`names(actual$repos)`:   "CRAN"
`names(expected$repos)`: "RSPM"

`actual$repos`:   "@CRAN@"                                                       
`expected$repos`: "https://packagemanager.rstudio.com/all/__linux__/focal/latest"

`actual$pkgType`:   "source"
`expected$pkgType`: "binary"

当我用 reprex::reprex() 包装它时,我得到了这个:

library(testthat)

set_options <- function(
  repos = c(RSPM = "https://packagemanager.rstudio.com/all/__linux__/focal/latest"),pkgType = pkgType
  )
}

test_that("Set options",expected$pkgType)
})
#> $repos
#>                                                            RSPM 
#> "https://packagemanager.rstudio.com/all/__linux__/focal/latest" 
#>                                                            CRAN 
#>                                   "https://cloud.r-project.org" 
#> 
#> $pkgType
#> [1] "binary"
#> 
#> ── FAILURE (<text>:22:3): Set options ──────────────────────────────────────────
#> `actual` not identical to `expected`.
#> Component "repos": Lengths (2,1) differ (string compare on first 1)

reprex package (v0.3.0) 于 2021 年 1 月 25 日创建

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)