Python pytest 基于容器实现依赖注入

三水 · 2022年08月09日 · 3363 次阅读

context 我是自己实现的逻辑,模仿 Java 的 spring

需要注释一段源码 _pytest.python.Class 中 collect 方法关于 init 方法的判断,无其他修改

pytest_make_collect_report 放到 conftest 或者自己注册插件都可

@pytest.hookimpl(hookwrapper=True, trylast=True)
def pytest_make_collect_report(self, collector):
    result = yield
    result_case = result._result.result
    for i in result_case:
        if isinstance(i, Class):
            newinstance = lambda s: my_newinstance(s, self.context)
              # 修改这个方法的实现,让他调用自己写的实例化方法,实现依赖注入
            setattr(i, "newinstance", types.MethodType(newinstance, i))
def my_newinstance(self, context):
    # 从容器中获取关于依赖注入的方法
    injection: AutoInjectBeanPostProcessor = context.get_bean("autoinject_bean_post_processor")
    # 解析init参数
    args = context.bean_factory.get_init_args(self.obj.__name__, self.obj)
    # 初始化
    obj = self.obj(**args)
    # 依赖注入
    injection.inject(obj.__class__.__name__, obj, context.bean_factory)
    # 返回对象
    return obj

Brand 类是由容器创建,在创建 test 类时会根据名字或者类型进行注入

在类中写_inject 也可以实现相同效果

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册