简体   繁体   English

如何使用unittest来断言断言?

[英]How to use unittest to assert an assert?

Let's say I have this function: 假设我有这个功能:

def to_upper(var):
    assert type(var) is str, 'The input for to_upper should be a string'
    return var.upper()

And a file for unit testing using unittest : 并使用unittest进行单元测试的文件:

class Test(unittest.TestCase):

    def test_1(self):
        -- Code here --


if __name__ == '__main__':
    unittest.main()

How do I test that if I call to_upper(9) it throws an assertion error? 如果我调用to_upper(9)它会抛出一个断言错误,我如何测试?

You can assert an assertion with assertRaises(AssertionError) : 您可以使用assertRaises(AssertionError)

def test_1(self):
    with self.assertRaises(AssertionError):
        to_upper(9)

Assertions are for debugging. 断言用于调试。 If there is some precondition that is important enough to verify with a unit test, check for it explicitly and raise a ValueError or TypeError , as appropriate, if it fails. 如果有一些重要的前置条件足以通过单元测试进行验证,请明确检查它并在适当的情况下引发ValueErrorTypeError (如果失败)。

In this case, you don't actually care the var is a str , though; 在这种情况下,你实际上并不关心varstr ; you just need it to have an upper method. 你只需要它有一个upper方法。

def to_upper(var):
    try:
        return var.upper()
    except AttributeError:
        raise TypeError("Argument has no method 'upper'")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM