Back
Close

Testing in Python

nate-trojian
3,478 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?
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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants