使用RequestFactory运行Django测试会返回__init__.py错误

时间:2014-02-10 18:54:37

标签: django django-testing django-tests

我不确定我做错了什么。我试图效仿这个例子:https://docs.djangoproject.com/en/1.6/topics/testing/advanced/#module-django.test.client

我已经创建了我的测试,回报很奇怪。

tests.py:

from django.contrib.auth.models import User
from django.test import TestCase
from django.test.client import RequestFactory
from project_name.app_name.views import ViewName

class UrlsViewsTest(TestCase):
    def setUp(self):
        # every test needs access to the request RequestFactory
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='dave', email='dave@mail.com', password='top_secret')

    def tearDown(self):
        # Delete those objects that are saved in setup
        self.user.delete()

    def test_view_name(self):
        #Create an instance of a GET request
        request = self.factory.get('/app/')

        # Recall that middleware are not suported. You can simulate a
        # logged-in user by setting request.user manually.
        request.user = self.user

        # Test ViewName() as if it were deployed at /app/
        response = ViewName(request)
        self.assertEqual(response.status_code, 200)

结果:

Creating test database for alias 'default'...
E
======================================================================
ERROR: test_view_name (project_name.app_name.tests.UrlsViewsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/dave/sandbox/project_name/project_name/app_name/tests.py", line 25, in test_view_name
    response = ViewName(request)
TypeError: __init__() takes exactly 1 argument (2 given)

----------------------------------------------------------------------
Ran 1 test in 0.168s

FAILED (errors=1)
Destroying test database for alias 'default'...

我无法弄清楚以下含义:

TypeError: __init__() takes exactly 1 argument (2 given)

如何理清这意味着什么以及如何解决?

我一直在寻找Django Google Groups和SO。我没有看到例子。

1 个答案:

答案 0 :(得分:0)

您不需要删除拆解中的对象,测试数据库将为TestCase类中的每个测试定义重置自身。只有在定义新代码的mock和mox之类的东西时才需要拆卸。

这是消息线程的摘要,因此可以将此问题记录为已回答:

解决方法1:

response = ViewName.as_view()(request)

溶液2:

# ignore importing ViewName and RequestFactory
response = self.client.login_as(user=self.user)
response = self.client.get('/app/')

解决方案3:直接单元测试您编写的功能

self.view = ViewName()
output = self.view.new_function(input)
self.assertEqual(output, expected)
相关问题