如何以Pythonic低耦合方式处理全局Context对象的共享与标识问题
符合Python风格的低耦合解决方案
核心思路:通过组合关系替代上下文传递
让Test实例持有其所属TestSuite的引用,既可以共享TestSuite的runtime,又能明确自身的测试数据和索引,同时保留单一全局context的设计初衷。
修改后的代码实现
TestSuite类
class TestSuite(object): def __init__(self, context): self.context = context # 创建Test时传入自身引用、测试数据及索引 self._tests = [ Test(self, test_data, idx) for idx, test_data in enumerate(context["tests"]) ] @property def runtime(self): try: return RuntimeFactory.create_runtime(self.context) except Exception as e: # 替换print为规范的异常抛出,便于上层处理 raise ValueError("runtime_id is missing or invalid") from e
Test类
class Test(object): def __init__(self, test_suite, test_data, index): self.test_suite = test_suite self.test_data = test_data # 当前测试的专属数据 self.index = index # 明确当前测试的索引 @property def runtime(self): # 直接复用TestSuite的runtime,实现全局共享 return self.test_suite.runtime @property def context(self): # 按需组合全局上下文与当前测试数据,保持单一context的设计 combined_context = self.test_suite.context.copy() combined_context["current_test"] = self.test_data combined_context["test_index"] = self.index return combined_context
方案优势
- 低耦合:
Test仅依赖TestSuite的公开接口(runtime和context属性),无需知晓内部实现细节 - 扩展性强:多层结构(如测试包含子输入列表)时,子组件只需持有上层组件的引用,即可逐层获取共享资源,无需修改所有类的上下文结构
- 符合单一职责:
TestSuite管理全局上下文和共享资源,Test专注于自身测试逻辑,分工清晰 - 规范异常处理:替换原有的print输出为异常抛出,符合Python错误处理的最佳实践
内容的提问来源于stack exchange,提问作者Ahasanul Haque
相关产品推荐
相关产品推荐

