【发布时间】:2022-10-16 22:36:28
【问题描述】:
假设我有一个具有以下功能的 python 模块:
def is_plontaria(plon: str) -> bool:
if plon is None:
raise RuntimeError("None found")
return plon.find("plontaria") != -1
对于该功能,我有以下单元测试:
def test_is_plontaria_null(self):
with self.assertRaises(RuntimeError) as cmgr:
is_plontaria(None)
self.assertEqual(str(cmgr.exception), "None found")
给定函数中的类型提示,输入参数应始终是已定义的字符串。但是类型提示是……提示。没有什么可以阻止用户传递它想要的任何东西,当先前的操作未能返回预期结果并且未检查这些结果时,None 特别是一个非常常见的选项。
所以我决定在单元测试中测试 None 并检查函数中的输入不是 None 。
问题是:类型检查器(pylance)警告我不应在该调用中使用 None :
Argument of type "None" cannot be assigned to parameter "plon" of type "str" in function "is_plontaria"
Type "None" cannot be assigned to type "str"
嗯,我已经知道了,这就是测试的目的。
消除该错误的最佳方法是什么?告诉 pylance 在每个测试/文件中忽略这种错误?或者假设传递的参数始终是正确的类型并删除该测试和函数中的 None 检查?
【问题讨论】:
标签: python python-3.x unit-testing python-unittest pylance