我遇到了一個問題,我需要測驗一個名為requests. 推薦的方法是使用monkeypatch來避免request呼叫,但所有資源都顯示了一種使用requests函式外部模塊執行此操作的方法:
import requests
def test_get_credentials(uri, code):
#the actual function, but rewritten here instead of just being imported
def mocked_get(uri, *args, **kwargs):
# this is a request answer mock to avoid calling external servers during tests
json = {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
mock = type("MockedReq", (), {})()
mock.json = json
obj = mock
return obj
monkeypatch.setattr(requests, "post", mocked_get)
credentials = requests.post(uri, data=code).json()
assert credentials == {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
但是我想使用匯入的函式,但沒有找到從匯入的函式中修補 requests 模塊的方法。就像是:
import requests
from external_auth import get_credentials
def test_get_credentials(uri, code):
def mocked_get(uri, *args, **kwargs):
json = {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
mock = type("MockedReq", (), {})()
mock.json = json
obj = mock
return obj
monkeypatch.setattr(requests, "post", mocked_get)
assert get_credentials(uri, code) == {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
uj5u.com熱心網友回復:
我發現修補匯入函式的方法是通過__globals__更改函式屬性get_credentials.__globals__["requests"]而不是僅僅get_credentials. 最終代碼如下所示:
import requests
from external_auth import get_credentials
def test_get_credentials(uri, code):
def mocked_get(uri, *args, **kwargs):
json = {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
mock = type("MockedReq", (), {})()
mock.json = json
obj = mock
return obj
monkeypatch.setattr(get_credentials.__globals__["requests"], "post", mocked_get)
assert get_credentials(uri, code) == {"token_type": "JWT", "access_token": "ioaUSHDAHwe9238hidnfiqh2wr89o"}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455837.html
