Skip to content

Commit

Permalink
Merge pull request #888 from JoshuaOloton/fix/newsletter-subscription
Browse files Browse the repository at this point in the history
fix: newsletter subscription
  • Loading branch information
johnson-oragui authored Aug 14, 2024
2 parents 5abdecd + bc34a6b commit 8b8355e
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 57 deletions.
4 changes: 3 additions & 1 deletion api/v1/services/newsletter.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"""
Expand Down
69 changes: 69 additions & 0 deletions tests/v1/newsletter/test_newsletter_subscribe.py
Original file line number Diff line number Diff line change
@@ -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="[email protected]",
)

@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": "[email protected]"
})

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
94 changes: 38 additions & 56 deletions tests/v1/newsletter/test_newsletter_unsubscribe.py
Original file line number Diff line number Diff line change
@@ -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="[email protected]")
db_session_mock.query(NewsletterSubscriber).filter().first.return_value = existing_subscriber
mock_unsubscribe.return_value = None

email_data = {"email": "[email protected]"}
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": "[email protected]"
})

# 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": "[email protected]"}
@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

0 comments on commit 8b8355e

Please sign in to comment.