编写Django测试以测试主页是否正确加载。我网站的主页不是' /'而是' / home /'和' /'和' / home'实际上会重定向到' / home /'
所以我为此编写了以下测试套件:
tests_main.py
from django.test import TestCase
class homepage_redirects(TestCase):
def test_redirect_homepage(self):
r1 = self.client.get('/')
r2 = self.client.get('/home')
self.assertEqual(r1.status_code, 301)
self.assertEqual(r1.url, '/home/')
self.assertEqual(r2.status_code, 301)
self.assertEqual(r2.url, '/home/')
class homepage_loads(TestCase):
def test_homepage(self):
r = self.client.get('/home/')
self.assertEqual(r.status_code, 200)
出于某种原因,homepage_redirects
测试不会失败,但homepage_loads
会因以下追溯而失败。
回溯
self.assertEqual(r.status_code, 200)
AssertionError: 404 != 200
奇怪的是,如果我去python django shell,我应该得到一个200状态代码。
Python Shell
In[1]: from django.test import Client
In[2]: c = Client()
In[3]: c.get('/home/')
Out[3]: <HttpResponse status_code=200, "text/html; charset=utf-8">
我做错了什么?
views.py
from django.shortcuts import render
def home_page(request):
return render(request, 'app/home_page.html')
urls.py
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.home_page),
]
答案 0 :(得分:0)
urlpatterns = [
path('admin/', admin.site.urls),
path('home/', views.home_page),
]
您可能想要添加?在您的网址中。比如
urlpatterns = [
path(r'^admin/?', admin.site.urls),
path(r'^home/?', views.home_page),
]