Here, we'll talk about testing in Django.
The test target is the following simple blog article list page.
project/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')
]
blog/urls.py
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('list/', views.PostList.as_view(), name='post_list')
]
blog/models.py
from django.db import models
class Post(models.model):
title = models.CharField('title', max_length=100)
body = models.TextField('Text')
created_at = models.DateTimeField('Creation date and time', auto_now_add=True)
updated_at = models.DateTimeField('Update date and time', auto_now=True)
class Meta:
ordering = ('-created_at')
def __str__(self):
return self.title
blog/views.py
from django.views import generic
class PostList(generic.ListView):
model = Post
template_name = 'blog/post_list.html'
blog/post_list.html
{% for post in post_list %}
<h1>{{ post.title }}</h1>
<p>{{ post.body }}</p>
{% endfor %}
You can use factory_boy
to create a record for testing.
blog/tests.py
import factory
from django.utils import timezone
from .models import Post
class PostFactory(factory.django.DjangoModelFactory):
title = 'Sample post'
body = 'This is a sample text.'
created_at = timezone.now()
updated_at = timezone.now()
class Meta:
model = Post
Here, we will create PostFactory
as a factory class for the Post
model.
You can set default values such as title
and text
.
blog/tests.py
from django.urls import reverse
from django.test import TestCase
class PostListTests(TestCase):
def test_get_queryset(self):
post_1 = PostFactory(
title='First Post',
body='This is the first post.'
)
post_2 = PostFactory(
title='Second Post',
body='This is the second post.'
)
res = self.client.get(reverse('blog:post_list'))
self.assertTemplateUsed(res, 'blog/post_list.html')
self.assertQuerysetEqual(
res.context['post_list'],
['<Post: Second Post>', '<Post: First Post>']
)
self.assertEqual(
res.context['post_list'][0].body,
'This is the first post.'
)
self.assertEqual(
res.context['post_list'][1].body,
'This is the second post.'
)
First, create a Post
record using the PostFactory
created above.
Then, the response when accessing the article list page is stored in the variable res
.
res
contains post_list
as the context created by view, so make sure you get the queryset you expected.
Also, in django tests, you can use ʻassertTemplateUsed to see if the HTML template specified in
views.py` is used.
To run the test, enter the following command:
$ python manage.py test (blog)
If you enter the application name at the end, the test will be executed only in the specified application.
Here, I explained the test in django. Testing is also important to prevent bugs as development progresses.
Recommended Posts