test: add category CRUD tests

This commit is contained in:
2026-04-18 17:01:42 +00:00
parent a54f015b64
commit 2734a7f4d2

View File

@@ -0,0 +1,81 @@
import pytest
from fastapi import status
class TestCategoryCRUD:
"""Test category creation, read, update, delete."""
def test_create_category(self, test_client):
"""Test creating a category."""
response = test_client.post(
"/api/categories",
json={
"name": "Electronics",
"description": "Electronic components"
}
)
assert response.status_code == status.HTTP_201_CREATED
data = response.json()
assert data["name"] == "Electronics"
def test_get_category_by_id(self, test_client, test_db):
"""Test retrieving a category by ID."""
from backend.models import Category
category = Category(name="Electronics", description="Electronic components")
test_db.add(category)
test_db.commit()
response = test_client.get(f"/api/categories/{category.id}")
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["name"] == "Electronics"
def test_list_categories(self, test_client, test_db):
"""Test listing all categories."""
from backend.models import Category
cat1 = Category(name="Electronics", description="Desc1")
cat2 = Category(name="Mechanical", description="Desc2")
test_db.add_all([cat1, cat2])
test_db.commit()
response = test_client.get("/api/categories")
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert len(data) >= 2
def test_update_category(self, test_client, test_db):
"""Test updating a category."""
from backend.models import Category
category = Category(name="Electronics", description="Old description")
test_db.add(category)
test_db.commit()
response = test_client.put(
f"/api/categories/{category.id}",
json={"description": "New description"}
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["description"] == "New description"
def test_delete_category_admin_only(self, test_client, test_db, admin_token):
"""Test deleting a category (admin only)."""
from backend.models import Category
category = Category(name="Electronics", description="Desc")
test_db.add(category)
test_db.commit()
cat_id = category.id
response = test_client.delete(
f"/api/categories/{cat_id}",
headers={"Authorization": f"Bearer {admin_token}"}
)
assert response.status_code == status.HTTP_204_NO_CONTENT
# Verify deletion
response = test_client.get(f"/api/categories/{cat_id}")
assert response.status_code == status.HTTP_404_NOT_FOUND