python - 从 pytest fixture 返回多个对象

标签 python unit-testing python-3.x pytest

我正在通过测试一个简单的事件发射器实现来学习如何使用 pytest。

基本上是这样的

class EventEmitter():
    def __init__(self):
        ...
    def subscribe(self, event_map):
        # adds listeners to provided in event_map events
    def emit(self, event, *args):
        # emits event with given args

为了方便,我创建了一个用于测试的Listener

class Listener():
    def __init__(self):
        ...
    def operation(self):
        # actual listener

目前,测试看起来像下面这样

@pytest.fixture
def event():
    ee = EventEmitter()
    lstr = Listener()
    ee.subscribe({"event" : [lstr.operation]})
    return lstr, ee

def test_emitter(event):
    lstr = event[0]
    ee = event[1]
    ee.emit("event")
    assert lstr.result == 7 # for example

为了测试事件发射器,我需要检查事件传播后监听器的内部状态是否发生了变化。因此,我需要两个对象,我想知道是否有更好的方法来做到这一点(也许使用两个固定装置而不是一个),因为这对我来说有点难看。

最佳答案

通常为了避免 tuples 并美化您的代码,您可以将它们重新组合成一个单元作为一个类,这已经为您完成,使用 collections.namedtuple:

import collections
EventListener = collections.namedtuple('EventListener', 'event listener')

现在修改你的 fixture :

@pytest.fixture
def event_listener():
 e = EventListener(EventEmitter(), Listener())
 e.event.subscribe({'event' : [e.listener.operation]})
 return e

现在修改你的测试:

def test_emitter(event_listener):
 event_listener.event.emit('event')
 assert event_listener.listener.result == 7

关于python - 从 pytest fixture 返回多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37351349/

相关文章:

python - 无法一次性返回所有结果

python - 需要帮助将字符串拆分为 3 个变量

python - 当我从模块内部运行文件时,文件导入有效,但当我通过从外部导入模块来运行文件时,文件导入无效

.net - FsCheck 和 NUnit 集成

unit-testing - 中等复杂度方法的 TDD

android - 我无法让 ViewActions.closeSoftKeyboard() 在 Espresso 2.2.2 中工作

python - 在图像分析中将阴影与其来源相关联

Python 无法导入 shapely

python - 这是 str.format 上的 Python 3 错误吗?

Python:每次函数运行时如何增加数字并存储在变量中