我如何模拟请求和响应?

2024-01-06

我正在尝试使用Python模拟包 http://www.voidspace.org.uk/python/mock模拟Pythonrequests模块。让我在下面的场景中工作的基本调用是什么?

在我的views.py中,我有一个函数可以每次调用不同的requests.get()调用

def myview(request):
  res1 = requests.get('aurl')
  res2 = request.get('burl')
  res3 = request.get('curl')

在我的测试类中,我想做这样的事情,但无法找出确切的方法调用

Step 1:

# Mock the requests module
# when mockedRequests.get('aurl') is called then return 'a response'
# when mockedRequests.get('burl') is called then return 'b response'
# when mockedRequests.get('curl') is called then return 'c response'

Step 2:

调用我的视图

Step 3:

验证响应包含 'a 响应'、'b 响应' 、'c 响应'

如何完成第 1 步(模拟请求模块)?


您可以这样做(您可以按原样运行此文件):

import requests
import unittest
from unittest import mock

# This is the class we want to test
class MyGreatClass:
    def fetch_json(self, url):
        response = requests.get(url)
        return response.json()

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    class MockResponse:
        def __init__(self, json_data, status_code):
            self.json_data = json_data
            self.status_code = status_code

        def json(self):
            return self.json_data

    if args[0] == 'http://someurl.com/test.json':
        return MockResponse({"key1": "value1"}, 200)
    elif args[0] == 'http://someotherurl.com/anothertest.json':
        return MockResponse({"key2": "value2"}, 200)

    return MockResponse(None, 404)

# Our test case class
class MyGreatClassTestCase(unittest.TestCase):

    # We patch 'requests.get' with our own method. The mock object is passed in to our test case method.
    @mock.patch('requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Assert requests.get calls
        mgc = MyGreatClass()
        json_data = mgc.fetch_json('http://someurl.com/test.json')
        self.assertEqual(json_data, {"key1": "value1"})
        json_data = mgc.fetch_json('http://someotherurl.com/anothertest.json')
        self.assertEqual(json_data, {"key2": "value2"})
        json_data = mgc.fetch_json('http://nonexistenturl.com/cantfindme.json')
        self.assertIsNone(json_data)

        # We can even assert that our mocked method was called with the right parameters
        self.assertIn(mock.call('http://someurl.com/test.json'), mock_get.call_args_list)
        self.assertIn(mock.call('http://someotherurl.com/anothertest.json'), mock_get.call_args_list)

        self.assertEqual(len(mock_get.call_args_list), 3)

if __name__ == '__main__':
    unittest.main()

重要的提示:如果你的MyGreatClass类生活在不同的包中,比如说my.great.package,你必须嘲笑my.great.package.requests.get而不仅仅是“request.get”。在这种情况下,您的测试用例将如下所示:

import unittest
from unittest import mock
from my.great.package import MyGreatClass

# This method will be used by the mock to replace requests.get
def mocked_requests_get(*args, **kwargs):
    # Same as above


class MyGreatClassTestCase(unittest.TestCase):

    # Now we must patch 'my.great.package.requests.get'
    @mock.patch('my.great.package.requests.get', side_effect=mocked_requests_get)
    def test_fetch(self, mock_get):
        # Same as above

if __name__ == '__main__':
    unittest.main()

Enjoy!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

我如何模拟请求和响应? 的相关文章

随机推荐

  • 为什么Android开发中一定要把这个Context作为参数传递呢?

    这是来自developer android com 上的课程 public void sendMessage View view Intent intent new Intent this DisplayMessageActivity cl
  • 打印对象如何会导致与 str() 和 repr() 不同的输出?

    我正在解释器上测试一些代码 我注意到一些意外的行为sqlite3 Row http docs python org library sqlite3 html sqlite3 Row class 我的理解是print obj总是会得到相同的结
  • django-compressor 离线生成错误

    我正在尝试使用 django compressor 压缩我的 CSS 文件 但我不断收到此错误 compressor exceptions OfflineGenerationError You have offline compressio
  • 如何在 React Navigation 中刷新

    一旦我删除用户令牌 用户就会重定向到登录页面 但是如果我用其他用户登录 主页仍然显示以前的用户信息 这是因为我没有刷新主页 如何在反应导航中手动重新初始化 主页 MainPage Logged in as matt gt Logout gt
  • 从后台工作人员更新 GUI

    问题的名称是 从后台工作人员更新 GUI 但正确的名字是 world 从后台工作人员更新 GUI 或从后台工作人员报告多个变量 整数除外 请让我解释一下我的情况 在一个程序中 我有一个后台工作人员来分析信息 分析的结果是 表单 GUI 元素
  • 像 root 用户一样运行 PHP shell_exec()

    我构建了一个 PHP 应用程序 在其中为 Linux debian Jessie 创建命令行功能 一切正常 但我需要能够使用一些命令 例如 root 用户 有没有办法使用 shell exec 或类似的命令通过 PHP 像 root 用户一
  • postgres 中的顺序扫描和位图堆扫描有什么区别?

    在解释命令的输出中 我发现了两个术语 顺序扫描 和 位图堆扫描 有人可以告诉我这两种扫描有什么区别吗 我使用的是PostgreSql http www postgresql org docs 8 2 static using explain
  • Node.js 和express.js 中基于组/规则的授权方法

    Express js 中基于角色的授权有哪些好的策略 特别是对于快递资源 With 快递资源 https github com visionmedia express resource没有处理程序 所以我认为有三种选择 使用中间件 将授权函
  • 服务器管理 - 需要脚本来监控服务器上的可用空间

    需要脚本来监控服务器上的可用空间如果可用内存空间达到某个阈值发送警报邮件 PS 我认为解决方案是 Power Shell Windows Timer Job 不过我对 Power Shell 还很陌生 您可以使用如下命令获取可用磁盘空间 w
  • PHP 中的日历日视图

    我正在努力向现有日历解决方案添加日视图选项 像许多实现自己的日历的人一样 我正在尝试对 Google 日历进行建模 他们有一个出色的日历解决方案 并且他们的日视图提供了很大的灵活性 大多数情况下 实施进展顺利 然而 当涉及到冲突事件时 我遇
  • 如何更改DataGridView中某些单元格的边框颜色?

    我需要编程更改 CellFormatting 事件中某些单元格的边框颜色 单个单元的板颜色可以更改吗 你可以画一个矩形 在此示例中 我在选定的单元格上放置了红色边框 private void dataGridView CellPaintin
  • 客户端服务器udp套接字

    您好 我有一个 udp 客户端服务器代码无法正常工作 我问一个一般性问题 Shane 是个好孩子吗 这两个代码都没有出现错误 但是当我运行它输出的代码时 数据报发送数据包 新的 DatagramPacket sendData sendDat
  • Scala 中的类型级编程

    我想更深入地了解 Scala 中的类型级编程 因此我开始做一些小练习 我从类型级别的皮亚诺数的实现开始 这是下面的代码 sealed trait PeanoNumType Type at the end indicates to the r
  • 我是否需要在返回容器副本的函数上添加锁?

    class Manager public list
  • 在其他 html 元素周围是否放置

    其他 html 元素应该放在哪里 选项1 放置输入元素
  • 如何根据 Y 轴对点向量进行排序?

    例如我有一组坐标 10 40 9 27 5 68 7 55 8 15 如何在不丢失已排序 Y 轴的正确 X 轴的情况下对这些坐标进行排序 从上面的示例中 我想对坐标进行排序 因此正确的输出将是 8 15 9 27 10 40 7 55 5
  • 错误:实例化 `func::<[closure]>` 时达到递归限制

    我正在尝试测试二叉搜索树是否有效 use std cell RefCell rc Rc pub struct TreeNode val i32 left Option
  • 有C++跨平台USB库吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我 将 用 Qt 编写一个应用程序 该应用程序将在 3 个主要操作系统 Windows Linux 和
  • Pycharm - 当 python 控制台使用 IPython 时等待 REPL 响应

    当 PyCharm Python 控制台配置为使用 IPython 时 该控制台的响应时间慢得难以忍受 以前的安装中并非如此 当 Python 控制台未配置为使用 IPython 并使用 IDLE 时 它会正常执行 较差的响应时间似乎与 R
  • 我如何模拟请求和响应?

    我正在尝试使用Python模拟包 http www voidspace org uk python mock模拟Pythonrequests模块 让我在下面的场景中工作的基本调用是什么 在我的views py中 我有一个函数可以每次调用不同