Django.test.client现有u上出现404错误

2024-04-25 09:11:27 发布

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

我刚开始学习单元测试,并一直坚持这个问题。在

我有这样的项目结构(现在是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中/网址.py我有:

^{pr2}$

在./myproject/myapp中/网址.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'),
)

我编写了basic test并将其放入./test/test中_示例.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

第一个测试运行正常,但第二个测试总是失败,状态代码为“404NotFound”。在

这两个URL在浏览器中都正常工作。在

我也试过了:

cd ./
python manage.py shell
>>> from django.test.client import Client
>>> c = Client()
>>> r = c.get('/myapp/example1/100100/')
>>> r.status_code
200

我就是不知道如何正确地运行这些测试。似乎没有一个模式作为参数传入视图对我有用。但是所有固定的url都可以通过django.test.client. 在

谢谢你!在

编辑:我刚发现我的myproject/myapp中有404个火/视图.py在

有一个代码:

def item(request, item_id):
    try:
        item = Item.objects.get(pk = int(item_id))
    except (ValueError, Item.DoesNotExist):     
        raise Http404

这就是物品编号例外情况。我不知道,为什么那东西没找到?在


Tags: djangopytestimportselfclienturlget