How to assert that a function call does not return

2019-09-20 04:26发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-09-20 05:07

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)

查看更多
登录 后发表回答