Printing custom diagnostic information if `testtha

2019-07-21 01:13发布

I use a testthat unit test to check whether the data.frame returned by a function is identical to the one I would expect it to return. If the test fails, testthat prints some diagnostic information, for instance:

MyFunction(df.orig) is not identical to df.expected. Differences: 
Names: 1 string mismatch

However, I would really like to see the actual output of the function, i.e. print the returned data.frame. Is there a way to print the output of the tested function (or some other custom diagnostic information) if a testthat test fails?

2条回答
走好不送
2楼-- · 2019-07-21 01:28

you could store the result of the expect_that in a temporary variable b, check if it fails inside the it construct and return b

b <- expect_that(df.orig, is_identical_to(df.expected))

if (!b$passed){

    #do something
}
查看更多
你好瞎i
3楼-- · 2019-07-21 01:43

Indirectly, yes! If you look at the arguments for expect_that, you'll see the "info" parameter - you can throw an anonymous function or a call in here that'll print the results. So, something like:

expect_that(df.orig, is_identical_to(df.expected), info = print(df.orig))

The disadvantage of this is that it will /always/ print df.orig or similar information, even if the test passes.

The only other way of doing it (and the only thing that would ensure it only triggers if an error occurs) would be to use tryCatch; something like:

tryCatch(
    expr = {
        expect_that(df.orig, is_identical_to(df.expected))
    }, 
    error = function(e){
        print(e)
        print(df.orig)
        #And anything else you want to only happen when errors do
    }
)

This is a lot clunkier-looking, but has a couple of advantages - it will only print df.orig if the expect_that call produces an error, you can output...well, anything you want, and you can produce different results for errors versus warnings. Fairly gnarly, however.

查看更多
登录 后发表回答