![](/img/trans.png)
[英]Clone from a Gitlab community private repo using a private token in Python script
[英]python unittest for Requests using gitlab private token
我有一個簡單的 class,看起來像這樣(它用於咨詢私有 Giltab 的“ini”樣式配置):remote_config.py
import requests
class RemoteConfig():
def __init__(self, config_endpoint, token):
self.config_endpoint = config_endpoint
self.token = token
def get_remote_settings(self):
headers= {'PRIVATE_TOKEN' : self.token}
params. = {'ref': 'master'}
response = requests.get(self.config_endopoint, params=params, headers=headers)
settings_from_remote = response.content.decode("utf-8")
return settings_from_remote
我需要為此代碼編寫單元測試。 如何在不實際調用 http 端點的情況下執行此操作?
到目前為止我正在嘗試這個:test_remote_config.py
import requests
import unittest
from private.remote_config import RemoteConfig # project code
class TestRemoteConfiguration(unittest.Testcase):
@patch(RemoteConfig.get_remote_settings)
def test_remote_config():
pass
如果我在此處停止並運行測試代碼,我將收到此錯誤: TypeError: Need a valid target to patch, You supplied <function RemoteConfig.get_remote_settings>
如何編寫正確的@patch
以啟動此測試?
要在不調用實際 http 端點的情況下測試此代碼,請模擬 requests.get() 的調用。
import unittest
from unittest import mock
from remote_config import RemoteConfig # project code
class TestRemoteConfiguration(unittest.TestCase):
def test_get_remote_settings(self):
url, token = "url", "token"
# create a RemoteConfig object
remote_config = RemoteConfig(url, token)
# mock the requests.get function
with mock.patch("requests.get") as get_request:
# set the return value of the mock to a fake response
get_request.return_value.content = b"{'foo': 'bar'}"
# call the get_remote_settings method
settings = remote_config.get_remote_settings()
# assert that the settings are equal to the expected settings
self.assertEqual(settings, "{'foo': 'bar'}")
# assert that the requests.get function was called with the correct parameters
get_request.assert_called_with(
url, params={"ref": "master"}, headers={"PRIVATE_TOKEN": token}
)
if __name__ == "__main__":
unittest.main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.