- Why Learn Assert Statements For Unit Tests?
- Table of Contents
- PyTest Python Assert Statements List
- 1. Equal to or not equal to [value]
- 2. type() is [value]
- 3. isinstance
- 4. Boolean is [Boolean Type]
- 5. in and not in [iterable]
- 6. Greater than or less than [value]
- 7. Modulus % is equal to [value]
- 8. any() assert statements
- 9. all() assert statements
- 10. Custom Python Objects
- 11. Iterables
- Combining Multiple And / Or Statements With Assert Statements:
- Testing Multiple Commands
- Unleash Your Potential with AI-Powered Prompt Engineering!
- Python 3.x UnitTest Assert Methods
- Typing Assert Statements
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.
Table of Contents
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) in ----> 1 assert 5 == 3 # Fail Example AssertionError:
assert 5 != 3 # Success Example assert 5 != 5 # Fail Example --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) in ----> 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) in ----> 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) in ----> 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) in ----> 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) in ----> 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) in ----> 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) in ----> 1 assert 5 > 7 # Fail Example AssertionError: assert 2 < 4 # Success Example assert 4 < 2 # Fail Example --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) in ----> 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) in ----> 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) in ----> 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:
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) in ----> 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) in ----> 1 assert isinstance(3, Iterable) # Fail Example AssertionError:
Want to improve your data skills?
See the best data engineering & data science books
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) in ----> 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) in ----> 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:
Unleash Your Potential with AI-Powered Prompt Engineering!
Dive into our comprehensive Udemy course and learn to craft compelling, AI-optimized prompts. Boost your skills and open up new possibilities with ChatGPT and Prompt Engineering.
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) in 1 yay = Test(5 , 'Phoenix') # Fail Example ----> 2 yay.test_all_class_arguments() 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:
Method | Checks | Version |
---|---|---|
assertEqual | a == b | 3.x |
assertNotEqual | a != b | 3.x |
assertTrue | bool(x) is True | 3.x |
assertFalse | bool(x) is False | 3.x |
assertIs | a is b | 3.x |
assertIsNot | a is not b | 3.x |
assertIsNone | x is None | 3.x |
assertIsNotNone | x is not None | 3.x |
assertIn | a in b | 3.x |
assertNotIn | a not in b | 3.x |
assertIsInstance | is instance(a,b) | 3.x |
assertNotIsInstance | not is instance(a,b) | 3.x |
assertRaises | fun(*args,**kwds) raises exc | 3.x |
assertRaisesRegexp | fun(*args,**kwds) raises exc(regex) | 3.x |
assertAlmostEqual | round(a-b,7) == 0 | 3.x |
assertNotAlmostEqual | round(a-b,7) != 0 | 3.x |
assertGreater | a > b | 3.x |
assertGreaterEqual | a >= b | 3.x |
assertLess | a < b | 3.x |
assertLessEqual | a | 3.x |
assertRegexpMatches | r.search(s) | 3.x |
assertNotRegexpMatches | not r.search(s) | 3.x |
assertItemsEqual | sorted(a) == sorted(b) | 3.x |
assertDictContainsSubset | all the key/value pairs in a exist in b | 3.x |
assertMultiLineEqual | strings | 3.x |
assertSequenceEqual | sequences | 3.x |
assertListEqual | lists | 3.x |
assertTupleEqual | tuples | 3.x |
assertSetEqual | sets or frozensets | 3.x |
assertDictEqual | dicts | 3.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) in ----> 1 example_class.test_subtract_function() # Successs 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!
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 😉