Skip to main content
 首页 » 编程设计

python之是否应该为包装第三方代码的方法编写测试用例

2025年05月04日69java哥

在我的应用程序中,我有验证 CIDR 地址的方法。它所做的只是环绕 ipv4 validate_cidr 方法:

def isValidCIDR(self, cidr): 
    return iptools.ipv4.validate_cidr(cidr) 

我个人不喜欢。我宁愿将验证检查放在 main() 中。

我这样做的唯一原因是因为我编写了测试来验证 CIDR 地址:

def test_input_for_valid_cidr_format(self): 
    cidr = '192.168.2.4/24' 
    self.assertTrue(self.scanner.isValidCIDR(cidr)) 

有必要写这样的测试吗?

请您参考如下方法:

另一个回答说:

The main advantage to having the test is that allows you to switch out the implementation later and be sure that it will still work as expected.

这就是我会为包装代码编写测试用例的确切原因。在某些时候,我可能想要针对包装代码的更新版本测试我的代码。如果我自己针对它编写测试,我将知道包装代码是否仍按我的用例的预期执行。

我还会编写测试以确保我在调用包装代码时不会犯愚蠢的错误(我犯了很多这样的错误)。即,以错误的顺序获取参数:

def foo(x, y): 
    # Wrapped function. 
    ... 
 
def call_foo(x, y): 
    # My wrapper 
    return foo(y, x)