iTranslated by AI
Django Tutorial (Blog App) Part 4: Unit Testing
In the previous article, Django Tutorial (Blog App Creation) ③ - Post List Display Edition, we used class-based generic views to display a list of posts created from the admin site.
While I would like to move on to adding CRUD operations such as post creation, details, editing, and deletion within the app, let's hold back and incorporate unit tests first.
About Django Testing
Adding more and more features is fun, but do you usually write tests?
Even those who have become able to create simple apps in Django through various tutorials might cause errors when they start tweaking things in their own way.
Also, you might only notice errors when actually operating the screen via a browser, even if no errors are output when Django is started with runserver.
There is, of course, the method of manually testing several operations, but doing that every time is nothing but a waste of time.
Therefore, I recommend performing unit tests using Django's features.
In Django, you can automate tests using the UnitTest class, so if you write the test code once at the beginning, you won't need to do the same thing over and over again.
Thinking about tests is just as important as thinking about development code; there is even a development methodology where you create tests before writing the code for the app's behavior.
Take this opportunity to learn how to perform tests, save your testing time, and spend your efforts on improving the app itself.
About the Folder Structure
At this point, your folder structure should look like this:
.
├── blog
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py # Note this
│ ├── urls.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── mysite
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── templates
└── blog
├── index.html
└── post_list.html
You might have noticed that a file named tests.py was automatically created under the blog directory.
While you could create test cases directly inside this tests.py, it is generally easier to manage if the files are separated by test type (e.g., model tests, view tests). Therefore, let's create a tests directory and create empty files inside it as shown below.
The key point is to also create an empty _init_.py file inside the tests directory so that the files within it are executed.
.
├── blog
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── __init__.py
│ ├── models.py
│ ├── tests # Added
│ │ ├── __init__.py
│ │ ├── test_models.py
│ │ ├── test_urls.py
│ │ └── test_views.py
......
Please note that Django will not recognize the modules unless their names start with "test".
How to Write Tests
In Django, we use Django's own TestCase class (django.test.TestCase), which extends Python's standard TestCase class (unittest.TestCase). This class allows you to use methods called assertions, which have the functionality to check whether a return value is the expected value.
Also, as mentioned before, test modules must start with the string "test," and test methods must also start with the string "test" (details will follow).
By following these rules, Django will find and automatically execute the test methods within your project.
test_models.py
Let's start by creating tests for the model first.
To review, the Post model described in blog/models.py looks like this:
models.py
...
class Post(models.Model):
title = models.CharField('Title', max_length=200)
text = models.TextField('Body')
date = models.DateTimeField('Date', default=timezone.now)
def __str__(self): # Define the value returned when the Post model is called directly
return self.title # Return the post title
For this model, let's test the following three cases this time.
- Nothing is registered in the initial state.
- When one record is created properly, only one record is counted.
- When data is saved with specified content and retrieved immediately, the same value as when it was saved is returned.
Let's start with the first one.
Open test_models.py and declare the necessary modules.
test_models.py
from django.test import TestCase
from blog.models import Post
Next, create a test class, making sure it inherits from TestCase.
test_models.py
from django.test import TestCase
from blog.models import Post
class PostModelTests(TestCase):
Now, let's write the test methods inside this PostModelTests class.
By starting a method with "test" within a class that inherits from TestCase,
Django automatically recognizes it as a test method.
Therefore, the method name after def must always start with test.
test_models.py
from django.test import TestCase
from blog.models import Post
class PostModelTests(TestCase):
def test_is_empty(self):
"""Check that nothing is registered in the initial state"""
saved_posts = Post.objects.all()
self.assertEqual(saved_posts.count(), 0)
The current Post model is stored in saved_posts,
and we use assertEqual to verify that the count (number of posts) is "0".
Now we are ready to perform one test.
Let's run it once right away.
To run the tests, execute the following command in the directory containing manage.py (inside mysite).
When executed, Django will find and run the test methods that follow the naming convention.
(blog) bash-3.2$ python3 manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 1 tests in 0.009s
OK
This means one test was executed and completed without errors.
By the way, we previously confirmed that the data in Post is empty (=0), but let's try making it expect that one piece of data exists.
test_models.py (temporary)
from django.test import TestCase
from blog.models import Post
class PostModelTests(TestCase):
def test_is_empty(self):
"""Check if one piece of data exists even though it is the initial state (error expected)"""
saved_posts = Post.objects.all()
self.assertEqual(saved_posts.count(), 1)
The test execution result at this time is as follows.
(blog) bash-3.2$ python3 manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
F
======================================================================
FAIL: test_is_empty (blog.tests.test_models.PostModelTests)
Check if one piece of data exists even though it is the initial state (error expected)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/masuyama/workspace/MyPython/MyDjango/blog/mysite/blog/tests/test_models.py", line 9, in test_is_empty
self.assertEqual(saved_posts.count(), 1)
AssertionError: 0 != 1
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
An AssertionError has occurred, and the test failed because it was not the expected result (the experiment was a success).
In Django tests, temporary registration of data into the database can also be executed using the create method,
so you can run the remaining tests that cannot be verified without registering data.
Below is how to write the model tests, so please refer to it.
test_models.py (full text)
from django.test import TestCase
from blog.models import Post
class PostModelTests(TestCase):
def test_is_empty(self):
"""Check that nothing is registered in the initial state"""
saved_posts = Post.objects.all()
self.assertEqual(saved_posts.count(), 0)
def test_is_count_one(self):
"""Test that when one record is created properly, only one record is counted"""
post = Post(title='test_title', text='test_text')
post.save()
saved_posts = Post.objects.all()
self.assertEqual(saved_posts.count(), 1)
def test_saving_and_retrieving_post(self):
"""Test that data saved with specified content returns the same value when retrieved immediately"""
post = Post()
title = 'test_title_to_retrieve'
text = 'test_text_to_retrieve'
post.title = title
post.text = text
post.save()
saved_posts = Post.objects.all()
actual_post = saved_posts[0]
self.assertEqual(actual_post.title, title)
self.assertEqual(actual_post.text, text)
test_urls.py
In addition to the model, you can also check whether the routing written in urls.py is working correctly.
To review, blog/urls.py looked like this:
blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('post_list', views.PostListView.as_view(), name='post_list'),
]
Since the routing above sets the routing according to the address entered under /blog/, we will test the cases where the part after /blog/ is '' (blank) and 'post_list'.
We use assertEqual to compare and check if the result of being redirected to each page via the view is as expected.
test_urls.py
from django.test import TestCase
from django.urls import reverse, resolve
from ..views import IndexView, PostListView
class TestUrls(TestCase):
"""Test the redirect when accessing with the URL to the index page"""
def test_post_index_url(self):
view = resolve('/blog/')
self.assertEqual(view.func.view_class, IndexView)
"""Test the redirect to the Post list page"""
def test_post_list_url(self):
view = resolve('/blog/post_list')
self.assertEqual(view.func.view_class, PostListView)
Let's run the tests once here.
Note that compared to the previous test that checked for an empty database, the number of test cases that register data has increased. You can see that the processes for creating and destroying the test database are now output in the message.
(blog) bash-3.2$ python3 manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.....
----------------------------------------------------------------------
Ran 5 tests in 0.007s
OK
Destroying test database for alias 'default'...
test_views.py
Finally, let's also test the views.
views.py looked like this:
views.py
from django.views import generic
from .models import Post # Import the Post model
class IndexView(generic.TemplateView):
template_name = 'blog/index.html'
class PostListView(generic.ListView): # Inherit the generic ListView class
model = Post # Call the model to be listed
In the IndexView test, we confirm that a status code of 200 (= success) is returned when accessing with the GET method.
test_views.py
from django.test import TestCase
from django.urls import reverse
from ..models import Post
class IndexTests(TestCase):
"""Test class for IndexView"""
def test_get(self):
"""Confirm that accessing with the GET method returns status code 200"""
response = self.client.get(reverse('blog:index'))
self.assertEqual(response.status_code, 200)
When you add a method in a view, no matter how little time you have for testing, make it a habit to create at least this minimum test case.
Let's also test the ListView.
Just like before, we will confirm that a status code of 200 is returned. Additionally, we will create a test that adds two pieces of data (posts), displays the post list, and confirms that the titles of the registered posts are each included in the list.
Note that we will use some special methods here.
As mentioned earlier, test methods should start with "test," but there are also methods called setUp and tearDown.
In the setUp method, you can register data to be used within the test cases, and in the tearDown method, you can delete the data registered in the setUp method.
(Note that in both cases, you need to explicitly describe what data is being registered.)
Writing processes to register the same data many times within the same test case is tedious and causes tests to take longer, so the idea is to consolidate common processes in one place.
Using these methods, test_views.py will look like this:
test_views.py
from django.test import TestCase
from django.urls import reverse
from ..models import Post
class IndexTests(TestCase):
"""Test class for IndexView"""
def test_get(self):
"""Confirm that accessing with the GET method returns status code 200"""
response = self.client.get(reverse('blog:index'))
self.assertEqual(response.status_code, 200)
class PostListTests(TestCase):
def setUp(self):
"""
Method for preparing the test environment. The name must be "setUp".
Create data here if there is common data you want to use within the same test class.
"""
post1 = Post.objects.create(title='title1', text='text1')
post2 = Post.objects.create(title='title2', text='text2')
def test_get(self):
"""Confirm that accessing with the GET method returns status code 200"""
response = self.client.get(reverse('blog:post_list'))
self.assertEqual(response.status_code, 200)
def test_get_2posts_by_list(self):
"""Confirm that when accessing with GET, the 2 additions added in the setUp method are returned"""
response = self.client.get(reverse('blog:post_list'))
self.assertEqual(response.status_code, 200)
self.assertQuerysetEqual(
# Since the Post model is set to return the title as the result of __str__, confirm that the returned titles match the posts
response.context['post_list'],
['<Post: title1>', '<Post: title2>'],
ordered = False # Specify to ignore order
)
self.assertContains(response, 'title1') # Confirm that the title of post1 is included in the html
self.assertContains(response, 'title2') # Confirm that the title of post2 is included in the html
def tearDown(self):
"""
Cleanup method to delete the data added in setUp.
Although it uses create, by naming the method "tearDown", it performs the opposite process of setUp = it deletes them.
"""
post1 = Post.objects.create(title='title1', text='text1')
post2 = Post.objects.create(title='title2', text='text2')
Running the tests in this state will execute a total of 8 tests across models, URLs, and views.
(blog) bash-3.2$ python3 manage.py test
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........
----------------------------------------------------------------------
Ran 8 tests in 0.183s
OK
Destroying test database for alias 'default'...
With this, we have been able to create unit tests for the code we've written so far.
There are other ways to perform redundant checks using Django-specific testing methods, such as whether the expected template is being called, but for now, even if you reuse existing patterns, make it a habit to create tests when increasing processing logic to save yourself the trouble of manual checks later on.
Next time, we will make it possible to create posts within the app.
→ Next Time
Django Tutorial (Blog App Creation) ⑤ - Post Creation Function Edition
Discussion