Testing in Python
nate-trojian
28.5K views
Testing in Python
Python comes with a few unique features specifically for testing. One of those features is Doctests. Doctests let you define simple unit tests right on your method. This is especially useful for test-driven development, where you have explicit examples you need to code against. Another one of those features is Mocking. Mocking allows you to overwrite an object and control it's behavior while testing.
Doctests
Can you make this doctest pass?
1
2
3
4
5
6
7
8
9
10
def square(x):
"""Returns the square of x.
>>> square(2)
4
>>> square(-2)
4
"""
return
Mocking
Mocking is Python's most powerful testing tool. A Mock Object completely overwrites the object you specify. This can be a class or a method. Mock Objects have two special fields, return_value and side_effect. Both of these fields effect the result of when a Mock is called.
For example:
1
2
3
4
5
6
7
8
9
10
from unittest import mock
def func():
return 3
# Overwriting the function with our mock
mock.patch("__main__.func", return_value=4).start()
# Did it work?
assert func() == 4
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.