python-3.x - 如何在“pytest.dependency”中使用测试数据/外部变量?
问题描述
下面的 pytest 代码可以正常工作,它会增加value
.
import pytest
pytest.value = 1
def test_1():
pytest.value +=1
print(pytest.value)
def test_2():
pytest.value +=1
print(pytest.value)
def test_3():
pytest.value +=1
print(pytest.value)
输出:
Prints
2
3
4
我不想执行test_2
,当value=2
有可能pytest.dependency()
吗?value
如果是,我该如何使用变量pytest.dependency
?
如果没有pytest.dependency
,还有其他选择吗?
或者有什么更好的方法来处理这种情况?
import pytest
pytest.value = 1
def test_1():
pytest.value +=1
print(pytest.value)
@pytest.dependency(value=2) # or @pytest.dependency(pytest.value=2)
def test_2():
pytest.value +=1
print(pytest.value)
def test_3():
pytest.value +=1
print(pytest.value)
你能指导我吗?这可以做到吗?这可能吗 ?
解决方案
如果您可以访问测试之外的值(如您的示例中的情况),则可以根据该值跳过夹具中的测试:
@pytest.fixture(autouse=True)
def skip_unwanted_values():
if pytest.value == 2:
pytest.skip(f"Value {pytest.value} shall not be tested")
在上面给出的示例中, wherepytest.value
设置为 2 之后,test_1
将被跳过。这是我得到的输出:test_2
test_3
...
test_skip_tests.py::test_1 PASSED [ 33%]2
test_skip_tests.py::test_2 SKIPPED [ 66%]
Skipped: Value 2 shall not be tested
test_skip_tests.py::test_3 SKIPPED [100%]
Skipped: Value 2 shall not be tested
failed: 0
======================== 1 passed, 2 skipped in 0.06s =========================
推荐阅读
- java - 如何在 Spring Boot 中模拟 Optional bean?
- python - 使用烧瓶生成并上传文件到s3
- lua - 有没有办法在 lua 中制作自定义 loadstring() 函数?
- django - Django REST Serializer 多对多字段仅通过表ID显示,需要多条记录的列表
- node.js - STRQSH 与 start.sh 的区别
- python - for循环不会显示结果
- datastage - 子字符串数据阶段作业参数
- neo4j - 如何优化以下 neo4j Cypher 查询
- python - Jupyter notebook 执行基于用户输入的自动化参数
- python - 给定元组列表,如何在 Pandas DataFrame 中对元组进行子集化?