zoukankan      html  css  js  c++  java
  • python代码覆盖率coverage简介与用法

    如果衡量单元测试对相应代码的测试重量,覆盖率是一个必要非充分条件,因此统计代码的覆盖率,检视单测是否充分,就尤为的重要。这里针对python-unittest的单测的覆盖率coverage进行使用说明与分析.

    参考链接:https://blog.csdn.net/xiaoxinyu316/article/details/53695342

    coverage简介:

    coverage是一种用于统计Python代码覆盖率的工具,通过它可以检测测试代码对被测代码的覆盖率如何。可以高亮显示代码中哪些语句未被执行,哪些执行了,方便单测。并且,coverage支持分支覆盖率统计,可以生成HTML/XML报告


    官方文档:http://coverage.readthedocs.org/en/latest/

    获取地址:http://pypi.python.org/pypi/coverage


    使用coverage统计代码覆盖率的步骤:

    • 安装coverage包: pip install coverage
    • 在源代码的根目录的路径下面,添加文件‘.coveragerc.py’
    1 # 文件中的代码为:
    2 [run]
    3 branch = True
    4 source = xxx #项目名称xxx
    • 进入当前待执行的文件路径下面
    • 执行
    1. coverage run --help   # 打印帮助信息
    2. coverage run test_xxx.py                # 执行test_xxx.py文件,会自动生成一个覆盖率统计结果文件.coverage
    3. coverage report -m(带有详细信息)                  # 查看coverage报告,读取.coverage文件并打印到屏幕上,可以在命令行里看到统计结果
    4. coverage html -d report                # 生成显示整体的covergae html形式的报告 (在当前同路径下生成一个report文件夹,里面包含html形式的报告。通过查看report文件夹下的内容即可)
    • 备注:coverage run test.py命令运行的文件,会统计项目中包括测试文件本身在内的所有文件,run参数的子参数—source可以指定要统计的文件:$ coverage run --source=totest.py test.py 可以只统计totest.py文件。
    • 注意事项:

    如果是针对单测的覆盖率统计,需要在单测文件test_xxx.py的代码的最后加上。这样可以执行整个单测代码,然后执行coverage run test_xxx.py 即可。

    1 if __name__ == "__main__":
    2     unittest.main()

     

    发散:

    • 原理:coverage.py利用了Python虚拟机的trace机制

    参考链接:https://blog.csdn.net/xluren/article/details/46799939

     

     

  • 相关阅读:
    LeetCode:Plus One
    LeetCode:Text Justification
    LeetCode:Sqrt(x)
    LeetCode:Climbing Stairs(编程之美2.9-斐波那契数列)
    LeetCode:Simplify Path
    LeetCode:Edit Distance
    LeetCode:Set Matrix Zeroes
    LeetCode:Search in Rotated Sorted Array I II
    LeetCode:Search a 2D Matrix
    LeetCode:Sort Colors
  • 原文地址:https://www.cnblogs.com/sunshine-blog/p/9815088.html
Copyright © 2011-2022 走看看