diff --git a/api/v1/services/newsletter.py b/api/v1/services/newsletter.py index 83259bb61..503586950 100644 --- a/api/v1/services/newsletter.py +++ b/api/v1/services/newsletter.py @@ -70,9 +70,11 @@ def unsubscribe(db: Session, request: EmailSchema) -> None: newsletter_subscriber = db.query(NewsletterSubscriber).filter(NewsletterSubscriber.email == request.email).first() if not newsletter_subscriber: raise HTTPException( - status_code=404, detail="Email not found." + status_code=400, + detail="No active subscription found for your email." ) db.delete(newsletter_subscriber) + db.commit() def delete(db: Session, id: str): """Deletes a single newsletter by id""" diff --git a/tests/v1/newsletter/test_newsletter_subscribe.py b/tests/v1/newsletter/test_newsletter_subscribe.py new file mode 100644 index 000000000..a05926060 --- /dev/null +++ b/tests/v1/newsletter/test_newsletter_subscribe.py @@ -0,0 +1,69 @@ +from datetime import datetime, timezone +from unittest.mock import MagicMock, patch + +import pytest +from fastapi.testclient import TestClient +from sqlalchemy.orm import Session +from uuid_extensions import uuid7 + +from api.db.database import get_db +from api.v1.models.contact_us import ContactUs +from api.v1.models.newsletter import NewsletterSubscriber +from main import app + + + +@pytest.fixture +def db_session_mock(): + db_session = MagicMock(spec=Session) + return db_session + +@pytest.fixture +def client(db_session_mock): + app.dependency_overrides[get_db] = lambda: db_session_mock + client = TestClient(app) + yield client + app.dependency_overrides = {} + + +def mock_subscriber(): + return NewsletterSubscriber( + id=str(uuid7()), + email="jane.doe@example.com", + ) + +@patch("api.v1.services.newsletter.NewsletterService.create") +@patch("api.v1.services.newsletter.NewsletterService.check_existing_subscriber") +def test_newsletter_subscribe(mock_create, mock_check_existing, db_session_mock, client): + """Tests the POST /api/v1/newsletter-subscription endpoint to ensure successful subscription with valid input.""" + + db_session_mock.add.return_value = None + db_session_mock.commit.return_value = None + db_session_mock.refresh.return_value = None + + mock_create.return_value = mock_subscriber() + mock_check_existing.return_value = None + + response = client.post('/api/v1/newsletter-subscription', json={ + "email": "jane.doe@example.com" + }) + + print('response', response.json()) + assert response.status_code == 201 + + +@patch("api.v1.services.newsletter.NewsletterService.create") +def test_newsletter_subscribe_missing_fields(mock_create, db_session_mock, client): + """Tests the POST /api/v1/newsletter-subscription endpoint for missing required fields.""" + + mock_create.return_value = mock_subscriber() + + db_session_mock.add.return_value = None + db_session_mock.commit.return_value = None + db_session_mock.refresh.return_value = None + + response = client.post('/api/v1/newsletter-subscription', json={ + + }) + + assert response.status_code == 422 diff --git a/tests/v1/newsletter/test_newsletter_unsubscribe.py b/tests/v1/newsletter/test_newsletter_unsubscribe.py index ec55e94e0..c69c30bcb 100644 --- a/tests/v1/newsletter/test_newsletter_unsubscribe.py +++ b/tests/v1/newsletter/test_newsletter_unsubscribe.py @@ -1,78 +1,60 @@ -import sys, os -import warnings - -warnings.filterwarnings("ignore", category=DeprecationWarning) -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) +from datetime import datetime, timezone +from unittest.mock import MagicMock, patch import pytest from fastapi.testclient import TestClient -from main import app +from sqlalchemy.orm import Session +from uuid_extensions import uuid7 + from api.db.database import get_db +from api.v1.models.contact_us import ContactUs from api.v1.models.newsletter import NewsletterSubscriber -from unittest.mock import MagicMock -from api.v1.services.user import oauth2_scheme, user_service - -def mock_deps(): - return MagicMock(id="user_id") +from main import app -def mock_oauth(): - return 'access_token' -client = TestClient(app) -# Mock the database dependency @pytest.fixture def db_session_mock(): - db_session = MagicMock() - yield db_session - -# Override the dependency with the mock -@pytest.fixture(autouse=True) -def override_get_db(db_session_mock): - def get_db_override(): - yield db_session_mock - - app.dependency_overrides[get_db] = get_db_override - yield - # Clean up after the test by removing the override - app.dependency_overrides = {} + db_session = MagicMock(spec=Session) + return db_session -class TestUnsubscribeNewsletter: +@pytest.fixture +def client(db_session_mock): + app.dependency_overrides[get_db] = lambda: db_session_mock + client = TestClient(app) + yield client + app.dependency_overrides = {} - @classmethod - def setup_class(cls): - app.dependency_overrides[user_service.get_current_super_admin] = mock_deps - @classmethod - def teardown_class(cls): - app.dependency_overrides = {} +@patch("api.v1.services.newsletter.NewsletterService.unsubscribe") +def test_newsletter_subscribe(mock_unsubscribe, db_session_mock, client): + """Tests the POST /api/v1/newsletter-subscription endpoint to ensure successful subscription with valid input.""" - def test_unsubscribe_success(self, db_session_mock): - # Arrange - existing_subscriber = NewsletterSubscriber(email="test@example.com") - db_session_mock.query(NewsletterSubscriber).filter().first.return_value = existing_subscriber + mock_unsubscribe.return_value = None - email_data = {"email": "test@example.com"} + db_session_mock.add.return_value = None + db_session_mock.commit.return_value = None + db_session_mock.refresh.return_value = None - # Act - response = client.post("/api/v1/newsletters/unsubscribe", json=email_data) + response = client.post('/api/v1/newsletters/unsubscribe', json={ + "email": "jane.doe@example.com" + }) - # Assert - assert response.status_code == 200 - assert response.json()["message"] == "Unsubscribed successfully." + print('response', response.json()) + assert response.status_code == 200 - def test_unsubscribe_email_not_found(self, db_session_mock): - # Arrange - db_session_mock.query(NewsletterSubscriber).filter().first.return_value = None - email_data = {"email": "notfound@example.com"} +@patch("api.v1.services.newsletter.NewsletterService.unsubscribe") +def test_newsletter_subscribe_missing_fields(mock_unsubscribe, db_session_mock, client): + """Tests the POST /api/v1/newsletter-subscription endpoint for missing required fields.""" - # Act - response = client.post("/api/v1/newsletters/unsubscribe", json=email_data) + mock_unsubscribe.return_value = None - # Assert - assert response.status_code == 404 - assert response.json()["message"] == "Email not found." + db_session_mock.add.return_value = None + db_session_mock.commit.return_value = None + db_session_mock.refresh.return_value = None -if __name__ == "__main__": - pytest.main() + response = client.post('/api/v1/newsletter-subscription', json={ + + }) + assert response.status_code == 422