Book Image

Django Design Patterns and Best Practices

By : Arun Ravindran
Book Image

Django Design Patterns and Best Practices

By: Arun Ravindran

Overview of this book

Table of Contents (19 chapters)
Django Design Patterns and Best Practices
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Mocking


Most real-life projects have various interdependencies between components. While testing one component, the result must not be affected by the behavior of other components. For example, your application might call an external web service that might be unreliable in terms of network connection or slow to respond.

Mock objects imitate such dependencies by having the same interface, but they respond to method calls with canned responses. After using a mock object in a test, you can assert whether a certain method was called and verify that the expected interaction took place.

Take the example of the SuperHero profile eligibility test mentioned in Pattern: Service objects (see Chapter 3, Models). We are going to mock the call to the service object method in a test using the Python 3 unittest.mock library:

# profiles/tests.py
from django.test import TestCase
from unittest.mock import patch
from django.contrib.auth.models import User

class TestSuperHeroCheck(TestCase):
    def test_checks_superhero_service_obj...