简体   繁体   English

模拟请求执行实际请求调用,而不是模拟

[英]Mocked request doing actual requests call, not mock

I am mocking a get request in my unittest code using requests-mock, but when I run the code during testing, it still tries to hit the actual URL instead of returning the mocked data.我是 mocking 在我的 unittest 代码中使用 requests-mock 获取请求,但是当我在测试期间运行代码时,它仍然试图命中实际的 URL 而不是返回模拟数据。

This is my code:这是我的代码:

    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)}")

This is my test code这是我的测试代码

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"))

The api_url in my code matches the URL I pass to m.get() .我的代码中的api_url与我传递给m.get()的 URL 匹配。 However, when I run the test, I do not get the value of "text" but instead I get a 401 Client Error: Unauthorized and a response from the server indicating "Bad credentials" which tells me it actually tried to contact the server instead of returning the text I had requested in the Mock.但是,当我运行测试时,我没有得到“text”的值,而是得到了401 Client Error: Unauthorized和来自服务器的响应,指示“Bad credentials”,这告诉我它实际上试图联系服务器返回我在 Mock 中要求的文本。

I'm lost.我迷路了。 As far as I can tell, I'm using this exactly as the docs indicate.据我所知,我完全按照文档指示使用它。 Any ideas?有任何想法吗?

So, it seems you can't use the request_mocker that way.所以,看来你不能那样使用 request_mocker 。 It has to be a decorator or context manager.必须是装饰器或上下文管理器。

I mean the context manager/decorator is just a pattern around normal code.我的意思是上下文管理器/装饰器只是普通代码的一种模式。 I haven't tested it but i think you just have to call m.start()/m.stop() .我还没有测试过,但我认为你只需要调用m.start()/m.stop()

It's generally used as a context manager or decorator because if you instantiate it once like that then your request history is going to include all requests across all unit tests which is very hard to make assertions about.它通常用作上下文管理器或装饰器,因为如果您像这样实例化它一次,那么您的请求历史记录将包括所有单元测试中的所有请求,这很难做出断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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