Printing custom diagnostic information if `testthat` test fails in `R`

倖福魔咒の 提交于 2019-12-11 02:37:15

问题


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?


回答1:


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.




回答2:


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
}


来源:https://stackoverflow.com/questions/26928253/printing-custom-diagnostic-information-if-testthat-test-fails-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!