Django test

Introduction

Here, we'll talk about testing in Django.

Test target

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 %}

Creating a factory class

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.

Creating a test

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.

Run the test

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.

Summary

Here, I explained the test in django. Testing is also important to prevent bugs as development progresses.

Recommended Posts

Django test
test
Django
[Django] Test standard LoginForm [TDD]
Test Driven Development with Django Part 3
django update
Django note 4
Test Driven Development with Django Part 4
Django memorandum
Jarque-Bera test
django search
Django installation
Test Driven Development with Django Part 6
Locust-Load test
Django Summary
Test Driven Development with Django Part 2
Post test
Django # 2 (template)
Django Note 5
Django hands-on
Touch django
django notes
Django Summary
Django basics
Django Shoho
Django defaults
Django + Docker
Django Glossary
Django search
Install Django
Django: References
Django Note 1
Django note 3
Test Driven Development with Django Part 1
Django note 2
Test Driven Development with Django Part 5
Django startup
Django notes
Django NullCharField
Django: Test Middleware that depends on another Middleware
Django Tutorial (Blog App Creation) ④ --Unit Test
Django tutorial summary for beginners by beginners ⑤ (test)
Django ~ settings.py edition ~
Django Heroku Deploy 1
Django HTML Template # 2
Django Contact Form 2
About the test
Django model: ManyToManyField
What is Django? .. ..
Django function-based view
Python Django Tutorial (5)
Django Learning Memo
Python Django Tutorial (2)
[Django] as_view () notes
First Django Challenge
django makemigarations createsuperuser
Django related sites
Internationalization with django
Django version check
django table creation
Django begins part 4