How To Use Django Test Client To Test Views

We have learnt how to create and run unit test in Django project in previous article Django Unit Test Example. But that example mainly focus on Django application models test. Django also provide class django.test.Client for you to test your Django application views. This example will tell you how to use it.

1. How To Use django.test.Client To Test Web Page In Django Shell.

django.test.Client behave like a light weight web browser, it provide method for you to send GET or POST request to a url, and then return a django.http.HttpResponse object. With this HttpResponse object, you can get various information from the response such as response status code, headers, cookies and the response content.

To use django.test.Client class to implement Django app views test, follow below steps.

  1. Open a terminal, and go to the Django project root folder.
  2. Run python3 manage.py shell command to go into Django shell console.
  3. Input below python code into the console line by line.
    # first need to import setup_test_environment, teardown_test_environment
    from django.test.utils import setup_test_environment, teardown_test_environment
    # import Client class.
    from django.test import Client
    
    # setup django test environment
    setup_test_environment(debug=True)
    
    # create an instance of django.test.Client class.
    client = Client()
    
    # request to the specified url with GET request method.    
    response = client.get(path='http://127.0.0.1:8000/dept_emp/')
    
    # print out the response status code and content. 
    print('Response status code : ' + str(response.status_code))
    print('Response content : ' + str(response.content))
    
    # teardown django test environment
    teardown_test_environment()

2. How To Use django.test.Client To Unit Test Django Application Views In Django Project.

We generally create unit test in Django project application folder, and we should create test case class by extend django.test.TestCase. We have told this in previous example Django Unit Test Example. Now we will also use django.test.Client in Django project test case class to test application views. To implement this, you do not need to instantiate django.test.Client object, because django.test.TestCase already has an attribute client which is just a django.test.Client class instance, you can use it directly.

Below example is based on article Django Bootstrap3 Example.

  1. Create a new python file tests_views.py in DjangoHelloWorld / dept_emp folder.
    add dept emp views test case python file
  2. Input below python source code in tests_views.py.
    from django.test import TestCase
    
    class ViewTest(TestCase):
    
        def test_home_page(self):
    
            print('******************test_home_page()**********************')
            # send GET request.
            response = self.client.get('/dept_emp/')
            print('Response status code : ' + str(response.status_code))
    
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, 'dept_emp/home_page.html')
    
    
        def test_login_use_empty_username_password(self):
    
            print('******************test_login_use_empty_username_password()**********************')
    
            login_account_test_data = {'username':'', 'password':''}
    
            # send POST request.
            response = self.client.post(path='/dept_emp/user_login/', data=login_account_test_data)
    
            print('Response status code : ' + str(response.status_code))
    
            #print('Response content : ' + str(response.content))
    
            self.assertEqual(response.status_code, 200)
    
            self.assertNotIn(b'User name can not be empty.', response.content)
    
            self.assertIn(b'Password can not be empty.', response.content)
    
    
        def test_login_username_or_password_not_correct(self):
    
            print('******************test_login_username_or_password_not_correct()**********************')
    
            login_account_test_data = {'username': 'admin', 'password': 'qqqqqq'}
    
            response = self.client.post(path='/dept_emp/user_login/', data=login_account_test_data)
    
            print('Response status code : ' + str(response.status_code))
    
            #print('Response content : ' + str(response.content))
    
            self.assertEqual(response.status_code, 200)
    
            # if the provided string exist in the response content html, then pass.
            self.assertIn(b'User name or password is not correct.', response.content)
    
        def test_login_success(self):
    
            print('******************test_login_success()**********************')
    
            login_account_test_data = {'username': 'admin', 'password': 'admin'}
    
            response = self.client.post(path='/dept_emp/user_login/', data=login_account_test_data)
    
            print('Response status code : ' + str(response.status_code))
    
            self.assertNotIn(b'User name or password is not correct', response.content)
    
            self.assertIn(b'Search', response.content)
  3. Go to this Django project root folder in a terminal.
  4. Run python3 manage.py test dept_emp.tests_views command to execute all the test case in tests_views.py module file.
  5. If you just want to run specified test case class in tests_views.py module, you can run python3 manage.py test dept_emp.tests_views.ViewTest
  6. If you want to run specified test function, you can run python3 manage.py test dept_emp.tests_views.ViewTest.test_login_success

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.