如何测试 HTTP 请求中的用户名和密码?

How do I test for a username and password in an HTTP request?

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

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

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

last_request.headers["Authorization"] 键上模拟请求(使用 requests-mock), Base64 encode the username and password, and assert (with 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}"