我做了什么
我编写了一个身份验证类,用于使用应用程序的API 密钥及其API 密钥秘密从 Twitter获取应用程序的不记名令牌,如Twitter 开发人员文档中所示。
我用requests_mock
这种方式模拟了适当的端点:
@pytest.fixture
def mock_post_bearer_token_endpoint(
requests_mock, basic_auth_string, bearer_token
):
requests_mock.post(
"https://api.twitter.com/oauth2/token",
request_headers={
"Authorization": f"Basic {basic_auth_string}",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
json={"token_type": "bearer", "access_token": f"{bearer_token}"},
)
我的测试方法是:
@pytest.mark.usefixtures("mock_post_bearer_token_endpoint")
def test_basic_auth(api_key, api_key_secret, bearer_token):
response = requests.post(
'https://api.twitter.com/oauth2/token',
data={"grant_type": "client_credentials"},
auth=TwitterBasicAuth(api_key, api_key_secret),
)
assert response.json()['access_token'] == bearer_token
(TwitterBasicAuth
我写的身份验证类在哪里,夹具basic_auth_string
是一个硬编码的字符串,可以通过适当地转换夹具获得api_key
)api_key_secret
。
它有效。
问题
但我真的对模拟端点不检查有效负载这一事实感到困扰。在这种特殊情况下,有效负载对于获取承载令牌至关重要。
我已经梳理了requests_mock
(and responses
, too) 的文档,但还没有弄清楚如何使端点仅在发布正确的有效负载时才使用不记名令牌进行响应。
请帮忙。