首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R:如何使用test测试依赖于外部程序的函数?

R:如何使用test测试依赖于外部程序的函数?
EN

Stack Overflow用户
提问于 2016-02-03 12:41:30
回答 1查看 489关注 0票数 1

我有一个函数bowtieIndex(bowtieBuildLocation, filename),它调用bowtie2-build。它的参数是在我的系统上的bowtie2 2构建位置和输出文件名。

如何在不对bowtie2 2构建位置进行硬编码的情况下为该函数编写测试?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-02 23:47:54

如果您在函数中所做的一切都是调用外部程序,那么您就不能直接测试它是否有效。如果没有代码本身,这很难具体回答,但是,例如,如果bowtieIndex调用system来运行外部程序,您可以模拟system将做什么,假装它工作了,或者失败了。查看testthat::with_mock的文档。

下面是三个例子。第一个参数是将执行的新代码,而不是真正的system函数。使用system函数调用的参数在函数定义中可以正常使用,如果您想要做非常具体的事情的话。我发现重复测试比编写复杂的替换函数更容易。第二个参数(代码块{ } )中的所有内容都是使用只看到替换系统函数(包括所有嵌套函数)的上下文执行的。在这个代码块之后,with_mock函数退出,真正的base::system自动返回作用域。哪些函数可以被模拟有一些限制,但是大量的基本函数可以被覆盖。

代码语言:javascript
复制
# Pretend that the system call exited with a specific error
with_mock(
    `base::system`= function(...) {
        stop("It didn't work");
    }, {
    expect_error( bowtieIndex( bowtieBuildLocation, filename ),
                  "It didn't work"
    )
})

# Pretend that the system call exited with a specific return value
with_mock(
    `base::system`= function(...) {
        return(127);
    }, {
    expect_error( bowtieIndex( bowtieBuildLocation, filename ),
                  "Error from your function on bad return value." )
    expect_false( file.exists( "someNotGeneratedFile" ))
})

# Pretend that the system call worked in a specific way
with_mock(
    `base::system`= function(...) {
        file.create("someGeneratedFile")
        return(0);
    }, {
    # No error
    expect_error( got <- bowtieIndex(bowtieBuildLocation, filename), NA )

    # File was created
    expect_true( file.exists( "someGeneratedFile" ))
})

# got variable holding results is actually available here, outside
# with_mock, so don't need to test everything within the function.
test_equal( got, c( "I", "was", "returned" ))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35177396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档