Book Image

Test-Driven Python Development

By : Siddharta Govindaraj
Book Image

Test-Driven Python Development

By: Siddharta Govindaraj

Overview of this book

This book starts with a look at the test-driven development process, and how it is different from the traditional way of writing code. All the concepts are presented in the context of a real application that is developed in a step-by-step manner over the course of the book. While exploring the common types of smelly code, we will go back into our example project and clean up the smells that we find. Additionally, we will use mocking to implement the parts of our example project that depend on other systems. Towards the end of the book, we'll take a look at the most common patterns and anti-patterns associated with test-driven development, including integration of test results into the development process.
Table of Contents (20 chapters)
Test-Driven Python Development
About the Author
About the Reviewers


Today, organizations encounter an ever-increasing delivery frequency problem. The days of delivering a new version every few years are long gone. The test-driven development process enables individuals and teams to deliver code that is not only robust but maintainable as well. Combine this with the rapid development speed of the Python language and you have a combination that enables the delivery of new features at the pace demanded by the market.

Test-Driven Python Development covers the end-to-end unit testing process, from the first simple test to complex tests that involve multiple components and interactions.

What this book covers

Chapter 1, Getting Started with Test-Driven Development, is the introductory chapter. It eases you into the TDD process by setting the context of why we need TDD and quickly getting started with a test.

Chapter 2, Red-Green-Refactor – The TDD Cycle, goes deeper into the TDD process, driving the implementation of our example project as we write more tests.

Chapter 3, Code Smells and Refactoring, explores common types of smelly code, and we go back to our example project and clean up the smells we find. A key benefit of TDD is that it provides a safety net so that we can go in and clean up messy code.

Chapter 4, Using Mock Objects to Test Interactions, shows the use of mocking to implement the parts of our example project that depend on other systems. How do you test code that depends on external subsystems? We answer that question here by introducing mock objects.

Chapter 5, Working with Legacy Code, is about the fact that we often need to clean up or add features to old code that doesn't have existing tests. This chapter looks at strategies for doing this by working through one of the modules in our sample application.

Chapter 6, Maintaining Your Test Suite, proves that unit tests are also code and good coding practices apply to test code as well. This means keeping them well organized and easy to maintain. This chapter covers techniques to do just that.

Chapter 7, Executable Documentation with doctest, goes through the usage of doctest by working through one of the modules of our application.

Chapter 8, Extending unittest with nose2, gives us a look at nose2, a powerful test runner and plugin suite that extends the unittest framework.

Chapter 9, Unit Testing Patterns, covers some other patterns for unit testing. We see how to speed up tests and how we can run specific subsets of tests. We also take a look at data-driven tests and mocking patterns.

Chapter 10, Tools to Improve Test-Driven Development, explains some popular third-party tools to help us improve our TDD practice. Some of these tools, such as py.test and trial, are test runners with some unique features.

Appendix A, Answers to Exercises, contains the answers to the exercises presented throughout this book. There are many possible solutions, each with their own advantages and disadvantages.

Appendix B, Working with Older Python Versions, describes the changes needed in order to apply the techniques in this book for older versions of Python because this book has been written for Python 3.4.

What you need for this book

You'll need the following software for this book: Python 3.4, nose 2, and lettuce.

Who this book is for

This book is intended for Python developers who want to use the principles of Test-Driven Development (TDD) to create efficient and robust applications. In order to get the best out of this book, you should have development experience with Python.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

import unittest
class StockTest(unittest.TestCase):
    def test_price_of_a_new_stock_class_should_be_None(self):
        stock = Stock("GOOG")
if __name__ == "__main__":

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

class Stock:

Any command-line input or output is written as follows:

python3 -m unittest discover

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Select the Publish JUnit test result report checkbox and enter the location of the nose2 unit test XML file."


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

You can also get a copy of the code from


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.