从 pytest 固定装置返回多个对象 [英] Returning multiple objects from a pytest fixture
问题描述
我正在通过测试一个简单的事件发射器实现来学习如何使用 pytest.
I am learning how to use pytest by testing a simple event emitter implementation.
基本上是这样的
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
类
For convenience, I created a Listener
class that is used in tests
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
为了测试事件发射器,我需要检查事件传播后监听器的内部状态是否发生了变化.因此,我需要两个对象,我想知道是否有更好的方法来做到这一点(也许可以使用两个固定装置而不是一个固定装置),因为这对我来说看起来有点难看.
In order to test event emitter, I need to check whether the inner state of the listener has changed after event propagation. Thus, I need two objects and I wonder if there is a better way to do this (maybe use two fixtures instead of one somehow) because this looks kinda ugly to me.
推荐答案
是的!在这种情况下,您可能需要两个灯具..
Yeah! probaly you will need two fixtures in this case..
你可以试试 @pytest.yield_fixture
像:
@pytest.yield_fixture
def event():
...
yield <event_properties>
@pytest.yield_fixture
def listener(event):
...
yield <listener_properties>
这篇关于从 pytest 固定装置返回多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!