Skip to content

Testing

Max Azatian edited this page Oct 5, 2024 · 1 revision

Test Structure

Tests are organized into two main categories:

  1. Unit Tests: Located in chat_service/app/tests/unit/
  2. Integration Tests: Located in chat_service/app/tests/integration/

Backend Tests

Unit Tests

Unit tests focus on testing individual components in isolation. Key unit test files include:

  • test_database.py: Tests database connection and operations
  • test_event_dispatcher.py: Verifies event dispatching mechanism
  • test_event_handlers.py: Checks event handler functionality
  • test_models.py: Ensures ORM models are correctly defined
  • test_redis_client.py: Tests Redis client operations
  • test_security.py: Verifies security-related utilities (e.g., password hashing)
  • test_unit_of_work.py: Tests the Unit of Work pattern implementation

Integration Tests

Integration tests verify the interaction between different components and the API endpoints. Key integration test files include:

  • test_auth.py: Tests authentication-related endpoints
  • test_chats.py: Verifies chat-related API functionality
  • test_messages.py: Checks message-related API endpoints
  • test_users.py: Tests user-related API operations

Test Configuration

  • conftest.py: Contains pytest fixtures and configuration for the test suite
  • pytest.ini: Pytest configuration file

Running Tests

To run the backend tests, navigate to the chat_service directory and execute:

pytest

This will run all unit and integration tests. To run specific test categories:

  • For unit tests only: pytest app/tests/unit
  • For integration tests only: pytest app/tests/integration

Continuous Integration

GitHub Actions are used for continuous integration. The workflow is defined in .github/workflows/tests.yml. This workflow:

  1. Sets up the Python environment
  2. Installs dependencies
  3. Runs the test suite
  4. Reports test coverage

Test Coverage

I use pytest-cov to measure test coverage. To generate a coverage report:

pytest --cov=app --cov-report=html

This command will create an HTML coverage report in the htmlcov directory.

Writing New Tests

When adding new features or modifying existing ones:

  1. Always add or update corresponding unit tests
  2. For API changes, update or add new integration tests
  3. Aim for high test coverage, especially for critical paths
  4. Use pytest fixtures to set up test data and dependencies
  5. Mock external services and dependencies in unit tests

Clone this wiki locally