How to assert that a function call does not return an error with unittest?

寵の児 提交于 2019-12-13 08:34:25

问题


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.

example:

assert function(a,b) is not error

or

if not assertRaises function(a, b)

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.

Full example:

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)

回答1:


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) 

(assuming standard Python unittest)



来源:https://stackoverflow.com/questions/36142282/how-to-assert-that-a-function-call-does-not-return-an-error-with-unittest

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