another way to write tests
I used unittest in how to make a Python Test Driven Development environment manually to run tests manually before I learned to run them automatically with pytest-watcher.
The unittest library is part of The Python Standard Library and can also be used to write tests, it is like a toolbox with different tools I can use to test code.
preview
I have these tests by the end of the chapter
questions about unittest
start the project
I name this project
unittestI open a terminal
I change directory to the
unittestfolder in thepumping_pythonfolderthe terminal shows
cd: no such file or directory: unittestI use uv to make a directory for the project and initialize it
the terminal shows
Initialized project `unittest` at `.../pumping_python/unittest`I change directory to
unittestthe terminal shows I am in the
unittestfolder.../pumping_python/unittestI make a directory for the tests
I make the
testsdirectory a Python packageDanger
use 2 underscores (__) before and after
initfor__init__.pynot_init_.pytouch tests/__init__.pyNew-Item tests/__init__.pyI make an empty file for the tests in the
testsfoldertouch tests/test_unittest.pyNew-Item tests/test_unittest.pyI open
test_unittest.pyfrom thetestsfolderI add the first failing test to
test_unittest.py1def test_failure(): 2 assert False is TrueI go back to the terminal
I use echo to add pytest to
requirements.txtecho "pytest" > requirements.txtI add pytest-watcher to the requirements file
echo "pytest-watcher" >> requirements.txtthe terminal goes back to the command line.
I use Out-File to add pytest to
requirements.txt"pytest" | Out-File requirements.txt -Encoding UTF8I add pytest-watcher to the requirements file
"pytest-watcher" >> requirements.txt
I use uv to install pytest-watcher with the requirements file
I add a git commit message
I use
pytest-watcherto run the teststhe terminal is my friend, and shows AssertionError
======================== FAILURES ======================== ______________________ test_failure ______________________ def test_failure(): > assert False is True E assert False is True test_unittest.py:2: AssertionError ================ short test summary info ================= FAILED test_unittest.py::test_failure - assert False is True =================== 1 failed in X.YZs ====================if the terminal does not show the same error, then check if
your
tests/__init__.pyhas two underscores (__) before and afterinitfor__init__.pynot_init_.pyyou ran
echo "pytest-watcher" >> requirements.txt, to addpytest-watcherto the requirements file
and try
uv run pytest-watcher . --now --patterns "**/*.py"againI add AssertionError to the list of Exceptions seen, in
test_unittest.py1def test_failure(): 2 assert False is True 3 4 5# Exceptions seen 6# AssertionErrorI change True to False in the assertion
1def test_failure(): 2 # assert False is True 3 assert False is False 4 5 6# Exceptions seen 7# AssertionErrorthe test passes.
test_dir_unittest
I want to see what comes with the unittest module.
RED: make it fail
I change
test_failureto test_dir_unittest intest_unittest.py1def test_dir_unittest(): 2 reality = dir(unittest) 3 my_expectation = [] 4 assert reality == my_expectation 5 6 7# Exceptions seenthe terminal is my friend, and shows NameError
NameError: name 'unittest' is not defined. Did you forget to import 'unittest'?I add NameError to the list of Exceptions seen
GREEN: make it pass
I add an import statement for unittest at the top of the file
1import unittest 2 3 4def test_dir_unittest():the terminal is my friend, and shows AssertionError
E AssertionError: assert ['BaseTestSui...tLoader', ...] == [] E E Left contains 44 more items, first extra item: 'BaseTestSuite' E Use -v to get more diffI click in the terminal where the tests are running then press v on the keyboard for pytest-watcher to show me more of the difference between
realityandmy_expectationand it shows AssertionErrorE ...Full output truncated (44 lines hidden), use '-vv' to showI press w on the keyboard in the terminal where the tests are running, to show the menu for pytest-watcher and it shows
I press c on the keyboard to change runner args, and the terminal shows
[pytest-watcher] Current runner args: [] Controls: > Enter : Invoke test runner > r : reset all runner args > c : change runner args > f : run only failed tests (--lf) > p : drop to pdb on fail (--pdb) > v : increase verbosity (-v) > e : Erase terminal screen > q : quit pytest-watcher Enter new runner args: -vvI type -+v+v then press enter to show the full difference, and the terminal shows AssertionError with the full list.
I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as
my_expectationCaution
Your list of attributes and methods may be different depending on your Python version
the test passes because when
import unittestruns, Python brings in an object for the unittest module from The Python Standard Library so I can use it intest_unittest.pyasunittest.This means that there is a file or folder on the computer named
unittestthat got added when I installed Python.I open a new terminal then make sure I am in the
unittestfolder
test_dir_unittest_testcase
One of the names in the list of attributes and methods of unittest is TestCase, this is the class (toolbox) that contains the things I will use to write tests for code.
RED: make it fail
I add a new test for the attributes and methods of TestCase
23 assert reality == my_expectation
24
25
26def test_dir_unittest_testcase():
27 reality = dir(unittest.TestCase)
28 my_expectation = []
29 assert reality == my_expectation
30
31
32# Exceptions seen
the terminal is my friend, and shows AssertionError
E AssertionError: assert
['__call__', ...__doc__', ...] == []
E
E Left contains 108 more items,
first extra item: '__call__'
E Use -v to get more diff
GREEN: make it pass
I click in the terminal where the tests are running then press v on the keyboard for pytest-watcher to show me more of the difference between
realityandmy_expectationand it shows AssertionErrorE ...Full output truncated (108 lines hidden), use '-vv' to showI press w on the keyboard in the terminal where the tests are running, to show the menu for pytest-watcher and it shows
I press c on the keyboard to change runner args, and the terminal shows
[pytest-watcher] Current runner args: [] Controls: > Enter : Invoke test runner > r : reset all runner args > c : change runner args > f : run only failed tests (--lf) > p : drop to pdb on fail (--pdb) > v : increase verbosity (-v) > e : Erase terminal screen > q : quit pytest-watcher Enter new runner args: -vvI type
-vvthen press enter to show the full difference, and the terminal shows AssertionError with the entire list.I copy (ctrl/command+c) the values from the terminal and paste (ctrl/command+v) them as
my_expectationThe test passes.
The __init__ method is in the list of attributes and methods because all objects inherit from ‘object’.
REFACTOR: make it better
I see names that begin with
assertand look like some of the assertions I have written so far.assert X is not Yassert X is Yassert X != Yassert X == Yassert not isinstance(X, Y)assert isinstance(X, Y)assert not issubclass(X, Y)assert issubclass(X, Y)I type these names below the test as a TODO list to test what I can do with them
test_assertIsNot
RED: make it fail
I go back to the terminal where the tests are running
I add a test for assertIsNot
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIsNot() missing 3 required positional arguments: 'self', 'expr1', and 'expr2'because a method of an instance takes the instance of the class (
self) it belongs to as the first argument.The definition of the assertIsNot method of the TestCase class of the unittest library (
unittest.TestCase.assertIsNot) has two required positional arguments. I imagine Python follows this path when unittest.TestCase.assertIsNot is calledunittest.TestCase.assertIsNot └── unittest └── class TestCase: └── def assertIsNot(self, expr1, expr2): └── return something
I add TypeError to the list of Exceptions seen
GREEN: make it pass
I change the call to use an instance instead of the unittest.TestCase class
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIsNot() missing 2 required positional arguments: 'expr1' and 'expr2'I no longer need to provide
selfbecause it is the instance of the class (unittest.TestCase()).I add two things to the call to unittest.TestCase.assertIsNot
the terminal is my friend, and shows AssertionError
AssertionError: unexpectedly identical: Nonebecause None is None.
I change the assertion to make it True
the test passes.
REFACTOR: make it better
I add an assertion to compare it with the assertIsNot method
the terminal is my friend, and shows AssertionError
E assert None is not NoneI change the assertion to make it True
the test passes.
I remove assertIsNot from the TODO list
I imagine Python follows this path when unittest.TestCase.assertIsNot is called
unittest.TestCase.assertIsNot
└── unittest
└── class TestCase:
└── def assertIsNot(self, expr1, expr2):
└── assert expr1 is not expr2
Compare the error message for assertIsNot(None, None) with the one for assert None is not None
AssertionError: unexpectedly identical: None
vs
assert None is not None
Which do you like better?
test_assertIs
RED: make it fail
I go back to the terminal where the tests are running
I add a test for the assertIs method
the terminal is my friend, and shows AssertionError
E assert False is True
GREEN: make it pass
I change the assertion to make it True
87def test_assertIs():
88 # assert False is True
89 assert False is False
90
91
92'assertIs'
the test passes.
REFACTOR: make it better
I add a call to the assertIs method
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIs() missing 3 required positional arguments: 'self', 'expr1', and 'expr2'because a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I change the call to use an instance instead of the unittest.TestCase class
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIs() missing 2 required positional arguments: 'expr1' and 'expr2'I no longer need to provide
selfbecause it is the instance of the class (unittest.TestCase())I add two things to the call to unittest.TestCase.assertIs
the terminal is my friend, and shows AssertionError
AssertionError: False is not Truebecause False is not True.
I change the assertion to make it True
the test passes.
I remove assertIs from the TODO list
I imagine Python follows this path when unittest.TestCase.assertIs is called
unittest.TestCase.assertIs
└── unittest
└── class TestCase:
└── def assertIs(self, expr1, expr2):
└── assert expr1 is expr2
Compare the error message for assertIs(False, True) with the one for assert False is True
AssertionError: False is not True
vs
E assert False is True
test_assertNotEqual
RED: make it fail
I go back to the terminal where the tests are running
I add a test for assertNotEqual
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertNotEqual() missing 2 required positional arguments: 'first' and 'second'the definition of the assertNotEqual method of the TestCase class of the unittest library (
unittest.TestCase.assertNotEqual) has two required positional arguments (firstandsecond).
GREEN: make it pass
I add two things to the call to unittest.TestCase.assertNotEqual
the terminal is my friend, and shows AssertionError
AssertionError: True == Truebecause True is True.
I change the assertion to make it True
the test passes.
REFACTOR: make it better
I add an assertion to compare it with the assertNotEqual method
the terminal is my friend, and shows AssertionError
E assert True != TrueI change the assertion to make it True
the test passes.
I remove assertNotEqual from the TODO list
I imagine Python follows this path when unittest.TestCase.assertNotEqual is called
unittest.TestCase.assertNotEqual
└── unittest
└── class TestCase:
└── def assertNotEqual(self, first, second):
└── assert first != second
Compare the error message for assertNotEqual(True, True) with the one for assert True != True
AssertionError: True == True
vs
E assert True != True
test_assertEqual
RED: make it fail
I go back to the terminal where the tests are running
I add a test for the assertEqual method
the terminal is my friend, and shows AssertionError
AssertionError: assert 0.0 == '0.0'
GREEN: make it pass
I change the assertion to make it True
104def test_assertEqual():
105 # assert 0.0 == '0.0'
106 assert 0.0 == 0.0
107
108
109'assertEqual'
the test passes.
REFACTOR: make it better
I add a call to the assertEqual method
the terminal is my friend, and shows AssertionError
AssertionError: 0.0 != '0.0'I change the assertion to make it True
the test passes.
I remove assertEqual from the TODO list
I imagine Python follows this path when unittest.TestCase.assertEqual is called
unittest.TestCase.assertEqual
└── unittest
└── class TestCase:
└── def assertEqual(self, first, second):
└── assert first == second
Compare the error message for assertEqual(0.0, '0.0') with the one for assert 0.0 == '0.0'
AssertionError: 0.0 != '0.0'
vs
AssertionError: assert 0.0 == '0.0'
test_assertNotIsInstance
RED: make it fail
I go back to the terminal where the tests are running
I add a test for the assertNotIsInstance method
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertNotIsInstance() missing 3 required positional arguments: 'self', 'obj', and 'cls'The definition of the assertNotIsInstance method of the TestCase class of the unittest library (
unittest.TestCase.assertNotIsInstance) has three required positional arguments (self,objandcls)A method of an instance takes the instance of the class (
self) it belongs to as the first argument.objis for the instance being tested.clsis for the object.
GREEN: make it pass
I change the call to use an instance instead of the unittest.TestCase class
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertNotIsInstance() missing 2 required positional arguments: 'obj' and 'cls'I add two things to the call to unittest.TestCase.assertNotIsInstance
the terminal is my friend, and shows AssertionError
AssertionError: <unittest.case.TestCase testMethod=runTest> is an instance of <class 'unittest.case.TestCase'>I change the assertion to make it True
the test passes because an object is not an instance of itself.
REFACTOR: make it better
I add an assertion to compare it with the assertNotIsInstance method
the terminal is my friend, and shows AssertionError
E AssertionError: assert not TrueI change the assertion to make it True
the test passes.
I remove assertNotIsInstance from the TODO list
I imagine Python follows this path when unittest.TestCase.assertNotIsInstance is called
unittest.TestCase.assertNotIsInstance
└── unittest
└── class TestCase:
└── def assertNotIsInstance(self, obj, cls):
└── assert not isinstance(obj, cls)
Compare the error message for unittest.TestCase().assertNotIsInstance(unittest.TestCase(), unittest.TestCase) with the one for assert not isinstance(unittest.TestCase(), unittest.TestCase)
AssertionError:
<unittest.case.TestCase testMethod=runTest>
is an instance of
<class 'unittest.case.TestCase'>
vs
AssertionError: assert not True
test_assertIs_instance
RED: make it fail
I go back to the terminal where the tests are running
I add a test for assertIsInstance
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIsInstance() missing 3 required positional arguments: 'self', 'obj', and 'cls'A method of an instance takes the instance of the class (
self) it belongs to as the first argument.objis for the instance being tested.clsis for the object.
GREEN: make it pass
I change the call to use an instance instead of the unittest.TestCase class
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIsInstance() missing 2 required positional arguments: 'obj' and 'cls'I add two things to the call to unittest.TestCase.assertIsInstance
the terminal is my friend, and shows AssertionError
AssertionError: <class 'unittest.case.TestCase'> is not an instance of <class 'unittest.case.TestCase'>I change the assertion to make it True
the test passes.
REFACTOR: make it better
I add an assertion to compare it with the assertIsInstance method
the terminal is my friend, and shows AssertionError
AssertionError: assert FalseI change the assertion to make it True
the test passes.
I add variables
I use the variables to remove repetition of
unittest.TestCaseandunittest.TestCase()the test is still green.
I remove assertIsInstance from the TODO list
I imagine Python follows this path when unittest.TestCase.assertIsInstance is called
unittest.TestCase.assertIsInstance
└── unittest
└── class TestCase:
└── def assertIsInstance(self, obj, cls):
└── assert isinstance(obj, cls)
Compare the error message for unittest.TestCase().assertIsInstance(unittest.TestCase, unittest.TestCase) with the one for assert isinstance(unittest.TestCase, unittest.TestCase)
AssertionError:
<class 'unittest.case.TestCase'>
is not an instance of
<class 'unittest.case.TestCase'>
vs
AssertionError: assert False
test_assertNotIsSubclass
Caution
test_assertNotIsSubclass will only work if your Python version is 3.14 or newer
RED: make it fail
I go back to the terminal where the tests are running
I add a test for assertNotIsSubclass
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertNotIsSubclass() missing 2 required positional arguments: 'cls' and 'superclass'clsis for the subclass being tested.superclassis for the parent class of the subclass being tested.
GREEN: make it pass
I add two things to the call to unittest.TestCase.assertNotIsSubclass
the terminal is my friend, and shows AssertionError
AssertionError: <unittest.case.TestCase testMethod=runTest> is not a classbecause an instance is not a class.
I change the assertion to use an object
the terminal is my friend, and shows AssertionError
AssertionError: <class 'unittest.case.TestCase'> is a subclass of <class 'object'>because all objects inherit from ‘object’.
I change the assertion to make it True
the test passes because the unittest.TestCase class is not a subclass of the dict class (the class for dictionaries).
REFACTOR: make it better
I add an assertion to compare it with the assertNotIsSubobject method
the terminal is my friend, and shows AssertionError
E AssertionError: assert not TrueI change the assertion to make it True
the test passes because the unittest.TestCase class is not a subclass of the list class (the class for lists).
I remove assertNotIsSubclass from the TODO list
I imagine Python follows this path when unittest.TestCase.assertNotIsSubclass is called
unittest.TestCase.assertNotIsSubclass
└── unittest
└── class TestCase:
└── def assertNotIsSubclass(self, cls, superclass):
└── assert not issubclass(cls, superclass)
Compare the error message for unittest.TestCase().assertNotIsSubclass(unittest.TestCase, object) with the one for assert not issubclass(unittest.TestCase, object)
AssertionError:
<class 'unittest.case.TestCase'>
is a subclass of <class 'object'>
vs
AssertionError: assert not True
test_assertIs_subclass
Caution
test_assertIs_subclass will only work if your Python version is 3.14 or newer
RED: make it fail
I go back to the terminal where the tests are running
I add a test for the assertIsSubobject method
the terminal is my friend, and shows TypeError
TypeError: issubclass() arg 1 must be a class
GREEN: make it pass
I change the instance to the object
the terminal is my friend, and shows AssertionError
AssertionError: assert FalseI change the assertion to make it True
the test passes.
I add a call to assertIsSubclass
the terminal is my friend, and shows TypeError
TypeError: TestCase.assertIsSubclass() missing 3 required positional arguments: 'self', 'cls', and 'superclass'A method of an instance takes the instance of the class (
self) it belongs to as the first argument.clsis for the subclass being testedsuperclassis for the parent class of the subclass being tested.
I change the call to use an instance instead of the unittest.TestCase class, then add two things to the parentheses
the terminal is my friend, and shows AssertionError
AssertionError: <unittest.case.TestCase testMethod=runTest> is not a classbecause an instance is not a class.
I change the instance to the object
the terminal is my friend, and shows AssertionError
AssertionError: <class 'unittest.case.TestCase'> is not a subclass of <class 'set'>I change the assertion to make it True
the test passes because all objects inherit from ‘object’.
REFACTOR: make it better
I remove assertIsSubclass from the TODO list
I imagine Python follows this path when unittest.TestCase.assertIsSubclass is called
unittest.TestCase.assertIsSubclass
└── unittest
└── class TestCase:
└── def assertIsSubclass(self, cls, superclass):
└── assert issubclass(cls, superclass)
Compare the error message for unittest.TestCase().assertIsSubclass(unittest.TestCase, tuple) with the one for assert issubclass(unittest.TestCase, set)
AssertionError:
<class 'unittest.case.TestCase'>
is not a subclass of <class 'tuple'>
vs
AssertionError: assert False
Which of the error messages in this chapter do you like better?
extract TOOLBOX variable
I make an instance of the unittest.TestCase class to use its assert methods in every test. I can use a variable to remove repetition of that process (unittest.TestCase()) from every test.
I add a variable for
unittest.TestCase()at the top of the file1import unittest 2 3 4TOOLBOX = unittest.TestCase() 5 6 7def test_dir_unittest():I use the variable for
unittest.TestCase()in test_assertIsNotthe test is still green.
I remove the commented lines from test_assertIsNot
I use the variable for
unittest.TestCase()in test_assertIsstill green.
I remove the commented lines from test_assertIs
I use the variable for
unittest.TestCase()in test_assertNotEqualgreen.
I remove the commented lines from test_assertNotEqual
I use the variable for
unittest.TestCase()in test_assertEqualstill green.
I remove the commented lines from test_assertEqual
I use the variable for
unittest.TestCase()in test_assertNotIsInstancethe test is still green.
I remove the commented lines from test_assertNotIsInstance
I use the variable for
unittest.TestCase()in test_assertIs_instancestill green.
I remove the commented lines from test_assertIs_instance
I use the variable for
unittest.TestCase()in test_assertNotIsSubclassgreen.
I remove the commented lines from test_assertNotIsSubclass
I use the variable for
unittest.TestCase()in test_assertIs_subclassstill green.
I remove the commented lines from test_assertIs_subclass
The unittest.TestCase() instance is now made once then used in every test for its assert methods.
The problem with this solution is that anyone reading it has to know what the TOOLBOX variable points to at the beginning of the file to understand why the calls work.
extract TestUnittest object
I can put the test functions together in an object since they are related.
RED: make it fail
I go back to the terminal where the tests are running
I add an object named
Unittestthis is a problem. I expect
TOOLBOX.assertEqual(True, False)to fail since True is not equal to FalseI add
Testto the name of the object4TOOLBOX = unittest.TestCase() 5 6 7# class Unittest(object): 8class TestUnittest(object): 9 10 def test_failure():the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_failure() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.
GREEN: make it pass
I add the staticmethod decorator to
test_failuresince I can use it if I do not want to addselfto the method definition. This way I do not send more information than what the method needs when it does not use anything that belongs to the objectthe terminal is my friend, and shows AssertionError
AssertionError: True != FalseI change False to True in the assertion
the test passes.
REFACTOR: make it better
I remove
test_failureI move test_dir_unittest to replace
test_failureas a method of the TestUnittest classCaution
Indentation matters in Python. It is how it knows what blocks belong to what function/method, object or module (Use 4 spaces)
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_dir_unittest() takes 0 positional arguments but 1 was givenI add the staticmethod decorator to test_dir_unittest
the test passes.
I add a call to the assertNotEqual method
the terminal is my friend, and shows AssertionError.
I change assertNotEqual to assertEqual
the test passes.
I move test_dir_unittest_testcase to make it a method of the TestUnittest class
TypeError: TestUnittest.test_dir_unittest_testcase() takes 0 positional arguments but 1 was givenI add the staticmethod decorator to test_dir_unittest_testcase
the test passes.
I add a call to the assertNotEqual method
the terminal is my friend, and shows AssertionError.
I change assertNotEqual to assertEqual
the test passes.
I indent (move with four spaces) test_assertIsNot to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertIsNot() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I add the staticmethod decorator to test_assertIsNot
the test passes.
I move test_assertIs to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertIs() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I add the staticmethod decorator to test_assertIs
the test passes.
I indent test_assertNotEqual to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertNotEqual() takes 0 positional arguments but 1 was givenbecause …
I add the staticmethod decorator to test_assertNotEqual
the test passes.
I move test_assertEqual to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertEqual() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I add the staticmethod decorator to test_assertEqual
the test passes.
I move test_assertNotIsInstance to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertNotIsInstance() takes 0 positional arguments but 1 was givenI add the staticmethod decorator to test_assertNotIsInstance
the test passes.
I move test_assertIs_instance to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertIs_instance() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I add the staticmethod decorator to test_assertIs_instance
the test passes.
I move test_assertNotIsSubclass to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertNotIsSubclass() takes 0 positional arguments but 1 was givenI add the staticmethod decorator to test_assertNotIsSubclass
the test passes.
I move test_assertIs_subclass to make it a method of the TestUnittest class
the terminal is my friend, and shows TypeError
TypeError: TestUnittest.test_assertIs_subclass() takes 0 positional arguments but 1 was givenbecause a method of an instance takes the instance of the class (
self) it belongs to as the first argument.I add the staticmethod decorator to test_assertIs_subclass
the test passes.
I add the
TOOLBOXvariable to TestUnittest to make it an object attributeI use the new object attribute for
TOOLBOXin test_dir_unittestthe terminal is my friend, and shows NameError
NameError: name 'self' is not definedI add
selfto the parentheses of test_dir_unittestthe terminal is my friend, and shows
E fixture 'self' not foundI remove the staticmethod decorator since I am using
selfin the test_dir_unittestthe test is green again.
I use the new object attribute for
TOOLBOXin test_dir_unittest_testcaseNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_dir_unittest_testcasegreen again.
I use the object attribute for
TOOLBOXin test_assertIsNotNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertIsNotthe test is green again.
I use the object attribute for
TOOLBOXin test_assertIsNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertIsgreen again.
I use the object attribute for
TOOLBOXin test_assertNotEqualNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertNotEqualthe test is green again.
I use the object attribute for
TOOLBOXin test_assertEqualNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertEqualgreen again.
I use the object attribute for
TOOLBOXin test_assertNotIsInstanceNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertNotIsInstancethe test is green again.
I use the object attribute for
TOOLBOXin test_assertIs_instanceNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertIs_instancethe test is green again.
I use the object attribute for
TOOLBOXin test_assertNotIsSubclassNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertNotIsSubclassthe test is green again.
I use the object attribute for
TOOLBOXin test_assertIs_subclassNameError: name 'self' is not definedI add
selfto the parentheses and comment out the staticmethod decorator for test_assertIs_subclassthe test is green again.
I remove the
TOOLBOXvariable because it is no longer used1import unittest 2 3 4# class Unittest(object): 5class TestUnittest(object):
use unittest.TestCase
I can use the unittest.TestCase class as a parent of the TestUnittest class which will allow me to use self to access its attributes and methods.
It also means I will not need the TOOLBOX object attribute which points to an instance of the unittest.TestCase class.
RED: make it fail
I go back to the terminal where the tests are running
I change the call to the assertEqual method in test_dir_unittest
the terminal is my friend, and shows AttributeError
AttributeError: 'TestUnittest' object has no attribute 'assertEqual'I add AttributeError to the list of Exceptions seen
GREEN: make it pass
I add unittest.TestCase as the parent of the TestUnittest class so that it can have all the attributes and methods of unittest.TestCase
4# class Unittest(object):
5# class TestUnittest(object):
6class TestUnittest(unittest.TestCase):
7
8 TOOLBOX = unittest.TestCase()
9
10 # @staticmethod
11 # def test_dir_unittest():
12 def test_dir_unittest(self):
13 reality = dir(unittest)
the test passes because
TestUnittest is now a subclass (child) of the unittest.TestCase class.
children inherit the attributes and methods of their parents.
selfis TestUnittest() inside TestUnittest.selfhas all the attributes and methods of unittest.TestCase because unittest.TestCase is the parent class.
class TestUnittest(unittest.TestCase):
└── def test_dir_unittest(self):
│ ...
└── self.assertEqual(reality, my_expectation)
└── TestUnittest().assertEqual(reality, my_expectation)
└── unittest.TestCase().assertEqual(
reality, my_expectation
)
└── unittest
└── class TestCase():
└── def assertEqual(self, first, second):
├── first = reality
├── second = my_expectation
...
REFACTOR: make it better
I remove the commented lines from test_dir_unittest and TestUnittest
1import unittest 2 3 4class TestUnittest(unittest.TestCase): 5 6 TOOLBOX = unittest.TestCase() 7 8 def test_dir_unittest(self): 9 reality = dir(unittest) 10 my_expectation = [I add an assertion to test_assertIs_subclass to show that TestUnittest is a subclass of the unittest.TestCase class
the terminal is my friend, and shows AssertionError
AssertionError: <class 'tests.test_unittest.TestUnittest'> is a subclass of <class 'unittest.case.TestCase'>I change the assertion to make it True
the test passes.
class TestUnittest(unittest.TestCase): └── def test_assertIs_subclass(self): │ ... └── self.assertIsSubclass(TestUnittest, unittest.TestCase) └── TestUnittest().assertIsSubclass( TestUnittest, unittest.TestCase ) └── unittest.TestCase().assertIsSubclass( TestUnittest, unittest.TestCase ) └── unittest └── class TestCase(): └── def assertIsSubclass( self, cls, superclass ): ├── cls = TestUnittest ├── superclass = unittest.TestCase ...I change
self.TOOLBOX.assertIsSubclasstoself.assertIsSubclassthe test is still green.
I remove the commented lines from test_assertIs_subclass
I change the call to the assertNotIsSubobject method in test_assertNotIsSubclass
still green.
class TestUnittest(unittest.TestCase): └── def test_assertNotIsSubclass(self): │ ... └── self.assertNotIsSubclass(unittest.TestCase, dict) └── TestUnittest().assertNotIsSubclass( unittest.TestCase, dict ) └── unittest.TestCase().assertNotIsSubclass( unittest.TestCase, dict ) └── unittest └── class TestCase(): └── def assertNotIsSubclass( self, cls, superclass ): ├── cls = unittest.TestCase ├── superclass = dict ...I remove the commented lines from test_assertNotIsSubclass
I add an assertion to test_assertIs_instance to show that
selfin the TestUnittest class is an instance of the unittest.TestCase classthe terminal is my friend, and shows AssertionError
AssertionError: < tests.test_unittest.TestUnittest testMethod=test_assertIs_instance > is an instance of <class 'unittest.case.TestCase'>I change assertNotIsInstance to assertIsInstance
the test passes.
class TestUnittest(unittest.TestCase): └── def test_assertIs_instance(self): │ ... └── self.assertIsInstance(self, unittest.TestCase) └── TestUnittest().assertIsInstance( self, unittest.TestCase ) └── unittest.TestCase().assertIsInstance( self, unittest.TestCase ) └── unittest └── class TestCase(): └── def assertIsInstance( self, obj, cls ): ├── obj = self ├── cls = unittest.TestCase ...I change
self.TOOLBOX.assertIsInstancetoself.assertIsInstanceI remove the commented lines from test_assertIs_instance
I change the call to the assertNotIsInstance method in test_assertNotIsInstance
the test is still green.
class TestUnittest(unittest.TestCase): └── def test_assertNotIsInstance(self): │ ... └── self.assertNotIsInstance( unittest.TestCase, unittest.TestCase ) └── TestUnittest().assertIsInstance( unittest.TestCase, unittest.TestCase ) └── unittest.TestCase().assertIsInstance( unittest.TestCase, unittest.TestCase ) └── unittest └── class TestCase(): └── def assertNotIsInstance( self, obj, cls ): ├── obj = unittest.TestCase ├── cls = unittest.TestCase ...I remove the commented lines from test_assertNotIsInstance
I change the call to assertEqual in test_assertEqual
still green.
class TestUnittest(unittest.TestCase): └── def test_assertEqual(self): │ ... └── self.assertEqual(0.0, 0.0) └── TestUnittest().assertEqual(0.0, 0.0) └── unittest.TestCase().assertEqual(0.0, 0.0) └── unittest └── class TestCase(): └── def assertEqual( self, first, second ): ├── first = 0.0 ├── second = 0.0 ...I remove the commented lines from test_assertEqual
I change the call to the assertNotEqual method in test_assertNotEqual
still green.
class TestUnittest(unittest.TestCase): └── def test_assertNotEqual(self): │ ... └── self.assertNotEqual(True, 0) └── TestUnittest().assertNotEqual(True, 0) └── unittest.TestCase().assertNotEqual(True, 0) └── unittest └── class TestCase(): └── def assertNotEqual( self, first, second ): ├── first = True ├── second = 0 ...I remove the commented lines from test_assertNotEqual
I change the call to the assertIs method in test_assertIs
green.
class TestUnittest(unittest.TestCase): └── def test_assertIs(self): │ ... └── self.assertIs(False, False) └── TestUnittest().assertIs(False, False) └── unittest.TestCase().assertIs(False, False) └── unittest └── class TestCase(): └── def assertIs( self, expr1, expr2 ): ├── expr1 = False ├── expr2 = False ...I remove the commented lines from test_assertIs
I change the call to the assertIsNot method in test_assertIsNot
the test is still green.
class TestUnittest(unittest.TestCase): └── def test_assertIsNot(self): │ ... └── self.assertIsNot(None, False) └── TestUnittest().assertIsNot(None, False) └── unittest.TestCase().assertIsNot(None, False) └── unittest └── class TestCase(): └── def assertIsNot( self, expr1, expr2 ): ├── expr1 = None ├── expr2 = False ...I remove the commented lines from test_assertIsNot
I change the call to the assertEqual method in test_dir_unittest_testcase
the test is still green.
I remove the commented lines from test_dir_unittest_testcase
I remove the
TOOLBOXobject attribute since it is no longer usedall the tests are still passing.
close the project
I close
test_unittest.pyI click in the terminal where the tests are running
I use q on the keyboard to leave the tests. The terminal goes back to the command line.
I change directory to the parent of
unittestthe terminal shows
.../pumping_pythonI am back in the
pumping_pythondirectory.
review
I can write tests with the unittest.TestCase class which comes with assert methods I can use in place of basic assert statements:
code from the chapter
what is next?
Would you like to test the other projects with unittest?
Would you like to test the assertion_error project with unittest?
rate pumping python
If this has been a 7 star experience for you, please CLICK HERE to leave a 5 star review of pumping python. It helps other people get into the book too.