Django使用开始备忘录(测试)

概要 – 摘要

因为有很多原因,我可能会使用Python/Django来开发Web应用程序。这是我用来记录Django测试环境建立等的备忘录。关于Web应用程序的实施,请查阅Django官方文档或者我的备忘录。

环境

操作系统:Windows 11
Python版本:3.10.7
Django版本:4.1.1

请注意以上事项

在执行命令时,使用PowerShell,并且可能需要以管理员身份运行才能正常工作。

自动化测试创建

这个测试对象是参考以下文章创建的投票样例应用程序。

    • Djangoチュートリアルその1

 

    • Djangoチュートリアルその2

 

    • Djangoチュートリアルその3

 

    Djangoチュートリアルその4

将其中的models.py作为测试对象。

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text
    def is_voted(self):
        return self.votes > 0

我会参考Django官方文档来编写自动测试代码。

from django.test import TestCase

from .models import Choice

class ChoiceModelTests(TestCase):

    def test_is_voted_ok(self):
        voted_choice = Choice(votes=1)
        self.assertIs(voted_choice.is_voted(), True)
    def test_is_voted_ng(self):
        new_choice = Choice()
        self.assertIs(new_choice.is_voted(), False)

通过以下命令执行已创建的测试代码:
使用命令 “py manage.py test polls”。

image.png

接下来,我们将选择views.py中的IndexView类(继承自generic.ListView)作为测试对象,并编写测试代码。
※在投票示例应用程序中,请先删除已注册的数据。

import datetime

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.views import generic

from .models import Choice, Question

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Question.objects.filter(
            pub_date__lte=timezone.now()
        ).order_by('-pub_date')[:5]

class DetailView(generic.DetailView):
    model = Question
    template_name = 'polls/detail.html'

class ResultsView(generic.DetailView):
    model = Question
    template_name = 'polls/results.html'

    def vote(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST['choice'])
        except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
            return render(request, 'polls/detail.html', {
                'question': question,
                'error_message': "You didn't select a choice.",
            })
        else:
            selected_choice.votes += 1
            selected_choice.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
import datetime

from django.urls import reverse
from django.test import TestCase
from django.utils import timezone

from .models import Choice, Question

def create_question(question_text, days):
    """
    Create a question with the given `question_text` and published the
    given number of `days` offset to now (negative for questions published
    in the past, positive for questions that have yet to be published).
    Do not insert this method into class QuestionIndexViewTests(TestCase).
    """
    time = timezone.now() + datetime.timedelta(days=days)
    return Question.objects.create(question_text=question_text, pub_date=time)

class QuestionIndexViewTests(TestCase):

    def test_no_questions(self):
        """
        If no questions exist, an appropriate message is displayed.
        """
        response = self.client.get(reverse('polls:index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No polls are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_past_question(self):
        """
        Questions with a pub_date in the past are displayed on the
        index page.
        """
        question = create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [question],
        )

    def test_future_question(self):
        """
        Questions with a pub_date in the future aren't displayed on
        the index page.
        """
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertContains(response, "No polls are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_future_question_and_past_question(self):
        """
        Even if both past and future questions exist, only past questions
        are displayed.
        """
        question = create_question(question_text="Past question.", days=-30)
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [question],
        )

    def test_two_past_questions(self):
        """
        The questions index page may display multiple questions.
        """
        question1 = create_question(question_text="Past question 1.", days=-30)
        question2 = create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [question2, question1],
        )

请使用以下命令执行创建的测试代码:
使用py manage.py test polls。

image.png

除了这个之外,Selenium的整合和LiveServerTestCase也在官方文档中介绍过。

最后

和创建应用程序时一样,我有点担心学习成本会是多少,但是教程的所需时间不到半天,我想。谢谢您看到最后。

广告
将在 10 秒后关闭
bannerAds