为什么Django测试失败了?

2024-06-09 05:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

每当我运行我的test.py时,我都会得到:

(blog-1rz6wx-6) λ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). .F.. ====================================================================== FAIL: test_post_detail_view (blog.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\ **** \Desktop\blog\blog\tests.py", line 40, in test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200

---------------------------------------------------------------------- Ran 4 tests in 0.776s

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

Mytest.py代码:

def test_post_detail_view(self):
    response = self.client.get('/post/1/')
    no_response = self.client.get('/post/100000')
    self.assertEqual(response.status_code, 200)
    self.assertEqual(no_response.status_code, 404)
    self.assertContains(response, 'A good title')
    self.assertTemplateUsed(response, 'post_detail.html')

settings.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('blog.urls')),
]

以及与views.py位于同一文件夹中的urls.py

from django.urls import path
from .views import BlogListView, BlogDetailView
urlpatterns = [
  path('post/<int:pk>', BlogDetailView.as_view(), name = 'post_detail'),
        path('',BlogListView.as_view(),name = 'home')
    ]

我不知道,当我将响应更改为response = self.client.get('')时,它确实产生了代码200,但使用的模板显然变成了'home.html

先谢谢你


Tags: pathnofrompytestimportselfview
2条回答

似乎/post/1/端点不存在。您可能希望尝试删除最后的/,同时确保您的fixture正在生成一个具有该id的post

我看起来您正在URL/post/1/中传递post id,但是当您在Django中运行测试时,它会创建一个单独的DB。要成功运行测试,您需要定义def setUp(self):并创建一个post以成功运行测试

相关问题 更多 >