我们如何在多个测试中维护一个变量并将其报告(到控制台或在文件中)?
假设您的模块中有一个名为
math_operations.py
的函数,用于计算两个数字的总和:
# math_operations.py
def add_numbers(a, b):
return a + b
让我们创建一个名为
test_math_operations.py
的 Pytest 测试模块,其中包含两个测试。我想保持两项测试的总分:
# test_math_operations.py
import pytest
from math_operations import add_numbers
@pytest.fixture
def score():
return {"score_pos": 0, "score_neg": 0}
def test_add_numbers_positive(score):
result = add_numbers(2, 3)
assert result == 5
score["score_pos"] =2
assert score["score_pos"] == 2
def test_add_numbers_negative(score):
result = add_numbers(-5, 10)
assert result == 5
score["score_neg"] = 3
assert score["score_neg"] == 3
#print(score)
如果我无法让 pytest 将分数字典输出给我,我希望获得分数的总值。
任何帮助将不胜感激。
您可以将它们放在一个类中并且它会起作用,只需确保测试位于类下并且固定装置处于类范围内
class DemoClass:
score_pos = 0
score_neg = 0
@pytest.fixture(score="class")
def score():
test = DemoClass
yield test
class TestDemo:
def test_add_numbers_positive(score):
...
def test_add_numbers_negative(score):
...