Change the default domain of Client() in unittest of Django
I am writing a unit test for Django views.
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)
The c = Client() takes the 'http://testserver' as domain which i want to overwrite ,i want to add my real 开发者_C百科domain in that test client ,is their way to customize the test Client ?
Django's Client
extends RequestFactory
so you should be able to pass in extra params as keyword arguments.
Try:
response = self.c.get('/emails/html/upload', SERVER_NAME="mydomain.com")
The code can help not only in unit test, but it can also help for DRF to use context in a serializer
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/')
精彩评论