簡體   English   中英

如何測試 Django 的 UpdateView?

[英]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')

但是,這個測試失敗了,因為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')

在 Django 3.2 中,您可以在這里找到規范的解決方案: https : //docs.djangoproject.com/fr/3.2/ref/urlresolvers/

在測試中,您只需要:

  • 使用包含在 slug 中的值創建對象,
  • 然后,用這些參數反轉它:
 self.topic = Book.objects.create(slug="test-update")
        self.response = self.client.get(reverse('book_update', args=[self.topic.slug]))

TestCaseself.assertContains(response, el, html=True) html= True將為您呈現TemplateResponse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM