我刚开始学习单元测试并遇到了这个问题。
我得到了这样的项目结构(现在是 Django 1.6.2):
./manage.py
./myproject
./myproject/urls.py
./myproject/myapp/
./myproject/myapp/urls.py
./myproject/myapp/views.py
./tests/
./test/test_example.py
在 ./myproject/urls.py 我有:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^myapp/', include('myproject.myapp.urls')),
)
在 ./myproject/myapp/urls.py 我有:
from django.conf.urls import patterns, url
urlpatterns = patterns('myproject.myapp.views',
url(r'^example1/$', 'itemlist'),
url(r'^example1/(?P<item_id>\w+)/$', 'item'),
)
我编写了基本测试并将其放入 ./test/test_example.py
import unittest
from django.test import Client
class PagesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
def test_itemlist(self):
response = self.client.get('/myapp/example1/')
self.assertEqual(response.status_code, 200)
def test_item(self):
response = self.client.get('/myapp/example1/100100/')
self.assertEqual(response.status_code, 200)
我像这样从 shell 运行这个测试:
cd ./tests
python manage.py test
第一次测试运行正常,但第二次测试总是以“404 not found”状态码失败。
两个 url 在浏览器中都可以正常工作。
另外,我试过这个:
cd ./
python manage.py shell
>>> from django.test.client import Client
>>> c = Client()
>>> r = c.get('/myapp/example1/100100/')
>>> r.status_code
200
我只是不知道如何正确运行这些测试。似乎没有任何模式作为参数传递给视图对我有用。但是 django.test.client 正确找到了所有固定的 url。
谢谢!
编辑:我刚刚在 myproject/myapp/views.py 中发现 404 起火
有一个代码:
def item(request, item_id):
try:
item = Item.objects.get(pk = int(item_id))
except (ValueError, Item.DoesNotExist):
raise Http404
这里是 Item.DoesNotExist 异常。我不知道,为什么找不到那个项目?