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
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Time to refactor


After a while, we might end up with a pretty good suite of characterization tests for the legacy code. We can now approach this code like any other well-tested code and start applying the bigger refactorings with an aim to improve the design before adding our new features.

For example, we might decide to extract the print_action method into a separate Action class, or the parse_file method into a Reader class.

The following is a FileReader class where we have moved the contents from the parse_file local method:

class FileReader:
    def __init__(self, filename):
        self.filename = filename

    def get_updates(self):
        updates = []
        with open("updates.csv", "r") as fp:
            for line in fp.readlines():
                symbol, timestamp, price = line.split(",")
                updates.append((symbol, datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f"), int(price)))
        return updates

We then use the Inject Dependencies pattern to pass the reader as...