首页 > 解决方案 > 在 Django 中模拟外部 API

问题描述

我正在尝试在 Django 中模拟外部 api,但不确定如何正确执行。

基本上,它必须模拟来自外部 API 的 json 数据,然后在所有值都有效的情况下创建一个新对象。

如果响应数据包含所有必填字段,程序会根据给定的 IP 地址获取地理位置数据并将对象保存在数据库中。那么,我如何模拟这个过程来测试新对象的创建呢?

服务.py

import os
import requests
from .exceptions import ExternalApiException

def get_location(ip):
    url = f'http://api.ipstack.com/{ip}' 
    params = {'access_key': os.environ.get('ACCESS_KEY')}
    try:
        res = requests.get(url, params=params)
        data = res.json()
        return {
            'ip':data['ip'],
            'country_name':data['country_name'],
            'region_code':data['region_code'],
            'city':data['city'],
            'latitude':data['latitude'],
            'longitude':data['longitude'],
            'zip_code':data['zip']
        }
    except requests.exceptions.ConnectionError:
        raise ExternalApiException('Connection error occured during the fetch process')
    except requests.exceptions.Timeout:
        raise ExternalApiException("Connection timeout. Please check your internet connection and try again later")
    except requests.exceptions.TooManyRedirects:
        raise ExternalApiException("Too many redirects")
    except requests.exceptions.RequestException:
        raise SystemExit(e)

测试.py

#I am lost in this part

@patch('geolocation.services.get_location')
def test_create_basic_geolocation(self, mock_request):
        """Test creating geolocation data"""
        payload = { 
            'ip': '',
        }
        res = self.client.post(LOCATIONS_URL, payload)

        self.assertTrue(res.data['ip'])

谢谢你的帮助。

标签: djangounit-testingdjango-rest-frameworkpython-requests

解决方案


只需像这样在模拟实例上分配 return_value


@patch('geolocation.services.get_location')
def test_create_basic_geolocation(self, mock_request):
        """Test creating geolocation data"""
        mock_request.return_value = {"ip": "hello", "country_name": "test"}
        payload = { 
            'ip': '',
        }
        res = self.client.post(LOCATIONS_URL, payload)

        self.assertTrue(res.data['ip'])

推荐阅读