Why Learn Assert Statements For Unit Tests?

Knowing how to write assert statements in Python allows you to easily write mini-tests for your code.

Additionally testing frameworks such as PyTest can work directly with assert statements to form fully functioning UnitTests.


You can also find a list of all of the different standard UnitTest Module examples here.

Firstly let’s review all of the different types of assert statements that we can make for PyTest.


PyTest Python Assert Statements List

# Module Imports
from types import *
import pandas as pd
import numpy as np
from collections.abc import Iterable

NB: Whenever you see # Success Example, this means that the assert test will succeed. However when you see # Fail Example, this means that the assert test will fail.


1. Equal to or not equal to [value]

assert 5 == 5 # Success Example

assert 5 == 3 # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-106-db6ee5a4bb16> in <module>
----> 1 assert 5 == 3 # Fail Example

AssertionError: 
assert 5 != 3 # Success Example

assert 5 != 5 # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-108-de24f583bfdf> in <module>
----> 1 assert 5 != 5 # Fail Example

AssertionError: 

2. type() is [value]

assert type(5) is int # Success Example

assert type(5) is not int # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-110-e4cc0467bcd9> in <module>
----> 1 assert type(5) is not int # Fail Example

AssertionError: 

3. isinstance

assert isinstance('5', str) # Success Example

assert isinstance('5', int) # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-112-28175282ec92> in <module>
----> 1 assert isinstance('5', int) # Fail Example

AssertionError: 
assert not isinstance('5', int) # Success Example

assert not isinstance('5', str) # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-116-1c215fe3a6a5> in <module>
----> 1 assert not isinstance('5', str) # Fail Example

AssertionError: 

4. Boolean is [Boolean Type]

true = 5==5
assert true is True # Success Example

assert true is False # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-118-45032f0eff77> in <module>
----> 1 assert true is False # Fail Example

AssertionError: 

5. in and not in [iterable]

list_one=[1,3,5,6]

assert 5 in list_one # Success Example
assert 5 not in list_one # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-121-90e8a0f2ef02> in <module>
----> 1 assert 5 not in list_one # Fail Example

AssertionError: 

6. Greater than or less than [value]

assert 5 > 4 # Success Example

assert 5 > 7 # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-123-3068a8105e75> in <module>
----> 1 assert 5 > 7 # Fail Example

AssertionError: 


assert 2 < 4 # Success Example

assert 4 < 2 # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-125-089b0fa99ac6> in <module>
----> 1 assert 4 < 2 # Fail Example

AssertionError: 

7. Modulus % is equal to [value]

assert 2 % 2 == 0 # Success Example

assert 2 % 2 == 1 # Fail Example
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-127-2c429e622b13> in <module>
----> 1 assert 2 % 2 == 1 # Fail Example

AssertionError: 

8. any() assert statements

example = [5,3,1,6,6]
booleans = [False, False,True, False]
>>> any(example)
True

>>> any(booleans)
True

Notice that the example list python list is True because at least one of the numbers is not a 0, all numbers above 0 are ‘Truthy’.

assert any(example) == True # Success Example
assert any(booleans) == True # Success Example

9. all() assert statements

>>> all(example)
True

>>> all(booleans)
False
assert all(example) # Success Example

assert all(booleans) # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-135-c422689f500e> in <module>
----> 1 assert all(booleans) # Fail Example

AssertionError: 

10. Custom Python Objects

It’s possible to identify if a class is a specific type of object. We can do this by using:

type(object).__name__
df = pd.DataFrame()

>>> type(df).__name__

'DataFrame'

type(df).__name__ == 'DataFrame' # True Boolean
type(df).__name__ is 'DataFrame' # True Boolean
type(df).__name__ == type([]).__name__ # False Boolean
type(df).__name__ is type([]).__name__ # False Boolean
assert(type(df).__name__ == 'DataFrame') # Success Example
assert(type(df).__name__ == type([]).__name__) # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-147-2332f54f50a3> in <module>
----> 1 assert(type(df).__name__ == type([]).__name__) # Fail Example

AssertionError: 

11. Iterables

It’s also possible to determine whether a variable is an iterable with:


from collections.abc import Iterable
iterable_item = [3,6,4,2,1]

>>> isinstance(iterable_item, Iterable)
True

>>> isinstance(5, Iterable)
False
assert isinstance(iterable_item, Iterable) # Success Example

assert isinstance(3, Iterable) # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-153-e96805891245> in <module>
----> 1 assert isinstance(3, Iterable) # Fail Example

AssertionError: 

Combining Multiple And / Or Statements With Assert Statements:

It’s also possible to combine multiple conditions with either OR or AND and to test the chained commands with the assert statement:

true_statement = 5 == 5 and 10 == 10
false_statement = 5 == 3 and 10 == 2

>>> print(true_statement, false_statement)
True False
assert true_statement # Success Example

assert false_statement # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-157-452ef20f327f> in <module>
----> 1 assert false_statement # Fail Example

AssertionError: 

true_or_statement = 5 == 5 or 3 == 3
false_or_statement = 7 == 3 or 10 == 1

>>> print(true_or_statement, false_or_statement)
True False
assert true_or_statement # Success Example

assert false_or_statement # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-161-38343a099bdc> in <module>
----> 1 assert false_or_statement # Fail Example

AssertionError: 

Testing Multiple Commands

Also we can test more than one thing at a time by having multiple assert statements inside of the same Python method:

class Test(object):
    def __init__(self, first_name, last_name ):
        self.first_name = first_name
        self.last_name = last_name

    def test_all_class_arguments(self):
        print('Testing both of the class variables to see whether they are both strings!')

        for _ in [self.first_name, self.last_name]:
            assert(type(_) is str)
        print('------')
        print('Passed all of the tests')
yay = Test('James' , 'Phoenix') # Success Example
yay.test_all_class_arguments()

Testing both of the class variables to see whether they are both strings!
------
Passed all of the tests
yay = Test(5 , 'Phoenix') # Fail Example
yay.test_all_class_arguments()

Testing both of the class variables to see whether they are both strings!

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-164-64cb2bee07e3> in <module>
      1 yay = Test(5 , 'Phoenix') # Fail Example
----> 2 yay.test_all_class_arguments()

<ipython-input-162-3ae9548ef4b7> in test_all_class_arguments(self)
      8 
      9         for _ in [self.first_name, self.last_name]:
---> 10             assert(type(_) is str)
     11         print('------')
     12         print('Passed all of the tests')

AssertionError: 

Python 3.x UnitTest Assert Methods

Below you’ll find a list of all of the UnitTest Assert Methods:

MethodChecksVersion
assertEquala == b3.x
assertNotEquala != b3.x 
assertTruebool(x) is True3.x
assertFalsebool(x) is False3.x
assertIsa is b3.x
assertIsNota is not b3.x
assertIsNonex is None3.x
assertIsNotNonex is not None3.x
assertIna in b3.x
assertNotIna not in b3.x
assertIsInstanceis instance(a,b)3.x
assertNotIsInstancenot is instance(a,b)3.x
assertRaisesfun(*args,**kwds) raises exc3.x
assertRaisesRegexpfun(*args,**kwds) raises exc(regex)3.x
assertAlmostEqualround(a-b,7) == 03.x
assertNotAlmostEqualround(a-b,7) != 03.x
assertGreatera > b3.x
assertGreaterEquala >= b3.x
assertLessa < b3.x
assertLessEquala <= b3.x
assertRegexpMatchesr.search(s)3.x
assertNotRegexpMatchesnot r.search(s)3.x
assertItemsEqualsorted(a) == sorted(b)3.x
assertDictContainsSubsetall the key/value pairs in a exist in b3.x
assertMultiLineEqualstrings3.x
assertSequenceEqualsequences3.x
assertListEquallists3.x
assertTupleEqualtuples3.x
assertSetEqualsets or frozensets3.x
assertDictEqualdicts3.x

Typing Assert Statements

As well as using simple assert statements, by importing the types module of python we can make more abstract assert statements on specific Types:

class Example():
    def __init__(self, id_, name):
        self._id = id_
        self.name = name

    def subtract(self):
        answer = 5 + 5
        return answer

    def test_lambda_function(self):
        assert(lambda x: x is LambdaType)

    def test_subtract_function(self):
        assert(self.subtract is LambdaType)
example_class = Example("123", 'James Phoenix')

>>> print(example_class._id, example_class.name)
123 James Phoenix

example_class.test_lambda_function() # Success Example 
example_class.test_subtract_function() # Fail Example

---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-169-e96c76763824> in <module>
----> 1 example_class.test_subtract_function() # Successs

<ipython-input-165-28a62a6c7adf> in test_subtract_function(self)
     12 
     13     def test_subtract_function(self):
---> 14         assert(self.subtract is LambdaType)

AssertionError: 

Above we’ve tested two class instance methods to see if either of them is a lambda: x style function!

You can find all of the different types here.


Hopefully this provides you with an extensive list of assert statements and methods for your Unit Tests.

Please let me know if you have any more examples that you’d like me to add them to this post πŸ˜‰

What's your reaction?