Testing in Python

nate-trojian
6,896 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

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?
def square(x):
"""Returns the square of x.
>>> square(2)
4
>>> square(-2)
4
"""
return
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

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:

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
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content