繁体   English   中英

使用自己的装饰器 pytest

[英]Using own decorators with pytest

我想在多个 pytest 测试文件中使用“助手”装饰器:

min311 = pytest.mark.skipif(sys.version_info < (3,11), reason="You need at least Python v3.11 to run this test")

...
@min311
def test_...

哪个是min311的最佳位置? 它不会从conftest.py自动导入。

鉴于此布局:

.
├── src
│   ├── conftest.py
│   └── mycode
│       ├── __init__.py
│       └── main.py
└── tests
    ├── conftest.py
    ├── __init__.py
    └── test_mycode.py

4 directories, 6 files

如果我在tests/conftest.py中定义min311 ,那么在test_mycode.py中我可以写:

from tests.conftest import min311

@min311
def test_something():
  ...

这假设我们从顶级目录运行pytest

这也适用于更简单的布局:

.
├── conftest.py
├── mycode
│   ├── __init__.py
│   └── main.py
└── tests
    ├── conftest.py
    ├── __init__.py
    └── test_mycode.py

如果您不想直接从conftest导入,只需将装饰器定义移动到更合适的地方。 我见过很多项目在他们的代码中包含类似test_helpers模块的东西:

.
├── conftest.py
├── mycode
│   ├── __init__.py
│   ├── main.py
│   └── test_helpers.py
└── tests
    ├── conftest.py
    └── test_mycode.py

那么你也能:

from mycode.test_helpers import min311

暂无
暂无

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

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