From 27bc7369812c8fa23a97ed8e402851dab01813a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Mon, 2 Mar 2026 16:18:02 +0200 Subject: [PATCH] Refactor database connection to use settings and improve test isolation with temporary DB --- app/__init__.py | 0 app/main.py | 1 - app/settings.py | 7 +++++++ app/test_main.py | 46 +++++++++++++++++++++++++--------------------- urls.db | Bin 8192 -> 12288 bytes 5 files changed, 32 insertions(+), 22 deletions(-) create mode 100644 app/__init__.py create mode 100644 app/settings.py diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/main.py b/app/main.py index 6ba6cb4..744d739 100644 --- a/app/main.py +++ b/app/main.py @@ -21,7 +21,6 @@ logger = logging.getLogger(__name__) # Database connection setup @asynccontextmanager async def lifespan(app: FastAPI): - conn = sqlite3.connect('urls.db') conn = sqlite3.connect(settings.database_url) conn.execute(""" CREATE TABLE IF NOT EXISTS urls ( diff --git a/app/settings.py b/app/settings.py new file mode 100644 index 0000000..3883334 --- /dev/null +++ b/app/settings.py @@ -0,0 +1,7 @@ +# app/settings.py + +import os + +# Example configuration +database_url = os.getenv("DATABASE_URL", "sqlite:///default.db") +debug = os.getenv("DEBUG", "True") == "True" \ No newline at end of file diff --git a/app/test_main.py b/app/test_main.py index b927a65..9355bf4 100644 --- a/app/test_main.py +++ b/app/test_main.py @@ -3,60 +3,64 @@ import sys import os sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) - -from app.main import settings +from app.main import app +from app import settings import tempfile import pytest -client = TestClient(app) +@pytest.fixture +def test_client(): + with tempfile.NamedTemporaryFile() as tmp: + settings.database_url = tmp.name + with TestClient(app) as c: + yield c -@pytest.fixture(autouse=True) +@pytest.fixture def use_temp_db(): with tempfile.NamedTemporaryFile() as tmp: settings.database_url = tmp.name yield -def test_home(): - response = client.get("/") +def test_home(test_client): + response = test_client.get("/") assert response.status_code == 200 assert response.json() == {"message": "URL Shortener API"} -def test_shorten_url(): - response = client.post("/shorten", json={"url": "https://google.com"}) +def test_shorten_url(test_client): + response = test_client.post("/shorten", json={"url": "https://google.com"}) assert response.status_code == 200 data = response.json() assert "short_url" in data short_url = data["short_url"] assert short_url.startswith("http://localhost:8000/") -def test_redirect(): - response = client.post("/shorten", json={"url": "https://google.com"}) +def test_redirect(test_client): + response = test_client.post("/shorten", json={"url": "https://google.com"}) short_url = response.json()["short_url"] code = short_url.split("/")[-1] - redirect = client.get(f"/{code}", allow_redirects=False) + redirect = test_client.get(f"/{code}", follow_redirects=False) assert redirect.status_code == 307 -def test_duplicate_url_returns_same_code(): - r1 = client.post("/shorten", json={"url": "https://example.com"}) - r2 = client.post("/shorten", json={"url": "https://example.com"}) +def test_duplicate_url_returns_same_code(test_client): + r1 = test_client.post("/shorten", json={"url": "https://example.com"}) + r2 = test_client.post("/shorten", json={"url": "https://example.com"}) assert r1.status_code == 200 assert r2.status_code == 200 assert r1.json()["short_url"] == r2.json()["short_url"] -def test_stats_endpoint(): - response = client.post("/shorten", json={"url": "https://stats-test.com"}) +def test_stats_endpoint(test_client): + response = test_client.post("/shorten", json={"url": "https://stats-test.com"}) code = response.json()["short_url"].split("/")[-1] - # trigger one redirect - client.get(f"/{code}", allow_redirects=False) + test_client.get(f"/{code}", follow_redirects=False) - stats = client.get(f"/stats/{code}") + stats = test_client.get(f"/stats/{code}") assert stats.status_code == 200 data = stats.json() assert data["clicks"] == 1 -def test_redirect_404(): - response = client.get("/nonexistent", allow_redirects=False) +def test_redirect_404(test_client): + response = test_client.get("/nonexistent", follow_redirects=False) assert response.status_code == 404 \ No newline at end of file diff --git a/urls.db b/urls.db index b82e8dfeb508175ae411ce4025eb8a1b62399c3c..32dc3f90ee423273c4ee50056481509790f70ba2 100644 GIT binary patch delta 490 zcmZp0Xh@hKEhx&sz`zW|Fu*iX#~3K6XMd9yD8$6C&cI*BufDNxJDetAeMWi)(}es=R`~p8`mY211MGSsasU7T delta 90 zcmZojXmFSyEy&Nnz`z8=Fu*ub$C#g=LC^jsFHne)zl?#uY_p*P2mj