python - 在pytest中模拟一个连接类

标签 python unit-testing mocking rabbitmq kombu

我有一个继承自 kombu.ConsumerProducerMixin 的类,我想在没有运行实际 rabbitmq 服务的情况下进行测试。

class Aggregator(ConsumerProducerMixin):

    def __init__(self, broker_url):
        exchange_name = 'chargers'
        self.status = 0
        self.connection = Connection(broker_url)
        ...

在我的测试文件中,我做了以下事情:

from unittest.mock import Mock, patch

from aggregator import Aggregator

@patch('kombu.connection.Connection')
def test_on_request(conn_mock):

    agg = Aggregator('localhost')
    m = Message("", {"action": "start"}, content_type="application/json")

使用调试器进入 Aggregator.__init__,我看到 connection 仍未修补为 Mock 实例:

(Pdb) self.connection
<Connection: amqp://guest:**@localhost:5672// at 0x7fc8b7f636d8>
(Pdb) Connection
<class 'kombu.connection.Connection'>

我的问题是如何正确修补连接,这样我就不需要 rabbitmq 来运行测试了?

最佳答案

好的,docs说明如下:

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. A couple of examples will help to clarify this.

因此,解决方案:

@patch('aggregator.aggregator.Connection')
def test_on_request(mock_connect):
    agg = Aggregator('localhost')

关于python - 在pytest中模拟一个连接类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42668625/

相关文章:

python 断言 float 列表

python - Pathlib 使用 Path.parents 访问 Path 时出错

angular - 模块 'StateService' 声明的意外值 'DynamicTestModule'

unit-testing - 在 PHPUnit/DBUnit 中关闭外键约束

java - 在模拟文件路径时如何编写有效的 JUnit 测试?

ruby - 如何使用 rspec/rspec-mocks stub 类方法

python - Django1.5 - python2.7 -如何显示和更新具有3个外键的数据库

python - Pytest 如何模拟依赖于其父调用参数的函数调用的副作用

firebase - 有没有办法对于Jest的方式模拟 firebase 模块?

python - Plone 3.1.2 - ATDocument.getText() 方法中的类型错误