【问题标题】:R: Problems with testthat test_file() within local environmentR:本地环境中的 testthat test_file() 问题
【发布时间】:2013-11-28 08:04:58
【问题描述】:

我在本地环境中调用 test_file 时遇到问题。

local({ newvar <- 1; expect_equal(newvar, 1); });

工作正常。

local({ 
  newvar <- 1; 
  test_that('newvar is equal to 1:', { expect_equal(newvar, 1) }); 
});

工作正常。

local( { newvar <- 1; test_file('simple.test.R'); });

错误:找不到对象“newvar”

simple.test.R 的内容很简单:

context('local env test');
test_that('local env test', { expect_equal(newvar, 1) })

帮助表示赞赏!谢谢。


编辑:

我要做的是从 shinyAce (https://github.com/trestletech/shinyAce) 读取一些代码,并检查它是否有效(满足一些定义的要求)。我正在使用“local()”,因此在 shinyAce 块中定义的任何分配变量都不会保留在环境中。

【问题讨论】:

    标签: r testing environment testthat


    【解决方案1】:

    这是test_file的来源:

    function (path, reporter = "summary") 
    {
        reporter <- find_reporter(reporter)
        with_reporter(reporter, {
            sys.source(path, new.env(parent = globalenv()), chdir = TRUE)
            end_context()
        })
    }
    

    关键是这样的:

    sys.source(path, new.env(parent = globalenv()), chdir = TRUE)
    

    文件在全局环境下的新环境中执行,而您的newvar仅在您创建的本地环境中可用。

    您的最终目标到底是什么?我们可以尝试提供帮助。还是你只是好奇?

    【讨论】:

    • 所以newvar 在测试运行中会发生变化?在simple_test.R 中,您可以创建一个接受newvar 参数的函数,然后将所有测试逻辑放入其中。如果你真的想要,你也可以定义你自己的test_file 版本来评估其他环境中的源文件。其中之一会起作用吗?
    • 我认为编写我自己的 test_file 版本是最好的解决方案。感谢您的帮助。
    • 不幸的是,您不能简单地编写自己的test_file 版本,因为test_file 使用的许多部分没有导出:find_reporterwith_reporter 等。所以您不能在你的新test_file,这很痛苦....
    • @GaborCsardi,您只需使用三重冒号运算符。例如,testthat:::find_reporter.
    • CRAN 上的 R 包中不允许这样做
    猜你喜欢
    • 2021-07-22
    • 2014-09-06
    • 2012-11-13
    • 2013-02-05
    • 2015-10-16
    • 2017-08-15
    • 2017-05-19
    • 1970-01-01
    • 2011-04-26
    相关资源
    最近更新 更多