首页 > 解决方案 > 如何在 python 中编写更好的验证/测试用例

问题描述

有一个对象很少有属性。我为测试用例编写了一个函数,用于检查属性是否满足。如果不满足该属性,该函数应抛出异常。

但是,我认为有更好的方法来编写这些测试用例。对象属性的子集如下:

x['polygon'] 是 >= 3 个整数 (x,y) 对的列表,以顺时针或逆时针顺序表示多边形的角。

当前功能如下:

def validate_object(x):
    """This function validates an object x that is supposed to represent an object
    inside an image, and throws an exception on failure.
    Specifically it is checking that:
      x['polygon'] is a list of >= 3 integer (x,y) pairs representing the corners
                    of the polygon in clockwise or anticlockwise order.
    """
    if type(x) != dict:
        raise ValueError('dict type input required.')

    if 'polygon' not in x:
        raise ValueError('polygon object required.')

    if not isinstance(x['polygon'], (list,)):
        raise ValueError('list type polygon object required.')

    points_list = x['polygon']
    if len(points_list) < 3:
        raise ValueError('More than two points required.')

    for x, y in points_list:
        if type(x) != int or type(y) != int:
            raise ValueError('integer (x,y) pairs required.')

    return

如果有人可以建议编写这些测试用例的更好方法,那将非常有帮助。

标签: python-3.xvalidationtestingtestcase

解决方案


推荐阅读