Testing in Python

nate-trojian
32.9K 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?

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:

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content