I'd like to have a function that sets repos
and pktType
options
Somehow a call to options()
seems to have different side effects depending on how it is called - and I would like to understand the cause of it.
This is the unit test for 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)
})
It works as desired when executing the code interactively or when sourcing it via 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 ??
However, when I run the test via devtools::test()
I get the following result:
[...]
? | 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"
And when I wrap it with reprex::reprex()
, I get this:
library(testthat)
set_options <- function(
repos = c(RSPM = "https://packagemanager.rstudio.com/all/__linux__/focal/latest"),
pkgType = "binary"
) {
options(
repos = repos,
pkgType = pkgType
)
}
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)
})
#> $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)
Created on 2021-01-25 by the reprex package (v0.3.0)
question from:
https://stackoverflow.com/questions/65880511/call-to-options-has-different-side-effects-dependening-on-how-it-is-called 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…