如何在不丢失身份验证的情况下模拟Session.request?

问题描述 投票:2回答:1

在测试使用请求库的Python软件时,建议模拟requests.sessions.Session.request

不幸的是,当我不得不处理HTTP身份验证时似乎并不是很好,我觉得我在请求中嘲笑一个太高的抽象层。我如何拦截/模拟请求,以便我不必自己处理身份验证(并获得适当的标头)?

python unit-testing python-requests
1个回答
3
投票

不要嘲笑Session,使用Transport Adapter。 =)

Session对象对请求进行了大量处理,并在该级别修补它将无法获得请求。

相反,写一个Transport Adapter,其send()方法存储PreparedRequest对象。

例如,请参阅the official docsan article I wrote。但是,你会想要这样的东西:

from requests.adapters import HTTPAdapter


class TestAdapter(HTTPAdapter):
    """
    A Transport Adapter that stores all requests sent, and provides pre-canned responses.
    """
    def __init__(self, responses):
        self.responses = responses
        self.requests = requests

    def send(self, request, *args, **kwargs):
        self.requests.append(request)
        return self.responses.pop(0)

为了使这个工作,responses将需要是一个urllib3.Response对象列表或类似请求可以使用的东西。 TestAdapter.requests将是requests.PreparedRequest对象的列表。

如果你不想做所有这些工作,你可以尝试像betamax这样的东西。

© www.soinside.com 2019 - 2024. All rights reserved.