如何断言函数调用不会在unittest中返回错误? [英] How to assert that a function call does not return an error with unittest?

查看:248
本文介绍了如何断言函数调用不会在unittest中返回错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论如何,unittest都可以断言一个函数调用不会导致错误,无论它是TypeError还是IOError等等.

Is there anyway with unittest to just assert that a function call does not result in an error, whether it is a TypeError, IOError, etc.

示例:

assert function(a,b) is not error

if not assertRaises function(a, b)

做到这一点的最佳方法是什么(不使用类)?我遇到的麻烦是,我在unittest中遇到的所有有用文档都是基于类的,而我不想使用基于类的

What is the best way to do this (without using classes)? The trouble I'm having is all the useful documentation I come a cross in unittest is all class based and I don't want to use class based.

完整示例:

def test_validate_params():
    assert test.validate_params('hackenv-re', 'test.username') is not errors
    assert test.validate_params('fakeenv', 'test.username') is error
    assert test.validate_params('hackevn-re', 'vagrant') is error
    counter += 1
    print "Test Passed {0}/5: validate_params".format(counter)

推荐答案

如果您的函数引发异常,则测试将失败.无需进行任何其他检查.如果您绝对愿意,可以执行以下操作:

If your function raises an exception, the test will fail. There is no need to do any additional checks. If you absolutely want to, you can do something like this:

try:
    function_under_test()
except Exception as e:
    self.fail("Unexpected exception %s" % e) 

(假设标准的Python单元测试)

(assuming standard Python unittest)

这篇关于如何断言函数调用不会在unittest中返回错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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