Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Django in Production

You're reading from  Django in Production

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781804610480
Pages 348 pages
Edition 1st Edition
Languages
Author (1):
Arghya Saha Arghya Saha
Profile icon Arghya Saha

Table of Contents (21) Chapters

Preface 1. Part 1 – Using Django and DRF to Build Modern Web Application
2. Chapter 1: Setting Up Django with DRF 3. Chapter 2: Exploring Django ORM, Models, and Migrations 4. Chapter 3: Serializing Data with DRF 5. Chapter 4: Exploring Django Admin and Management Commands 6. Chapter 5: Mastering Django Authentication and Authorization 7. Part 2 – Using the Advanced Concepts of Django
8. Chapter 6: Caching, Logging, and Throttling 9. Chapter 7: Using Pagination, Django Signals, and Custom Middleware 10. Chapter 8: Using Celery with Django 11. Chapter 9: Writing Tests in Django 12. Chapter 10: Exploring Conventions in Django 13. Part 3 – Dockerizing and Setting Up a CI Pipeline for Django Application
14. Chapter 11: Dockerizing Django Applications 15. Chapter 12: Working with Git and CI Pipelines Using Django 16. Part 4 – Deploying and Monitoring Django Applications in Production
17. Chapter 13: Deploying Django in AWS 18. Chapter 14: Monitoring Django Application 19. Index 20. Other Books You May Enjoy

Writing Tests in Django

In Chapter 8, we learned about Celery and how we can write Celery tasks to solve our problem of long-running tasks. Celery helps us to implement periodic tasks using Celery Beat. So, with all the knowledge we have gained so far, we can create applications that solve business use cases. One thing we should always remember is that writing code is easy, especially when doing so from scratch, but the hard part comes when we have to maintain the code and add new features/improve features in the existing code base. This is where one of the most important concepts of programming enters the picture – testing.

In this chapter, we shall learn the different aspects of testing and why testing is important, learning how to write maintainable test cases that don’t make your system brittle but give you the flexibility and confidence to ship new features fast.

Here are the topics we’ll be covering in this chapter:

  • Introducing the different...

Technical requirements

In this chapter, we shall learn about the concepts of testing; we expect you to be well-versed in the concepts of Django, as covered in the previous chapters. We assume that you to have a basic understanding of testing in the software development domain. Also, you should have a basic understanding of how to write test cases in Python and have some experience in writing unit/integration test cases for your code.

Here is the GitHub repository that has all the code and instructions for this chapter: https://github.com/PacktPublishing/Django-in-Production/tree/main/Chapter09.

Important note

In this chapter, we are learning test cases, and we will be writing/taking code examples from the previous chapter. Since we are covering a lot of concepts, it is not possible to include all the code snippets in this chapter. To follow along better, it is recommended that you follow the code sample saved in the GitHub repo. Also, feel free to reach out to me via Discord...

Introducing the different types of tests in software development

All of us developers love to write code and build systems and applications. All of us hate attending meetings. Another thing most developers hate is writing tests. We all have been there. When I started my career, and whenever I was asked by my senior/mentor to write test cases for code, I would dread the thought. It would take almost double the time to write test cases for the code than it took to build the feature.

But tests are a necessary evil, and now that I am a senior engineer building dozens of scalable systems, I always prefer to write tests for any project I work on. This gives me the confidence to ship my code to production without the fear of breaking the existing system, and this helps in the faster shipping of features.

When we build new features, we always test the code manually. For example, if I had to write code to find out whether a number is prime or not, I would write the code and then pass...

Setting up tests for Django and DRF

In this chapter, we shall primarily focus on how to write unit tests and integration tests for Django and DRF projects. In the Python and Django community, there is a long-standing debate over which of the following packages is better for writing tests for projects:

We shall not get into the debate and allow developers to decide which package is better from their own experience and preference. We shall take the simple route and follow what the Django official documentation recommends, using the default Django unittest to set up tests and learn them.

Let us now get started with writing test cases...

Writing basic tests in DRF

Let us write a basic test for an API that sends a static response. First, let us have a basic API that returns "hello world!" as a response to a GET request. Add the following code to the blog/views.py file:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def basic_req(request):
  if request.method == 'GET':
    resp = {"msg": "hello world!"}
    return Response(data=resp, status=status.HTTP_200_OK)

The URL is configured as /blog/hello-world/, by adding the following code to the blog/urls.py file:

urlpatterns = [
    path("hello-world/", views.basic_req),
]

We have now created a basic URL that responds with a "hello world" response. We will now write a test case to verify the response for this API. In the following...

Learning best practices to write tests

So far, we have explored all the advantages of writing test cases and also how we can write them for different Django components. In this section, we shall learn about best practices to write test cases.

Using unit tests more often

Writing test cases is always tricky, and it is very difficult to write test cases for all scenarios. As applications become complex, developers may not be able to write test cases to cover all scenarios, so the best approach to tackle this problem is by writing maximum unit tests. Whenever we are writing new business logic, we generally add small functions/methods that will have new/updated business logic, so writing unit tests for such functions helps to add more coverage. If we have written modular code, then it is easy to write unit tests for our application, and this is something that developers need to understand – writing test cases is difficult only when the application code is not modular and structured...

Exploring Test-Driven Development

TDD is a type of development process where we first write the tests that will fail, followed by writing our application code, which will make all the failing tests pass. This helps us to write smaller code blocks and also have a set contract on what each function/method should provide as output. TDD is a thought process, and new developers might need some handholding to shift to this mind space.

We shall not go into the details of TDD; there is a course that explores this in detail: https://www.packtpub.com/product/hands-on-test-driven-development-with-python-video/9781789138313.

With this, we wrap up all the topics related to writing tests in Django/DRF.

Summary

In this chapter, we learned different testing techniques and the value that tests add to the development cycle and production stability. We explored how to set up tests in DRF and write test cases for different scenarios. We learned how to use third-party packages such as factory_boy to improve the developer experience of writing tests.

We saw a few best practices and recommendations to improve test cases in the development cycle. Postman as a tool can be very helpful in writing tests to monitor contracts; we learned how we can use Postman features to write integration tests for our APIs.

In Chapter 10, we will discuss the best practices/conventions that you can follow while developing applications in Django and DRF. Conventions and good practices are mostly subjective and come from years of experience in writing production-level code. I am also going to share my views and the lessons I have learned from working on different projects related to Django in the next chapter...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Django in Production
Published in: Apr 2024 Publisher: Packt ISBN-13: 9781804610480
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}