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 ?

1
  • 2
    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 :)
    – adamnfish
    Commented Jun 9, 2011 at 10:25

2 Answers 2

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")
1
  • 4
    yes working i directly add SERVER_NAME in client like C = Client(SERVER_NAME="mydomain.com")
    – Shashi
    Commented Jun 9, 2011 at 10:47
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/')
1
  • Giving some words explaining your answer goes a long way beyond a "just code" answer. Commented Nov 21, 2018 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.