Unit
Testing
with
Python
Materials available at: http://bit.ly/CUUnitTesting
Overview
- What is unit testing
- Why do unit testing
- Python crash course
- How to do unit testing in Python
What is Unit Testing?
- Goal: Isolate a unit of code and test its' correctness
- Test it through using it in a "test" method and by asserting some behavior to be true
- By testing every unit you can ensure that the whole program is correct
- These tests can be automated or manual
- Tests are executed often to ensure the code is working
Good Unit Tests
- Short and sweet
- Quick execution
- One desired functionality per test
- Cover all of the code
- Contain good code
- Including readability and best practices
- Have explicit method names
Why bother with Unit Testing?
- You can ensure that future changes do not break the existing functionality
- Easier to find where the code is wrong
- If you write the unit tests first it often simplifies development, this is called Test Driven Development
Python Crash Course
REPL
Read - Evaluate - Print - Loop
Python 3.7.2+ (default, Feb 27 2019, 15:41:59)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, world!")
Hello, world!
Functions
def foo(argument_1, argument_2):
return argument_1 + argument_2
>>> foo(1, 2)
3
Conditionals
if number == 1:
print("one")
elif number == 2:
print("two")
elif number == 3:
print("three")
Classes
class Jody:
def __init__(self, love_for_gryffn):
self.has_dog = True
self.love_for_dog = love_for_gryffn
def grade_homework(self, grade):
if grade > 90:
return "A"
else:
return "F"
>>> strausser = Jody(10000)
>>> strausser.grade_homework(101)
"A"
Imports
import math
>>> print(math.log(10))
2.302585092994046
How to Unit Test in Python 3
- UnitTest
- DocTest
- Quick and dirty way of doing unit tests
- Searches for REPL-like blocks in the comment at the top of a function
- ut-doctest.py
- "Classic" way of doing unit tests
- Create a new class containing functions that do the testsĀ
- ut-unittest.py
Additional Resources
- To learn Python:
- To learn more about testing in Python:
Unit Testing with Python
By Alex Day
Unit Testing with Python
Introduction to unit testing with python in mind
- 783