gpt4 book ai didi

python - Django 测试,变更请求

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:57 26 4
gpt4 key购买 nike

我有一个来自 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()

我在我的 View 中使用它(例如“different_view”):

token = request.secretballot_token

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

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

而且我想将此测试中的帖子发送到/different_view/但使用我自己的更改 token 。

最佳答案

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

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)

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

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

关于python - Django 测试,变更请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com