如何让mypy识别pytest的expect()会终止测试?
解决Mypy对测试代码中非空校验的冗余问题
你当前的测试逻辑里,expect(transaction).not_to(be_none())已经能完成非空断言,但为了让Mypy识别transaction的非空类型,不得不添加冗余的if transaction is None判断代码,上千个测试用例的重复编写会造成大量冗余。以下是几种更简便的解决方案:
方案一:使用Mypy类型断言cast
直接通过cast明确告知Mypy变量的具体类型,运行时无额外开销,完全适配测试场景:
from typing import cast def test_transaction(self, the_client): [...] transaction = cast(Transaction, transactions.filter([...]).first()) expect(transaction).not_to(be_none()) expect(transaction.client).to(equal(the_client)) [...]
方案二:自定义复用型非空断言函数
封装一个兼顾运行时断言和类型提示的函数,一次定义即可在所有测试用例中复用:
from typing import TypeVar, Type T = TypeVar('T') def assert_not_none(obj: T | None) -> T: assert obj is not None return obj
测试代码中调用:
def test_transaction(self, the_client): [...] transaction = assert_not_none(transactions.filter([...]).first()) expect(transaction).not_to(be_none()) expect(transaction.client).to(equal(the_client)) [...]
注:如果觉得assert和expect的断言重复,可以去掉函数里的assert,仅保留类型提示逻辑,Mypy依然能识别变量类型。
方案三:检查Django Stubs版本兼容性
你已安装Django Stubs,可确认其版本是否为最新——新版本的Django Stubs对QuerySet.first()的类型推断可能有优化,但如果仍返回Optional[T],前两种方案依然是更直接的选择。
内容的提问来源于stack exchange,提问作者Skaman Sam
相关产品推荐
相关产品推荐

