Change the default domain of Client() in unittest of Django
Asked Answered
P

2

23

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","[email protected]", "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 domain in that test client ,is their way to customize the test Client ?

Pilsen answered 9/6, 2011 at 10:5 Comment(1)
FYI: TestCase automatically adds self.client as an instance of Client, so you don't need to do self.c = Client() in setUp. Just change self.c.get in your test methods to test.client.get :)Tumblebug
T
40

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")
Tumblebug answered 9/6, 2011 at 10:32 Comment(1)
yes working i directly add SERVER_NAME in client like C = Client(SERVER_NAME="mydomain.com")Pilsen
P
1

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/')
Pozsony answered 21/11, 2018 at 7:30 Comment(1)
Giving some words explaining your answer goes a long way beyond a "just code" answer.Tansey

© 2022 - 2024 — McMap. All rights reserved.