基于pytest实现Python单元测试以及代码覆盖率报告生成,以及在jenkins沙箱中实现自动化测试与报告生成采集

单元测试工具-pytest

安装

pip install pytest

pytest运行规则

  • 会自动运行当前目录下文件名符合test_.py和_test.py规则的代码
  • 会自动执行代码中以test_开头的函数
  • 会自动运行以Test开头的类之中,test_开头的方法,并且不能带有__init__ 方法
  • 所有的包package必须要有__init__.py文件
  • 断言直接使用assert xxx

编写和执行单元测试

要求,单元测试文件名符合格式test_*.py

# content of test_sample.py
def func(x):
    return x + 1


def test_answer():
    assert func(3) == 5

命令行运行pytest可以得到测试结果如下

$ pytest
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item

test_sample.py F                                                     [100%]

================================= FAILURES =================================
_______________________________ test_answer ________________________________

    def test_answer():
>       assert func(3) == 5
E       assert 4 == 5
E        +  where 4 = func(3)

test_sample.py:6: AssertionError
========================= short test summary info ==========================
FAILED test_sample.py::test_answer - assert 4 == 5
============================ 1 failed in 0.12s =============================

额外的测试设置

可以参考官方文档https://docs.pytest.org/en/7.1.x/index.html

运行并生成Junit式的report

执行以下命令即可运行测试,并生成Junit格式的测试报告

pytest [targetfile] --junitxml=./report/report.xml

代码覆盖率-coverage

安装coverage

pip install coverage

在linux系统上需要安装环境依赖: python-devgcc

sudo apt-get install python3-dev gcc
<!-- 或者 -->
sudo yum install python3-devel gcc

运行覆盖率测试

coverage run my_program.py arg1 arg2
blah blah ..your program's output.. blah blah

此操作会在当前目录下生成.coverage文件,记录了文件的执行情况。然后可以使用以下命令生成自己想要格式的覆盖率报告。

coverage report|html|xml|json

其中xml格式可以被cobertura识别,用于jenkins的报告收集。

更多信息

参考官方文档:https://coverage.readthedocs.io/en/6.4.4/index.html

在Jenkins中获取测试报告以及代码覆盖率报告

如果是conda环境可以使用以下命令生成单测报告以及代码覆盖率报告

stage ("code check") {
            steps {
                bat """conda activate node4j \
                && pytest --junitxml=./report/report.xml \
                && coverage run -m pytest \
                && coverage xml"""
            }
        }

完成代码测试后使用post代码块收集生成的报告

post {
    always {
        junit 'report/report.xml'
        cobertura autoUpdateHealth: false, autoUpdateStability: false, coberturaReportFile: 'coverage.xml', conditionalCoverageTargets: '70, 0, 0', failUnhealthy: false, failUnstable: false, lineCoverageTargets: '80, 0, 0', maxNumberOfBuilds: 0, methodCoverageTargets: '80, 0, 0', onlyStable: false, sourceEncoding: 'ASCII', zoomCoverageChart: false
    }
}
Logo

一站式 AI 云服务平台

更多推荐