我需要进行测试以查看我的视图是否正常运行。但是,我在测试文件中找不到如何使用请求对象。
我的查看功能是:
def track_view(request):
user_email, user_order = request.session['email'], request.session['order']
if request.method == 'POST':
client_id = request.META.get('HTTP_HOST').split(':8000')[0]
payload = "{ \n\"description\": \"Rastreio de pedido\", \n\"subject\": \"Rastreamento " + user_order + ' ' + user_email + "\", \n\"email\": \"" + user_email + "\", \n\"priority\": " + str(
priority['low']) + ", \n\"status\": " + str(status['closed']) + ", \n\"group_id\": " + str(group[
'Logística']) + ", \n\"type\": \"Rastrear Pedido\", \n\"product_id\": " + str(client[client_id]) + "}"
headers = {
'Content-Type': "application/json",
'Cache-Control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers, auth=('XXX', 'X'))
print(response.text)
context = {'email_variable': user_email,
'order_variable': user_order}
return redirect('atendimento:final_view')
logo_image = 'client_logo/' + request.META.get('HTTP_HOST').split(':8000')[0] + '.png'
context = {'logo_image': logo_image,
'user_email': request.POST.get('email'),
'user_order': request.session['order']}
return render(request, 'atendimento/track_page.html', context)
我该如何进行工作以测试对该视图的不同输入?
答案 0 :(得分:2)
您应该使用test client来测试请求。
def test_track_view(self):
session = self.client.session
session['email'] = 'foo@bar.com'
session['user_order'] = 'whatever'
url = reverse('my-url')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
请注意,您可能还希望模拟出requests对象,以使您的测试实际上不会向外部API发出请求。
还请注意,手动构建JSON字符串确实不是一个好习惯。而是创建一个字典,然后将其转储到JSON:
payload = { "description": "Rastreio de pedido", ... "priority": priority['low'], "status": status['closed'], "group_id": group['Logística']...}
response = requests.request("POST", url, data=json.dumps(payload), headers=headers, auth=('XXX', 'X'))