[concept]OOP & Tooling
Testing Your Code
# theory
A test is just code that checks other code. The simplest test is assert:
if the condition is false it raises, if it's true nothing happens.
def double(n):
return n * 2
assert double(4) == 8
assert double(0) == 0
print("tests passed")
For anything real, the standard library has unittest. You write a class
that subclasses TestCase and use assertEqual and friends.
import unittest, io
class TestText(unittest.TestCase):
def test_upper(self):
self.assertEqual("abc".upper(), "ABC")
suite = unittest.TestLoader().loadTestsFromTestCase(TestText)
result = unittest.TextTestRunner(stream=io.StringIO()).run(suite)
print("passed" if result.wasSuccessful() else "failed")
The point of tests: change code with confidence. If a test goes red you broke something, and you find out now instead of in production.
# examples [2]
# example 01 · assert-based checks
Cheap, immediate, good for quick sanity checks
1
2
3
4
5
6
7
🐍
# example 02 · unittest with a captured runner
Run the suite and report success without noisy output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
# challenges [2]
# challenge 01/02todo
Write a function double(n) that returns n*2. Assert that double(4) == 8 and double(0) == 0, then print 'tests passed'.
1
2
3
4
5
6
7
8
9
10
11
12
🐍
# challenge 02/02todo
Write a unittest TestCase with one test asserting 'abc'.upper() == 'ABC'. Run it with a TextTestRunner whose stream is an io.StringIO(), then print 'passed' if the result was successful.
1
2
3
4
5
6
7
8
9
10
11
12
🐍