5

我正在为 Django 应用程序编写测试,并在我的测试类上使用一个属性来存储它应该测试的视图,如下所示:

# IN TESTS.PY
class OrderTests(TestCase, ShopTest):
    _VIEW = views.order

    def test_gateway_answer(self):
        url = 'whatever url'
        request = self.request_factory(url, 'GET')
        self._VIEW(request, **{'sku': order.sku})


# IN VIEWS.PY
def order(request, sku)
    ...

我的猜测是我遇到的问题是因为我调用了OrderTests类的属性,python 假设我想发送self然后order得到错误的参数。很容易解决......只是不要将它用作类属性,但我想知道在这种情况下是否有办法告诉python不要发送自我。

谢谢。

4

1 回答 1

9

This happens because in Python functions are descriptors, so when they are accessed on class instances they bind their first (assumed self) parameter to the instance.

You could access _VIEW on the class, not on the instance:

class OrderTests(TestCase, ShopTest):
    _VIEW = views.order

    def test_gateway_answer(self):
        url = 'whatever url'
        request = self.request_factory(url, 'GET')
        OrderTests._VIEW(request, **{'sku': order.sku})

Alternatively, you can wrap it in staticmethod to prevent it being bound to the instance:

class OrderTests(TestCase, ShopTest):
    _VIEW = staticmethod(views.order)

    def test_gateway_answer(self):
        url = 'whatever url'
        request = self.request_factory(url, 'GET')
        self._VIEW(request, **{'sku': order.sku})
于 2013-04-16T14:16:06.480 回答