Skip to content

Conversation

@nishika26
Copy link
Collaborator

@nishika26 nishika26 commented Jul 10, 2025

Summary

Target issue is #274
Explain the motivation for making this change. What existing problem does the pull request solve?
Previously, our test suite used a db fixture that maintained a single long-lived session for the entire pytest session, along with a single TestClient.
This approach caused all tests to operate on the same committed database state and share the same session throughout the test run, increasing the risk of stale session state and unintended interactions between tests.
Additionally, cleanup required explicitly deleting data at the end of the session, which was cumbersome.

Checklist

Before submitting a pull request, please ensure that you mark these task.

  • Ran fastapi run --reload app/main.py or docker compose up in the repository root and test.
  • If you've fixed a bug or added code that is tested and has test cases.

Notes

  • Converted the db fixture to:

    • Use scope="function" (per-test) instead of session.

    • Open a transaction for each test and roll it back after the test finishes, ensuring a base DB for every test.

    • Now when we will have this transaction setup in place, our test data won't touch our real data. Every test runs in an isolated sandbox and rolls back at the end.

  • Add a savepoint (session.begin_nested()) at the start of each test to allow app code to safely call .commit() during tests without breaking the outer transaction.

    • Added an event listener to automatically re-establish a savepoint after every commit.
  • Kept the seed_baseline fixture at scope="session":

    • Runs only once before the first test.

    • Seeds deterministic baseline data that all tests can rely on. to understand more, check this

  • Overrode get_db in the client fixture:

    • Ensures that FastAPI’s get_db dependency returns the test’s transaction-bound session (db).

    • Without this, FastAPI routes would open their own sessions, which would not see uncommitted test data. To understand more about, check here

  • Made client, superuser_token_headers, and normal_user_token_headers function-scoped to align with the per-test db.

Summary by CodeRabbit

  • Tests
    • Improved test isolation and reliability by updating database session management for tests.
    • Changed test client and authentication fixtures to function scope for better isolation.
    • Updated test functions to use the test client fixture.
    • Introduced a new fixture to seed baseline data once per test session.

@nishika26 nishika26 self-assigned this Jul 10, 2025
@nishika26 nishika26 added the enhancement New feature or request label Jul 10, 2025
@nishika26 nishika26 moved this to In Progress in Dev Priorities Jul 10, 2025
@nishika26 nishika26 linked an issue Jul 10, 2025 that may be closed by this pull request
@codecov
Copy link

codecov bot commented Jul 10, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

📢 Thoughts on this report? Let us know!

@nishika26 nishika26 marked this pull request as ready for review July 10, 2025 10:00
@nishika26 nishika26 requested a review from vijay-T4D July 10, 2025 10:01
@fatchat
Copy link

fatchat commented Jul 11, 2025

@coderabbitai

@coderabbitai
Copy link

coderabbitai bot commented Jul 11, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get information about the current PR to understand the context
gh pr view 278 --json title,body,author,state,files,additions,deletions,commits

# Also check what files were modified in this PR
gh pr diff 278 --name-only

Length of output: 4253


@fatchat Hello! I see you've tagged me on PR #278 which introduces per-test database transactions for proper test isolation and rollback. This looks like a significant improvement to the testing infrastructure!

The codecov report shows excellent coverage - all modified lines are covered by tests, which is great to see for testing infrastructure changes.

How can I help you with this PR? Would you like me to:

  • Review the specific changes in the test configuration
  • Analyze the testing approach and provide feedback
  • Help with any questions about the transaction-based testing setup
  • Something else?

Just let me know what you need assistance with!

@coderabbitai
Copy link

coderabbitai bot commented Jul 11, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@fatchat I see you've tagged me again! I'm ready to help with PR #278.

Could you please let me know what specific assistance you need? For example:

  • Would you like me to review the database transaction setup in the test files?
  • Do you need help with any specific test configuration or implementation?
  • Are there any particular files or changes you'd like me to analyze?
  • Do you have questions about the testing approach or best practices?

Just let me know what you'd like me to focus on and I'll provide detailed assistance!


🏁 Script executed:

#!/bin/bash
# Get detailed information about the current PR
gh pr view 278 --json title,body,author,state,files,additions,deletions,commits,reviews

# Check the current status and any recent activity
gh pr checks 278

# Get the actual diff to understand what changes were made
gh pr diff 278

Length of output: 9186


@fatchat Great! I've reviewed the changes in PR #278. This is an excellent improvement to your testing infrastructure! Let me break down what I see:

🎯 Key Improvements

1. Per-Test Transaction Isolation

  • Changed db fixture from scope="session" to scope="function"
  • Each test now runs in its own transaction that rolls back automatically
  • This eliminates test interference and ensures clean state for each test

2. Smart Savepoint Management

nested = session.begin_nested()

@event.listens_for(session, "after_transaction_end")
def restart_savepoint(sess, trans):
    if trans.nested and not trans._parent.nested:
        sess.begin_nested()

This is particularly clever - it allows your application code to call .commit() during tests without breaking the outer transaction.

3. Baseline Data Seeding

  • Separated seeding into a session-scoped seed_baseline fixture
  • Seeds deterministic data once before all tests run
  • Tests can rely on this baseline data being available

4. Dependency Override

app.dependency_overrides[get_db] = lambda: db

This ensures FastAPI uses the test's transaction-bound session instead of opening new connections.

Benefits

  • True Test Isolation: No more shared state between tests
  • Faster Cleanup: No need to manually delete data
  • Reliable Results: Tests can't interfere with each other
  • Realistic Testing: App code can commit normally during tests

🤔 Considerations

The implementation looks solid overall. The only thing to watch for is ensuring that any tests requiring committed data (like testing background tasks that query the database) work correctly with this setup.

🔍 Minor Note

In the test file, you added client: TestClient parameters to functions that don't seem to use the client directly. This ensures the fixture dependency chain is properly established, which is good practice.

Is there anything specific about this testing setup you'd like me to dive deeper into or any questions about the implementation?

@nishika26 nishika26 changed the title Testing: Per test db transaction for proper teadown/rollback Testing: Per test db transaction for proper rollback Jul 11, 2025
@AkhileshNegi AkhileshNegi changed the title Testing: Per test db transaction for proper rollback Testcases: Using DB Transactions Jul 12, 2025
@coderabbitai
Copy link

coderabbitai bot commented Jul 12, 2025

Walkthrough

Test fixtures in the FastAPI backend were refactored to use transactional savepoints for improved test isolation. Fixture scopes for db, client, and authentication headers were changed to function-level. Tests were updated to accept the client fixture, and database seeding was moved to a new session-scoped fixture.

Changes

File(s) Change Summary
backend/app/tests/conftest.py Refactored fixtures for transactional test isolation; changed fixture scopes; added seed_baseline fixture; removed manual cleanup and unused fixtures.
backend/app/tests/api/routes/collections/test_collection_info.py Updated test functions to accept client: TestClient as a parameter for HTTP requests.

Poem

In the warren of tests, a change was made,
With transactions nested, old worries fade.
Fixtures now scoped to function, not all,
Each test hops alone, no data to sprawl.
The client arrives, with a session so neat—
A rabbit’s delight: isolation complete! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@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: 0

🔭 Outside diff range comments (1)
backend/app/tests/api/routes/collections/test_collection_info.py (1)

11-11: Critical: Remove module-level client and use the fixture parameter.

The module-level client on line 11 bypasses the transactional testing setup. Test functions receive the proper client fixture but continue using the module-level instance, which doesn't have the get_db dependency override.

Remove the module-level client:

-client = TestClient(app)
-
 original_api_key = "ApiKey No3x47A5qoIGhm0kVKjQ77dhCqEdWRIQZlEPzzzh7i8"

The test functions already receive the correct client parameter from the fixture and will use it automatically since there's no module-level variable shadowing it.

Also applies to: 41-98

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

17-35: Excellent implementation of transactional test isolation!

The nested transaction approach with automatic savepoint re-establishment is a robust solution that allows application code to commit normally while maintaining test isolation.

Regarding the static analysis hint about the unused nested variable on line 23: This is a false positive. The variable starts the nested transaction which remains active throughout the test. Consider adding a comment to clarify this for future maintainers.

 def db() -> Generator[Session, None, None]:
     connection = engine.connect()
     transaction = connection.begin()
     session = Session(bind=connection)
 
-    nested = session.begin_nested()
+    # Start nested transaction - variable not referenced but transaction remains active
+    nested = session.begin_nested()
 
     @event.listens_for(session, "after_transaction_end")
     def restart_savepoint(sess, trans):
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1b6c7fa and aa94be1.

📒 Files selected for processing (2)
  • backend/app/tests/api/routes/collections/test_collection_info.py (3 hunks)
  • backend/app/tests/conftest.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.11.9)
backend/app/tests/conftest.py

23-23: Local variable nested is assigned to but never used

Remove assignment to unused variable nested

(F841)

🔇 Additional comments (2)
backend/app/tests/conftest.py (2)

38-42: Well-designed baseline data seeding approach.

Moving the seeding to a separate session-scoped fixture ensures deterministic baseline data is available for all tests while keeping it separate from the per-test transactional sessions.


45-49: Correct alignment of client fixture with transactional testing.

The function-scoped client properly integrates with the transactional db fixture by overriding the get_db dependency, ensuring routes see the test's uncommitted data.

@AkhileshNegi AkhileshNegi merged commit ae40f00 into main Jul 14, 2025
3 checks passed
@AkhileshNegi AkhileshNegi deleted the enhancement/transactional_db branch July 14, 2025 06:37
@github-project-automation github-project-automation bot moved this from In Progress to Closed in Dev Priorities Jul 14, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jul 22, 2025
2 tasks
@coderabbitai coderabbitai bot mentioned this pull request Jul 24, 2025
2 tasks
@coderabbitai coderabbitai bot mentioned this pull request Aug 8, 2025
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request on hold

Projects

Status: Closed

Development

Successfully merging this pull request may close these issues.

Testing: Proper db rollback/teardown in place

4 participants