R:在本地环境中testthat test_file()的问题

时间:2021-07-30 22:56:03

I am having problems with a call to test_file within a local environment.

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

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

Works fine.

工作正常。

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

works fine.

工作正常。

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

Error: object 'newvar' not found

错误:找不到对象'newvar'

Contents of simple.test.R are simply:

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

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

Help appreciated! Thanks.

帮助赞赏!谢谢。


Edit:

编辑:

What I'm trying to do is read some code from shinyAce (https://github.com/trestletech/shinyAce), and check it is valid (mets some defined requirements). I was using 'local()' so that any assigned variables defined in the shinyAce block would not remain in the environment.

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

1 个解决方案

#1


2  

Here's the source for test_file:

这是test_file的源代码:

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

The key line is this:

关键是这样的:

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

The file is executed in a new environment under the global environment, while your newvar is only available in a local environment of your creation.

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

What exactly is your end goal here? We can try to help. Or were you just curious?

你的最终目标究竟是什么?我们可以尝试提供帮助。或者你只是好奇吗?

#1


2  

Here's the source for test_file:

这是test_file的源代码:

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

The key line is this:

关键是这样的:

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

The file is executed in a new environment under the global environment, while your newvar is only available in a local environment of your creation.

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

What exactly is your end goal here? We can try to help. Or were you just curious?

你的最终目标究竟是什么?我们可以尝试提供帮助。或者你只是好奇吗?