如果`R`中的`testthat`测试失败,则打印自定义诊断信息 [英] Printing custom diagnostic information if `testthat` test fails in `R`

查看:196
本文介绍了如果`R`中的`testthat`测试失败,则打印自定义诊断信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用testthat单元测试来检查某个函数返回的data.frame是否与我希望它返回的那个相同.如果测试失败,则testthat打印一些诊断信息,例如:

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

但是,我真的很想看看该函数的实际输出,即打印返回的data.frame.如果testthat测试失败,是否可以打印已测试功能的输出(或一些其他自定义诊断信息)?

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?

推荐答案

间接,是的!如果查看expect_that的参数,则会看到"info"参数-您可以在此处抛出匿名函数或调用以打印结果.所以,像这样:

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))

这样做的缺点是,即使测试通过,它也会/始终/打印df.orig或类似信息.

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

执行此操作的唯一其他方法(以及唯一可以确保在发生错误时仅 触发的操作)是使用tryCatch;.像这样:

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
    }
)

这看起来很笨拙,但是有两个优点-仅在Expect_that调用产生错误,您可以输出...好吧,想要的任何东西以及可以产生不同的结果时,才打印df.orig.错误与警告的结果.但是,相当不合时宜.

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.

这篇关于如果`R`中的`testthat`测试失败,则打印自定义诊断信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆