[英]How to test Django's UpdateView?
作為一個簡化的例子,我為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')
但是,這個測試失敗了,因為book
的author
在POST
請求后似乎沒有更新,即使在從數據庫刷新后也是如此:
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')
在 Django 3.2 中,您可以在這里找到規范的解決方案: https : //docs.djangoproject.com/fr/3.2/ref/urlresolvers/
在測試中,您只需要:
self.topic = Book.objects.create(slug="test-update")
self.response = self.client.get(reverse('book_update', args=[self.topic.slug]))
TestCase
有self.assertContains(response, el, html=True)
。 html= True
將為您呈現TemplateResponse
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.