Django 测试,变更请求

Django testing, change request

我有一个来自 secretballot 的中间件

class SecretBallotMiddleware(object):
    def process_request(self, request):
        request.secretballot_token = self.generate_token(request)

    def generate_token(self, request):
        raise NotImplementedError


class SecretBallotIpMiddleware(SecretBallotMiddleware):
    def generate_token(self, request):
        return request.META['REMOTE_ADDR']


class SecretBallotIpUseragentMiddleware(SecretBallotMiddleware):
    def generate_token(self, request):
        s = ''.join((request.META['REMOTE_ADDR'], request.META.get('HTTP_USER_AGENT', '')))
        return md5(s.encode('utf8')).hexdigest()

我在我看来使用这个(例如 'different_view'):

token = request.secretballot_token

如何在我的测试中更改此令牌表单请求?

class BasicTest(TestCase):
    def test_one(self):
        self.client.request['secretballot_token']='asd' #??
        response = self.client.post('/different_view/')

我想在此测试中将 post 发送到 /different_view/ 但使用我自己的更改令牌。

如果您希望通过中间件在没有 运行 的情况下测试视图,您可以使用 RequestFactory 生成请求并将其直接传递到您的视图中。

def test_one(self):
    # create a request
    request = RequestFactory().post('/different_view')
    request.secretballot_token = 'asd'

    # function based view
    response = different_view(request)
    # class based view
    response = DifferentView.as_view()(request) 

如果您需要在测试视图的同时测试中间件,您应该在测试中传递 HTTP headers

def test_one(self):
    # pass http headers
    response = self.client.post(path='/different_view'/,
        REMOTE_ADDR='12.34.56.78',
        HTTP_USER_AGENT='...'
    )