W09C Full
W09C Full
2. unittesting
4. Tasks
2 / 19
Motivation: Limits of Doctests
What are some barriers that prevent you from creating doctests?
3 / 19
Motivation: Limits of Doctests
4 / 19
unittest
Some unit tests can be written with a doctest. For these, you
don’t have to use the unittest module to write a unit test.
5 / 19
Unit Testing
6 / 19
Code Framework
1 import unittest
2 class Test<function's name>(unittest.TestCase):
3 def test_<descriptive test case name>(self):
4 any number of lines of
5 code you need for set up/tear down
6 self.assert<option>(a, b, message)
7
7 / 19
Example 1
1 import unittest
2 MSG = 'abs(), input: {}, expected: {}, received: {}'
3 class TestAbs(unittest.TestCase):
4 def test_positive(self):
5 input_val = 8
6 expected = 8
7 result = abs(input_val)
8 self.assertEqual(expected, result,
9 MSG.format(input_val, expected, result))
10 unittest.main()
8 / 19
assert Methods
In the above, we saw a unittest that used assertEqual. Other
tests are available.
assertEqual(a, b) a == b assertNotEqual(a, b)
assertIs(a, b) a is b assertIsNot(a, b)
assertIn(a, b) a in b assertNotIn(a, b)
A program with higher code coverage has more of its source code
executed by a particular test suite. There are python packages
that can measure this!
Task 1
Take the function abs from last class, and construct unit tests
for it.
Task 2
Take the function indices from last class, and construct unit
tests for it.
13 / 19
No Equivalent Docttest
Task 3
Recall Task 2 from the lecture on CSVs (W07C):
14 / 19
Recall: Why do we write tests?
15 / 19
Testing Overview
There are many types of testing ...
Sanity testing
Usability testing
Security testing
Performance testing
Smoke testing
Happy path testing
Gorilla testing
... who comes up with these names, anyway?
16 / 19
Levels of Testing
Each of those types of testing takes a different approach or has a
different goal. When testing functionality, there are four levels:
1. Unit Testing: Does a module work? Often performed by
developers, followed by testers.
19 / 19