Turn your manual testers into automation experts Request a DemoStart testRigor Free

Django Testing

Django Testing

Django is a highly regarded open-source framework for Python, renowned for its versatility, scalability, and security. Major organizations such as Mozilla, Pinterest, Instagram, Disqus, and National Geographic leverage Django to power their applications, attesting to its robustness and capability to handle complex requirements.

  • Scalable
    Its 'shared nothing' architecture allows you to add hardware resources such as database servers, caching servers, or web/application servers at any stage without constraints. This flexible structure facilitates efficient scalability, accommodating growth, and changing needs. Django also boasts its own built-in caching framework, enhancing its handling of performance optimization tasks.
  • Versatile
    It's not bound to a specific type of application; whether you want to create Content Management Systems (CMS), social networking sites, or delve into the realm of scientific computing platforms, Django provides a solid foundation. Its adaptable and feature-rich nature allows developers to create a wide variety of applications with relative ease.
  • Secure
    Django steps ahead of the curve by integrating numerous built-in provisions to fortify your application. It's equipped to prevent common security issues such as cross-site scripting (XSS), SQL injection attacks, cross-site request forgery (CSRF), and clickjacking.

A Django project primarily comprises three major components: models, views, and templates. Models define the structure of your data, views dictate what data is displayed to the user, and templates determine how this data is rendered. Upon receiving a request, Django maps the URL to the corresponding view, thus effectively directing the request through the application.

Testing is a vital part of any software development process, and Django is no exception. As suggested by the testing pyramid, a Django-based application can be tested at different levels of granularity via:

Unit Testing

The base tier of the testing pyramid is unit testing, which forms an important part of the testing process. It involves testing individual components of the application in isolation. As your application grows, you'll need lightweight testing strategies in place to ensure that each component works as expected. Unit tests are meant to be lightweight since they do not require the entire system to be booted for test execution.

Django offers many powerful tools, extending from Python libraries, which can assist you in writing test cases with ease. Let's explore these.

The test client is a Python class that enables you to test and interact with your Django-powered application's views by providing a dummy web browser. However, note that this is not intended to replace other in-browser frameworks.

Here's an example of what a test case using the test client might look like:
import unittest
from django.test import Client
    
class SimpleTest(unittest.TestCase):
  def setUp(self):
    # Every test needs a client.
    self.client = Client()
  
  def test_details(self):
    # Issue a GET request.
    response = self.client.get('/customer/details/')
    
    # Check that the response is 200 OK.
    self.assertEqual(response.status_code, 200)
    
    # Check that the rendered context contains 5 customers.
    self.assertEqual(len(response.context['customers']), 5)

Building on the unittest library, Django provides additional extensions. The unittest.TestCase is extended to derive SimpleTestCase, TransactionTestCase, TestCase, and LiveServerTestCase. Each of these classes possesses additional features that are useful when you need to write different types of tests, such as matching two URLs, testing two XML or JSON fragments for equality, and using database fixtures

TestCase is the most common class used for writing tests in Django.

Here's an example of how tests written using TestCase can appear:
from django.core import mail
from django.test import TestCase


class ContactTests(TestCase):
  def test_post(self):
    with self.captureOnCommitCallbacks(execute=True) as callbacks:
      response = self.client.post(
        '/contact/',
        {'message': 'I like your site'},
      )
    
    self.assertEqual(response.status_code, 200)
    self.assertEqual(len(callbacks), 1)
    self.assertEqual(len(mail.outbox), 1)
    self.assertEqual(mail.outbox[0].subject, 'Contact Form')
    self.assertEqual(mail.outbox[0].body, 'I like your site')
Here's another example:
from django.test import TestCase

class MyTests(TestCase):
  @classmethod
  def setUpTestData(cls):
    # Set up data for the whole TestCase
    cls.foo = Foo.objects.create(bar="Test")
    ...
  
  def test1(self):
    # Some test using self.foo
    ...
  
  def test2(self):
    # Some other test using self.foo
    ...

Django supports Tox, a tool for running automated tests in different virtual environments, and django-docker-box, which allows you to run tests across supported databases and Python versions. You can learn more about them in the provided resources.

Integration Testing

Although unit tests help monitor the health of individual methods, there is a need for tests that examine whether these methods and services can collaboratively produce the desired results. This is where integration testing comes into play. Typically, these test cases target scenarios that involve integrations with databases, file systems, network infrastructure, or other third-party applications. Since integration tests are intended to be lighter weight compared to end-to-end tests, it is crucial to strategically mock data.

For instance, imagine a scenario where it's essential to ensure that the service does not fetch critical data when the API response is erroneous. In this situation, you can mock the API response to always yield a failure, enabling your test case to proceed.

Below is an example of a test case that asserts if vendor information is fetched and is as expected.
from django.urls import reverse

class VendorTesting(TestCase):
  def test_getAddedVender(self):
    payload = {“name”: “Adam”, “contact”: “+45678932”,       
              “businessType”:”groceries”,
              “email”:”adam@groceries.com”}
    
    Header = {'HTTP_AUTHORIZATION': 'auth_token'}
    
    response = Client().post(reverse('VendorAPI'), 
              data = json.dumps(payload)),
              content_type = 'application/json',
              **header)
    
    getVendor = vendor.objects.filter(name=”Adam”)
    self.assertNotNone(getVendor)

Using factory methods to mock data is a good idea when writing integration tests. You can read more about the various methods to handle such requirements here.

End-to-End Testing

In end-to-end testing, it's essential to check complete workflows. These tests necessitate the entire system to be up and running. You can accomplish this using the following methods:
  • Selenium-based tools with LiveServerTestCase
  • testRigor

Using LiveServerTestCase to run Selenium testing

LiveServerTestCase offers a critical functionality - it enables you to launch a live Django server, which is beneficial when you want to run functional tests. Selenium is supported in this context, and you can write test cases by installing the Selenium package into your project.

Here's what the test might look like:
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.webdriver import WebDriver

class MySeleniumTests(StaticLiveServerTestCase):
  fixtures = ['user-data.json']
  
  @classmethod
  def setUpClass(cls):
    super().setUpClass()
    cls.selenium = WebDriver()
    cls.selenium.implicitly_wait(10)
  
  @classmethod
  def tearDownClass(cls):
    cls.selenium.quit()
    super().tearDownClass()
  
  def test_login(self):
    self.selenium.get('%s%s' % (self.live_server_url, '/login/'))
    username_input = self.selenium.find_element(By.NAME, "username")
    username_input.send_keys('myuser')
    password_input = self.selenium.find_element(By.NAME, "password")
    password_input.send_keys('secret')
    self.selenium.find_element(By.XPATH, '//input[@value="Log in"]').click()

testRigor for end-to-end testing

You can use testRigor, which addresses key challenges faced by Selenium users. testRigor is specifically designed for end-to-end testing, and is known for the ease of no-code test creation and minimal test maintenance.

You can conduct cross-platform and cross-browser testing without major configuration steps. Tests are on the UI level and do not include implementation details, meaning they aren't going to break as long as the UI stays the same.

testRigor has a lot of smart features which make the lives of QA engineers much easier. For example, you can manipulate session storage and local storage with ease. Here's a sample command:
get item "item-name" from session storage and save it as "varName"
Here's another example that shows how to call APIs and assert values:
call api post "http://dummy.restapiexample.com/api/v1/create" with headers "Content-Type:application/json" and "Accept:application/json" and body "{\"name\":\"James\",\"salary\":\"123\",\"age\":\"32\"}" and get "$.data.name" and save it as "createdName"
check that stored value "createdName" itself contains "James"

Conclusion

Recognizing the importance of having testing strategies in place for your application is crucial for developing high-quality products. With Django, you can develop robust code and test cases. The framework offers many key features that simplify the process of writing and maintaining test cases.