|
| 1 | +from fastapi.testclient import TestClient |
| 2 | +from app.main import app |
| 3 | + |
| 4 | +client = TestClient(app) |
| 5 | + |
| 6 | +def test_root_and_hello(): |
| 7 | + res = client.get("/") |
| 8 | + assert res.status_code == 200 |
| 9 | + assert res.json() == {"message": "Welcome to the API"} |
| 10 | + |
| 11 | + res = client.get("/hello") |
| 12 | + assert res.status_code == 200 |
| 13 | + assert res.json() == {"message": "Hello World"} |
| 14 | + |
| 15 | +def test_register_and_duplicate_user(): |
| 16 | + res = client.post("/auth/register", json={"username": "charlie", "password": "pass123"}) |
| 17 | + assert res.status_code == 200 |
| 18 | + assert "id" in res.json() |
| 19 | + |
| 20 | + res = client.post("/auth/register", json={"username": "charlie", "password": "pass123"}) |
| 21 | + assert res.status_code == 400 |
| 22 | + assert res.json()["detail"] == "Username already registered" |
| 23 | + |
| 24 | +def test_login_with_correct_and_wrong_credentials(): |
| 25 | + res = client.post("/auth/token", data={"username": "charlie", "password": "pass123"}) |
| 26 | + assert res.status_code == 200 |
| 27 | + token = res.json()["access_token"] |
| 28 | + assert token is not None |
| 29 | + |
| 30 | + res = client.post("/auth/token", data={"username": "charlie", "password": "wrongpass"}) |
| 31 | + assert res.status_code == 400 |
| 32 | + assert res.json()["detail"] == "Incorrect username or password" |
| 33 | + |
| 34 | +def test_protected_endpoints_with_token(): |
| 35 | + # Login |
| 36 | + res = client.post("/auth/token", data={"username": "charlie", "password": "pass123"}) |
| 37 | + token = res.json()["access_token"] |
| 38 | + headers = {"Authorization": f"Bearer {token}"} |
| 39 | + |
| 40 | + # Crear item |
| 41 | + item = {"name": "Monitor", "price": 189.99, "in_stock": True} |
| 42 | + res = client.post("/items/", json=item, headers=headers) |
| 43 | + assert res.status_code == 200 |
| 44 | + created = res.json() |
| 45 | + assert created["name"] == "Monitor" |
| 46 | + assert created["price"] == 189.99 |
| 47 | + assert created["in_stock"] is True |
| 48 | + |
| 49 | + # Listar items |
| 50 | + res = client.get("/items/", headers=headers) |
| 51 | + assert res.status_code == 200 |
| 52 | + items = res.json() |
| 53 | + assert isinstance(items, list) |
| 54 | + assert any(i["name"] == "Monitor" for i in items) |
| 55 | + |
| 56 | +def test_protected_endpoints_without_token(): |
| 57 | + item = {"name": "ShouldFail", "price": 0.0, "in_stock": False} |
| 58 | + res = client.post("/items/", json=item) |
| 59 | + assert res.status_code == 401 |
| 60 | + |
| 61 | + res = client.get("/items/") |
| 62 | + assert res.status_code == 401 |
0 commit comments