From 337c25e13ba268ba64241c6ee429d02957d88941 Mon Sep 17 00:00:00 2001 From: Tharun Kumar Reddy Ette Date: Tue, 10 Feb 2026 15:32:49 +0530 Subject: [PATCH] Initial FastAPI project with tests --- .gitignore | 5 +++++ main.py | 26 ++++++++++++++++++++++++++ tests/__init__.py | 0 tests/test_users.py | 29 +++++++++++++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 main.py create mode 100644 tests/__init__.py create mode 100644 tests/test_users.py diff --git a/.gitignore b/.gitignore index e69de29b..5ab5ef0a 100644 --- a/.gitignore +++ b/.gitignore @@ -0,0 +1,5 @@ +venv/ +__pycache__/ +.pytest_cache/ +*.pyc +.env \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 00000000..0683eef3 --- /dev/null +++ b/main.py @@ -0,0 +1,26 @@ +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel + +app = FastAPI() + +class User(BaseModel): + id: int + name: str + email: str + +users_db = [] + +@app.get("/") +def health_check(): + return {"message": "FastAPI is running successfully"} + +@app.post("/users", status_code=201) +def create_user(user: User): + if any(u["id"] == user.id for u in users_db): + raise HTTPException(status_code=400, detail="User already exists") + users_db.append(user.model_dump()) + return user + +@app.get("/users") +def get_users(): + return users_db \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/test_users.py b/tests/test_users.py new file mode 100644 index 00000000..b50195e4 --- /dev/null +++ b/tests/test_users.py @@ -0,0 +1,29 @@ +from fastapi.testclient import TestClient +import sys +import os + +sys.path.append(os.path.dirname(os.path.dirname(__file__))) + +from main import app + +client = TestClient(app) + +def test_create_user(): + response = client.post( + "/users", + json={"id": 1, "name": "Tharun", "email": "tharun@test.com"} + ) + assert response.status_code == 201 + assert response.json()["name"] == "Tharun" + +def test_get_users(): + response = client.get("/users") + assert response.status_code == 200 + assert isinstance(response.json(), list) + +def test_duplicate_user_not_allowed(): + response = client.post( + "/users", + json={"id": 1, "name": "Duplicate", "email": "dup@test.com"} + ) + assert response.status_code == 400 \ No newline at end of file