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

Shashi
  • 2,137
  • 3
  • 22
  • 37
  • 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 Jun 09 '11 at 10:25

2 Answers2

39

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")
adamnfish
  • 10,935
  • 4
  • 31
  • 40
  • 4
    yes working i directly add SERVER_NAME in client like C = Client(SERVER_NAME="mydomain.com") – Shashi Jun 09 '11 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/')
madjardi
  • 5,649
  • 2
  • 37
  • 37