Unit Testing with Pytest
Relevant source files
The following files were used as context for generating this wiki page:
The unit testing framework in GentelmeN-CorE is designed to validate the core logic of the bot, including database interactions, third-party API integrations, and command handling. By utilizing pytest alongside the standard unittest library and extensive mocking, the project ensures that individual components function correctly in isolation without requiring active connections to external services like Telegram, KuCoin, or Hugging Face.
The test suite serves as a critical quality assurance tool, covering edge cases such as network failures, missing API tokens, and unauthorized access attempts. Developers can execute the tests using the command python -m pytest tests/ -v to get a verbose output of the validation process.
Sources: tests/test_commands.py:1-6, requirements.txt:6
Test Architecture and Components
The testing infrastructure relies on mocking external dependencies to simulate real-world scenarios. This is primarily achieved through the unittest.mock module, which allows the replacement of complex objects like the Telegram bot instance or API clients with MagicMock objects.
Core Testing Modules
The test suite is organized into sections mirroring the project's internal structure:
- Helpers: Validates message delivery logic and parameter forwarding.
- Database: Ensures table initialization, data caching, and graceful failure handling when the database is unavailable.
- Integrations: Tests the logic for interacting with Brave Search and Hugging Face image generation.
- Commands: Validates bot commands, authorization checks, and voice message processing.
Sources: tests/test_commands.py:14-386
Mocking Strategy
The project uses decorators like @patch to intercept calls to external libraries such as requests, psycopg2, and tempfile.
This diagram illustrates how the Test Suite isolates logic by replacing real external services with controlled Mocks.
Sources: tests/test_commands.py:46-51, tests/test_commands.py:126-130
Testing Database Operations
The TestInitDb, TestGetUserData, and TestUpdateUserDb classes verify that the bot interacts correctly with the PostgreSQL backend. The tests ensure that the system defaults to sensible values (e.g., English language and specific AI models) if the database connection fails or if a user is not found.
| Test Case | Objective | Expected Behavior |
|---|---|---|
test_no_db_url_returns_immediately | Check behavior without DATABASE_URL | Function exits without raising exceptions |
test_returns_cached_values | Verify local cache performance | Data is retrieved from user_prefs dict before DB |
test_db_error_returns_defaults | Handle connection loss | Returns 'EN' and 'llama-3.3-70b-versatile' |
Sources: tests/test_commands.py:46-121, core/database.py:34-71
Integration and API Testing
Testing for integrations.py focuses on handling diverse API responses, including successful data retrieval, HTTP errors, and timeouts.
Image Generation and Search
The TestGenerateImageHf class simulates Hugging Face API interactions. It tests successful PNG byte returns and various failure modes like a missing HF_TOKEN or a 503 Service Unavailable status.
This sequence shows the flow of a successful image generation test using a mocked POST request.
Sources: tests/test_commands.py:151-196, core/integrations.py:28-51
Command and Authorization Testing
The TestCheckBalance and TestHandleVoice classes are critical for verifying security and complex workflows.
Authorization Logic
Tests verify that sensitive commands like /balance are restricted based on the OWNER_USER_ID environment variable or a fallback username check.
- Authorized: If the
user_idmatchesOWNER_USER_ID, access is granted. - Unauthorized: If credentials do not match, the bot replies with "Brak dostępu" (Access Denied).
Sources: tests/test_commands.py:205-257, core/commands.py:82-99
Voice Processing Workflow
The handle_voice test validates the temporary file lifecycle and routing. It ensures that voice transcriptions starting with "rysuj" are correctly routed to the image generation logic.
Logic flow for testing voice command processing and automatic cleanup of temporary files.
Sources: tests/test_commands.py:280-345, core/commands.py:209-241
Summary of Testing Utilities
The project defines a utility function _make_message within the test suite to quickly generate mock Telegram message objects with configurable parameters like user_id, chat_id, and text. This streamlines the setup phase for command tests.
Sources: tests/test_commands.py:198-206