Book Image

Crafting Test-Driven Software with Python

By : Alessandro Molina
Book Image

Crafting Test-Driven Software with Python

By: Alessandro Molina

Overview of this book

Test-driven development (TDD) is a set of best practices that helps developers to build more scalable software and is used to increase the robustness of software by using automatic tests. This book shows you how to apply TDD practices effectively in Python projects. You’ll begin by learning about built-in unit tests and Mocks before covering rich frameworks like PyTest and web-based libraries such as WebTest and Robot Framework, discovering how Python allows you to embrace all modern testing practices with ease. Moving on, you’ll find out how to design tests and balance them with new feature development and learn how to create a complete test suite with PyTest. The book helps you adopt a hands-on approach to implementing TDD and associated methodologies that will have you up and running and make you more productive in no time. With the help of step-by-step explanations of essential concepts and practical examples, you’ll explore automatic tests and TDD best practices and get to grips with the methodologies and tools available in Python for creating effective and robust applications. By the end of this Python book, you will be able to write reliable test suites in Python to ensure the long-term resilience of your application using the range of libraries offered by Python for testing and development.
Table of Contents (18 chapters)
1
Section 1: Software Testing and Test-Driven Development
6
Section 2: PyTest for Python Testing
13
Section 3: Testing for the Web
16
About Packt

Using mocks

As you've probably noticed, when we use dummy objects, stubs, or spies, we always end up working with the unittest.mock module. That's because mock objects could be seen as dummy objects that provide some stubs mixed with spies.

Mocks are able to be passed around and they usually do nothing, behaving pretty much like dummy objects.

If we had a read_file function accepting a file object with a read method, we could provide a Mock instead of a real file; Mock.read will just do nothing:

>>> def read_file(f):
... print("READING ALL FILE")
... return f.read()
...
>>> from unittest.mock import Mock
>>> m = Mock()
>>> read_file(m)
READING ALL FILE

If instead of doing nothing, we want to make it act like a stub, we can provide a canned response to have Mock.read return a predefined string:

>>> m.read.return_value = "Hello World"
>>> print(read_file(m))
Hello World

If we don't want to just fill...