Testing in Django
Automated testing is an extremely useful bug-killing tool for the modern web developer specifically on Django
Django TestCase
Django’s unit tests use a Python standard library module: unittest. This module defines tests using a class-based approach.
Here is an example which subclasses from django.test.TestCase, which is a subclass of unittest.TestCase that runs each test inside a transaction to provide isolation:
for example
from django.test import TestCase
from .models import Student
# Create your tests here.
class TestStudentModel(TestCase):
def test_create_student(self):
student1 = Student.objects.create(first_name="John", last_name="doe", admission_number=1)
payload = Student.objects.last()
# test data
self.assertEqual(payload.first_name, "John")
self.assertEqual(payload.last_name, "doe")
When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.TestCase
)
For more details about unittest, see the Python documentation.
Running The Test
in any file whose name begins with test
, automatically build a test suite out of those test cases, and run that suite.
and run with this command
python manage.py test
and you will show the output
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
Destroying test database for alias 'default'...