-
Notifications
You must be signed in to change notification settings - Fork 4
feat: Add automatic mock user initialization at startup #480
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
🚀 Development Environment OptionsThis repository supports Dev Containers for a consistent development environment. Option 1: GitHub Codespaces (Recommended)Create a cloud-based development environment:
Option 2: VS Code Dev Containers (Local)Use Dev Containers on your local machine:
Option 3: Traditional Local SetupSet up the development environment manually: # Clone the repository
git clone https://github.com/manavgup/rag_modulo.git
cd rag_modulo
git checkout feature/mock-user-auto-initialization
# Initialize development environment
make dev-init
make dev-build
make dev-up
make dev-validateAvailable CommandsOnce in your development environment: make help # Show all available commands
make dev-validate # Validate environment setup
make test-atomic # Run atomic tests
make test-unit # Run unit tests
make lint # Run lintingServices AvailableWhen running
This automated message helps reviewers quickly set up the development environment. |
PR Review: Automatic Mock User Initialization at StartupI've reviewed PR #480 and have the following feedback: ✅ Strengths1. Excellent Problem-Solution FitThe feature addresses a real developer pain point - manual script execution after database wipes is eliminated. The automatic initialization on startup is the right approach. 2. Clean Architecture
3. Comprehensive DocumentationThe new
4. Graceful Error Handling
5. Backward CompatibilityThe manual
|
| Component | Test Status | Files |
|---|---|---|
initialize_default_users() |
❌ 0% | None found |
ensure_mock_user_exists() |
✅ Indirect | e2e tests only |
create_mock_user.py |
❌ 0% | Script not tested |
| Provider initialization | ✅ 100% | unit + integration |
🔒 Security Assessment
✅ Safe Practices
- Only activates when
SKIP_AUTH=true - Uses existing
ensure_mock_user_exists()(battle-tested) - No hardcoded credentials added
- Proper settings-based configuration
⚠️ Potential Risks
- No validation that
SKIP_AUTHis actually false in production - Could be exploited if environment misconfigured
- No audit logging of mock user creation
💡 Recommendations
- Add startup check that fails fast if
SKIP_AUTH=trueANDENVIRONMENT=production - Add audit log entry when mock users are created
- Consider adding metric/telemetry for monitoring
🎯 Recommendations Summary
Must Fix (Before Merge)
- ✅ Add unit tests for
initialize_default_users()(5 test cases minimum) - ✅ Move import to module level (line 106 → line 10)
- ✅ Update PR description to mention provider update fix
Should Fix (Nice to Have)
- 📝 Improve logging in
main.pyfor better observability - 📝 Add security note to documentation
- 🔒 Add production environment check
Could Fix (Future Enhancement)
- 🧪 Add integration test for full startup flow
- 📊 Add telemetry/metrics for mock user creation
📝 Style & Convention Compliance
Per CLAUDE.md:
- ✅ Service-based architecture
- ✅ Type hints present
- ✅ Async/await not needed (sync operation)
- ✅ Error handling with custom exceptions
- ❌ Tests missing (violates policy)
- ✅ 120 char line length
⚠️ Import organization needs improvement
🎭 Overall Assessment
Code Quality: 7/10
Test Coverage: 2/10 (critical gap)
Documentation: 9/10 (excellent!)
Architecture: 8/10
Security: 7/10
Recommendation: REQUEST CHANGES
The feature is well-designed and solves a real problem, but lacks test coverage for the core new functionality. The import organization issue should also be fixed.
Once tests are added, this will be a great addition to the codebase. The documentation is exemplary!
🤖 Generated with Claude Code
Co-Authored-By: Claude noreply@anthropic.com
Implements automatic mock user creation during application startup when SKIP_AUTH=true, eliminating need for manual script execution after database wipes. Problem: - Database wipes required manual mock user creation - Developers had to remember to run create_mock_user.py - Inconsistent development environment setup - Lost productivity waiting for manual steps Solution: - Added SystemInitializationService.initialize_default_users() - Called automatically during backend startup (main.py lifespan) - Follows same pattern as provider/model initialization - Only creates mock user when SKIP_AUTH=true (development mode) Implementation: 1. system_initialization_service.py: - New method: initialize_default_users() - Checks SKIP_AUTH setting - Calls ensure_mock_user_exists() if enabled - Graceful error handling with logging 2. main.py: - Calls initialize_default_users() after provider init - Part of application lifespan startup sequence - Logs success/failure 3. create_mock_user.py: - Manual script for edge cases - Useful for testing/debugging - Documents mock user configuration - Fixed Ruff linting: uses contextlib.suppress 4. database-management-scripts.md: - Comprehensive documentation - Usage examples - Troubleshooting guide Benefits: - Zero manual steps after database wipes - Consistent mock user across all developers - Automatic recovery from database resets - Better developer experience Files Changed: - backend/rag_solution/services/system_initialization_service.py - backend/main.py - backend/scripts/create_mock_user.py - docs/development/database-management-scripts.md Testing: - Tested with database wipe + restart - Mock user auto-created on startup - No manual intervention required 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
442b48b to
0d015e8
Compare
Code Review - PR #480: Automatic Mock User InitializationOverviewThis PR adds automatic mock user creation during backend startup when ✅ Strengths1. Excellent Architecture & Consistency
2. Code Quality
3. Backward Compatibility
4. Developer Experience
🔍 Observations & Suggestions1. Missing Test Coverage
|
After rebasing on main which includes PR #482 (Provider type safety fix), the code now passes LLMProviderUpdate Pydantic model instead of dict to update_provider(). Updated test expectations accordingly. Fixes unit test failure in CI.
Code Review - PR #480: Automatic Mock User InitializationSummaryThis PR implements automatic mock user creation during application startup when ✅ Strengths1. Excellent Design Pattern
2. Robust Error Handlingdef initialize_default_users(self, raise_on_error: bool = False) -> bool:
try:
# ... implementation
return True
except Exception as e:
logger.error(f"Error initializing default users: {e!s}")
if raise_on_error:
raise
return False
3. Smart Conditional Logic
4. Comprehensive Documentation
5. Test Updates
|
Addresses Priority 1 and Priority 2 issues from code review: ## Priority 1 - Documentation Mismatch (FIXED) - Removed database-management-scripts.md from this PR - Documentation referenced wipe_database.py and restore_database.py which are in PR #481, not this PR - Eliminates confusion and keeps PRs focused ## Priority 2 - Startup Logging (FIXED) - Updated main.py to check return value of initialize_default_users() - Uses raise_on_error=True for consistency with provider initialization - Logs accurate success/failure status instead of unconditional message - Follows same pattern as provider initialization (backend/main.py:153-157) ## Priority 2 - Unit Test Coverage (FIXED) - Added 4 comprehensive unit tests for initialize_default_users(): * test_initialize_default_users_skip_auth_true - Creates user when SKIP_AUTH=true * test_initialize_default_users_skip_auth_false - Skips when SKIP_AUTH=false * test_initialize_default_users_error_no_raise - Graceful error handling * test_initialize_default_users_error_with_raise - Raises when requested - All tests pass locally (4/4) - Patches core.mock_auth.ensure_mock_user_exists correctly ## Test Results All new tests passing: - test_initialize_default_users_skip_auth_true PASSED - test_initialize_default_users_skip_auth_false PASSED - test_initialize_default_users_error_no_raise PASSED - test_initialize_default_users_error_with_raise PASSED Addresses review comment: #480 (comment)
Code Review - PR #480: Automatic Mock User Initialization✅ Overall AssessmentThis is a high-quality PR that successfully automates mock user creation during application startup. The implementation is clean, well-tested, and follows the project's established patterns. Great work! 🎯 Strengths
🔍 Minor Issues & Suggestions1. Dynamic Import Concern (Low Priority)Location: from core.mock_auth import ensure_mock_user_existsIssue: Dynamic import inside the method may surprise future maintainers. Suggestion: Consider importing at the top with other imports: from core.mock_auth import ensure_mock_user_existsThen use it conditionally: if self.settings.skip_auth:
logger.info("Initializing mock user for development (SKIP_AUTH=true)")
user_id = ensure_mock_user_exists(self.db, self.settings)Rationale:
2. Startup Failure Behavior (Medium Priority)Location: Current Behavior: success = system_init_service.initialize_default_users(raise_on_error=True)
if success:
logger.info("Default users initialized successfully")
else:
logger.warning("Default users initialization skipped or failed")Issue: With
It never returns Suggestion: try:
system_init_service.initialize_default_users(raise_on_error=True)
logger.info("Default users initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize default users: {e}")
# Let the outer exception handler catch this
raiseOR change to success = system_init_service.initialize_default_users(raise_on_error=False)
if not success and settings.skip_auth:
logger.warning("Mock user creation failed in SKIP_AUTH mode")Question: Should mock user creation failure be fatal in development mode? Current behavior with 3. Test Coverage Gap (Low Priority)The unit tests properly mock
Example: def test_startup_creates_mock_user_integration(db_session, test_settings):
"""Test that application startup creates mock user in database."""
test_settings.skip_auth = True
service = SystemInitializationService(db_session, test_settings)
result = service.initialize_default_users(raise_on_error=False)
assert result is True
# Verify user exists in database
user_service = UserService(db_session, test_settings)
user = user_service.user_repository.get_by_email(test_settings.mock_user_email)
assert user is not None
assert user.email == test_settings.mock_user_email4. Documentation Enhancement (Low Priority)The
🔒 Security Considerations✅ No Security Issues Detected
⚡ Performance Considerations✅ Negligible Performance Impact
🧪 Testing RecommendationsRun these commands to validate: # Unit tests (should pass)
make test testfile=backend/tests/unit/test_system_initialization_service_unit.py
# Full test suite
make unit-tests
# Manual validation
docker compose down -v # Wipe database
SKIP_AUTH=true make run-app # Should auto-create mock user
# Check logs for: "Mock user initialized successfully"📋 Checklist Before Merge
🎖️ RecommendationAPPROVE with minor suggestions - This PR is ready to merge. The suggestions above are optional improvements that don't block merging. The implementation solves a real developer pain point (manual user creation after DB wipes) with minimal code and follows established patterns. The test coverage is solid, and the feature is well-isolated to development mode. Great job! 🚀 |
Summary
Implements automatic mock user creation during application startup when
SKIP_AUTH=true, eliminating manual script execution after database wipes.Problem
After database wipes, developers had to manually:
create_mock_user.pySolution
✅ Added
SystemInitializationService.initialize_default_users()✅ Called automatically during backend startup (main.py lifespan)
✅ Follows same pattern as provider/model initialization
✅ Only creates mock user when
SKIP_AUTH=true(development mode)Implementation Details
1. system_initialization_service.py
initialize_default_users()SKIP_AUTHsettingensure_mock_user_exists()if enabled2. main.py
initialize_default_users()after provider initialization3. create_mock_user.py
contextlib.suppress(Ruff linting fix)4. database-management-scripts.md
Benefits
Files Changed
backend/rag_solution/services/system_initialization_service.pybackend/main.pybackend/scripts/create_mock_user.pydocs/development/database-management-scripts.mdTesting
Type
🤖 Generated with Claude Code