python-3.x - mock @patch 不修补 redis 类

标签 python-3.x redis mocking

我正在尝试使用 mockredis 模拟 redis 类,如下所示。但是原始的 redis 类没有被屏蔽。

测试命中数.py

import unittest
from mock import patch

import mockredis
import hitcount

class HitCountTest(unittest.TestCase):

    @patch('redis.StrictRedis', mockredis.mock_strict_redis_client)
    def testOneHit(self):
        # increase the hit count for user peter
        hitcount.hit("pr")
        # ensure that the hit count for peter is just 1
        self.assertEqual(b'0', hitcount.getHit("pr"))

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

点击次数.py

import redis

r = redis.StrictRedis(host='0.0.0.0', port=6379, db=0)

def hit(key):
    r.incr(key)

def getHit(key):
    return (r.get(key))

我哪里出错了?

最佳答案

当您import hitcount 模块时,您构建redis.StrictRedis() 对象并将其分配给r。在这个导入之后,redis.StrictRedis类的每个补丁都不能对r引用产生影响,至少你修补了一些redis.StrictRedis 的方法。

所以你需要做的是修补 hitcount.r 实例。按照(未经测试的)代码通过将 hitcount.r 实例替换为您想要的模拟对象来完成工作:

@patch('hitcount.r', mockredis.mock_strict_redis_client(host='0.0.0.0', port=6379, db=0))
def testOneHit(self):
    # increase the hit count for user peter
    hitcount.hit("pr")
    # ensure that the hit count for peter is just 1
    self.assertEqual(b'0', hitcount.getHit("pr"))

关于python-3.x - mock @patch 不修补 redis 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28863081/

相关文章:

python - 按升序对月份名称字符串列表进行排序

python - 使用带有 Redis 后端的 Celery 的多个安装

php - 从 Redis 中获取数组数据 - 如何存储和检索

c# - 如何模拟输入异常的函数?

scala - 修改从 Scala 中的方法返回的值(Highcharts lib)

python - 从 CSV 文件中删除双引号

python - 我如何在不事先下载和转换的情况下将音频从 pytube 流式传输到 FFMPEG 和 discord.py

python - 从另一个文件调用函数以在模板中使用

redis - 既然 Redis Cluster 自带分片、复制和自动故障转移,我还需要使用 Sentinel 来处理故障转移吗?

unit-testing - 我是否应该通过单元测试覆盖代码,即使它已经被集成测试覆盖?