gpt4 book ai didi

python - 如何测试Django的UpdateView?

转载 作者:太空狗 更新时间:2023-10-30 00:42:40 25 4
gpt4 key购买 nike

作为一个简化的示例,我为 Book 模型编写了一个 UpdateView,以及一个在成功时重定向到的 ListView :

from django.urls import reverse
from django.views.generic import ListView
from django.views.generic.edit import UpdateView
from .models import Book


class BookUpdate(UpdateView):
model = Book
fields = ['title', 'author']


class BookList(ListView):
model = Book

Book 模型定义为

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100, blank=True)

def get_absolute_url(self):
return reverse('books-list')

urls.py 在哪里

from django.urls import path
from books.views import BookUpdate, BookList


urlpatterns = [
path('books/', BookList.as_view(), name='books-list'),
path('book/<int:pk>/', BookUpdate.as_view(), name='book-update')
]

books/tests.py 中,我尝试编写以下测试:

class BookUpdateTest(TestCase):
def test_update_book(self):
book = Book.objects.create(title='The Catcher in the Rye')

response = self.client.post(
reverse('book-update', kwargs={'pk': book.id}),
{'author': 'J.D. Salinger'})

self.assertEqual(response.status_code, 200)

book.refresh_from_db()
self.assertEqual(book.author, 'J.D. Salinger')

然而,这个测试失败了,因为 bookauthorPOST 请求后似乎没有更新,即使在从数据库:

FAIL: test_update_book (books.tests.BookUpdateTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/kurtpeek/Documents/Scratch/book_project/books/tests.py", line 46, in test_update_book
self.assertEqual(book.author, 'J.D. Salinger')
AssertionError: '' != 'J.D. Salinger'
+ J.D. Salinger

另一方面,如果我运行开发服务器并手动填写字段,一切似乎都按预期工作。我如何为 UpdateView 编写单元测试以捕获用户更新字段、提交表单并对相应对象进行更改?

最佳答案

似乎如果您POST 到一个表单,您必须发布所有必填字段,而不仅仅是您正在更新的字段——即使基础模型的必填字段已经有一个值。此外,成功更新后返回的状态代码是 302 'Found',而不是 200 'OK'。所以下面的测试通过了:

class BookUpdateTest(TestCase):
def test_update_book(self):
book = Book.objects.create(title='The Catcher in the Rye')

response = self.client.post(
reverse('book-update', kwargs={'pk': book.id}),
{'title': 'The Catcher in the Rye', 'author': 'J.D. Salinger'})

self.assertEqual(response.status_code, 302)

book.refresh_from_db()
self.assertEqual(book.author, 'J.D. Salinger')

关于python - 如何测试Django的UpdateView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48814830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com