Welcome to the first lesson of our course on building a TODO App with Django. In this course, we will cover how to implement APIs and test them using Django REST Framework. Testing is a crucial part of software development because it ensures that our code works as expected and helps catch bugs early.
In this lesson, we will focus on understanding the basics of Django testing. By the end of this lesson, you will know how to set up and write basic tests using Django's TestCase framework.
The core of Django testing revolves around the TestCase class, which is part of the django.test module. This class allows you to create and run tests using a variety of assertion methods to check the correctness of your code.
Think of the TestCase class as a blueprint for creating individual tests. It provides various methods to simulate different test scenarios and check for expected outcomes.
In this lesson, we won't yet write actual tests for the Todo project. Instead, we will recall and practice the very basics of Python's testing using simple operations with integers, lists and dictionaries. In the next lesson, we will start building actual tests.
Before writing our test cases, we need to set up the necessary data. This is where the setUp method comes into play. The setUp method is used to initialize any data or state that will be used across multiple test methods.
Here is an example setup:
In this setup:
self.xandself.yare numeric variables.self.list1,self.list2, andself.list3are lists.
These variables will be used in our subsequent test methods.
Let's write some basic test methods to understand how the TestCase class works. We'll test simple arithmetic operations like addition, subtraction, multiplication, and division. Each test within a test case is represented as a class method, and its name must start with test_.
Here:
test_additionchecks if10 + 5is equal to15.test_subtractionchecks if10 - 5is equal to5.test_multiplicationchecks if10 * 5is equal to50.test_divisionchecks if10 / 5is equal to2.
Each test method uses self.assertEqual to compare the expected result with the actual result. An assertion is a statement in programming used to determine if a condition is true. If the condition evaluates to true, the program continues to run. If it evaluates to false, the program throws an error. In testing, assertions are used to validate that the output of a function or a piece of code matches the expected result.
