如何在 'pytest.dependency' 中使用 test-data/external 变量?
How can I use test-data/external variable in '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
我不想在 value=2
时执行 test_2
pytest.dependency()
可以吗?如果是,我如何在 pytest.dependency
中使用变量 value
?
如果不是 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")
在上面给出的示例中,pytest.value
在 test_1
之后设置为 2,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 =========================
下面的 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
我不想在 value=2
test_2
pytest.dependency()
可以吗?如果是,我如何在 pytest.dependency
中使用变量 value
?
如果不是 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")
在上面给出的示例中,pytest.value
在 test_1
之后设置为 2,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 =========================