"""A separate database for each test.

Install: python -m pip install fastapi httpx pytest
Run: python -m pytest database_test_example.py
"""

from contextlib import closing
from pathlib import Path
import sqlite3

from fastapi import FastAPI
from fastapi.testclient import TestClient


def create_app(database_path):
    """Build an app using the given database for initialization and requests."""
    database_path = Path(database_path)
    with closing(sqlite3.connect(database_path)) as connection:
        connection.execute("CREATE TABLE IF NOT EXISTS notes (text TEXT)")

    app = FastAPI()

    @app.get("/notes")
    def notes():
        with closing(sqlite3.connect(database_path)) as connection:
            rows = connection.execute("SELECT text FROM notes ORDER BY rowid").fetchall()
        return [row[0] for row in rows]

    @app.post("/notes")
    def add_note(text: str):
        with closing(sqlite3.connect(database_path)) as connection:
            connection.execute("INSERT INTO notes (text) VALUES (?)", (text,))
            connection.commit()
        return {"saved": text}

    return app


def test_add_note(tmp_path):
    # pytest gives this test its own temporary directory.
    app = create_app(tmp_path / "test.db")
    with TestClient(app) as client:
        response = client.post("/notes", params={"text": "Read chapter 3"})
        assert response.status_code == 200
        assert client.get("/notes").json() == ["Read chapter 3"]


def test_new_database_is_empty(tmp_path):
    # This test gets a different directory, with none of the other test's data.
    app = create_app(tmp_path / "test.db")
    with TestClient(app) as client:
        assert client.get("/notes").json() == []
