如何在python中模拟post请求,以便它可以接受不同的输入值并根据输入返回不同的值?

2024-10-04 03:16:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是原始的post请求

result = requests.post('api/' + tenant_name + '/getdomain', json=query_to_execute, verify=False,timeout=100)
json_result = result.json()x

这里要执行的查询将是以下格式的聚合mongodb查询

[{$match: {}}, {$limit:25}]

现在我已经有了一个单元测试用例类

def mock_another_post_request(arg):
     ret_values=[
     [ { "name":"Abcd",'Age':25},
     { "name":"asfcd",'Age':45},],
     [{ "name":"sdfd",'Age':42},]
     ]

     return ret_values[arg]



class MyTests (unittest.TestCase):
     def setup(self):
          patcher = patch('requests.post',new = mock_another_post_request)
          patcher.start()

          self.addCleanup(patch.stopall)

     def MyTestCase():
          expected_result =[ 
          { "name":"Abcd",'Age':25},
          { "name":"asfcd",'Age':45},]
          assertEqual expected_result = get_all_docs()

我很困惑我在做什么,目标是模拟请求。根据作为有效负载的一部分发送的输入,我应该能够返回不同的值,我该怎么做? 提前谢谢


Tags: namejsonagerequestdefanotherargresult