Skip to Content
Test-Driven Development with Python, 2nd Edition
book

Test-Driven Development with Python, 2nd Edition

by Harry Percival
August 2017
Intermediate to advanced
624 pages
12h 18m
English
O'Reilly Media, Inc.
Content preview from Test-Driven Development with Python, 2nd Edition

Chapter 19. Using Mocks to Test External Dependencies or Reduce Duplication

In this chapter we’ll start testing the parts of our code that send emails. In the FT, you saw that Django gives us a way of retrieving any emails it sends by using the mail.outbox attribute. But in this chapter, I want to demonstrate a very important testing technique called mocking, so for the purpose of these unit tests, we’ll pretend that this nice Django shortcut doesn’t exist.

Note

Am I telling you not to use Django’s mail.outbox? No; use it, it’s a neat shortcut. But I want to teach mocks because they’re a useful general-purpose tool for unit testing external dependencies. You may not always be using Django! And even if you are, you may not be sending email—any interaction with a third-party API is a good candidate for testing with mocks.

Before We Start: Getting the Basic Plumbing In

Let’s just get a basic view and URL set up first. We can do so with a simple test that our new URL for sending the login email should eventually redirect back to the home page:

accounts/tests/test_views.py

from django.test import TestCase


class SendLoginEmailViewTest(TestCase):

    def test_redirects_to_home_page(self):
        response = self.client.post('/accounts/send_login_email', data={
            'email': 'edith@example.com'
        })
        self.assertRedirects(response, '/')

Wire up the include in superlists/urls.py, plus the url in accounts/urls.py, and get the test passing with something a bit like this:

accounts/views.py

from django.core.mail ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Test-Driven Development with Python, 3rd Edition

Test-Driven Development with Python, 3rd Edition

Harry Percival

Publisher Resources

ISBN: 9781491958698Errata Page