我正在为Django视图编写单元测试。
class TestLog(unittest.TestCase):
"""Test for Contact"""
def setUp(self):
self.c = Client()
try:
self.bob = User.objects.create_user("mojo","b@example.com", "bmojo")
except :
print ''
def test_get_emails(self):
response = self.c.get('/text/')
self.assertEqual(response.status_code, 200)
def test_htmlemils(self):
response = self.c.get('/emails/html/upload')
self.assertEqual(response.status_code, 200)
c = Client()将'http:// testserver'作为我要覆盖的域,我想在该测试客户端添加我的真实域,是他们自定义测试客户端的方式吗?
答案 0 :(得分:25)
Django的Client
extends RequestFactory
所以你应该能够传递额外的参数作为关键字参数。
尝试:
response = self.c.get('/emails/html/upload', SERVER_NAME="mydomain.com")
答案 1 :(得分:0)
该代码不仅可以帮助进行单元测试,还可以帮助DRF在序列化程序中使用上下文
ResponseSerializer(instance=obj, context={'request': get_request}).data
from django.test.client import RequestFactory
rf = RequestFactory()
rf.defaults['SERVER_NAME'] = 'my-site.com'
get_request = rf.get('/hello/')