Unittest Django:模拟外部API,什么是正确的方法?

时间:2018-05-03 14:30:13

标签: python django unit-testing mocking

我在理解模拟如何工作以及如何使用模拟对象编写单元测试时遇到问题。每当我的模型调用save()方法时,我想模拟外部api调用。 我的代码: models.py

from . import utils

class Book(Titleable, Isactiveable, Timestampable, IsVoidable, models.Model):
   title
   orig_author
   orig_title
   isbn 

    def save(self, *args, **kwargs):
        if self.isbn:
            google_data = utils.get_original_title_and_name(self.isbn)
            if google_data:
                self.original_author = google_data['author']
                self.original_title = google_data['title']
        super().save(*args, **kwargs)

utils.py

def get_original_title_and_name(isbn, **kawargs):
    isbn_search_string = 'isbn:{}'.format(isbn)
    payload = {
        'key': GOOGLE_API_KEY,
        'q': isbn_search_string,
        'printType': 'books',
    }
    r = requests.get(GOOGLE_API_URL, params=payload)
    response = r.json()
    if 'items' in response.keys():
        title = response['items'][THE_FIRST_INDEX]['volumeInfo']['title']
        author = response['items'][THE_FIRST_INDEX]['volumeInfo']['authors'][THE_FIRST_INDEX]

        return {
            'title': title,
            'author': author
        }
    else:
        return None

我开始阅读文档并编写测试:

test.py

from unittest import mock
from django.test import TestCase
from rest_framework import status
from .constants import THE_FIRST_INDEX, GOOGLE_API_URL, GOOGLE_API_KEY

class BookModelTestCase(TestCase):
    @mock.patch('requests.get')
    def test_get_original_title_and_name_from_google_api(self, mock_get):
        # Define new Mock object
        mock_response = mock.Mock()
        # Define response data from Google API
        expected_dict = {
            'kind': 'books#volumes',
            'totalItems': 1,
            'items': [
                {
                    'kind': 'books#volume',
                    'id': 'IHxXBAAAQBAJ',
                    'etag': 'B3N9X8vAMWg',
                    'selfLink': 'https://www.googleapis.com/books/v1/volumes/IHxXBAAAQBAJ',
                    'volumeInfo': {
                        'title': "Alice's Adventures in Wonderland",
                        'authors': [
                            'Lewis Carroll'
                        ]
                    }
                }
                    ]
            }

        # Define response data for my Mock object
        mock_response.json.return_value = expected_dict
        mock_response.status_code = 200

        # Define response for the fake API
        mock_get.return_value = mock_response

首先,我无法为target正确写@mock.patch。如果将target定义为utuls.get_original_title_and_name.requests.get,我会得到ModuleNotFoundError。此外,我无法理解如何对外部API进行虚假调用并验证收到的数据(如果我已经定义了mock_response.json.return_value = expected_dict?,是否有必要)并验证我的save()方法是否正常工作?

如何为此案例编写测试?有人能解释一下这个案子吗?

1 个答案:

答案 0 :(得分:4)

您应该模拟测试代码的直接协作者。对于Book utils。适用于utils的{​​{1}}。

对于requests

BookModelTestCase

然后您可以创建一个单独的测试用例来测试class BookModelTestCase(TestCase): @mock.patch('app.models.utils') def test_save_book_calls_google_api(self, mock_utils): mock_utils.get_original_title_and_name.return_value = { 'title': 'Google title', 'author': 'Google author' } book = Book( title='Some title', isbn='12345' ) book.save() self.assertEqual(book.title, 'Google title') self.assertEqual(book.author, 'Google author') mock_utils.get_original_title_and_name.assert_called_once_with('12345')

get_original_title_and_name