Django测试客户端问题

2 投票
2 回答
3155 浏览
提问于 2025-04-15 19:23

我遇到一个问题……我们正在用Django写一个项目,我想用django.test.client和nose测试框架来进行测试。

我们的代码是这样的:

from simplejson import loads
from urlparse import urljoin

from django.test.client import Client

TEST_URL = "http://smakly.localhost:9090/"

def test_register():

    cln = Client()

    ref_data = {"email": "unique@mail.com", "name": "Василий", "website": "http://hot.bear.com", "xhr": "true"}

    print urljoin(TEST_URL, "/accounts/register/")
    response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data))

    print response["message"]

在nose的输出中,我发现了:

Traceback (most recent call last):
  File "/home/psih/work/svn/smakly/eggs/nose-0.11.1-py2.6.egg/nose/case.py", line 183, in runTest
    self.test(*self.arg)
  File "/home/psih/work/svn/smakly/src/smakly.tests/smakly/tests/frontend/test_profile.py", line 25, in test_register
    response = loads(cln.post(urljoin(TEST_URL, "/accounts/register/"), ref_data))
  File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 313, in post
    response = self.request(**r)
  File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 225, in request
    response = self.handler(environ)
  File "/home/psih/work/svn/smakly/parts/django/django/test/client.py", line 69, in __call__
    response = self.get_response(request)
  File "/home/psih/work/svn/smakly/parts/django/django/core/handlers/base.py", line 78, in get_response
    urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
  File "/home/psih/work/svn/smakly/parts/django/django/utils/functional.py", line 273, in __getattr__
    return getattr(self._wrapped, name)
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'

我的settings.py文件里确实有这个属性。

如果我用标准的urllib2.urlopen().read()从服务器获取数据,那是可以正常工作的。

有没有什么想法可以解决这个问题?

2 个回答

0

不怕自夸:正是因为这些原因,我制作了一个测试库,可以帮助你用urllib2来测试应用程序。

文档在这里:http://readthedocs.org/docs/django-sane-testing/en/latest/

你可能想做的一个例子是,比如说,在django-http-digest的测试中

0

如果你想用nose这个工具,可能需要用到django-nose。

http://github.com/jbalogh/django-nose

我建议你使用TestCase这个类。

http://docs.djangoproject.com/en/dev/topics/testing/

http://www.djangoproject.com/documentation/models/test_client/

撰写回答