django - 在 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'])
谢谢你的帮助。
解决方案
只需像这样在模拟实例上分配 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'])
推荐阅读
- oauth-2.0 - 如何使用 Azure AD 作为 Cognito 的身份提供者来实现客户端凭据流
- spring-boot - SpringCloud,ReactorServiceInstanceLoadBalancer,RequestContextHolder.getRequestAttributes() 有时为空
- jupyter-notebook - Jupyter 仪表板目录
- unity3d - Unity:从输入字段中获取文本
- react-native - GoogleAPIs 与 React Native / Expo 的集成
- laravel - 多输入搜索表单
- html - 如何在 ::-webkit-scrollbar-button 中添加伪元素
- python - Discord.py:如何从用户输入消息中获取命令的确切字词?
- video - 怎么给视频加水印。即 png 和 text
- file - Visual Studio Code 打开多个实例