Skip to content

test: increase coverage for metadata database module#1199

Open
Riddhi8077 wants to merge 7 commits intoAOSSIE-Org:mainfrom
Riddhi8077:test/metadata-coverage
Open

test: increase coverage for metadata database module#1199
Riddhi8077 wants to merge 7 commits intoAOSSIE-Org:mainfrom
Riddhi8077:test/metadata-coverage

Conversation

@Riddhi8077
Copy link

@Riddhi8077 Riddhi8077 commented Feb 26, 2026

This PR increases test coverage for the metadata database module.

Functions Covered:

  • db_create_metadata_table
  • db_get_metadata
  • db_update_metadata

Changes:

  • Added deterministic unit tests for table creation and default row insertion.
  • Covered metadata retrieval and update flows.
  • Tested update behavior using both internal and external database cursors.
  • Included JSON decoding edge case validation.
  • No production logic was modified.

Coverage:
Before: 14%
After: 88%

How to run tests:
pytest --cov=app --cov-report=term-missing

Summary by CodeRabbit

  • Tests

    • Added isolated database tests covering connection behavior, PRAGMA settings, commit/rollback semantics, connection lifecycle, and metadata lifecycle (create/read/update and handling corrupted data). Replaced the previous global shared test setup with a temporary-database fixture that scopes setup/teardown to a temp file.
  • Chores

    • Minor formatting adjustment to the repository ignore configuration.

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 26, 2026

Walkthrough

Replaced a session-scoped autouse test setup with a temp_db_path fixture that provides a temporary SQLite file and monkeypatches database paths; added new SQLite-focused tests for connection behavior and metadata; and inserted a blank line in backend/.gitignore.

Changes

Cohort / File(s) Summary
Ignore file tweak
backend/.gitignore
Inserted a single blank line between sections; no change to ignore patterns.
Test fixture replaced
backend/tests/conftest.py
Removed session-scoped autouse setup_before_all_tests; added temp_db_path(monkeypatch) fixture that creates a temp SQLite file, monkeypatches DATABASE_PATH across database modules, yields the path, and deletes the file after tests. Removed explicit global table-creation and TEST_MODE toggling.
Connection tests (new)
backend/tests/database/test_connection.py
Added tests for get_db_connection: verifies sqlite3 connection type and PRAGMA settings, commit-on-success, rollback-on-exception, and connection closure behavior; uses temp_db_path.
Metadata tests (new)
backend/tests/database/test_metadata.py
Added tests for metadata functions (db_create_metadata_table, db_get_metadata, db_update_metadata): table creation, default and updated retrieval, cursor-based updates with explicit commit, and handling of invalid JSON; uses temp DB via monkeypatch.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

Python

Poem

🐰 I nibble temp files by lamp and moon,

PRAGMAs hum softly, transactions tune,
Commits keep carrots, rollbacks set them free,
Metadata burrows snug beneath a tree,
Hops of tests — tidy, quick, and soon.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main objective of the PR: adding unit tests to increase coverage for the metadata database module.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/.gitignore`:
- Around line 7-8: Remove the duplicate ignore patterns ".coverage" and
".pytest_cache/" that were added near the top of the .gitignore; these entries
already exist later in the "Unit test / coverage reports" section, so delete the
top occurrences and leave the existing entries in that section (look for the
patterns ".coverage" and ".pytest_cache/" to locate the duplicates).

In `@backend/tests/conftest.py`:
- Around line 28-93: The four test functions
(test_connection_creation_and_pragmas, test_commit_on_success,
test_rollback_on_exception, test_connection_closed_after_context) should be
removed from conftest.py and placed into the test module that already contains
the duplicate tests (e.g., test_connection.py), leaving conftest.py to only
expose the temp_db_path fixture; ensure the temp_db_path fixture (and imports
like get_db_connection) remain in conftest.py and that the moved tests import
nothing extra (they will use the fixture from conftest.py).

In `@backend/tests/database/test_connection.py`:
- Around line 1-93: This file duplicates the temp_db_path fixture and tests
already defined elsewhere; remove the duplication by keeping a single shared
fixture and the tests in one place: delete the temp_db_path fixture from this
file and ensure the fixture named temp_db_path remains in conftest (or,
alternatively, delete this entire file and keep the tests in conftest if you
prefer); specifically, keep the test functions
test_connection_creation_and_pragmas, test_commit_on_success,
test_rollback_on_exception, and test_connection_closed_after_context in only one
location and ensure the single temp_db_path fixture is defined only once
(conftest) so tests do not run twice or shadow each other.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b270a35 and 6bcd03f.

📒 Files selected for processing (4)
  • backend/.gitignore
  • backend/tests/conftest.py
  • backend/tests/database/test_connection.py
  • backend/tests/database/test_metadata.py

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

1 similar comment
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

1 similar comment
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

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.

♻️ Duplicate comments (1)
backend/tests/database/test_connection.py (1)

9-74: ⚠️ Potential issue | 🟠 Major

Consolidate these tests into a single location to avoid duplicate execution.

backend/tests/database/test_connection.py currently duplicates the same four tests already present in backend/tests/conftest.py (see backend/tests/conftest.py:27-92). This will run the same assertions twice and increases maintenance cost. Keep these tests in one module only (preferably here) and leave only shared fixtures in conftest.py.

As per coding guidelines, "Look for code duplication."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/database/test_connection.py` around lines 9 - 74, The four
tests (test_connection_creation_and_pragmas, test_commit_on_success,
test_rollback_on_exception, test_connection_closed_after_context) are duplicated
elsewhere; remove the duplicate copies from conftest.py and keep these test
implementations only in this test_connection.py module, leaving conftest.py to
contain shared fixtures only (e.g., temp_db_path and get_db_connection provider
functions). Ensure you only remove the test function definitions from
conftest.py and not the fixture code (retaining any helper fixtures or imports
used by these tests).
🧹 Nitpick comments (1)
backend/tests/database/test_connection.py (1)

52-56: Use a specific expected exception in the rollback-path test.

At Line 52, pytest.raises(Exception) is too broad and can hide unintended failures. Use a specific exception type raised by the test trigger.

Suggested refinement
-    with pytest.raises(Exception):
+    with pytest.raises(RuntimeError, match="Force rollback"):
         with get_db_connection() as conn:
             conn.execute("CREATE TABLE test (id INTEGER);")
             conn.execute("INSERT INTO test (id) VALUES (1);")
-            raise Exception("Force rollback")
+            raise RuntimeError("Force rollback")

As per coding guidelines, "Ensure that test code is automated, comprehensive, and follows testing best practices."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/database/test_connection.py` around lines 52 - 56, The test
currently uses a broad pytest.raises(Exception) while the inner code raises a
generic Exception; change the test to use a specific exception type (e.g.,
RuntimeError) by updating the raised error in the rollback block and matching
pytest.raises(RuntimeError) so get_db_connection() rollback-path test asserts a
precise exception; update the raise "Force rollback" to raise
RuntimeError("Force rollback") and replace pytest.raises(Exception) with
pytest.raises(RuntimeError).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@backend/tests/database/test_connection.py`:
- Around line 9-74: The four tests (test_connection_creation_and_pragmas,
test_commit_on_success, test_rollback_on_exception,
test_connection_closed_after_context) are duplicated elsewhere; remove the
duplicate copies from conftest.py and keep these test implementations only in
this test_connection.py module, leaving conftest.py to contain shared fixtures
only (e.g., temp_db_path and get_db_connection provider functions). Ensure you
only remove the test function definitions from conftest.py and not the fixture
code (retaining any helper fixtures or imports used by these tests).

---

Nitpick comments:
In `@backend/tests/database/test_connection.py`:
- Around line 52-56: The test currently uses a broad pytest.raises(Exception)
while the inner code raises a generic Exception; change the test to use a
specific exception type (e.g., RuntimeError) by updating the raised error in the
rollback block and matching pytest.raises(RuntimeError) so get_db_connection()
rollback-path test asserts a precise exception; update the raise "Force
rollback" to raise RuntimeError("Force rollback") and replace
pytest.raises(Exception) with pytest.raises(RuntimeError).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a7ba929 and 676096d.

📒 Files selected for processing (1)
  • backend/tests/database/test_connection.py

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

1 similar comment
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

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.

🧹 Nitpick comments (1)
backend/tests/conftest.py (1)

18-25: Table creation order could cause confusion with foreign key relationships.

The db_create_faces_table() (line 20) and db_create_album_images_table() (line 23) reference the images table via foreign keys, but db_create_images_table() is called later at line 24. While SQLite doesn't enforce FK existence at table creation time, this ordering is counterintuitive and could lead to issues if test data insertion is added to this fixture later.

Consider reordering to create tables before their dependents:

♻️ Suggested reordering for clarity
     db_create_YOLO_classes_table()
+    db_create_folders_table()
+    db_create_images_table()
     db_create_clusters_table()
     db_create_faces_table()
-    db_create_folders_table()
     db_create_albums_table()
     db_create_album_images_table()
-    db_create_images_table()
     db_create_metadata_table()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/conftest.py` around lines 18 - 25, Reorder the table-creation
calls so parent tables are created before their dependents: move
db_create_images_table() to run before db_create_faces_table() and
db_create_album_images_table() (i.e., ensure db_create_images_table() is called
prior to db_create_faces_table() and db_create_album_images_table()); keep other
calls intact so any tables that reference images via foreign keys are created
after images to avoid confusing ordering and potential future test-data
insertion issues.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/tests/conftest.py`:
- Around line 18-25: Reorder the table-creation calls so parent tables are
created before their dependents: move db_create_images_table() to run before
db_create_faces_table() and db_create_album_images_table() (i.e., ensure
db_create_images_table() is called prior to db_create_faces_table() and
db_create_album_images_table()); keep other calls intact so any tables that
reference images via foreign keys are created after images to avoid confusing
ordering and potential future test-data insertion issues.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 676096d and c00a02d.

📒 Files selected for processing (1)
  • backend/tests/conftest.py

@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

1 similar comment
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/tests/conftest.py (1)

1-13: ⚠️ Potential issue | 🟡 Minor

Remove unused imports.

sqlite3 (line 4) and all db_create_* functions (lines 7-13) are imported but never used in this file. These appear to be leftovers from the removed setup_before_all_tests fixture.

🧹 Proposed fix
 import pytest
 import os
 import tempfile
-import sqlite3
-
-# Import database table creation functions
-from app.database.faces import db_create_faces_table
-from app.database.images import db_create_images_table
-from app.database.face_clusters import db_create_clusters_table
-from app.database.yolo_mapping import db_create_YOLO_classes_table
-from app.database.albums import db_create_albums_table, db_create_album_images_table
-from app.database.folders import db_create_folders_table
-from app.database.metadata import db_create_metadata_table
+
 
 `@pytest.fixture`
 def temp_db_path(monkeypatch):
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/conftest.py` around lines 1 - 13, Remove the unused imports in
backend/tests/conftest.py: delete the imported module symbol sqlite3 and the
unused function symbols db_create_faces_table, db_create_images_table,
db_create_clusters_table, db_create_YOLO_classes_table, db_create_albums_table,
db_create_album_images_table, db_create_folders_table, and
db_create_metadata_table so the file only imports pytest, os, and tempfile (or
whatever remaining imports are actually used).
🧹 Nitpick comments (1)
backend/tests/conftest.py (1)

48-48: Remove trailing whitespace.

Line 48 contains trailing whitespace which violates PEP 8.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/conftest.py` at line 48, Remove the trailing whitespace on line
48 of backend/tests/conftest.py (strip the extra space/whitespace character at
the end of that line) so the file conforms to PEP 8; no code logic changes are
required—just delete the trailing space and save the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@backend/tests/conftest.py`:
- Around line 1-13: Remove the unused imports in backend/tests/conftest.py:
delete the imported module symbol sqlite3 and the unused function symbols
db_create_faces_table, db_create_images_table, db_create_clusters_table,
db_create_YOLO_classes_table, db_create_albums_table,
db_create_album_images_table, db_create_folders_table, and
db_create_metadata_table so the file only imports pytest, os, and tempfile (or
whatever remaining imports are actually used).

---

Nitpick comments:
In `@backend/tests/conftest.py`:
- Line 48: Remove the trailing whitespace on line 48 of
backend/tests/conftest.py (strip the extra space/whitespace character at the end
of that line) so the file conforms to PEP 8; no code logic changes are
required—just delete the trailing space and save the file.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c00a02d and 703fe9c.

📒 Files selected for processing (1)
  • backend/tests/conftest.py

@Riddhi8077
Copy link
Author

@coderabbitai Review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 26, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 26, 2026

✅ Actions performed

Reviews resumed.

Removed unused imports and commented-out code from conftest.py.
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

1 similar comment
@github-actions
Copy link
Contributor

⚠️ No issue was linked in the PR description.
Please make sure to link an issue (e.g., 'Fixes #issue_number')

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.

🧹 Nitpick comments (1)
backend/tests/conftest.py (1)

6-36: Good refactoring — test functions properly moved out.

The fixture-only structure now follows pytest conventions. The temp_db_path fixture provides good test isolation with proper cleanup.

Two observations:

  1. raising=False silently ignores missing attributes — If a module doesn't have DATABASE_PATH, the patch will be skipped without notice. This is fine if intentional (e.g., future-proofing), but could mask configuration errors.

  2. Type hints are missing — Consider adding for consistency with Python best practices.

Optional: Add type hints
+from typing import Generator
+from pytest import MonkeyPatch
+
+
 `@pytest.fixture`
-def temp_db_path(monkeypatch):
+def temp_db_path(monkeypatch: MonkeyPatch) -> Generator[str, None, None]:
     """
     Creates a temporary SQLite database file
     and patches DATABASE_PATH in all database modules.
     """
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/tests/conftest.py` around lines 6 - 36, The temp_db_path pytest
fixture currently uses monkeypatch.setattr(..., raising=False) which silently
skips if a target module/attribute is missing; change this to raising=True (or
explicitly import each module and assert hasattr(module, "DATABASE_PATH") before
patching) so missing DATABASE_PATH attributes raise errors during tests; also
add a return type hint to the fixture signature (temp_db_path -> str or
Iterator[str] if using yield) and import the corresponding typing symbol (e.g.,
Iterator) so the fixture has explicit type annotations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@backend/tests/conftest.py`:
- Around line 6-36: The temp_db_path pytest fixture currently uses
monkeypatch.setattr(..., raising=False) which silently skips if a target
module/attribute is missing; change this to raising=True (or explicitly import
each module and assert hasattr(module, "DATABASE_PATH") before patching) so
missing DATABASE_PATH attributes raise errors during tests; also add a return
type hint to the fixture signature (temp_db_path -> str or Iterator[str] if
using yield) and import the corresponding typing symbol (e.g., Iterator) so the
fixture has explicit type annotations.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 703fe9c and 9286a63.

📒 Files selected for processing (1)
  • backend/tests/conftest.py

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.

1 participant