简体   繁体   English

如何使用 request-mock 测试带有请求的自定义身份验证处理程序?

[英]How to use request-mock to test custom Authentication Handlers with Requests?

I know I can easily use requests-mock to get calls/custom sessions calls quickly.我知道我可以轻松地使用 requests-mock 快速获取呼叫/自定义会话呼叫。 Now I have a custom authenticator:现在我有一个自定义身份验证器:

 class SimpsonsAuth(requests.auth.AuthBase):
     def __call__(self, r):
         # Implement my authentication
         r.headers['Authentication'] = "Crusty the Clown"
         return r
>>> import requests
>>> import requests_mock

>>> with requests_mock.mock() as m:
...     m.get('http://test.com, text='resp')
...     resp = requests.get('http://test.com', auth=SimpsonsAuth())

When the mocked get doesn't raise the auth.当模拟的get不提高 auth. How do I fire off that Authentication handler?如何触发该身份验证处理程序?

You might need to supply a more complete example, because as written the auth plugin will add the header every time.您可能需要提供一个更完整的示例,因为编写的 auth 插件每次都会添加标题。

import requests
import requests_mock

class SimpsonsAuth(requests.auth.AuthBase):
     def __call__(self, r):
         # Implement my authentication
         r.headers['Authentication'] = "Crusty the Clown"
         return r

with requests_mock.mock() as m:
    m.get('http://test.com', text='resp')
    resp = requests.get('http://test.com', auth=SimpsonsAuth())
    print(m.last_request.headers)

Prints印刷

{'User-Agent': 'python-requests/2.24.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Authentication': 'Crusty the Clown'}

Then it becomes more about how you implement your auth plugin as to how you handle the flow, doing a basic copy from the inbuilt Digest Auth :然后它变得更多关于您如何实现您的身份验证插件以及您如何处理流程,从内置的 Digest Auth做一个基本的副本:

import requests
import requests_mock


class SimpsonsAuth(requests.auth.AuthBase):
    def __init__(self, *args, **kwargs):
        super(SimpsonsAuth, self).__init__(*args, **kwargs)
        self.header = None

    def handle_401(self, r, **kwargs):
        if r.status_code == 401:
            # do some stuff
            self.header = "Crusty the Clown"

            prep = r.request.copy()
            prep.headers['Autentication'] = self.header
            _r = r.connection.send(prep, **kwargs)
            _r.history.append(r)
            _r.request = prep
            return _r

        return r

    def __call__(self, r):
        r.register_hook('response', self.handle_401)

        if self.header:
            r.headers['Authentication'] = self.header

        return r


with requests_mock.mock() as m:
    m.get('http://test.com',
          text='resp',
          request_headers={'Authentication': 'Crusty the Clown'})

    m.get('http://test.com', status_code=401)

    auth = SimpsonsAuth()
    resp = requests.get('http://test.com', auth=auth)

    for req in m.request_history:
        print(req.url, req.headers)

Returns退货

http://test.com/ {'User-Agent': 'python-requests/2.24.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
http://test.com/ {'User-Agent': 'python-requests/2.24.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Autentication': 'Crusty the Clown'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM