[英]Re-using data structure in pytest
I am working on a fairly versatile Python data structure while writing tests for every bit of functionality.我正在研究一个相当通用的 Python 数据结构,同时为每一个功能编写测试。 Most of the tests re-instantiate the same structure, ie with the same values, such that a specific method can be tested.
大多数测试重新实例化相同的结构,即具有相同的值,以便可以测试特定的方法。 For example:
例如:
class T():
def __init__(self, data):
self.data = data
def min(self):
return 'min'
def max(self):
return 'max'
class TestT():
def test_min():
t = T(values)
assert t.min() == 'min'
def test_max():
t = T(values)
assert t.max() == 'max'
What is the proper way of re-using this t
instance?重用这个
t
实例的正确方法是什么? I am only beginning and the tests are starting to take too long to execute.我才刚刚开始,测试开始需要很长时间才能执行。 I want to speed them up.
我想加快他们的速度。
Note: I am aware I could parametrize
and getattr
in this particular example but it would still instantiate t
twice, once for each test.注意:我知道在这个特定的例子中我可以
parametrize
和getattr
但它仍然会实例化t
两次,每次测试一次。
I looked at pytest.fixtures however it seems that making a fixture return this t
would just do the same thing, re-instantiating it.我查看了pytest.fixtures但是似乎使夹具返回这个
t
只会做同样的事情,重新实例化它。
Pytest cache seems to be made for this but I do not understand from the documentation how to use it (what is request
in the example?). Pytest 缓存似乎是为此而制作的,但我从文档中不明白如何使用它(示例中的
request
是什么?)。
Lastly, just storing t
in a (class) variable doesn't seem to speed up the tests.最后,仅将
t
存储在(类)变量中似乎并不能加快测试速度。
It seems that my understanding of pytest fixtures was incomplete.看来我对pytest装置的理解是不完整的。 The following works just fine:
以下工作正常:
class Test():
@pytest.fixture(scope='class')
def data(self):
return ...
def test_min(data):
assert data.min() == 'min'
def test_max(data):
assert data.max() == 'max'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.