Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 简单的django单元测试给出404-正确的设置程序是什么?_Python_Django_Unit Testing - Fatal编程技术网

Python 简单的django单元测试给出404-正确的设置程序是什么?

Python 简单的django单元测试给出404-正确的设置程序是什么?,python,django,unit-testing,Python,Django,Unit Testing,我的Django项目进展缓慢,我认为单元测试是个好主意。我正试图围绕一个视图编写一个简单的单元测试,但是我得到的未找到请求的URL/索引在此服务器上未找到。。为什么会这样 这是我的单元测试 from django.test import TestCase class BookerIndexTests(TestCase): def test_anonymous_request(self): response = self.client.get('booker:index'

我的Django项目进展缓慢,我认为单元测试是个好主意。我正试图围绕一个视图编写一个简单的单元测试,但是我得到的
未找到请求的URL/索引在此服务器上未找到。

。为什么会这样

这是我的单元测试

from django.test import TestCase

class BookerIndexTests(TestCase):
    def test_anonymous_request(self):
        response = self.client.get('booker:index')
        self.assertEqual(response.status_code, 200)
在我的
url.py
中,我的索引有一行:
url(r'^$',views.index,name='index'),


我是否缺少设置步骤?为什么这个基本单元测试会抛出404错误?

您将URL模式名传递给
client.get()
,而不是实际路径。您需要传递实际的索引路径,根据urlconf-“/”

您正在将URL模式名称传递给
client.get()
,而不是实际的路径。您需要传递实际的索引路径,根据urlconf-“/”

,正如Daniel Roseman指出的,您不能在
client.get()中直接使用模式名。如果您想使用模式名称而不是路径本身,可以使用
反向
。您的代码可以如下所示:

from django.test import TestCase
from django.core.urlresolvers import reverse


class BookerIndexTests(TestCase):
    def test_anonymous_request(self):
        response = self.client.get(reverse('booker:index'))
        self.assertEqual(response.status_code, 200)

这通常是我在测试套件中所做的,因为我更喜欢在路径上使用模式名。

正如Daniel Roseman指出的,您不能在
client.get()中直接使用模式名。
。如果您想使用模式名称而不是路径本身,可以使用
反向
。您的代码可以如下所示:

from django.test import TestCase
from django.core.urlresolvers import reverse


class BookerIndexTests(TestCase):
    def test_anonymous_request(self):
        response = self.client.get(reverse('booker:index'))
        self.assertEqual(response.status_code, 200)

这通常是我在测试套件中所做的,因为我更喜欢在路径上使用模式名。

谢谢。传递URL模式名称不是更方便测试吗?因为如果将来实际的URL路径发生更改,我们不必修改所有测试?谢谢。传递URL模式名称不是更方便测试吗,因为如果将来实际的URL路径发生更改,我们不必修改所有测试?