测试用例引发什么异常:字符串长度>值? - Python

What exception to raise for testcase: string length > value? - Python

我正在做一些测试,在某些情况下我有一些提升,例如:

@staticmethod
def concat_strings(string1, string2):
    if type(string1) is not str or type (string2) is not str:
        raise TypeError
    return string1 + string2

@staticmethod
def concat_3strings(string1, string2, string3):
    if type(string1) is not str or type(string2) is not str or type(string3) is not str:
        raise TypeError
    return string1+string2+string3

现在,如果我想检查字符串的长度最大为 10,那会是 "attribute error",或者我应该做什么样的加注?为什么是那个?

例如:

    @staticmethod
    def concat_2strings_tam(string1, string2):
        if len(string1)>10 or len(string2)>10:
            raise AttributeError
        return string1+string2

来自 python 文档:

exception ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

所以听起来你想要 ValueError,除非你想定义自己的自定义异常 class。