在py.test docs中,它描述了将工厂方法声明为固定装置,例如:
@pytest.fixture
def make_foo():
def __make_foo(name):
foo = Foo()
foo.name = name
return foo
return __make_foo
与仅定义make_foo函数并使用它相比,这样做有什么好处/缺点?我不明白为什么它是固定装置。
答案 0 :(得分:3)
实际上,最重要的优点是能够使用其他固定装置,并为您提供pytest的依赖项注入。 另一个优点是允许您将参数传递给工厂,而这些参数在普通灯具中必须是静态的。
看这个例子:
<script>
Y.on('domready', function () {
Y.all(".Blog-meta-item.Blog-meta-item--date").each(function(){
var postDate = Y.one("time").getAttribute("datetime");
var postYear = postDate.substring(0,4);
var postMonth = postDate.substring(5,7)-1;
var postDay = postDate.substring(8,10);
var transDate = new Date(postYear, postMonth, postDay);
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var dateString = transDate.toLocaleDateString('es-ES', options);
Y.one("time").setHTML(dateString);
});
});
</script>
您现在可以编写一个获取@pytest.fixture
def mocked_server():
with mock.patch('something'):
yield MyServer()
@pytest.fixture
def connected_client(mocked_server):
client = Client()
client.connect_to(mocked_server, local_port=123) # local_port must be static
return client
的测试,但是您不能更改端口。
如果您需要与多个客户进行测试该怎么办?你也不能。
如果您现在写:
connected_client
您现在可以编写一个接收@pytest.fixture
def connect_client(mocked_server):
def __connect(local_port):
client = Client()
client.connect_to(mocked_server, local_port)
return client
return __connect
工厂的测试,并调用它以获取初始化的客户端(在任何端口上以及需要多少次!)!
答案 1 :(得分:1)
一个示例可能是会话级设备,例如:
@pytest.fixture(scope="session")
def make_foo():
def __make_foo(name):
foo = Foo()
foo.name = name
return foo
return __make_foo
这样,Pytest将确保在测试期间仅存在一个工厂实例。特别是这个示例可能不会从中获得很多好处,但是如果外部函数进行了大量处理(例如从文件读取或初始化数据结构),那么总体上可以节省大量时间。
答案 2 :(得分:0)
如果您有许多简单的工厂,则可以使用装饰器简化它们的创建:
def factory_fixture(factory):
@pytest.fixture(scope='session')
def maker():
return factory
maker.__name__ = factory.__name__
return maker
@factory_fixture
def make_stuff(foo, bar):
return 'foo' + str(foo + bar)
这等同于
@pytest.fixture(score='session')
def make_stuff():
def make(foo, bar):
return 'foo' + str(foo + bar)
return
答案 3 :(得分:-2)
请参见下面的代码,这可以回答您的问题。
df <- type.convert(df)
输出如下所示:
import pytest
@pytest.fixture
def make_foo():
def __make_foo(name):
print(name)
return __make_foo
def test_a(make_foo):
make_foo('abc')
def test_b(make_foo):
make_foo('def')
基本上,您可以在工厂固定装置中传递参数,并可以根据需要使用。