Test code that takes payments

v0.0.1

Tests of payment code should never call a live provider. Mishka Pay ships a test kit that answers provider calls inside the test process, signs webhook events the way Stripe does and gives you sample objects, so tests run offline, in parallel and without sleeps. This guide sets up the kit, stubs a payment read, tests a webhook listener, runs against Stripe's mock server and sandbox, tests renewals with test clocks and checks a provider you write. If you build an extension for Mishka CMS, the same kit tests its payment code.

Before you begin

  • Mishka Pay installed. The installer already writes the test helper and config below. See Get Started.
  • For the optional sections, Docker for Stripe's mock server and a Stripe sandbox key (sk_test_...).

Set up the kit

elixir
# test/test_helper.exs
MishkaPay.Test.setup!()
MishkaPay.Test.await_plugin!(MishkaPay.Providers.Stripe)
ExUnit.start()

# config/test.exs
config :mishka_pay,
  req_options: [plug: {Req.Test, MishkaPay.Client}]

setup!/0 starts the plugin registry and the tables the kit needs. await_plugin!/1 returns once a plugin your application starts is registered, which happens a moment after boot, so the first test cannot run too early.

Stub the provider

Give the test keys, then answer every provider request with a function of the connection:

elixir
test "a paid order gives access" do
  MishkaPay.Test.start_plugin!(MishkaPay.Providers.Stripe)

  MishkaPay.Test.put_keys("stripe", %{
    secret_key: "sk_test_1"
  })

  MishkaPay.Test.stub_http(fn conn ->
    Req.Test.json(conn, %{
      "id" => "pi_1",
      "object" => "payment_intent",
      "status" => "succeeded",
      "amount" => 1999,
      "currency" => "usd"
    })
  end)

  assert {:ok, %MishkaPay.Payment{status: :paid}} =
           MishkaPay.fetch_payment("stripe", "pi_1")
end
  • put_keys/3 and stub_http/1 belong to the test process and what it starts, so tests that use only them can be async: true.
  • start_plugin!/1 changes an event every test sees, so those tests are async: false. It only waits for a plugin your application already runs, which is the case for a host that starts its providers, as Mishka CMS does.
  • Wait on messages or telemetry (assert_receive, :telemetry_test.attach_event_handlers/2). Never use Process.sleep.

Test a webhook listener

Post a signed event through the real endpoint code with deliver_event/5. The result is the test connection.

elixir
setup do
  MishkaPay.Test.start_plugin!(MishkaPay.Providers.Stripe)

  MishkaPay.Test.put_keys("stripe", %{
    secret_key: "sk_test_kit",
    webhook_secret: "whsec_test_kit"
  })

  :ok
end

test "a subscription update reaches the listener" do
  MishkaPay.Test.start_plugin!(MyApp.Pay.OnEvent)

  conn =
    MishkaPay.Test.deliver_event(
      "site-a",
      "customer.subscription.updated",
      MishkaPay.Test.stripe_object(:subscription),
      "whsec_test_kit"
    )

  assert conn.status == 200

  assert MishkaPay.Test.deliver_event(
           "site-a",
           "x.y",
           %{},
           "whsec_wrong"
         ).status == 400
end
  • signed_event/4 gives {body, headers} for your own request. signed_thin_event/4 does the same for a thin event notification, and the webhook then reads the related object, so stub that read with stub_http/1.
  • stripe_object(kind, overrides) gives one object of each kind: :payment_intent, :checkout_session, :charge, :refund, :dispute, :invoice, :subscription, :customer and :tax_id.
  • A wrong secret gives 400, which is what Stripe would see.

Use Stripe's real request shapes

A hand-written stub can drift from Stripe. Stripe publishes a mock server that answers its real request shapes. Run it and forward stub_http/1 to it:

bash
docker run -p 12111:12111 stripe/stripe-mock

Run against the sandbox

Live sandbox tests belong behind a tag that is excluded unless the key is set, and they accept only test keys. Develop on a Stripe Sandbox, not on the test mode of your main account, because some flows only run in a sandbox.

  • Test cards: 4242 4242 4242 4242 (Visa), 5555 5555 5555 4444 (Mastercard), 4000 0025 0000 3155 (3D Secure), 4000 0000 0000 0002 (declined) and 4000 0000 0000 9995 (insufficient funds). Use any future date and any CVC.
  • 4000 0000 0000 0259 pays and opens a dispute a moment later. Evidence text "winning_evidence" wins it and "losing_evidence" loses it in test mode.
  • Server-side, use test payment methods such as pm_card_visa. Never send a card number through your server.
  • A refund with reason :fraudulent puts the card on the account's Radar block list, and later payments with it are declined. Use other reasons in tests.

Test renewals with test clocks

A test clock moves time on Stripe's servers, so you can see what a renewal, a trial end or a failed card does to a subscription.

elixir
alias MishkaPay.Providers.Stripe.TestClock
# create/2, fetch/2, advance/3, list/1 and delete/2,
# with test keys only

Create a clock, make the customer on it, subscribe, advance the clock and read it until its status is :ready. Then read the subscription again. Old clocks, with their customers and subscriptions, are removed by a task:

bash
mix mishka_pay.stripe.clean_clocks \
  --tenant site-42 \
  --older-than 2

mix mishka_pay.stripe.clean_clocks \
  --name "live renewal" \
  --dry-run

The task refuses live keys. --older-than is in hours (1 by default, and 0 takes every clock). --dry-run lists and deletes nothing. A customer made on a test clock is left out of list_customers/3. Read it by id with fetch_customer/3.

Test PayPal without keys

MishkaPay.Test.PayPal.stub!() answers as PayPal does, with no keys and no network. See Take payments with PayPal. Sandbox tests for PayPal run only when the keys are in the environment, so CI needs no secrets.

Test a provider you write

A provider is a plugin that implements MishkaPay.Provider. This line runs the contract tests every provider must pass:

elixir
use MishkaPay.ProviderCase, provider: MyApp.Pay.Acme

Next steps