简体   繁体   English

我们可以在conftest.py之外定义pytest钩子吗?

[英]can we define pytest hooks outside conftest.py?

i did some research in the sites below but i haven't still figured out if we can define pytest hooks (eg pytest_runtest_makereport) other than in the conftest.py file. 我在下面的网站做了一些研究,但我还没弄清楚我们是否可以定义除conftest.py文件之外的pytest钩子(例如pytest_runtest_makereport)。 basically, what i am trying to figure out is if i avoid duplicating conftest.py files by defining a hook inside a base class, for example, so other projects (or classes) consuming this base class can inherit these hooks. 基本上,我想弄清楚的是,如果我通过在基类中定义一个钩子来避免重复conftest.py文件,例如,所以使用这个基类的其他项目(或类)可以继承这些钩子。

thanks a lot. 非常感谢。

references i've used: 我用过的参考文献:

The recommended way would be to move this hooks into an appropriate plugin, but you can force a module to be interpreted as one by declaring a pytest_plugins variable in a conftest file in your project: 建议的方法是将此挂钩移动到适当的插件中,但您可以通过在项目的conftest文件中声明pytest_plugins变量来强制将模块解释为一个模块:

pytest_plugins = ['myproject.plugin'] # myproject.plugin contains hooks

Or you can use the -p flag to py.test : 或者你可以使用-p标志来py.test

py.test -p myproject.module

Note that the last option can be configured in your pytest.ini as well: 请注意,最后一个选项也可以在pytest.ini配置:

[pytest]
addopts = -p myproject.module

There is a easy way to achieve that, just put all pytest hooks in a python file, and import it to the conftest.py file in your test pillar folder. 有一种简单的方法可以实现这一点,只需将所有pytest挂钩放在python文件中,然后将其导入测试支柱文件夹中的conftest.py文件即可。

For example: in conftest.py of your test pillar 例如:在测试支柱的conftest.py中

from custom_hooks import *

Then you can reuse all hooks. 然后你可以重用所有的钩子。

And if you want to overwrite one, just define it again in conftest.py. 如果你想覆盖一个,只需在conftest.py中再次定义它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM