0

Using Mock with Django Part 2

 3 years ago
source link: https://snakeycode.wordpress.com/2019/11/19/using-mock-with-django-part-2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using Mock with Django Part 2

If you need to make some tests that do not involve lots of database interactions, consider using the builtin Python unittest.TestCase along with the Python mock package. One reason to do this is these tests will be much faster than Django TestCase because the database will not need to be setup each time.

Here is some code to test a function that returns a model field value:

import unittest
import mock

from data.models import Job


def my_func():
    job = Job.objects.get(id=2)  # a Django model
    return job.number  # number is a field in the Job model


def mock_get_job(**kwargs):
    job = mock.Mock(spec=Job)
    if kwargs['id'] == 2:
        job.number = '123'
    else:
        job.number = '456'
    return job


class Test1(unittest.TestCase):
    @mock.patch('data.models.Job.objects.get', mock_get_job)
    def test_1(self):
        number = my_func()
        self.assertEqual('123', number)
[\code]

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK