1

I have a function bowtieIndex(bowtieBuildLocation, filename) that calls bowtie2-build. It's parameters are the bowtie2-build location on my system and the output filename.

How do I write a test for this function without hard-coding the bowtie2-build location?

4

1 に答える 1

3

関数内で外部プログラムを呼び出しているだけの場合、それが直接機能するかどうかをテストすることはできません。コード自体がなければ、具体的に答えるのは難しいですが、たとえば、外部プログラムを実行するためにbowtieIndex呼び出している場合は、機能したか失敗したかのように見せかけて、何をするかをモックできます。のドキュメントを参照してください。systemsystemtestthat::with_mock

以下に 3 つの例を示します。system最初のパラメーターは、実際の関数の代わりに実行される新しいコードです。非常に具体的なことをしたい場合、system関数が呼び出されたパラメーターは、関数定義で通常どおり使用できます。複雑な置換関数を記述するよりも、繰り返しテストする方が簡単だと思います。2 番目のパラメーターであるコード ブロック { } 内のすべてが、ネストされたすべての関数呼び出しを含む、置換システム関数のみを参照するコンテキストで実行されます。このコード ブロックの後、with_mock関数は終了し、実数base::systemは自動的にスコープに戻ります。モックできる関数にはいくつかの制限がありますが、驚くほど多くの基本関数をオーバーライドできます。

# 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" ))
于 2016-03-02T23:47:54.727 に答える