Django测试用例response.status_code失败及模板匹配问题求助
解决Django测试中的404和NoReverseMatch问题
看起来你的测试遇到的问题主要来自三个核心原因:根URL配置错误、未使用URL命名空间,以及由此连锁导致的模板验证失败。我们一步步来修复:
1. 修正项目根目录的urls.py
你现在的根urls.py错误地直接复制了应用的URL配置,没有把registry应用的URL挂载到正确的路径下——这是导致404错误的根本原因。
把根urls.py改成这样:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), # 将registry应用的URL映射到/Registry/前缀下,和你测试中使用的路径对应 path('Registry/', include('registry.urls')), ]
2. 修正测试代码中的URL反向解析
因为你的应用设置了app_name='registry',Django的URL命名空间规则要求你在反向解析视图时必须带上命名空间前缀。同时,直接访问URL时要使用完整的路径:
修改后的测试代码:
from django.test import TestCase, SimpleTestCase from django.urls import reverse # Create your tests here. class RegistryTest(SimpleTestCase): def test_homepage_status(self): # 使用和根urls.py配置对应的完整URL路径 response = self.client.get('/Registry/search/') self.assertEqual(response.status_code, 200) def test_homepage_url_name(self): # 加上应用命名空间前缀:registry:search response = self.client.get(reverse('registry:search')) self.assertEqual(response.status_code, 200) def test_homepage_template(self): response = self.client.get('/Registry/search/') self.assertTemplateUsed(response, 'registry/search_registry.html')
3. 为什么模板测试会失败?
因为前两个测试请求返回了404,Django根本没有执行你的search视图,自然也就没有渲染模板。解决前两个问题后,这个测试会自动通过——你的模板路径templates/registry/search_registry.html是完全正确的,Django会自动搜索应用下的templates目录。
现在重新运行python manage.py test Registry,三个测试应该都能顺利通过了!
内容的提问来源于stack exchange,提问作者Carlo Cogni
相关产品推荐
相关产品推荐

