Django-Python 中是否有用于 TDD 方法的样板模板

问题描述 投票:0回答:1

我正在一边做一个项目,一边努力训练自己习惯 Django 中的 TDD 方法。

我不知道为什么我会遇到这个失败的测试

(venv) osahenru@osahenru ~/D/q-4> pytest -k test_can_post_questions
============================= test session starts ==============================
platform linux -- Python 3.10.12, pytest-8.1.1, pluggy-1.5.0
django: version: 5.0.4, settings: config.settings (from ini)
rootdir: /home/osahenru/Documents/q-4
configfile: pytest.ini
plugins: django-4.8.0
collected 5 items / 4 deselected / 1 selected                                  

app/tests/test_views.py F                                                [100%]

=================================== FAILURES ===================================
______________________ TestEvent.test_can_post_questions _______________________

self = <test_views.TestEvent testMethod=test_can_post_questions>

    def test_can_post_questions(self):
        event = Event.objects.create(name='Python Ghana')
        data = {
            'text': 'how are you?',
        }
        response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data)
>       self.assertIsInstance(response.context['form'], QuestionCreateForm)
E       TypeError: 'NoneType' object is not subscriptable

app/tests/test_views.py:52: TypeError
=========================== short test summary info ============================
FAILED app/tests/test_views.py::TestEvent::test_can_post_questions - TypeError: 'NoneType' object is not subscriptable
======================= 1 failed, 4 deselected in 0.53s ========================
(venv) osahenru@osahenru ~/D/q-4 [0|1]> 

这是导致错误消息的测试

def test_can_post_questions(self):
        event = Event.objects.create(name='Python Ghana')
        data = {
            'text': 'how are you?',
        }
        response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data)
        self.assertIsInstance(response.context['form'], QuestionCreateForm)
        self.assertEqual(response.status_code, 302)

这是查看功能

def questions(request, pk):
    event = Event.objects.get(id=pk)
    questions = Question.objects.filter(event=event)
    
    form = QuestionCreateForm()
    if request.method == 'POST':
        form = QuestionCreateForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.event = event
            question.save()
            return redirect('questions', pk=pk)
        
    context = {
        'form': form,
        'questions': questions,
        'event': event
    }
    return render(request, 'questions.html', context)

作为 TDD 方法的初学者,是否有用于编写一般单元测试和专门针对 Django 的单元测试的样板?我真的很难接受这个概念。谢谢

python django unit-testing tdd
1个回答
0
投票

这里测试的响应是帖子之后的重定向,它没有上下文。如果您想查看 final 响应的上下文,您需要将

follow=True
添加到您的
self.client.post(
调用中 - 有关客户端参数的更多信息,请参阅文档

就样板而言,我使用的主要经验法则是,如果我编写了它,我就会测试它。所以你不需要测试表单的提交能力,因为 django 会处理这个问题,并且希望它已经经过了很好的测试。以您的代码为例,我将测试 Question.event 项目是否被适当添加,因为这是您自己对默认提交表单流程的添加。

© www.soinside.com 2019 - 2024. All rights reserved.