![](/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.