【问题标题】:Running Django Tests with RequestFactory is returning __init__.py errors使用 RequestFactory 运行 Django 测试返回 __init__.py 错误
【发布时间】:2014-02-10 18:54:36
【问题描述】:

我不确定我做错了什么。我正在尝试遵循以下示例: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。我没有看到示例。

【问题讨论】:

  • 调用 response = ViewName(request) 有问题是不是与类名冲突?
  • 什么是 ViewName?它是基于类的视图的功能吗?你为什么不想用测试客户端调用你的视图呢?
  • 试试ViewName.as_view()(request)
  • @DanielRoseman ViewName 是一个基于类的视图。我不确定我是否理解您的第二个问题。
  • @sneawo 现在回复是as_view() takes exactly 1 argument (2 given)

标签: django django-testing django-tests


【解决方案1】:

您不需要在拆解中删除对象,测试数据库将为 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)

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多