-
Notifications
You must be signed in to change notification settings - Fork 29
test: add pytest framework and initial test cases #18
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
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
39a2a93
test: add pytest framework and initial test cases
SparkZou 42d4988
Merge branch 'main' into feature/1205-testing-framework
SparkZou 8f2abfd
fix: address PR review feedback for testing framework
SparkZou aa6f55a
refactor: use subprocess isolation for env validation tests
SparkZou f626b6b
fix: address Copilot review feedback for test improvements
SparkZou File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| """Pytest configuration and fixtures.""" | ||
|
|
||
| import os | ||
|
|
||
| import pytest | ||
|
|
||
|
|
||
| @pytest.fixture(scope="session", autouse=True) | ||
| def setup_test_env(): | ||
| """Set up test environment variables for all tests.""" | ||
| os.environ["OPENAI_API_KEY"] = "test-key-for-testing" | ||
| # Use PostgreSQL from docker-compose for testing | ||
| # Default credentials match docker-compose.yml defaults | ||
| # Note: Port 54320 is the host-mapped port from docker compose | ||
| os.environ["DATABASE_URL"] = "postgresql+psycopg://postgres:postgres@localhost:54320/memu" | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| """Test environment variable validation using subprocess isolation. | ||
|
|
||
| This module uses subprocess isolation to test module-level initialization errors. | ||
| This approach avoids issues with shared module state and ensures clean test isolation. | ||
| """ | ||
|
|
||
| import subprocess | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| # Project root directory (parent of tests/) | ||
| PROJECT_ROOT = Path(__file__).parent.parent | ||
|
|
||
|
|
||
| def _run_import_test(env_vars: dict[str, str], remove_vars: list[str] | None = None) -> subprocess.CompletedProcess: | ||
| """ | ||
| Run a subprocess that attempts to import app.main with specified environment. | ||
|
|
||
| Args: | ||
| env_vars: Environment variables to set | ||
| remove_vars: Environment variables to remove (if any) | ||
|
|
||
| Returns: | ||
| CompletedProcess with returncode, stdout, and stderr | ||
| """ | ||
| import os | ||
|
|
||
| # Start with a clean environment based on current env | ||
| env = os.environ.copy() | ||
|
|
||
| # Remove specified variables | ||
| if remove_vars: | ||
| for var in remove_vars: | ||
| env.pop(var, None) | ||
|
|
||
| # Set specified variables | ||
| env.update(env_vars) | ||
|
|
||
| # Run Python subprocess that imports app.main | ||
| result = subprocess.run( | ||
| [sys.executable, "-c", "from app.main import app; print(app.title)"], | ||
| env=env, | ||
| capture_output=True, | ||
| text=True, | ||
| cwd=str(PROJECT_ROOT), | ||
| timeout=30, # Prevent tests from hanging indefinitely | ||
| ) | ||
| return result | ||
|
|
||
|
|
||
| def test_app_requires_openai_api_key(): | ||
| """Test that app refuses to start when OPENAI_API_KEY is not set.""" | ||
| result = _run_import_test( | ||
| env_vars={ | ||
| "DATABASE_URL": "postgresql+psycopg://test:test@localhost:5432/test", | ||
| }, | ||
| remove_vars=["OPENAI_API_KEY"], | ||
| ) | ||
|
|
||
| assert result.returncode != 0 | ||
| assert "OPENAI_API_KEY environment variable is not set or is empty" in result.stderr | ||
|
|
||
|
|
||
| def test_app_refuses_empty_openai_api_key(): | ||
| """Test that app refuses to start when OPENAI_API_KEY is empty.""" | ||
| result = _run_import_test( | ||
| env_vars={ | ||
| "OPENAI_API_KEY": "", | ||
| "DATABASE_URL": "postgresql+psycopg://test:test@localhost:5432/test", | ||
| }, | ||
| ) | ||
|
|
||
| assert result.returncode != 0 | ||
| assert "OPENAI_API_KEY environment variable is not set or is empty" in result.stderr | ||
|
SparkZou marked this conversation as resolved.
|
||
|
|
||
|
|
||
| def test_app_requires_database_url(): | ||
| """Test that app refuses to start when DATABASE_URL is not set.""" | ||
| result = _run_import_test( | ||
| env_vars={ | ||
| "OPENAI_API_KEY": "test-key", | ||
| }, | ||
| remove_vars=["DATABASE_URL", "DATABASE_HOST", "DATABASE_USER", "DATABASE_PASSWORD", "DATABASE_NAME"], | ||
| ) | ||
|
|
||
| assert result.returncode != 0 | ||
| assert "Database configuration is incomplete" in result.stderr | ||
|
|
||
|
|
||
| def test_app_with_individual_db_vars(): | ||
| """Test that app starts with individual DATABASE_* variables.""" | ||
| result = _run_import_test( | ||
| env_vars={ | ||
| "OPENAI_API_KEY": "test-key", | ||
| "DATABASE_HOST": "localhost", | ||
| "DATABASE_PORT": "54320", | ||
| "DATABASE_USER": "test_user", | ||
| "DATABASE_PASSWORD": "test_pass", | ||
| "DATABASE_NAME": "test_db", | ||
| }, | ||
| remove_vars=["DATABASE_URL"], | ||
| ) | ||
|
|
||
| assert result.returncode == 0 | ||
| assert "memU Server" in result.stdout | ||
|
|
||
|
|
||
| def test_app_starts_with_valid_openai_api_key(): | ||
| """Test that app starts successfully with valid OPENAI_API_KEY.""" | ||
| result = _run_import_test( | ||
| env_vars={ | ||
| "OPENAI_API_KEY": "test-valid-key", | ||
| "DATABASE_URL": "postgresql+psycopg://test:test@localhost:5432/test", | ||
| }, | ||
| ) | ||
|
|
||
| assert result.returncode == 0 | ||
| assert "memU Server" in result.stdout | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| """Tests for the application's root ("/") endpoint.""" | ||
|
|
||
| import pytest | ||
| from fastapi.testclient import TestClient | ||
|
|
||
|
|
||
| @pytest.fixture(scope="module") | ||
| def client(): | ||
| """Create FastAPI test client with proper env setup.""" | ||
| try: | ||
| from app.main import app | ||
|
|
||
| return TestClient(app) | ||
| except Exception as exc: | ||
| pytest.skip(f"Could not initialize test client due to application setup error: {exc}") | ||
|
|
||
|
|
||
| def test_root_endpoint(client): | ||
| """Test root endpoint returns welcome message.""" | ||
| response = client.get("/") | ||
| assert response.status_code == 200 | ||
| data = response.json() | ||
| assert "message" in data | ||
| assert data["message"] == "Hello MemU user!" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.