【问题标题】:Is it possible to mock more requests types in one test method?是否可以在一种测试方法中模拟更多请求类型?
【发布时间】:2022-01-08 02:14:51
【问题描述】:

是否可以在一种方法中模拟更多请求类型(GETPOSTPUT 等...)?我可以使用 mock.patch 装饰器模拟一种类型的请求。但是,如何在一种测试方法中模拟更多类型?我正在为它寻找一个 Pythonic 和优雅的解决方案(我更喜欢 mock.patch 装饰器,但我也愿意接受其他解决方案)。

您可以在下面看到我的问题的示例:

source.py

import requests


def source_function():
    x = requests.get("get_url.com")
    requests.post("post_url.com/{}".format(x.text))

test.py

import unittest
from unittest import mock

from source import source_function


class TestCases(unittest.TestCase):
    @mock.patch("requests.get")
    def test_source_function(self, mocked_get):
        mocked_get.return_value = mock.Mock(status_code=201, json=lambda: {"data": {"id": "test"}})
        source_function()  # The POST request is not mocked.

【问题讨论】:

  • 你需要修补source.requests.get,所以是实际调用发生的地方。
  • 当然,我在生产代码中这样做,但它不能解决我的问题。如何在一种测试方法中模拟 GET 和 POST 请求类型?这是我的问题。
  • 您可以随意模拟。尝试模拟 post 方法并得到错误?
  • 我可以分别模拟 GET/POST/PUT 等...但我不知道如何在一种测试方法中模拟更多。

标签: python python-3.x unit-testing python-requests


【解决方案1】:

我找到了解决方案。我只需要一个接一个地传递模拟对象。

source.py

import requests


def source_function():
    x = requests.get("http://get_url.com")
    print("Get resp: {}".format(x.json()))
    y = requests.post("http://post_url.com")
    print("Post resp: {}".format(y.json()))

test.py

import unittest
from unittest import mock

import source


class TestCases(unittest.TestCase):
    @mock.patch("source.requests.get")
    @mock.patch("source.requests.post")
    def test_source_function(self, mocked_post, mocked_get):
        mocked_get.return_value = mock.Mock(status_code=200, json=lambda: {"data_get": {"id": "test"}})
        mocked_post.return_value = mock.Mock(status_code=200, json=lambda: {"data_post": {"id": "test"}})
        source.source_function()


# Entry point of script.
if __name__ == "__main__":
    unittest.main()

输出:

>>> python3 test.py
Get resp: {'data_get': {'id': 'test'}}
Post resp: {'data_post': {'id': 'test'}}
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

只有顺序很重要。顶部装饰器的模拟对象应该是最后一个(在我的例子中是GET 方法模拟对象)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-04
    • 2018-05-26
    • 2020-12-01
    • 2020-12-08
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    相关资源
    最近更新 更多