首页 > 解决方案 > 模拟请求执行实际请求调用,而不是模拟

问题描述

我正在使用 requests-mock 在我的 unittest 代码中模拟一个 get 请求,但是当我在测试期间运行代码时,它仍然会尝试访问实际的 URL,而不是返回模拟的数据。

这是我的代码:

    try:
        response = requests.get(api_url, auth=requests.auth.HTTPBasicAuth(username, password))
        response.raise_for_status()
    except requests.ConnectionError as e:
        raise dke.CLIError(f"Could not connect to Artifactory server to get NPM auth information: {str(e)}")

这是我的测试代码

class MyTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        m = requests_mock.Mocker()
        m.get('https://artifactory.apps.openshift-sandbox.example.com/artifactory/api/npm/auth',
              text=("_auth = base64string==\n"
                    "always-auth = true\n"
                    "email = shareduser@fake.com"))

我的api_url代码中的 与我传递给的 URL 匹配m.get()。但是,当我运行测试时,我没有得到“text”的值,而是得到了401 Client Error: Unauthorized 一个来自服务器的响应,指示“Bad credentials”,它告诉我它实际上试图联系服务器而不是返回文本我曾要求在模拟。

我迷路了。据我所知,我完全按照文档指示使用它。有任何想法吗?

标签: requests-mock

解决方案


所以,看来你不能那样使用 request_mocker 。它必须是装饰器或上下文管理器。


推荐阅读