我正在使用pytest. 我想为库公开的每个函数尝试多个测试用例,因此我发现将类中每个方法的测试分组很方便。我要测试的所有函数都具有相同的签名并返回相似的结果,因此我想使用超类中定义的辅助方法对结果进行一些断言。简化版本会像这样运行:
class MyTestCase:
function_under_test: Optional[Callable[[str], Any]] = None
def assert_something(self, input_str: str, expected_result: Any) -> None:
if self.function_under_test is None:
raise AssertionError(
"To use this helper method, you must set the function_under_test"
"class variable within your test class to the function to be called.")
result = self.function_under_test.__func__(input_str)
assert result == expected_result
# various other assertions on result...
class FunctionATest(MyTestCase):
function_under_test = mymodule.myfunction
def test_whatever(self):
self.assert_something("foo bar baz")
Run Code Online (Sandbox Code Playgroud)
在 中assert_something,有必要调用__func__()该函数,因为将函数分配给类属性使其成为该类的绑定方法——否则self将作为第一个参数传递给外部库函数,在那里它没有任何意义.
此代码按预期工作。但是,它会产生 MyPy …