我们如何在多个测试中维护一个变量并将其报告(在控制台或文件中)?

假设您在一个名为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)

@R.K收到 comments 后Updated test_math_operations.py(见下文)

# test_math_operations.py
import pytest
from math_operations import add_numbers

class DemoClass:
  score_pos = 0
  score_neg = 0

@pytest.fixture() # (score="class")
def score():
  test = DemoClass
  yield test

scoreClass = DemoClass()

class TestDemo:
    global scoreClass
    def test_add_numbers_positive(score):
        result = add_numbers(2, 3)
        assert result == 5
        scoreClass.score_pos =2

    def test_add_numbers_negative(score):
        result = add_numbers(-5, 10)
        assert result == 5
        scoreClass.score_neg = 3

print(scoreClass.score_neg, scoreClass.score_neg)

如果我不能得到乐谱词典给我,我想要分数的总价值.

任何帮助都将不胜感激.

推荐答案

解决这个问题的一种方法是使用一个带有scope=module的fixture:

# test_math_operations.py
import pytest
from math_operations import add_numbers


@pytest.fixture(scope="module")
def score():
    the_score = {"score_pos": 0, "score_neg": 0}
    yield the_score
    print(f"\nSUMMARY\n{the_score=}")


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

输出:

$ pytest -v -s

test_math_operations.py::test_add_numbers_positive PASSED
test_math_operations.py::test_add_numbers_negative PASSED
SUMMARY
the_score={'score_pos': 2, 'score_neg': 3}

注意到

  • 我使用模块作用域来确保每个模块只有一个词典
  • 不是返回,而是I yield,然后在屈服后,我可以打印汇总
  • 在调用pytest时,我使用-s选项来显示print函数的输出

Python-3.x相关问答推荐

如何将CSV或FDF数据解析到Python词典并注入到模板PDF表单中?

检测点坐标 - opencv findContours()

使用 iloc 或 loc 对多列进行过滤

通过 Pandas 通过用户定义函数重命名数据框列

为什么不能用格式字符串 '-' 绘制点?

过滤并获取数据框中条件之间的行

numpy是如何添加@运算符的?

合并问卷中多列中的稀疏问题 - Pandas

从日志(log)文件中查找延迟最低的用户

列表中的重复数字与列表理解

Python socket.error: [Errno 13] 权限被拒绝

多个返回函数的列表理解?

在带有 M1 芯片(基于 ARM 的 Apple Silicon)的 Mac 上安装较早版本的 Python(3.8 之前)失败

PySpark python 问题:Py4JJavaError: An error occurred while calling o48.showString

在 Pandas 数据框中显示对图

带百分号的 Python 字符串格式

如何在python中创建代码对象?

如何在 QGraphicsView 中启用平移和zoom

在 Python 中生成马尔可夫转移矩阵

有没有办法在多个线程中使用 asyncio.Queue ?