Testing Strategy
Relevant source files
The following files were used as context for generating this wiki page:- core/tests/client/test_utcp_client.py
- plugins/communication_protocols/http/tests/test_http_communication_protocol.py
- plugins/tool_search/in_mem_embeddings/tests/test_in_mem_embeddings_search.py
- plugins/tool_search/in_mem_embeddings/tests/test_integration.py
- plugins/communication_protocols/text/tests/test_text_communication_protocol.py
- plugins/communication_protocols/http/tests/test_openapi_converter_auth.py
- plugins/communication_protocols/mcp/tests/test_mcp_http_transport.py
- README.md
The testing strategy for python-utcp is built upon a modular and comprehensive approach, leveraging pytest and its ecosystem. Due to the project's asynchronous nature, pytest-asyncio is fundamental for writing and running async tests. The strategy emphasizes unit testing of individual components in isolation and integration testing to ensure seamless operation between the core system and its various plugins.
Tests are co-located with the source code in tests subdirectories, reflecting the project's structure (e.g., core/tests/, plugins/communication_protocols/http/tests/). This ensures that each package (core and individual plugins) can be tested independently, which is crucial for a plugin-based architecture. Mocking and dependency injection are heavily used to isolate components, while live in-memory servers are employed to test communication protocols realistically.
Sources: core/README.md, core/tests/client/test_utcp_client.py, plugins/communication_protocols/http/tests/test_http_communication_protocol.py
Test Structure and Execution
The project's tests are organized to mirror its modular structure. Core functionalities are tested within core/tests, and each plugin contains its own tests directory. This allows for focused testing of a specific package or running the entire suite.
The primary tool for test execution is pytest. The following commands are used to run the tests:
- Run all tests:
python -m pytest - Run tests for the core library:
python -m pytest core/tests/ - Run tests for a specific plugin (e.g., HTTP):
python -m pytest plugins/communication_protocols/http/tests/ -v - Run tests with coverage:
python -m pytest --cov=utcp --cov-report=xml
Sources: README.md:430-447
Core Component Testing (UtcpClient)
The core UtcpClient is tested in isolation by mocking its primary dependencies: CommunicationProtocol, ConcurrentToolRepository, and ToolSearchStrategy. This is achieved by creating mock implementations of these interfaces directly within the test file.
The diagram below shows the mock classes used to test the UtcpClientImplementation.
These mocks are injected into the UtcpClient instance during tests, allowing for precise control over the behavior of its dependencies and verification of interactions. For example, when testing call_tool, the MockCommunicationProtocol can be configured to return a specific result, and the test can assert that the protocol's call_tool method was invoked with the correct arguments.
pytest-asyncio fixtures are used to provide instances of these mocks and sample data, ensuring a clean state for each test function.
# core/tests/client/test_utcp_client.py:157-161
@pytest_asyncio.fixture
async def mock_tool_repository():
"""Create a mock tool repository."""
return MockToolRepository()
Sources: core/tests/client/test_utcp_client.py:157-161
A special fixture, isolated_communication_protocols, is used to clear the global registry of CommunicationProtocol implementations before each test, preventing test leakage.
Sources: core/tests/client/test_utcp_client.py:214-216
Communication Protocol Plugin Testing
A key aspect of the testing strategy is the validation of communication protocol plugins. This is accomplished by creating live, in-memory test servers that the protocol implementation can communicate with during tests.
HTTP Protocol Testing
The utcp-http plugin tests use aiohttp.test_utils to spin up a test server with predefined routes that mimic a real UTCP provider.
An app fixture defines the server and its endpoints:
/tools: A discovery endpoint that returns aUtcpManual./tool: The endpoint for actual tool execution, which checks for authentication headers./token: An OAuth2 token endpoint.
Sources: plugins/communication_protocols/http/tests/test_http_communication_protocol.py:11-100
The following sequence diagram illustrates a typical test for calling a tool with authentication.
This approach allows for comprehensive testing of various features:
| Feature | Test Implementation | Source File |
|---|---|---|
| API Key Auth | A fixture provides a HttpCallTemplate with ApiKeyAuth. The test server validates the X-API-Key header. | test_http_communication_protocol.py:141-150 |
| Basic Auth | A fixture provides a HttpCallTemplate with BasicAuth. The test server checks for the Authorization: Basic ... header. | test_http_communication_protocol.py:153-162 |
| OAuth2 Auth | A fixture provides a HttpCallTemplate with OAuth2Auth. The protocol first calls the /token endpoint, then uses the received token to call the /tool endpoint. | test_http_communication_protocol.py:165-178 |
| Path Parameters | The URL in the HttpCallTemplate contains placeholders (e.g., /tool/{param1}). The test asserts that these are correctly substituted. | test_http_communication_protocol.py:291-304 |
| Error Handling | A dedicated /error endpoint on the test server returns an HTTP error, allowing tests to verify that the protocol correctly handles failed requests. | test_http_communication_protocol.py:192-208 |
Other Protocol Testing Patterns
The pattern of using live local services is adapted for other protocols:
- Text Protocol: Tests for the
utcp-textplugin usetempfileto create temporary files and directories. TheTextCommunicationProtocolis then tested on its ability to read these files as tool manuals or tool outputs.
Sources: plugins/communication_protocols/text/tests/test_text_communication_protocol.py:108-135 - MCP Protocol: Tests for the
utcp-mcpplugin use Python'ssubprocessmodule to launch a mock MCP server as a separate process. The test then communicates with this process over HTTP to validate the MCP transport.
Sources: plugins/communication_protocols/mcp/tests/test_mcp_http_transport.py:20-51
Tool Search Plugin Testing
Testing for non-communication plugins, like tool search strategies, is divided into unit and integration tests.
Unit Testing
Unit tests for search strategies, such as InMemEmbeddingsSearchStrategy, focus on testing the algorithm in isolation. This is done by:
- Using a
MockToolRepositoryto provide a controlled set of tools. - Using
unittest.mock.patchto mock external dependencies like the sentence-transformer embedding model. This avoids slow, non-deterministic, or network-dependent operations. - Testing specific logic, such as similarity threshold filtering, tag filtering, and result limiting.
The following flowchart shows the logic for a search test with a similarity threshold.
Integration Testing
Integration tests ensure that the plugin works correctly within the larger UTCP ecosystem. For a search plugin, this involves:
- Calling the plugin's
register()function to make it available to the core system. - Verifying that the plugin is discoverable through the core
ToolSearchStrategyConfigSerializer. - Creating an instance of the search strategy using the core serializer to confirm that configuration is handled correctly.
- Running a basic search to ensure end-to-end functionality with a real
InMemToolRepository.
# plugins/tool_search/in_mem_embeddings/tests/test_integration.py:73-85
@pytest.mark.asyncio
async def test_strategy_creation_through_core(register_plugin):
"""Test creating strategy instance through the core serialization system."""
from utcp.interfaces.tool_search_strategy import ToolSearchStrategyConfigSerializer
serializer = ToolSearchStrategyConfigSerializer()
strategy_config = {
"tool_search_strategy_type": "in_mem_embeddings",
"model_name": "all-MiniLM-L6-v2",
"similarity_threshold": 0.3
}
strategy = serializer.validate_dict(strategy_config)
Sources: plugins/tool_search/in_mem_embeddings/tests/test_integration.py:73-85
Feature-Specific Testing
Complex, self-contained features like the OpenApiConverter have their own dedicated tests. These tests validate the feature's logic by using real-world data. For example, test_openapi_converter_auth.py fetches a live OpenAPI specification from api.apis.guru, converts it to a UtcpManual, and then asserts that the resulting tools, their parameters, and their authentication methods are correctly parsed.
This approach ensures that the converter is robust enough to handle the complexities and variations of real-world API specifications.
Sources: plugins/communication_protocols/http/tests/test_openapi_converter_auth.py:12-21
Conclusion
The testing strategy for python-utcp is robust and multi-faceted, designed to ensure the reliability of both the core framework and its extensible plugins. Key pillars of the strategy include the modular separation of tests, heavy use of pytest and pytest-asyncio, dependency isolation through mocking, and realistic validation of communication protocols using live, in-memory test servers. This comprehensive approach supports independent plugin development and provides strong guarantees about the correctness and interoperability of all components within the UTCP ecosystem.
Sources: core/tests/client/test_utcp_client.py, plugins/communication_protocols/http/tests/test_http_communication_protocol.py, plugins/tool_search/in_mem_embeddings/tests/test_integration.py