Chapter 14. Testing, Debugging, and Exceptions
Testing rocks, but debugging? Not so much. The fact that thereâs no compiler to analyze your code
before Python executes it makes testing a critical part of development. The
goal of this chapter is to discuss some common problems related to testing, debugging,
and exception handling. It is not meant to be a gentle introduction to test-driven
development or the unittest
module. Thus, some familiarity with testing concepts
is assumed.
14.1. Testing Output Sent to stdout
Problem
You have a program that has a method whose output goes to standard
Output (sys.stdout
). This almost always means that it emits text to
the screen. Youâd like to write a test for your code to prove that,
given the proper input, the proper output is displayed.
Solution
Using the unittest.mock
moduleâs patch()
function, itâs pretty simple to mock out
sys.stdout
for just a single test, and put it back again, without messy
temporary variables or leaking mocked-out state between test cases.
Consider, as an example, the following function in a module mymodule
:
# mymodule.py
def
urlprint
(
protocol
,
host
,
domain
):
url
=
'{}://{}.{}'
.
format
(
protocol
,
host
,
domain
)
(
url
)
The built-in print
function, by default, sends output to sys.stdout
. In order
to test that output is actually getting there, you can mock it out
using a stand-in object, and then make assertions about what happened. Using
the unittest.mock
moduleâs patch()
method makes it convenient to replace objects ...
Get Python Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.