【问题标题】:Why is this django test is failing?为什么这个 django 测试失败了?
【发布时间】:2021-02-09 08:29:00
【问题描述】:

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

(blog-1rz6wx-6) λ python manage.py test 创建测试数据库 别名“默认”... 系统检查未发现任何问题(0 静音)。 。F.. ==================================================== ==================== 失败:test_post_detail_view (blog.tests.BlogTests) -------------------------------------------------- -------------------- Traceback(最近一次调用最后一次):文件 “C:\Users\ **** \Desktop\blog\blog\tests.py”,第 40 行,在 test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200

----------------------------------- ----------------------- 在 0.776 秒内运行 4 次测试

FAILED (failures=1) 正在销毁别名“default”的测试数据库...

我的 test.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')

urls.pysettings.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,但 TemplateUsed 显然变成了 'home.html

先谢谢了。

【问题讨论】:

    标签: python django testing url


    【解决方案1】:

    /post/1/ 端点似乎不存在。您可能想尝试消除最后的 /,同时确保您的固定装置会生成具有该 ID 的帖子。

    【讨论】:

    • 谢谢!这解决了这个问题,天哪,我处理了这个问题大约 2 个小时。非常感谢,感觉好笨 rn lmao
    【解决方案2】:

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

    【讨论】:

    • 好的,所以我的 setUp 是这样的:def setUp(self): self.user = get_user_model().objects.create_user( username = 'testuser', email = 'test@email.com', password = 'secret' ) self.post = Post.objects.create( title = 'A good title', body = 'Nice body content', author = self.user, )
    • 好的,@hd1 已经帮我解决了这个问题,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多