使用类、模块或项目的fixture
有时测试用例不需要直接访问一个fixture对象,比如,测试可能需要将一个空目录作为当前工作目录来操作,但其他方面并不关心具体目录。这就可以使用标准tempfile和pytest fixtures来实现,我们分离fixture的创建到confest.py文件中:

通过usefixtures标记在测试模块中声明其使用:

因为使用了usefixtures标记,因此执行时每个测试方法都需要cleandir fixture,就像为每个测试方法指定了一个“cleandir”函数参数一样。运行后的结果:

可以指定多个fixtures:

可以使用pytestmark在测试模块级别指定fixture的使用:

也可以将项目中所有测试所需的fixtures放入ini文件中:

注意:
该方法不适用于fixture function。比如,下面示例将不会按照期望的来工作:

当前,这种方式不会产生任何错误或警告,但是后期将会改进https://github.com/pytest-dev/pytest/issues/3664
网友评论