-
Notifications
You must be signed in to change notification settings - Fork 24
Add authentication tests and GitHub Actions workflow #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
This commit introduces a test suite for the email-based authentication
endpoints (`/auth/signup/email` and `/auth/login/email`).
Key changes include:
1. **Test Implementation (`backend/tests/auth/test_auth_routes.py`):**
* Comprehensive tests covering successful registration and login.
* Tests for error scenarios: existing email, incorrect password,
non-existent user.
* Parameterized tests for invalid input validation (missing fields,
short passwords, invalid email formats) returning 422 errors.
2. **Mocking (`backend/tests/conftest.py`):**
* MongoDB Mocking: Implemented an auto-use pytest fixture (`mock_db`)
using `mongomock-motor` to simulate MongoDB interactions. This
fixture patches `app.auth.service.get_database` to ensure
`AuthService` uses the mock database during tests.
* Firebase Mocking: Added a session-scoped fixture (`mock_firebase_admin`)
to mock `firebase_admin.initialize_app`, `credentials.Certificate`,
and `auth`. This prevents actual Firebase SDK initialization, which
is not needed for these tests and might fail in CI environments.
3. **Test Configuration (`backend/pytest.ini`):**
* Created `pytest.ini` to define test-specific environment
variables (e.g., `SECRET_KEY`, `TESTING=True`).
* Configured `asyncio_mode` and test discovery patterns.
4. **Dependencies (`backend/requirements.txt`):**
* Added `pytest`, `pytest-asyncio`, `httpx`, `mongomock-motor`,
and `pytest-env` to support the testing framework and environment
configuration.
All 13 tests for the authentication routes are passing. The test setup
ensures that tests are isolated and do not depend on external services
like a live MongoDB instance or Firebase.
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughNew infrastructure for backend testing has been introduced. This includes a GitHub Actions workflow for automated test runs, pytest configuration, expanded backend test dependencies, and the addition of comprehensive authentication route tests. Test fixtures for mocking Firebase and MongoDB are also provided to enable isolated and reliable test execution. Changes
Poem
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (8)
backend/tests/conftest.py (2)
5-5: Remove unused import.The
osimport is not used in the code and should be removed.-import os # Added
54-69: Remove debug print statements for cleaner test output.The debug print statements should be removed from the production test fixtures to avoid cluttering the test output.
@pytest_asyncio.fixture(scope="function", autouse=True) async def mock_db(): - print("mock_db fixture: Creating AsyncMongoMockClient") mock_mongo_client = AsyncMongoMockClient() - print(f"mock_db fixture: mock_mongo_client type: {type(mock_mongo_client)}") mock_database_instance = mock_mongo_client["test_db"] - print(f"mock_db fixture: mock_database_instance type: {type(mock_database_instance)}, is None: {mock_database_instance is None}") # Ensure we are patching the correct target # 'app.database.get_database' is where the function is defined. # 'app.auth.service.get_database' is where it's imported and looked up by AuthService. # Patching where it's looked up can be more robust. with patch("app.auth.service.get_database", return_value=mock_database_instance) as mock_get_database_function: - print(f"mock_db fixture: Patching app.auth.service.get_database. Patched object: {mock_get_database_function}") - print(f"mock_db fixture: Patched return_value: {mock_get_database_function.return_value}, type: {type(mock_get_database_function.return_value)}") yield mock_database_instance # yield the same instance for direct use if needed - print("mock_db fixture: Restoring app.auth.service.get_database").github/workflows/run-tests.yml (2)
12-12: Remove trailing spaces.There are trailing spaces on multiple lines that should be cleaned up for better code hygiene.
runs-on: ubuntu-latest - + steps: - uses: actions/checkout@v4 - + with: python-version: '3.12' - + pip install -r requirements.txt - +Also applies to: 15-15, 20-20, 26-26
31-31: Consider running all tests instead of a specific file.The workflow currently only runs tests from
backend/tests/auth/test_auth_routes.py. Consider running all tests to ensure comprehensive coverage as the test suite grows.- pytest backend/tests/auth/test_auth_routes.py + pytest backend/tests/backend/tests/auth/test_auth_routes.py (4)
3-3: Remove unused imports.The imports for
FastAPIandsettingsare not used in the test file and should be removed for cleaner code.-from fastapi import FastAPI, status +from fastapi import status -from app.config import settings # To potentially override settings if needed, or check valuesAlso applies to: 5-5
27-27: Remove debug print statement.The debug print statement should be removed from the production test code.
- print(f"Response text for test_signup_with_email_success: {response.text}") # Print response text
107-116: Simplify conditional logic using logical OR operator.The nested if-elif statements can be simplified by combining conditions with logical OR operators for better readability.
# Specific checks for error types for Pydantic v2 - if description == "short_password" and error_type == "string_too_short": - error_found = True - break - elif description == "invalid_email" and error_type == "value_error": # Simpler check, msg gives more detail - error_found = True - break - elif "missing" in description and error_type == "missing": + if (description == "short_password" and error_type == "string_too_short") or \ + (description == "invalid_email" and error_type == "value_error") or \ + ("missing" in description and error_type == "missing"): error_found = True break
234-240: Simplify conditional logic using logical OR operator.Similar to the signup validation test, this conditional logic can be simplified.
- if description == "invalid_email_format" and error_type == "value_error": # Simpler check - error_found = True - break - elif "missing" in description and error_type == "missing": + if (description == "invalid_email_format" and error_type == "value_error") or \ + ("missing" in description and error_type == "missing"): error_found = True break
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
.github/workflows/run-tests.yml(1 hunks)backend/pytest.ini(1 hunks)backend/requirements.txt(1 hunks)backend/tests/auth/test_auth_routes.py(1 hunks)backend/tests/conftest.py(1 hunks)
🧰 Additional context used
🪛 Gitleaks (8.26.0)
backend/pytest.ini
3-3: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
🪛 actionlint (1.7.7)
.github/workflows/run-tests.yml
17-17: the runner of "actions/setup-python@v4" action is too old to run on GitHub Actions. update the action's version to fix this issue
(action)
🪛 YAMLlint (1.37.1)
.github/workflows/run-tests.yml
[error] 12-12: trailing spaces
(trailing-spaces)
[error] 15-15: trailing spaces
(trailing-spaces)
[error] 20-20: trailing spaces
(trailing-spaces)
[error] 26-26: trailing spaces
(trailing-spaces)
🪛 Ruff (0.11.9)
backend/tests/conftest.py
4-4: firebase_admin imported but unused
Remove unused import: firebase_admin
(F401)
5-5: os imported but unused
Remove unused import: os
(F401)
backend/tests/auth/test_auth_routes.py
3-3: fastapi.FastAPI imported but unused
Remove unused import: fastapi.FastAPI
(F401)
5-5: app.config.settings imported but unused
Remove unused import: app.config.settings
(F401)
107-112: Combine if branches using logical or operator
Combine if branches
(SIM114)
110-115: Combine if branches using logical or operator
Combine if branches
(SIM114)
234-239: Combine if branches using logical or operator
Combine if branches
(SIM114)
🪛 Pylint (3.3.7)
backend/tests/auth/test_auth_routes.py
[refactor] 107-115: Unnecessary "elif" after "break", remove the leading "el" from "elif"
(R1723)
[refactor] 234-239: Unnecessary "elif" after "break", remove the leading "el" from "elif"
(R1723)
🔇 Additional comments (3)
backend/pytest.ini (1)
1-14: Test configuration looks good.The pytest configuration properly sets up the test environment with appropriate settings for async testing and test discovery patterns. The hardcoded SECRET_KEY is acceptable for testing purposes and clearly marked as such.
backend/tests/conftest.py (1)
8-50: Well-designed Firebase mocking strategy.The session-scoped Firebase Admin SDK mocking is comprehensive and properly isolates external dependencies. The fixture correctly mocks all necessary Firebase components and handles cleanup appropriately.
backend/tests/auth/test_auth_routes.py (1)
18-241: Excellent test coverage and structure.The test suite provides comprehensive coverage of authentication scenarios including:
- Successful signup and login flows
- Error handling for existing users and invalid credentials
- Input validation with parametrized tests
- Proper async testing patterns
- Database interaction verification
The use of parametrized tests for validation scenarios is particularly well done, and the test isolation through mocking is properly implemented.
Introduce a test suite for email-based authentication, covering registration and login scenarios, including error handling and input validation. Implement mocking for MongoDB and Firebase to ensure tests run in isolation. Add a GitHub Actions workflow to automate the execution of these tests on pull requests and pushes.
Summary by CodeRabbit
New Features
Tests
Chores