From ced2950b60861ede87b27685248f8befad37ce1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Wed, 4 Mar 2026 10:47:06 +0200 Subject: [PATCH 1/4] Dockerizing the project --- .dockerignore | 6 ++++++ .gitignore | 3 ++- Dockerfile | 13 +++++++++++++ README.md | 6 ++++++ app/utils.py | 9 --------- docker-compose.yml | 30 ++++++++++++++++++++++++++++++ requirements.txt | 9 +++++++++ 7 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile delete mode 100644 app/utils.py create mode 100644 docker-compose.yml create mode 100644 requirements.txt diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..babefb6 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +venv +__pycache__ +*.pyc +*.db +.git +.env \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1bbc918..1cd01d9 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ __pycache__ .pytest_cache/ venv/ test.txt -diff.txt \ No newline at end of file +diff.txt +test.db \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6de4317 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.12-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +EXPOSE 8000 + +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file diff --git a/README.md b/README.md index 5dc2252..56118da 100644 --- a/README.md +++ b/README.md @@ -30,4 +30,10 @@ python -m pytest --cov=app --cov-report=term-missing ```bash cd /opt/kjc/int/URL-shortener alembic revision --autogenerate -m "create urls table" +``` + +## Running project in Docker container +```bash +cd /opt/kjc/int/URL-shortener +docker compose up --build ``` \ No newline at end of file diff --git a/app/utils.py b/app/utils.py deleted file mode 100644 index efe5e4f..0000000 --- a/app/utils.py +++ /dev/null @@ -1,9 +0,0 @@ -# app/utils.py - -import string -import random - -def generate_short_code(length=6): - characters = string.ascii_letters + string.digits - return ''.join(random.choice(characters) for _ in range(length)) - \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..67eea49 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,30 @@ +version: "3.9" + +services: + db: + image: postgres:16 + container_name: url_shortener_db + restart: always + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: url_db + volumes: + - postgres_data:/var/lib/postgresql/data + + app: + build: . + container_name: url_shortener_app + depends_on: + - db + environment: + DATABASE_URL: postgresql+psycopg2://postgres:postgres@db:5432/url_db + BASE_URL: http://localhost:8000 + ports: + - "8000:8000" + command: > + sh -c "alembic upgrade head && + uvicorn app.main:app --host 0.0.0.0 --port 8000" + +volumes: + postgres_data: \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0c2599e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi==0.124.4 +uvicorn[standard]==0.33.0 +sqlalchemy==2.0.47 +psycopg2-binary==2.9.10 +alembic==1.14.1 +pydantic-settings==2.8.1 + +pytest==8.3.5 +pytest-cov==5.0.0 \ No newline at end of file From 2dfd625b5ed9f96ed29f92612e2838e02697499a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Wed, 4 Mar 2026 11:59:39 +0200 Subject: [PATCH 2/4] Make postgress run from it's own container --- README.md | 6 +++--- docker-compose.yml | 16 ++++++++++------ test.db | Bin 32768 -> 0 bytes 3 files changed, 13 insertions(+), 9 deletions(-) delete mode 100644 test.db diff --git a/README.md b/README.md index 56118da..0896889 100644 --- a/README.md +++ b/README.md @@ -13,11 +13,11 @@ source venv/bin/activate python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 ``` Then check:
-http://127.0.0.1:8000
-http://127.0.0.1:8000/docs +http://localhost:9995
+http://localhost:9995/docs Test Short URL Endpoint:
-http://127.0.0.1:8000/shorten +http://localhost:9995/shorten ## Running a test ```bash diff --git a/docker-compose.yml b/docker-compose.yml index 67eea49..56b48a7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,3 @@ -version: "3.9" - services: db: image: postgres:16 @@ -11,20 +9,26 @@ services: POSTGRES_DB: url_db volumes: - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 5s + timeout: 5s + retries: 5 app: build: . container_name: url_shortener_app depends_on: - - db + db: + condition: service_healthy environment: DATABASE_URL: postgresql+psycopg2://postgres:postgres@db:5432/url_db - BASE_URL: http://localhost:8000 + BASE_URL: http://localhost:9995 ports: - - "8000:8000" + - "9995:9995" command: > sh -c "alembic upgrade head && - uvicorn app.main:app --host 0.0.0.0 --port 8000" + uvicorn app.main:app --host 0.0.0.0 --port 9995" volumes: postgres_data: \ No newline at end of file diff --git a/test.db b/test.db deleted file mode 100644 index 32c0952eda4287d15152e7a947ee4b2250b99716..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 32768 zcmeI(%WvaE90zbac9TuiWR^pSinM4}LZVS$iJfHIN<2*KLPY9rTnDkz3d>DQ*EElA z>{b;lhg}dSZd}+4e*jm``~`6B0dYYbmkV6>#DST-oo+!$tCe>1wd!O%9{*_gV=}oh|tC_dx`}!@qI1w+K$i5MaW~xh~;I$j>nSZy*W>mIw z5_Edk_EdB1{8R>?WA)})Z_Y(C*VAIH_n3EPpLCnP?KSvUbkM=Fv8{hd$M@)-LHT{U z=ryt*$+1j6E#8+x0sK3iZeZ6t4VM?38w9EuKA0C{ znRHtG;nK~Eblq!(#Q(uwSSpo+HAOHafKmY;|fB*y_009UdvR#J3(;lZ?3KRffM*Ef$ImW^-e3I06siJJ=* z_ggsCIo@B^1mo#7!xC8&w79CB?zMNjm0=T(oKKu~Z>_*P?NO~wwIsJ$C|<}auCLx$ zFXT!$60CtT`Bor5ke|r!EP(?85P$##AOHafKmY;|fB*y_0D)&F@QSn{4yX9xl@&Q7 zsiRvH3lP%FQht;_v2t=v(&EEN7Z(fq^Z$DS`HtKpKayXcSqD)O1Rwwb2tWV=5P$## zAOHafKww4$uFGs2#lLN$kYAM-RPoX+2huf}ZJM}r%fxFk+b-~5n+5vw|8s%-M$X9} z-dG!2u9zB2n1Rwwb2tWV=5P$##AOHaf%(B3oB#N@kKP8EOMk10Fk0&|F z)me5y-yr}22tWV=5P$##AOHafKmYk5r~m)} From 03ba3fb3c23632ba9aeca40d00f3ae241d437102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Thu, 5 Mar 2026 11:46:48 +0200 Subject: [PATCH 3/4] Improve test coverance and fixes according to tests --- Dockerfile | 4 +- Makefile | 11 ++ README.md | 45 +++++--- alembic/env.py | 1 - .../0132ba841ec5_create_urls_table.py | 2 - app/api/routes.py | 13 ++- app/main.py | 12 +- app/schemas/url.py | 6 +- app/services/url_service.py | 10 +- app/tests/conftest.py | 11 +- app/tests/test_config.py | 16 +++ app/tests/test_models.py | 32 ++++++ app/tests/test_routes.py | 3 - app/tests/test_services.py | 106 ++++++++++++++++++ app/tests/test_utils.py | 19 ++++ pyproject.toml | 6 + requirements.txt | 3 +- 17 files changed, 256 insertions(+), 44 deletions(-) create mode 100644 Makefile create mode 100644 app/tests/test_config.py create mode 100644 app/tests/test_models.py create mode 100644 app/tests/test_services.py create mode 100644 app/tests/test_utils.py create mode 100644 pyproject.toml diff --git a/Dockerfile b/Dockerfile index 6de4317..cd277ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -8,6 +8,6 @@ RUN pip install --no-cache-dir -r requirements.txt COPY . . -EXPOSE 8000 +EXPOSE 9995 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "9995"] \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5259bc0 --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +run: + uvicorn app.main:app --reload --port 9995 + +test: + pytest --cov=app --cov-report=term-missing + +docker: + docker compose up --build + +lint: + ruff check . \ No newline at end of file diff --git a/README.md b/README.md index 0896889..97f609d 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,38 @@ -# URL-shortener -URL-shortener project to showcase python use +# URL Shortener API + +Production-ready URL Shortener built with FastAPI, PostgreSQL, Docker, and Alembic. + +![Tests](https://img.shields.io/badge/tests-passing-brightgreen) +![Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen) +![Python](https://img.shields.io/badge/python-3.12-blue) + +## Techstack + +FastAPI, PostgreSQL, SQLAlchemy 2.0, Alembic, Docker, Pytest and Pydantic v2 + +## Features + +Shorten URLs, Redirect, Click tracking, Stats endpoint, Collision handling, 90%+ test coverage, Dockerized and Alembic migrations + +## Local Setup -## Create venv ```bash -cd /opt/kjc/int/URL-shortener +cd python3 -m venv venv source venv/bin/activate ``` -## Run locally -```bash -python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000 +Create .env: ``` +DATABASE_URL=sqlite:///./test.db +BASE_URL=http://localhost:8000 +``` + +Run: +```bash +python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 9995 +``` + Then check:
http://localhost:9995
http://localhost:9995/docs @@ -19,21 +40,19 @@ http://localhost:9995/docs Test Short URL Endpoint:
http://localhost:9995/shorten -## Running a test +## Run Tests ```bash -PYTHONPATH=./ pytest -export PYTHONPATH=$(pwd) -python -m pytest --cov=app --cov-report=term-missing +pytest --cov=app --cov-report=term-missing ``` ## Running Alembic revision ```bash -cd /opt/kjc/int/URL-shortener +cd alembic revision --autogenerate -m "create urls table" ``` ## Running project in Docker container ```bash -cd /opt/kjc/int/URL-shortener +cd docker compose up --build ``` \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py index 4125426..4d83369 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -3,7 +3,6 @@ from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from app.db.base import Base -from app.db import models from app.core.config import settings target_metadata = Base.metadata diff --git a/alembic/versions/0132ba841ec5_create_urls_table.py b/alembic/versions/0132ba841ec5_create_urls_table.py index a6633ce..8685400 100644 --- a/alembic/versions/0132ba841ec5_create_urls_table.py +++ b/alembic/versions/0132ba841ec5_create_urls_table.py @@ -7,8 +7,6 @@ Create Date: 2026-03-02 09:13:50.764599 """ from typing import Sequence, Union -from alembic import op -import sqlalchemy as sa # revision identifiers, used by Alembic. diff --git a/app/api/routes.py b/app/api/routes.py index 164d9e7..14391f7 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -27,10 +27,16 @@ def shorten_url( request: URLCreate, db: Session = Depends(get_db), ): - short_url = url_service.create_short_url(db, str(request.url)) + normalized_url = str(request.url).rstrip("/") + short_url = url_service.create_short_url(db, normalized_url) return {"short_url": short_url} +@router.get("/health") +def health(): + return {"message": "healthy"} + + @router.get("/{short_code}") def redirect_to_url( short_code: str, @@ -63,8 +69,3 @@ def get_url_stats( ) return stats - - -@router.get("/health", response_model=MessageResponse) -def health_check(): - return {"message": "healthy"} \ No newline at end of file diff --git a/app/main.py b/app/main.py index 256bcea..0d93ad3 100644 --- a/app/main.py +++ b/app/main.py @@ -1,5 +1,6 @@ # app/main.py +import logging from fastapi import FastAPI from contextlib import asynccontextmanager from app.core.config import settings @@ -7,11 +8,18 @@ from app.db.session import engine from app.db.base import Base from app.api.routes import router +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", +) + +import os +from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): - - Base.metadata.create_all(bind=engine) + if os.getenv("TESTING") != "1": + Base.metadata.create_all(bind=engine) yield def create_app() -> FastAPI: diff --git a/app/schemas/url.py b/app/schemas/url.py index ab24c28..7ef7c14 100644 --- a/app/schemas/url.py +++ b/app/schemas/url.py @@ -14,11 +14,11 @@ class URLResponse(BaseModel): class URLStatsResponse(BaseModel): - original_url: HttpUrl + original_url: str clicks: int created_at: datetime - last_accessed: Optional[datetime] = None - + last_accessed: Optional[datetime] + class MessageResponse(BaseModel): message: str \ No newline at end of file diff --git a/app/services/url_service.py b/app/services/url_service.py index 7c2300d..85d0ac2 100644 --- a/app/services/url_service.py +++ b/app/services/url_service.py @@ -18,9 +18,12 @@ def create_short_url(db: Session, original_url: str) -> str: Create a shortened URL or return existing one if already present. """ + # ✅ Normalize FIRST (critical fix) + normalized_url = original_url.rstrip("/") + # 1️⃣ Check if URL already exists existing = db.execute( - select(URL).where(URL.original_url == original_url) + select(URL).where(URL.original_url == normalized_url) ).scalar_one_or_none() if existing: @@ -37,7 +40,7 @@ def create_short_url(db: Session, original_url: str) -> str: if not collision: new_url = URL( short_code=short_code, - original_url=original_url, + original_url=normalized_url, # ✅ store normalized version ) db.add(new_url) db.commit() @@ -45,9 +48,8 @@ def create_short_url(db: Session, original_url: str) -> str: return f"{settings.base_url}/{new_url.short_code}" - # If we somehow fail multiple times raise RuntimeError("Failed to generate unique short code") - + def get_original_url(db: Session, short_code: str) -> Optional[str]: """ diff --git a/app/tests/conftest.py b/app/tests/conftest.py index 55dffc8..a46cd1e 100644 --- a/app/tests/conftest.py +++ b/app/tests/conftest.py @@ -2,6 +2,7 @@ import pytest from sqlalchemy import create_engine +from sqlalchemy.pool import StaticPool from sqlalchemy.orm import sessionmaker from fastapi.testclient import TestClient @@ -9,21 +10,18 @@ from app.main import app from app.db.base import Base from app.db.session import get_db +import os +os.environ["TESTING"] = "1" # Use in-memory SQLite for tests TEST_DATABASE_URL = "sqlite+pysqlite:///:memory:" - @pytest.fixture(scope="function") def db_session(): - """ - Creates a new database session for a test. - Rolls back everything after test finishes. - """ - engine = create_engine( TEST_DATABASE_URL, connect_args={"check_same_thread": False}, + poolclass=StaticPool, ) TestingSessionLocal = sessionmaker( @@ -32,7 +30,6 @@ def db_session(): bind=engine, ) - # Create tables Base.metadata.create_all(bind=engine) db = TestingSessionLocal() diff --git a/app/tests/test_config.py b/app/tests/test_config.py new file mode 100644 index 0000000..c4bbae9 --- /dev/null +++ b/app/tests/test_config.py @@ -0,0 +1,16 @@ +from app.core.config import get_settings + +def test_get_settings_returns_same_instance(): + s1 = get_settings() + s2 = get_settings() + + assert s1 is s2 # lru_cache should return same instance + +def test_default_settings_values(): + settings = get_settings() + + assert settings.app_name == "URL Shortener" + assert settings.host == "0.0.0.0" + assert settings.port == 8000 + assert settings.debug is True + assert isinstance(settings.allowed_hosts, list) \ No newline at end of file diff --git a/app/tests/test_models.py b/app/tests/test_models.py new file mode 100644 index 0000000..fa813a2 --- /dev/null +++ b/app/tests/test_models.py @@ -0,0 +1,32 @@ +from app.db.models import URL + +def test_url_model_defaults(db_session): + url = URL( + short_code="abc123", + original_url="https://example.com", + ) + + db_session.add(url) + db_session.commit() + db_session.refresh(url) + + assert url.id is not None + assert url.clicks == 0 + assert url.created_at is not None + assert url.last_accessed is None + +def test_url_repr(db_session): + url = URL( + short_code="xyz789", + original_url="https://repr-test.com", + ) + + db_session.add(url) + db_session.commit() + db_session.refresh(url) + + repr_output = repr(url) + + assert "URL" in repr_output + assert "xyz789" in repr_output + assert "https://repr-test.com" in repr_output \ No newline at end of file diff --git a/app/tests/test_routes.py b/app/tests/test_routes.py index c1edf37..2be8365 100644 --- a/app/tests/test_routes.py +++ b/app/tests/test_routes.py @@ -1,8 +1,5 @@ # app/tests/test_routes.py -import pytest - - def test_home(client): response = client.get("/") assert response.status_code == 200 diff --git a/app/tests/test_services.py b/app/tests/test_services.py new file mode 100644 index 0000000..64ef768 --- /dev/null +++ b/app/tests/test_services.py @@ -0,0 +1,106 @@ +import pytest +from unittest.mock import patch + +from app.services import url_service +from app.db.models import URL + + +def test_create_short_url_creates_new(db_session): + short_url = url_service.create_short_url( + db_session, + "https://new-url.com", + ) + + assert short_url.startswith("http://") + + entry = db_session.query(URL).first() + assert entry is not None + assert entry.original_url == "https://new-url.com" + + +def test_create_short_url_returns_existing(db_session): + first = url_service.create_short_url( + db_session, + "https://duplicate.com", + ) + + second = url_service.create_short_url( + db_session, + "https://duplicate.com", + ) + + assert first == second + assert db_session.query(URL).count() == 1 + + +def test_create_short_url_collision_failure(db_session): + with patch( + "app.services.url_service.generate_short_code", + return_value="fixedcode", + ): + # First insert works + url_service.create_short_url(db_session, "https://a.com") + + # Force collision repeatedly + with pytest.raises(RuntimeError): + url_service.create_short_url(db_session, "https://b.com") + + +def test_get_original_url_success(db_session): + short_url = url_service.create_short_url( + db_session, + "https://lookup.com", + ) + code = short_url.split("/")[-1] + + original = url_service.get_original_url(db_session, code) + + assert original == "https://lookup.com" + + +def test_get_original_url_not_found(db_session): + result = url_service.get_original_url(db_session, "missing") + assert result is None + + +def test_increment_clicks_success(db_session): + short_url = url_service.create_short_url( + db_session, + "https://click-test.com", + ) + code = short_url.split("/")[-1] + + success = url_service.increment_clicks(db_session, code) + + assert success is True + + entry = db_session.query(URL).first() + assert entry.clicks == 1 + assert entry.last_accessed is not None + + +def test_increment_clicks_not_found(db_session): + result = url_service.increment_clicks(db_session, "missing") + assert result is False + + +def test_get_stats_success(db_session): + short_url = url_service.create_short_url( + db_session, + "https://stats.com", + ) + code = short_url.split("/")[-1] + + url_service.increment_clicks(db_session, code) + + stats = url_service.get_stats(db_session, code) + + assert stats is not None + assert stats["original_url"] == "https://stats.com" + assert stats["clicks"] == 1 + assert stats["created_at"] is not None + + +def test_get_stats_not_found(db_session): + stats = url_service.get_stats(db_session, "missing") + assert stats is None \ No newline at end of file diff --git a/app/tests/test_utils.py b/app/tests/test_utils.py new file mode 100644 index 0000000..9ae308f --- /dev/null +++ b/app/tests/test_utils.py @@ -0,0 +1,19 @@ +import string +from app.utils.short_code import generate_short_code + +def test_generate_short_code_length(): + code = generate_short_code(8) + assert len(code) == 8 + +def test_generate_short_code_is_alphanumeric(): + code = generate_short_code(12) + allowed = string.ascii_letters + string.digits + + for char in code: + assert char in allowed + +def test_generate_short_code_randomness(): + code1 = generate_short_code() + code2 = generate_short_code() + + assert code1 != code2 # extremely unlikely to fail \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..6f42fb5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,6 @@ +[tool.ruff] +line-length = 88 +target-version = "py312" + +[tool.pytest.ini_options] +pythonpath = ["."] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 0c2599e..36e12fa 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,4 +6,5 @@ alembic==1.14.1 pydantic-settings==2.8.1 pytest==8.3.5 -pytest-cov==5.0.0 \ No newline at end of file +pytest-cov==5.0.0 +ruff==0.15.4 \ No newline at end of file From 2776f5dfa7e57db92edd3fa46347ed2beb030b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Katariina=20J=C3=A4rvenm=C3=A4ki?= Date: Thu, 5 Mar 2026 14:57:54 +0200 Subject: [PATCH 4/4] Enabling testing inside Docker container --- .env.example | 3 +++ .gitignore | 43 ++++++++++++++++++++++++++++++++++++++++--- README.md | 12 +++++++----- docker-compose.yml | 2 ++ requirements.txt | 3 ++- 5 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..d7665eb --- /dev/null +++ b/.env.example @@ -0,0 +1,3 @@ +DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/url_db +BASE_URL=http://localhost:8000 +DEBUG=True \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1cd01d9..df27453 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,44 @@ -app/__pycache__ -__pycache__ -.pytest_cache/ +# Environment variables +.env +.env.local +.env.* + +# Keep the example file for setup instructions +!.env.example + +# Virtual environments venv/ +.env/ + +# Python bytecode and cache +__pycache__/ +*.pyc +*.pyo +*.pyd +.python-version + +# Pytest cache +.pytest_cache/ + +# IDE/editor files +.vscode/ +.idea/ +*.swp +*.swo + +# Docker-related files +*.log +docker-compose.override.yml + +# Coverage reports +htmlcov/ +.coverage +coverage.xml + +# Logs +*.log + +# Extras test.txt diff.txt test.db \ No newline at end of file diff --git a/README.md b/README.md index 97f609d..7409153 100644 --- a/README.md +++ b/README.md @@ -40,11 +40,6 @@ http://localhost:9995/docs Test Short URL Endpoint:
http://localhost:9995/shorten -## Run Tests -```bash -pytest --cov=app --cov-report=term-missing -``` - ## Running Alembic revision ```bash cd @@ -55,4 +50,11 @@ alembic revision --autogenerate -m "create urls table" ```bash cd docker compose up --build +``` + +## Running tests in Docker container +```bash +cd +docker compose up --build +docker compose exec app pytest --cov=app --cov-report=term-missing ``` \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 56b48a7..1b4dcbc 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -26,6 +26,8 @@ services: BASE_URL: http://localhost:9995 ports: - "9995:9995" + volumes: + - .:/app # Mount current directory to /app inside container command: > sh -c "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 9995" diff --git a/requirements.txt b/requirements.txt index 36e12fa..44fedad 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,4 +7,5 @@ pydantic-settings==2.8.1 pytest==8.3.5 pytest-cov==5.0.0 -ruff==0.15.4 \ No newline at end of file +ruff==0.15.4 +httpx==0.24.1 \ No newline at end of file