Skip to content
Snippets Groups Projects
test_visit.py 2.31 KiB
import json
from unittest.mock import patch
import pytest
import responses
import stripe

from stripe_checkout.stripe_checkout.models import Event, Order


@responses.activate
@pytest.mark.django_db
def test_list_visitors(client, user):
    client.force_login(user)
    rv = client.get("/visitors/")
    assert rv.status_code == 200


@responses.activate
@pytest.mark.django_db
def test_update_visitor(client, user, visitor_id):
    client.force_login(user)
    rv = client.post(f"/visitors/{visitor_id}/")
    assert rv.status_code == 302


@responses.activate
@pytest.mark.django_db
def test_create_invoice(client, visitor_id):
    """
    test that the create-intent endpoint returns a redirect url
    """
    assert not Order.objects.count()

    rv = client.post(f"/checkout/{visitor_id}/", data={"payment_method": "invoice"})
    assert rv.status_code == 303
    assert Order.objects.count() == 1


@responses.activate
@pytest.mark.django_db
def test_exchange_rate(client, default_exchange_rate, visitor_id):
    client.post(f"/checkout/{visitor_id}/", data={"payment_method": "invoice"})
    call_args = stripe.Invoice.create.call_args[1]
    assert call_args["custom_fields"][0] == {
        "name": "GBP VAT Rate",
        "value": "GBP 1.60 (0.8000)",
    }


@responses.activate
@pytest.mark.django_db
def test_event_webhook(client):
    event = {
        "type": "invoice.paid",
        "data": {"object": {"id": "stripe-invoice"}},
    }
    with patch(
        "stripe.Webhook.construct_event", side_effect=lambda b, *_: json.loads(b)
    ):
        rv = client.post(
            "/stripe-event-webhook/", json.dumps(event), content_type="application/json"
        )
    assert rv.status_code == 200
    assert Event.objects.exists()


@responses.activate
@pytest.mark.django_db
def test_event_webhook_disallowed_when_not_whitelisted(client, settings):
    settings.STRIPE_WEBHOOK_ALLOWED_IPS = ["1.1.1.1"]
    with patch(
        "stripe.Webhook.construct_event", side_effect=lambda b, *_: json.loads(b)
    ):
        rv = client.post(
            "/stripe-event-webhook/",
            json.dumps(
                {
                    "type": "invoice.paid",
                    "data": {"object": {"id": "stripe-invoice"}},
                }
            ),
            content_type="application/json",
        )
    assert rv.status_code == 403