def test_most_built_in_classes_cannot_be_monkey_patched(self): try: int.is_even = lambda self: (self % 2) == 0 except Exception as ex: err_msg = ex.args[0] self.assertRegex(err_msg, "can't set attributes of built-in")
时间: 2024-04-21 21:27:58 浏览: 19
这个修改后的测试用例中,`int.is_even` 属性被定义为一个 lambda 函数,用于判断一个整数是否为偶数。由于 `int` 类型是不可变类型,因此对其属性进行修改时会抛出一个异常,这个异常信息被保存在 `err_msg` 变量中。然后通过 `self.assertRegex()` 方法来判断异常信息中是否包含 "can't set attributes of built-in" 字符串,如果包含则测试通过,否则测试失败。
然而,由于内置类型是不允许被猴子补丁的,因此这个测试用例无法通过。如果你想要测试猴子补丁,可以将 `int` 类型改为自己定义的一个类,然后再进行猴子补丁。具体可以参考我上一个回答中的示例代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)