Tests

create-mountaineer-app sets up pytest and pytest-asyncio, along with fixtures for configuration and database access. The examples below test the data a controller returns and the rows its actions change.

Test Structure

Project Setup

The generated project keeps tests and shared fixtures in __tests__/:

my_webapp/
├── __tests__/
│   ├── __init__.py
│   ├── conftest.py          # Test configuration and fixtures
│   └── test_*.py           # Your test files
├── controllers/
├── models/
├── views/
└── pyproject.toml

Test Configuration

Base Configuration (conftest.py)

The generated conftest.py sets up:

  • Automatic config setup with test database configuration
  • A database connection fixture for each test
  • Schema recreation so tests start with an empty database

You can view the complete implementation in the template conftest.py.

Key Fixtures Available

The generated test configuration provides these fixtures:

  • config: Auto-used fixture that sets up test-time configuration
  • db_connection: Async fixture providing a clean database connection for each test

Environment Variables

Create a .env.test file for test-specific configuration:

TEST_POSTGRES_HOST=localhost
TEST_POSTGRES_USER=my_webapp
TEST_POSTGRES_PASSWORD=mysecretpassword
TEST_POSTGRES_DB=my_webapp_test_db
POSTGRES_PORT=5438

Core Testing Patterns

Testing Controller Render Functions

Call render() with known dependencies and check its returned data. These tests exercise the controller's Python logic; they do not render the React page.

Testing Render with Data

Insert two todos, supply a request with a known IP address, and check that render() returns them:

import pytest
from fastapi import Request
from unittest.mock import Mock
from my_webapp.controllers.home import HomeController, HomeRender
from my_webapp.models.todo import TodoItem

@pytest.mark.asyncio
async def test_home_render_with_todos(db_connection):
    """Test that the home controller renders todo data correctly."""
    controller = HomeController()
    
    # Set up test data in the database - this simulates having real todos
    await db_connection.insert([
        TodoItem(description="Learn Mountaineer", completed=False),
        TodoItem(description="Build awesome app", completed=True)
    ])
    
    # Create a mock request (this would normally come from FastAPI)
    mock_request = Mock(spec=Request)
    mock_request.client = Mock()
    mock_request.client.host = "127.0.0.1"
    
    # Call the render method - this is what happens when a user visits the page
    result = await controller.render(
        request=mock_request,
        db_connection=db_connection
    )
    
    # Verify the response structure and data
    assert isinstance(result, HomeRender)
    assert result.client_ip == "127.0.0.1"
    assert len(result.todos) == 2
    
    # Check that both todos are present with correct data
    todo_descriptions = [todo.description for todo in result.todos]
    assert "Learn Mountaineer" in todo_descriptions
    assert "Build awesome app" in todo_descriptions

Testing Render with Empty State

With no todos in the database, render() should still return a valid payload with an empty list:

@pytest.mark.asyncio
async def test_home_render_empty_state(db_connection):
    """Test that the render function handles empty data gracefully."""
    controller = HomeController()
    
    mock_request = Mock(spec=Request)
    mock_request.client = Mock()
    mock_request.client.host = "192.168.1.1"
    
    # Call render with empty database
    result = await controller.render(
        request=mock_request,
        db_connection=db_connection
    )
    
    # Should still return valid structure with empty todos
    assert isinstance(result, HomeRender)
    assert result.client_ip == "192.168.1.1"
    assert len(result.todos) == 0

Testing Action Functions (Sideeffects & Passthroughs)

For actions that write data, check the database after the call. Adapt the calls below to your controller's signature, including the request context required by decorated actions. HTTP validation needs a request test, and frontend refreshes need a browser test.

Testing Data Creation

Start with one todo, add another, and check that both rows exist. Also check the new row's generated ID and default completion state:

import pytest
from my_webapp.controllers.home import HomeController
from my_webapp.models.todo import TodoItem
from iceaxe import select

@pytest.mark.asyncio
async def test_add_todo_action(db_connection):
    """Test adding a new todo item via sideeffect."""
    controller = HomeController()
    
    # Set up initial state - maybe the user already has one todo
    await db_connection.insert([
        TodoItem(description="Existing task", completed=False)
    ])
    
    # Simulate user action - adding a new todo
    await controller.add_todo(
        payload={"description": "New important task"},
        db_connection=db_connection
    )
    
    # Verify the database was updated correctly
    todos = await db_connection.exec(select(TodoItem))
    assert len(todos) == 2  # Original + new todo
    
    # Find the new todo and verify its properties
    new_todos = [todo for todo in todos if todo.description == "New important task"]
    assert len(new_todos) == 1
    new_todo = new_todos[0]
    assert new_todo.completed is False  # Should default to incomplete
    assert new_todo.id is not None     # Should have generated ID

Testing Data Updates

For a toggle_todo action, check that the completion flag changes and the description stays the same:

@pytest.mark.asyncio
async def test_toggle_todo_action(db_connection):
    """Test updating a todo's completion status."""
    controller = HomeController()
    
    # Create a todo to modify
    todo_id = "550e8400-e29b-41d4-a716-446655440000"
    await db_connection.insert([
        TodoItem(
            id=todo_id,
            description="Task to complete",
            completed=False
        )
    ])
    
    # Simulate user toggling the todo completion
    await controller.toggle_todo(
        payload={"todo_id": todo_id},
        db_connection=db_connection
    )
    
    # Verify the todo was updated
    todos = await db_connection.exec(select(TodoItem))
    updated_todo = todos[0]
    assert updated_todo.completed is True
    assert updated_todo.description == "Task to complete"  # Description unchanged

Testing Error Handling

When an action rejects invalid input, check both the error and the database state. A direct Python call only raises a Pydantic ValidationError if your code performs that validation; FastAPI's request validation runs at the HTTP boundary.

@pytest.mark.asyncio
async def test_action_with_validation_error(db_connection):
    """Test that action functions handle invalid input properly."""
    controller = HomeController()
    
    # Test with invalid payload - missing required field
    with pytest.raises(ValidationError):
        await controller.add_todo(
            payload={"invalid_field": "value"},  # Missing 'description'
            db_connection=db_connection
        )
    
    # Verify no data was created in the database
    todos = await db_connection.exec(select(TodoItem))
    assert len(todos) == 0

Running Tests

Basic Test Execution

# Run all tests
pytest

# Run tests with verbose output
pytest -v

# Run specific test file
pytest __tests__/test_render.py

# Run tests matching a pattern
pytest -k "render"

Database Testing

Make sure your test database is running before executing database tests:

# Start test database (if using Docker)
docker compose -f docker-compose.test.yml up -d

# Run database tests
pytest __tests__/ -v

# Clean up
docker compose -f docker-compose.test.yml down

Reference

For more examples of testing patterns, see: