gpt4 book ai didi

Django 测试 : URL mapping to the Class Based View

转载 作者:行者123 更新时间:2023-12-04 16:04:49 24 4
gpt4 key购买 nike

我是 Django 测试的新手,所以尝试基本的测试代码。但是它在第二个测试类中显示了一个错误

测试.py

from django.test import TestCase,Client
from .views import PostList
from django.urls import resolve


class SmokeTest2(TestCase):
def test_math(self):
self.assertEqual(1+1,2)

class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
found = resolve('/')
print({'found':found})
self.assertEqual(found.func(), PostList)

views.py

class PostList(ListView):
model = Post
template_name = 'home.html'

urls.py

urlpatterns = [
path('',views.PostList.as_view(),name ='list'),
]

当我打印 found 时显示 o/p

{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}

但是还是报错

(blog_env) PS D:\django\blog_env\mysite> python manage.py test
D:\django\blog_env\mysite
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'found': ResolverMatch(func=blog.views.PostList, args=(), kwargs={}, url_name=list, app_names=[], namespaces=[])}
E.
======================================================================
ERROR: test_root_url_resolves_to_home_page_view (blog.tests.HomePageTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\django\blog_env\mysite\blog\tests.py", line 19, in test_root_url_resolves_to_home_page_view
self.assertEqual(found.func(), PostList)
TypeError: view() missing 1 required positional argument: 'request'

----------------------------------------------------------------------
Ran 2 tests in 0.069s

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

最佳答案

我刚才被这个问题刺痛了,最终在 documentation 中找到了解决方案

基于类的 View 需要按名称进行比较,因为 as_view() 生成的函数不会因对象 ID 不同而相等,因此断言应如下所示:

from django.test import TestCase
from django.urls import resolve
from .views import HomePageView

class HomePageViewViewTest(TestCase):
def test_resolve_to_home_page_view(self):
resolver = resolve('/')
self.assertEqual(resolver.func.__name__, HomePageView.as_view().__name__)

关于Django 测试 : URL mapping to the Class Based View,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51414993/

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