O'Reilly logo

Test-Driven Development with Python, 2nd Edition by Harry J.W. Percival

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required