• Python单元测试


    在Python的圈子里常流行一句话:"动态一时爽,重构火葬场",我们知道Python写起来很方便,但在重构或者对某部分代码修改时, 可能会造成"牵一发而动全身",所以对于Python项目,特别是大型项目来说单元测试来保证代码质量是非常有必要的。

    单元测试(Unit Testing)

    1. 针对程序模块进行正确性检验

    2. 一个函数、一个类进行验证

    3. 自底向上保证程序的正确性

    单元测试的目的:

    1. 保证代码逻辑的正确性

    2. 使得代码易测,高类聚、低耦合

    3. 回归测试放在改一处整个服务不可用的情况

    单元测试一般需要覆盖正常值、异常值和边界值,示例如下:

    bin.py

     1 def binary_search(b_list, target):
     2     """
     3     二分查找
     4     :param b_list:
     5     :param target:
     6     :return:
     7     """
     8     b_list = sorted(b_list)
     9     left, right = 0, len(b_list) - 1
    10     while left <= right:
    11         mid = (left + right) // 2
    12         if b_list[mid] > target:
    13             right = mid - 1
    14         elif b_list[mid] < target:
    15             left = mid + 1
    16         else:
    17             return mid
    18     return None
    19 
    20 
    21 def test():
    22     # 正常值
    23     assert binary_search([3, 5, 7, 8, 9], 5) == 1
    24 
    25     # 边界值
    26     assert binary_search([3, 5, 7, 8, 9], 3) == 0
    27     assert binary_search([3, 5, 7, 8, 9], 9) == 4
    28 
    29     # 异常值
    30     assert binary_search([3, 5, 7, 8, 9], 0) is None
    31     assert binary_search([], 3) is None

    运行 pytest bin.py,如果测试用例全部通过则:

  • 相关阅读:
    重载运算符 && 构造函数 的写法
    2019 ICPC Asia Xuzhou Regional
    中国剩余定理
    求逆元
    Exgcd
    Leading Robots
    大家好
    AtCoder Grand Contest 047 部分题解
    CodeForces 1389E Calendar Ambiguity 题解
    CodeForces 1380F Strange Addition 题解
  • 原文地址:https://www.cnblogs.com/FG123/p/10765941.html
Copyright © 2020-2023  润新知