小编Lov*_*ode的帖子

pytest 标记:标记整个目录/包

我正在使用 Pytest 测试多个版本的组件。有些测试可以在所有版本上运行,有些是特定于版本的。例如

tests
|
|-- version1_tests
|   |-- test_feature_1_1.py
|   |-- test_feature_1_2.py
|   |-- test_feature_1_n.py
| 
|-- version2_tests
|   |-- test_feature_2_1.py
|   |-- test_feature_2_2.py
|   |-- test_feature_2_n.py
|
|-- common_tests
|   |-- test_feature_common_1.py
|   |-- test_feature_common_2.py
|   |-- test_feature_common_n.py
Run Code Online (Sandbox Code Playgroud)

我想标记我的测试,以便我可以选择是否要从命令行测试版本 1 (version1_tests + common_tests) 或版本 2 (version2_tests + common_tests)。

我目前这样做的方式是针对每个测试模块,我添加一个 pytest 标记,然后从命令行指定标记。例如,在test_feature_1_1.py

import pytest
pytestmark = pytest.mark.version1

class TestSpecificFeature(object):
    ...
Run Code Online (Sandbox Code Playgroud)

然后运行: python -m pytest -m "common and version1"

这工作正常,但我必须手动将标记添加到每个模块,这很乏味,因为实际上有几十个(而不是示例中的 3 个)。

我们曾经使用 Robot Framework,通过在__init__.robot文件中添加标签来“标记”整个文件夹是微不足道的。在 Pytest …

python testing pytest

7
推荐指数
1
解决办法
2480
查看次数

当生成器被包装以充当上下文管理器时,使用 Python 生成器的 .send()

Python 的 contextlib 提供了将生成器转变为上下文管理器的包装器:

from contextlib import contextmanager

@contextmanager
def gen():
    yield

with gen() as cm:
    ...
Run Code Online (Sandbox Code Playgroud)

生成器提供了将值发送到刚刚生成的生成器的能力:

def gen():
    x = yield
    print(x)

g = gen()
next(g)
g.send(1234) # prints 1234 and raises a StopIteration because we have only 1 yield
Run Code Online (Sandbox Code Playgroud)

有什么办法可以同时获得这两种行为吗?我想将一个值发送到我的上下文管理器中,以便在处理__exit__. 所以像这样:

from contextlib import contextmanager

@contextmanager
def gen():
    x = yield
    # do something with x

with gen() as cm:
    # generator already yielded from __enter__, so we can send
    something.send(1234)
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是一个好/合理的想法。我觉得它确实打破了一些抽象层,因为我假设上下文管理器是作为包装的生成器实现的。

如果这是一个可行的想法,我不确定something应该是什么。

python generator

6
推荐指数
1
解决办法
535
查看次数

标签 统计

python ×2

generator ×1

pytest ×1

testing ×1