【问题标题】:Having trouble to complete Unittest class based views in DJANGO无法在 DJANGO 中完成基于 Unittest 类的视图
【发布时间】:2019-05-30 22:06:53
【问题描述】:

如何使用 django 完成此视图单元测试? 我开始使用 unittest,但由于某种原因,我无法成功完成第一个基于类的视图测试。

models.py

class BookListView(ListView):
    model = Book
    context_object_name = 'books'
    template_name = 'snippets/list.html'

urls.py

from django.contrib import admin
from django.urls import path, include
from .views import (BookListView)
from . import views


app_name = 'snippets'
urlpatterns = [
    path('', views.index, name='book_list'),

views.py

from django.test import TestCase, Client
from django.urls import reverse
from snippets.models import Book
import json



class TestViews(TestCase):

    def setUp(self):
        self.client = Client()

    def test_book_list_GET(self):
        response = self.client.get(reverse('snippets:book_list'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'snippets/list.html')

下面是终端崩溃的反馈

self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.061s

FAILED (failures=1)
Destroying test database for alias 'default'...

【问题讨论】:

  • 您正在向客户端传递 URL 名称,而不是实际路径。
  • 有什么例子吗?我正在浏览整个互联网,似乎找不到与我上面使用的不同的任何东西。我已经为 URL 名称添加了“反向”,仍然没有通过测试。

标签: python django python-3.x unit-testing python-unittest


【解决方案1】:

如前所述:

class TestViews(TestCase):

    def setUp(self):
        self.client = Client()

    def test_book_list_GET(self):
        response = self.client.get('snippets:book_list')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'snippets/list.html')

您需要在此处传递 url,django.urls.utils.reverse 将为您提供视图的相对 url

【讨论】:

  • 有什么例子吗?我正在浏览整个互联网,似乎找不到任何与我上面使用的不同的东西。我已经为 URL 名称添加了“反向”,仍然没有通过测试。
  • 您的书单网址是否接受任何参数
  • 不,唯一没有提到的是在 BookListView(ListView) 中使用的paginate_by = 5。顺便说一句,现在错误是AssertionError: 302 != 200
  • 可能 django 将 path 重定向到 path/ 导致 302
猜你喜欢
  • 2021-09-27
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2023-02-07
  • 2019-05-09
  • 2014-02-21
相关资源
最近更新 更多