gpt4 book ai didi

python - 单元测试 python 请求?

转载 作者:行者123 更新时间:2023-11-28 20:07:31 25 4
gpt4 key购买 nike

我有几个方法想要进行单元测试,它们使用 Python requests 库。本质上,他们正在做这样的事情:

def my_method_under_test(self):
r = requests.get("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput',
'InstanceId': 'i-123456'})
# do other stuffs

我基本上希望能够测试一下

  1. 它实际上是在提出请求。
  2. 它正在使用 GET 方法。
  3. 它使用正确的参数。
  4. 等等

问题是我希望能够在不实际发出请求的情况下对此进行测试,因为它会花费太长时间并且某些操作可能具有破坏性。

如何快速轻松地模拟和测试它?

最佳答案

一个简单的模拟怎么样:

from mock import patch

from mymodule import my_method_under_test

class MyTest(TestCase):

def test_request_get(self):
with patch('requests.get') as patched_get:
my_method_under_test()
# Ensure patched get was called, called only once and with exactly these params.
patched_get.assert_called_once_with("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput', 'InstanceId': 'i-123456'})

关于python - 单元测试 python 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16864851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com