简体   繁体   English

python 使用 gitlab 私有令牌的请求单元测试

[英]python unittest for Requests using gitlab private token

I have a simple class that looks like this (it is used to consult a private Giltab for "ini" style configuration): remote_config.py我有一个简单的 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

I need to write a unittest for this code.我需要为此代码编写单元测试。 How can I do this without actually callling the http endpoint?如何在不实际调用 http 端点的情况下执行此操作?

So far I am trying this: test_remote_config.py到目前为止我正在尝试这个: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

If I stop here and run the test code, I am getting this error: TypeError: Need a valid target to patch, You supplied <function RemoteConfig.get_remote_settings> How can I code the correct @patch to get this test started?如果我在此处停止并运行测试代码,我将收到此错误: TypeError: Need a valid target to patch, You supplied <function RemoteConfig.get_remote_settings>如何编写正确的@patch以启动此测试?

To test this code without calling the actual http endpoint, mock the call of requests.get().要在不调用实际 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM