Skip to content

[Bug] 修复测试中的资源泄漏并改进单例隔离 / Fix Resource Leaks in Tests & Improve Singleton Isolation #104

@SunYanbox

Description

@SunYanbox

问题描述 / Problem Description
在运行测试套件时,部分测试(尤其是涉及 DatabaseManagerToolRegistry 的测试)会出现 ResourceWarning,提示未正确关闭数据库连接。同时 ToolRegistry 的单例模式在测试之间会相互干扰,因为其内部依赖的 DatabaseManager 也保留了全局状态。
When running the test suite, some tests (especially those involving DatabaseManager and ToolRegistry) produce ResourceWarning about unclosed database connections. Additionally, the ToolRegistry singleton interferes across tests because its internal DatabaseManager also retains global state.

修改内容 / Changes Made

  1. test_database_manager.py:在并发写入测试的每个线程中添加 finally: db.close(),确保即使发生异常也会关闭连接,避免 ResourceWarning

  2. test_tool_registry.py:在 isolate_tool_registry fixture 中导入 DatabaseManager,并在测试后调用 DatabaseManager.reset_instances(),清理所有数据库单例实例,防止状态污染。

  3. test_database_manager.py: Added finally: db.close() inside each thread of the concurrent write test, ensuring the connection is closed even if an exception occurs, eliminating ResourceWarning.

  4. test_tool_registry.py: In the isolate_tool_registry fixture, import DatabaseManager and call DatabaseManager.reset_instances() after each test, cleaning up all database singleton instances to prevent state pollution.

影响范围 / Impact

  • 减少测试运行时的警告噪音,提高日志可读性。

  • 提升测试隔离性,避免因前一个测试的残留数据或连接导致后续测试失败。

  • 不影响生产代码逻辑。

  • Reduces warning noise during test execution, improving log readability.

  • Enhances test isolation, preventing later tests from failing due to leftover connections or state from previous tests.

  • No impact on production code logic.

相关文件 / Related Files

  • tests/core/test_database_manager.py
  • tests/core/test_tool_registry.py

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions