Pytest Equivalents of unittest assertions

Pytest is a good alternative to the venerable built-in unittest library for unit testing in Python. Out of the box Pytest can run all of your existing unittest tests.

If you see unit testing examples online or in a book they are often written as unittest tests. You'll notice that for unittest there are different assert statements for each type of assertion. For Pytest you use only the native assert command. Here I'm going to give simple examples of each unittest assertXXXX and its Pytest assert equivalent.

For each of the unittest examples assume that the test is within a test class. I won't show these each time, but they'd look something like this:

import unittest

class SomeTestCase(unittest.TestCase):
     def some_test(self):
         # test code here

And as a note, all of these examples are Python3. Not all of the unittest assertions are available in Python 2.7.

assertEqual

a = 5
b = 5
# unittest
assertEqual(a, b)
# pytest
assert a == b

assertNotEqual

a = 5
b = 6
# unittest
assertNotEqual(a,b)
# pytest
assert a != b

assertTrue

a = True
# unittest
assertTrue(a)
# pytest
assert a

assertFalse

b = False
# unittest
assertFalse(b)
# pytest
assert not b

assertIs

a = 5
b = a
# unittest
assertIs(a, b)
# pytest
assert a is b

assertIsNot

a = 5
b = 5
# unittest
assertIsNot(a, b)
# pytest
assert a is not b

assertIsNone

a = None
# unittest
assertIsNone(a)
# pytest
assert a is None

assertIsNotNone

a = 5
# unittest
assertIsNotNone(a)
# pytest
assert a is not None

assertIn

a = 2
b = [1, 2, 3, ]
# unittest
assertIn(a, b)
# pytest
assert a in b

assertNotIn

a = 4
b = [1, 2, 3, ]
# unittest
assertNotIn(a, b)
# pytest
assert a not in b

assertIsInstance

a = 5
b = 10
# unittest
assertIsIntance(a, b)
# pytest
assert isintance(a, b)

Comments

Comments powered by Disqus