Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Becoming an Enterprise Django Developer

You're reading from  Becoming an Enterprise Django Developer

Product type Book
Published in Jun 2022
Publisher Packt
ISBN-13 9781801073639
Pages 526 pages
Edition 1st Edition
Languages
Author (1):
Michael Dinder Michael Dinder
Profile icon Michael Dinder

Table of Contents (15) Chapters

Preface 1. Part 1 – Starting a Project
2. Chapter 1: Undertaking a Colossal Project 3. Chapter 2: Project Configuration 4. Chapter 3: Models, Relations, and Inheritance 5. Part 2 – Django Components
6. Chapter 4: URLs, Views, and Templates 7. Chapter 5: Django Forms 8. Chapter 6: Exploring the Django Admin Site 9. Chapter 7: Working with Messages, Email Notifications, and PDF Reports 10. Part 3 – Advanced Django Components
11. Chapter 8: Working with the Django REST Framework 12. Chapter 9: Django Testing 13. Chapter 10: Database Management 14. Other Books You May Enjoy

Chapter 9: Django Testing

This chapter is dedicated to testing and debugging a Django project. Django has a wide range of test classes built into its framework that are used to write automated test scripts. As we build each app and/or component of a project, we can run one command at any time to ensure that every component still works as it should. This is great for regression testing, which means testing a new or changed component, making sure that it does not affect the intended behavior of existing components or the entire system as a whole. For most of what we will cover in this chapter, we do not need to install any third-party packages. The last thing we will cover is the Django Debug Toolbar (DjDT), which does require us to install a third-party package to use.

In this chapter, we will cover the following topics:

  • Writing automated test scripts
  • Creating unit test cases
  • Testing view classes and their get and post methods
  • Testing view classes that require...

Technical requirements

To work with the code in this chapter, the following tools will need to be installed on your local machine:

  • Python version 3.9 – used as the underlying programming language for the project
  • Django version 4.0 – used as the backend framework of the project
  • pip package manager – used to manage third-party Python/Django packages

We will continue to work with the solution created in Chapter 2, Project Configuration. However, it is not necessary to use the Visual Studio IDE. The main project itself can be run using another IDE or run independently using a terminal or command-line window from within the project root folder, which is where the manage.py file resides. Whatever editor or IDE you are using, a virtual environment will also be needed to work with the Django project. Instructions for how to create a project and virtual environment can be found in Chapter 2, Project Configuration. You will need a database to store...

Preparing for this chapter

Start by creating a new app in your project called chapter_9 by following the steps discussed in Chapter 2, Project Configuration, in the subsection titled Creating a Django app. As discussed in that section, don't forget to change the value of the name = variable for your app class found in the /becoming_a_django_entdev/becoming_a_django_entdev/chapter_9/apps.py file to now point to the path where you installed your app. Be sure to also include this app in the INSTALLED_APPS variable found in the settings.py file as well.

In the main urls.py file of the site, add the following two paths:

# /becoming_a_django_entdev/urls.py
...
urlpatterns = [
    path(
        '',   
        include(
            'becoming_a_django_entdev.chapter_9.urls&apos...

Understanding automated testing in Django

Automated testing is helpful for a number of reasons. Developers use it when refactoring old components that need to be modified. Test scripts are used to regression test older components to see whether they were affected negatively by any new additions. Django offers several test classes that are an extension of the standard Python library called unittest. You can learn more about this package here: https://docs.python.org/3/library/unittest.html. The Django test classes are all found in the django.test library. The most commonly used class is TestCase.

The following list depicts all of the test classes that are available in the django.test library:

  • SimpleTestCase – this is the smallest test possible, extending the Python unittest library. This class will not interact with a database.
  • TransactionTestCase – this test extends the SimpleTestCase class and allows for database transactions.
  • TestCase – this...

Getting started with unit testing

Unit testing is the act of testing the smallest components possible, such as logic statements, for example, 1 + 1 equals 2. That is what the SimpleTest class that the Visual Studio IDE created for us is actually testing for. These can be utility methods, conditional or comparison statements, Django models, forms, email messages, and so on.

Let's practice writing a simple test script and then write another to include our models.

Basic unit test script

In this exercise, we will write a very basic test class that executes two different test methods. These tests will not interact with a database and are only used to compare True and False statements. The class as a whole can be used as a boilerplate when creating new test classes and modified as needed.

Follow these steps:

  1. In your /chapter_9/tests.py file, add the structure of the class, as shown:
    # /becoming_a_django_entdev/chapter_9/tests.py
    from django.test import SimpleTestCase...

Testing HTTP view requests

In this section, we will expand on the basic test cases that we previously wrote to include HTTP view requests. When testing view classes, whether they are a method-based view or a class-based view, they will both use the same TestCase class that we have been using so far.

In the following subsections, we will perform two tests, one for a method-based view and the other for a class-based view.

Testing method-based views

In this exercise, we will test the practice_year_view() method, written in Chapter 4, URLs, Views, and Templates. What we are comparing in this test is whether the response code that gets returned equals the value of 200, which means a successful response.

Follow these steps to create your test case:

  1. In your /chapter_9/tests.py file, add the following YearRequestTestCase class and methods:
    # /becoming_a_django_entdev/chapter_9/tests.py
    ...
    from django.contrib.auth.models import AnonymousUser
    from django.test import ......

Testing authenticated view requests

In this section, we will be building on the same request test cases that we just built to remove the AnonymousUser class and perform our own authentication, requiring only permitted users. We have a few view classes that we wrote in Chapter 8, Working with the Django REST Framework, that require user authentication. Let's create test scripts that allow us to authenticate with an actual user when performing an automated test. This is where loading the chapter_8/urls.py file when preparing for this chapter comes into play. Django provides a class called Client found in the django.test library that lets us perform user authentication when testing a view class.

In the following subsection, we will implement the Client class when performing authentication.

Using the Client() class

In this exercise, we will test the custom API endpoint written in Chapter 8, Working with the Django REST Framework, in the GetSellerHTMLView class. This is the...

Testing Django REST API endpoints

This section will introduce writing test cases that test Django REST framework endpoints. When testing any REST API endpoints created using the Django REST framework, we need to use the APITestCase class provided by the rest_framework.test library. We also should use the APIClient() class provided by that same library when requiring authentication, instead of using the Client() class as we did before.

In the following exercises, we will create one test class that performs two tests: the first will create an engine object and the other will update an object.

Creating an object test case

This test will use the POST request method to send data to the http://localhost:8000/chapter-8/engines/ endpoint and create an engine object in the database. Since we are loading a data fixture that contains only two engine objects with the IDs 1 and 2, we should expect the new object to be created at index 3, but your results may vary. We will refer back to...

Using the DjDT

The DjDT is a third-party package that integrates a set of configurable panels that display debug information in real time to the developer. Other third-party packages can be installed to add additional panels to this toolbar. With that in mind, you could also build your own panels too. We will only be installing the DjDT package by itself and then explaining each of its most common features, guiding you through using it, interpreting what it is showing you. To learn more about all of its capabilities, visit https://pypi.org/project/django-debug-toolbar/ and https://django-debug-toolbar.readthedocs.io/en/latest/.

Installing the DjDT

To get started with installing the DjDT, follow these steps:

  1. Add the django-debug-toolbar package to your requirements.txt file and install it into your virtual environment via that file or run the following pip command, making sure your virtual environment is already active:
    PS C:\Projects\Packt\Repo\becoming_a_django_entdev...

Summary

By now, we have developed a solid understanding of how automated testing in Django is performed. We wrote several test cases that test many of the exercises done in previous chapters. We practiced writing test cases that simulate success and others that deliberately trigger a failure to better understand what is happening. We even discovered how to write test cases that work with the Django REST framework. After we worked with automated testing, we then installed what I would consider the most powerful tool of them all, the DjDT. The DjDT is used for real-time debugging of developers' code as they write that code and run their projects locally.

In the next chapter, we will learn how to use the DjDT to monitor performance as we learn how to optimize database queries.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Becoming an Enterprise Django Developer
Published in: Jun 2022 Publisher: Packt ISBN-13: 9781801073639
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}