Skip to content

Conversation

@omertuc
Copy link
Contributor

@omertuc omertuc commented Oct 8, 2025

Description

The coverage on this file was poor, adding some unit-tests to improve it.

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement

Related Tickets & Documents

  • Related Issue #
  • Closes #
    LCORE-519

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

  • Tests
    • Added a comprehensive unit test suite for the database layer covering engine/session setup, table creation, SQLite and PostgreSQL configurations (including certificate handling), error paths, and debug/logging scenarios. Strengthens reliability and guards against regressions. No user-facing changes.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 8, 2025

Walkthrough

Adds a new unit test module for app.database that validates engine/session initialization, table creation, SQLite/Postgres engine construction (including CA cert and schema handling), and the initialize_database control flow using fixtures and mocks.

Changes

Cohort / File(s) Summary
Database unit tests
tests/unit/app/test_database.py
New test suite covering global DB state reset/restore, get_engine/get_session behavior for initialized/uninitialized states, create_tables with/without engine, _create_sqlite_engine directory and error cases, _create_postgres_engine with default/custom schemas and CA cert handling, and initialize_database workflows for SQLite and PostgreSQL with mocks and error-path assertions.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor TestRunner
  participant Config
  participant DB as app.database
  participant FS as Filesystem
  participant SA as SQLAlchemy
  participant PG as Postgres

  TestRunner->>DB: initialize_database(config)
  DB->>Config: inspect db.type, url, options
  alt sqlite
    DB->>FS: ensure DB file directory exists
    FS-->>DB: ok / error
    DB->>SA: create_engine(sqlite://..., connect_args)
    SA-->>DB: Engine / error
  else postgres
    DB->>SA: create_engine(postgres://..., ssl options)
    SA-->>DB: Engine / error
    DB->>SA: engine.connect()
    SA-->>DB: Connection / error
    DB->>PG: set search_path / create schema (if requested)
    PG-->>DB: ok / error
  end
  DB->>SA: sessionmaker(bind=engine)
  SA-->>DB: SessionFactory
  DB-->>TestRunner: (engine, SessionLocal) or raise on failure
  note over TestRunner,DB: Tests assert calls, return values, call counts, and error handling
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I twitch my whiskers at mocked delights,
Paws pat engines through sleepless nights—
Schemas spring, certs snugly kept,
Sessions wake while errors slept.
Hop, test, hop—this warren's blessed! 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly summarizes the main change of this pull request by stating that unit tests are being added for database.py and references the relevant ticket number. It is concise, specific, and directly related to the changeset without extraneous detail or vague wording. This makes it easy for reviewers and future readers to quickly understand the primary intent of the PR.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10b9822 and 01d700f.

📒 Files selected for processing (1)
  • tests/unit/app/test_database.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/unit/app/test_database.py
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build-pr
  • GitHub Check: e2e_tests (ci)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 44435d2 and 10b9822.

📒 Files selected for processing (1)
  • tests/unit/app/test_database.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: All modules start with descriptive module-level docstrings explaining purpose
Use logger = logging.getLogger(name) for module logging after import logging
Define type aliases at module level for clarity
All functions require docstrings with brief descriptions
Provide complete type annotations for all function parameters and return types
Use typing_extensions.Self in model validators where appropriate
Use modern union syntax (str | int) and Optional[T] or T | None consistently
Function names use snake_case with descriptive, action-oriented prefixes (get_, validate_, check_)
Avoid in-place parameter modification; return new data structures instead of mutating arguments
Use appropriate logging levels: debug, info, warning, error with clear messages
All classes require descriptive docstrings explaining purpose
Class names use PascalCase with conventional suffixes (Configuration, Error/Exception, Resolver, Interface)
Abstract base classes should use abc.ABC and @AbstractMethod for interfaces
Provide complete type annotations for all class attributes
Follow Google Python docstring style for modules, classes, and functions, including Args, Returns, Raises, Attributes sections as needed

Files:

  • tests/unit/app/test_database.py
tests/{unit,integration}/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

tests/{unit,integration}/**/*.py: Use pytest for all unit and integration tests
Do not use unittest in tests; pytest is the standard

Files:

  • tests/unit/app/test_database.py
tests/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

tests/**/*.py: Use pytest-mock to create AsyncMock objects for async interactions in tests
Use the shared auth mock constant: MOCK_AUTH = ("mock_user_id", "mock_username", False, "mock_token") in tests

Files:

  • tests/unit/app/test_database.py
🧬 Code graph analysis (1)
tests/unit/app/test_database.py (3)
src/models/config.py (4)
  • config (139-145)
  • SQLiteDatabaseConfiguration (74-77)
  • PostgreSQLDatabaseConfiguration (86-104)
  • db_type (130-136)
src/app/database.py (6)
  • get_engine (20-26)
  • get_session (34-40)
  • create_tables (29-31)
  • _create_sqlite_engine (43-54)
  • _create_postgres_engine (57-98)
  • initialize_database (101-129)
src/configuration.py (1)
  • database_configuration (140-144)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: e2e_tests (ci)
  • GitHub Check: build-pr
🔇 Additional comments (7)
tests/unit/app/test_database.py (7)

1-14: LGTM!

The module docstring is clear, and the imports are appropriate for comprehensive unit testing. The pylint directive appropriately allows testing of protected methods.


46-64: LGTM!

The test cases properly cover both the initialized and uninitialized states with clear assertions.


66-87: LGTM!

The test cases correctly handle both states, and the mock setup properly simulates SessionLocal as a session factory.


89-111: LGTM!

The test cases properly mock dependencies and verify both successful table creation and error handling when the engine is not initialized.


113-146: LGTM!

The test suite comprehensively covers the SQLite engine creation: successful creation with a real engine, directory validation, and error handling. The use of temporary directories is appropriate.


148-237: LGTM!

Comprehensive test coverage for PostgreSQL engine creation, including default/custom schemas, CA certificate handling, and all error paths. The tests properly verify URL construction, connection arguments, and schema creation logic.


239-337: LGTM!

The test suite effectively covers database initialization for both SQLite and PostgreSQL. The helper methods reduce duplication, and the tests properly verify debug mode behavior (affecting the echo parameter), engine creation calls, and sessionmaker configuration.

Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please use pytest Mocker, not unittests.mock

See https://issues.redhat.com/browse/LCORE-417 that should fix all existing tests.

TY in advance!

The coverage on this file was poor, adding some unit-tests to improve
it.
Copy link
Contributor

@tisnik tisnik left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@tisnik tisnik merged commit 60fcbce into lightspeed-core:main Oct 9, 2025
18 of 19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants