File size: 2,306 Bytes
afa4de7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import os
import pytest
from unittest.mock import patch, MagicMock
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
# Skip all tests in this module if Stripe secret key is not set
STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY")
if not STRIPE_SECRET_KEY:
pytest.skip(
"Stripe not configured – skipping payment tests",
allow_module_level=True)
@pytest.fixture
def mock_stripe():
with patch("stripe.checkout.Session.create") as mock:
yield mock
def test_create_checkout_session_missing_stripe_key(monkeypatch):
monkeypatch.setenv("STRIPE_SECRET_KEY", "")
response = client.post(
"/api/v1/payments/create-checkout-session",
json={
"api_key": "test_key",
"success_url": "https://example.com/success",
"cancel_url": "https://example.com/cancel"})
assert response.status_code == 500
assert "Stripe not configured" in response.json()["detail"]
def test_create_checkout_session_free_key(mock_stripe):
# Mock tracker.get_tier to return Tier.FREE
with patch("app.core.usage_tracker.tracker") as mock_tracker:
mock_tracker.get_tier.return_value = "free"
mock_stripe.return_value = MagicMock(
id="cs_test_123", url="https://checkout.stripe.com/pay")
response = client.post(
"/api/v1/payments/create-checkout-session",
json={
"api_key": "test_key",
"success_url": "https://example.com/success",
"cancel_url": "https://example.com/cancel"})
assert response.status_code == 200
data = response.json()
assert "sessionId" in data
assert "url" in data
def test_create_checkout_session_pro_key():
with patch("app.core.usage_tracker.tracker") as mock_tracker:
mock_tracker.get_tier.return_value = "pro"
response = client.post(
"/api/v1/payments/create-checkout-session",
json={
"api_key": "test_key",
"success_url": "https://example.com/success",
"cancel_url": "https://example.com/cancel"})
assert response.status_code == 400
assert "Only free tier keys can be upgraded" in response.json()[
"detail"]
|