(这个问题也在 Github here 上被问到)
将 R 升级到 4.0.2 后测试似乎失败了,sort
的算法在 testthat
改变了。下图显示,base::sort()
和 browser()
在 R 4.0.2 中很好(请参阅 this 问题,为什么要添加此检查。):
y <- c("Schaffhausen", "Schwyz", "Seespital", "SRZ")
print(sort(y))
# [1] "Schaffhausen" "Schwyz" "Seespital" "SRZ"
browser()
print(sort(y))
# [1] "Schaffhausen" "Schwyz" "Seespital" "SRZ"
但是如果你创建了一个包,就叫它 testsort
, 使用 usethis::use_testthat()
添加测试环境并在 /testsort/tests/testthat/
中添加一个文件“test-sort.R”test_that("test sort", {
xx <- c("Schaffhausen", "Schwyz", "Seespital", "SRZ")
print("")
# bowser()
print(sort(xx))
expect_equal(sort(xx), c("Schaffhausen", "Schwyz", "Seespital", "SRZ"))
})
你得到==> devtools::test()
Loading testsort
Testing testsort
v | OK F W S | Context
/ | 0 | sort[1] ""
[1] "SRZ" "Schaffhausen" "Schwyz" "Seespital"
v | 1 | sort
== Results =============================================================================
OK: 1
Failed: 0
Warnings: 0
Skipped: 0
我用过 debug(sort)
和 devtools::test()
在 RStudio 控制台(!)中,但无法弄清楚会发生什么。R.version
platform x86_64-w64-mingw32
arch x86_64
os mingw32
system x86_64, mingw32
status
major 4
minor 0.2
year 2020
month 06
day 22
svn rev 78730
language R
version.string R version 4.0.2 (2020-06-22)
nickname Taking Off Again
目前,testthat
2.3.2 是最新的,也就是说没有更新版本的 testthat。感谢来自 test 的 @Ulugbek Umirov :
10.5 CRAN notes
CRAN will run your tests on all CRAN platforms: Windows, Mac, Linux and Solaris. There are a few things to bear in mind:
Note that tests are always run in the English language (LANGUAGE=EN) and with C sort order (LC_COLLATE=C). This minimises spurious differences between platforms.
最佳答案
跨平台再现性更为重要。将排序规则设置为 C
确保测试在所有平台上给出相同的结果。
如果 sort
,则处理此更改的选项造成问题 (排序取决于排序规则)** 您至少有 3 个不同的选项:
stringr::sort()
的使用: 新依赖stringr
包裹myfun <- function(my_collation = "German_Switzerland.1252", ...) {
my_locale <- Sys.getlocale("LC_COLLATE"))
on.exit(expr = Sys.setlocale("LC_COLLATE", my_locale))
Sys.setlocale("LC_COLLATE", my_collation)
r <- sort(...)
return(r)
}
感谢 on.exit()
,没有使用新的软件包withr-Package
它负责处理 on.exit
部分myfun <- function(my_collation = "German_Switzerland.1252", …) {
withr::local_collate(my_collation)
r <- sort(…)
return(r)
}
关于r - 为什么testthat 2.3.2使用了不同的sort(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63336729/