|
| 1 | +from unittest.mock import MagicMock, patch |
| 2 | + |
| 3 | +import pytest |
| 4 | +from fastapi.testclient import TestClient |
| 5 | +from sqlalchemy.orm import Session |
| 6 | + |
| 7 | +from api.db.database import get_db |
| 8 | +from api.v1.services.faq import faq_service |
| 9 | +from main import app |
| 10 | + |
| 11 | + |
| 12 | +@pytest.fixture |
| 13 | +def mock_db_session(): |
| 14 | + db_session = MagicMock(spec=Session) |
| 15 | + return db_session |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture |
| 19 | +def client(mock_db_session): |
| 20 | + app.dependency_overrides[get_db] = lambda: mock_db_session |
| 21 | + client = TestClient(app) |
| 22 | + yield client |
| 23 | + app.dependency_overrides = {} |
| 24 | + |
| 25 | + |
| 26 | +def test_filter_faq_by_category(mock_db_session, client): |
| 27 | + """Test to verify the response for filtering FAQs by category.""" |
| 28 | + |
| 29 | + mock_faq_data_grouped = { |
| 30 | + "General": [ |
| 31 | + {"question": "What is FastAPI?", |
| 32 | + "answer": "FastAPI is a modern web framework for Python."}, |
| 33 | + {"question": "What is SQLAlchemy?", |
| 34 | + "answer": "SQLAlchemy is a SQL toolkit and ORM for Python."} |
| 35 | + ] |
| 36 | + } |
| 37 | + |
| 38 | + with patch.object(faq_service, 'fetch_all_grouped_by_category', return_value=mock_faq_data_grouped): |
| 39 | + response = client.get('/api/v1/faqs/?category=General') |
| 40 | + response_data = response.json() |
| 41 | + |
| 42 | + assert response.status_code == 200 |
| 43 | + assert response_data["status_code"] == 200 |
| 44 | + assert response_data["message"] == "FAQs retrieved successfully" |
| 45 | + assert "General" in response_data["data"] |
| 46 | + assert len(response_data["data"]["General"]) == 2 |
| 47 | + assert response_data["data"]["General"][0]["question"] == "What is FastAPI?" |
| 48 | + assert response_data["data"]["General"][1]["question"] == "What is SQLAlchemy?" |
| 49 | + |
| 50 | + |
| 51 | +def test_filter_faq_category_not_found(mock_db_session, client): |
| 52 | + """Test when the requested category does not exist.""" |
| 53 | + |
| 54 | + mock_faq_data_grouped = {} |
| 55 | + |
| 56 | + with patch.object(faq_service, 'fetch_all_grouped_by_category', return_value=mock_faq_data_grouped): |
| 57 | + response = client.get('/api/v1/faqs/?category=UnknownCategory') |
| 58 | + response_data = response.json() |
| 59 | + |
| 60 | + assert response.status_code == 200 |
| 61 | + assert response_data["status_code"] == 200 |
| 62 | + assert response_data["message"] == "FAQs retrieved successfully" |
| 63 | + assert response_data["data"] == {} |
0 commit comments