【问题标题】:How do I test for a username and password in an HTTP request?如何在 HTTP 请求中测试用户名和密码?
【发布时间】:2019-08-29 13:56:22
【问题描述】:

我正在发出一个包含基本身份验证的 HTTP GET 请求(使用 requests library):

requests.get("https://httpbin.org/get", auth=("fake_username", "fake_password"))

如何测试请求中是否存在正确的用户名和密码?

【问题讨论】:

    标签: python python-requests httprequest pytest basic-authentication


    【解决方案1】:

    模拟请求(使用requests-mock),Base64 对用户名和密码进行编码,并在last_request.headers["Authorization"] 键上断言(使用pytest)。例如:

    def test_make_request():
        with requests_mock.Mocker() as mock_request:
            mock_request.get(requests_mock.ANY, text="success!")
            requests.get("https://httpbin.org/get", auth=("fake_username", "fake_password"))
    
        encoded_auth = b64encode(b"fake_username:fake_password").decode("ascii")
    
        assert mock_request.last_request.headers["Authorization"] == f"Basic {encoded_auth}"
    

    【讨论】:

      猜你喜欢
      • 2015-02-15
      • 2016-08-16
      • 2015-05-28
      • 1970-01-01
      • 2018-05-01
      • 2019-12-23
      • 2019-08-14
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多