简体   繁体   中英

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 :

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?

You can assert an assertion with 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.

In this case, you don't actually care the var is a str , though; you just need it to have an upper method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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