作为我第一次尝试在 python 中创建 API 测试,我的测试文件目前如下所示:
from django.test import TestCase, RequestFactory
from customer.models import Customer, CustomerStatus
from customer.views import CustomerPartialView
from rest_framework.test import APIRequestFactory
import pprint
from django.utils import timezone
class CustomerTest(TestCase) :
def setUp(self) :
self.factory = RequestFactory()
self.cust_status = CustomerStatus.objects.create(
status_id=1,name="banned",description="test desc" )
self.customer = Customer.objects.create(
guid='b27a3251-56e0-4870-8a03-27b0e92af9e5',
created_date=timezone.now(),
status_id=1,first_name='Hamster')
def test_get_customer(self) :
"""
Ensure we can get a customer from db through the API
"""
factory = APIRequestFactory()
request = factory.get('/customer/b27a3251-56e0-4870-8a03-27b0e92af9e5')
reponse = CustomerPartialView(request)
#in here I need something to check:
#response.data.first_name = "Hamster"
我想要实现的是将虚拟数据插入数据库,然后使用 APIRequestFactory 检索单个客户记录并确保他们的名字与我期望的相符。
我已经设法做到了这一点,但不确定下一步该做什么。
我的问题是:
- 我走的路对吗?
- 如何测试我的结果,即
response.data.first_name = hamster? - 是否有更好的方法来实现我想要实现的目标
我是 python 的新手,所以如果我的代码中有任何重大错误,我提前道歉。
谢谢
请您参考如下方法:
如果我理解正确,我认为你的问题可能是你使用 response.data.first_name 而不是 response.data['first_name'] 作为响应.data 是一个字典。
所以应该是这样的:
self.assertEqual(response.data['first_name'], 'Hamster')
或者,我推荐的是:
self.assertEqual(response.data['first_name'], self.customer.first_name)
我还认为将请求 url 更改为 '/customer/%s' % self.customer.guid 会更整洁一些 节省您重新编写字符串的时间。
