7

私はちょうど今、R を使った単体テストを始めたばかりで、これまでのところ難しいそりを見つけています。私がやりたいことは、R コンソールに移動し、test()testthat を入力して、R パッケージ内のすべてのファイルのテストを実行することです。

ここに私の環境があります:

sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-apple-darwin15.2.0 (64-bit)
Running under: OS X 10.11.4 (El Capitan)

そしてディレクトリ構造:

math
-- R
------ math.R
------ add.R 
------ subtract.R
-- tests
------ testthat.R 
------ testthat
---------- test_add.R
---------- test_subtract.R
---------- test_math.R

関連ファイルの次のサンプルを使用します。

数学.R

source('add.R')
source('subtract.R')

doubleAdd <- function(x){
    return(add(x,x) + add(x,x))
}

add.R

add <- function(a,b){
    return(a + b)
}

testthat.R

library(testthat)
library(math)

test_check("math")

test_add.R

context('add tests')

test_that('1 + 1 = 2', {
    expect_equal(2, add(1,1))
})

エラー:

R コンソールでは、次の結果が得られます。

library(devtools)
test()
<b>Loading math
Loading required package: testthat
Error in file(filename, "r", encoding = encoding) (from math.R#1) : 
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'add.R': No such file or directory
</b>

ただし、作業ディレクトリを切り替えてsetwd('R')math.R を実行すると、正常にdoubleAdd機能します。また、math.R を削除するか、「R」ディレクトリから math.R を移動すると、問題なくtest()動作します。

test()すべての R ファイルに対してテストを実行するには、これらのファイルをどのようにセットアップすればよいですか?

4

1 に答える 1

3

パッケージを構築している場合は、使用しないでくださいsource。関数をNAMESPACEファイルにエクスポートするか、roxygenを使用して実行するだけです。add.R作業ディレクトリが何であれ、探しているため、エラーが発生する可能性があります。

これは、基本的なパッケージのセットアップを使用して、ゼロから始めるための実行です。

add.R - R/ ディレクトリ内

#' @export
add <- function(a,b){
  return(a + b)
}

test_add.R - tests/testthat/ ディレクトリ内

context('add tests')

test_that('1 + 1 = 2', {
  expect_equal(2, add(1,1))
})

コンソールで実行

library(devtools)
# setup testing framework
use_testthat()

# update NAMESPACE and other docs
document()

# run tests
test()

Loading math
Loading required package: testthat
Testing math
add tests : .

DONE 

- 実際には export する必要さえありませんadd。テストしている内部関数の場合は、引き続き機能します。sourceパッケージでの使用をやめてください。

于 2016-03-25T18:33:39.853 に答える