taler-merchant-demos

Python-based Frontends for the Demonstration Web site
Log | Files | Refs | README | LICENSE

merchant_samples_test.go (11751B)


      1 package web
      2 
      3 import (
      4 	"bytes"
      5 	"context"
      6 	"encoding/base64"
      7 	"encoding/json"
      8 	"image/png"
      9 	"net/http"
     10 	"net/http/httptest"
     11 	"net/url"
     12 	"reflect"
     13 	"strings"
     14 	"testing"
     15 	"time"
     16 
     17 	"git.taler.net/taler-merchant-demos/internal/backend"
     18 )
     19 
     20 func sampleRequest(app *App, method, path, body string) *httptest.ResponseRecorder {
     21 	req := httptest.NewRequest(method, path, strings.NewReader(body))
     22 	req.Host = "test_landing_backends"
     23 	req.Header.Set("X-Forwarded-Host", "proxy.internal")
     24 	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
     25 	req.Header.Set("X-Forwarded-Prefix", "/demo")
     26 	req.Header.Set("Accept-Language", "de")
     27 	rec := httptest.NewRecorder()
     28 	app.ServeHTTP(rec, req)
     29 	return rec
     30 }
     31 
     32 func sampleApp(t *testing.T, handler http.HandlerFunc) *App {
     33 	t.Helper()
     34 	opts := Options{Shop: "landing", Currency: "TESTKUDOS", PublicURLs: PublicURLs{Landing: "https://public.example/samples-demo/"}}
     35 	if handler != nil {
     36 		server := httptest.NewServer(handler)
     37 		t.Cleanup(server.Close)
     38 		merchant, err := backend.New(server.URL+"/instances/landing-samples/", "samples-key")
     39 		if err != nil {
     40 			t.Fatal(err)
     41 		}
     42 		opts.SamplesBackend = merchant
     43 	}
     44 	app, err := New(opts)
     45 	if err != nil {
     46 		t.Fatal(err)
     47 	}
     48 	return app
     49 }
     50 
     51 func TestSamplesDisabled(t *testing.T) {
     52 	app := sampleApp(t, nil)
     53 	if strings.Contains(sampleRequest(app, "GET", "/en/", "").Body.String(), "merchant-samples") {
     54 		t.Fatal("samples advertised while disabled")
     55 	}
     56 	for _, path := range []string{"/merchant-samples", "/en/merchant-samples", "/en/merchant-samples/receipts/id"} {
     57 		if got := sampleRequest(app, "GET", path, "").Code; got != 404 {
     58 			t.Errorf("%s returned %d", path, got)
     59 		}
     60 	}
     61 	if got := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample=earn").Code; got != 404 {
     62 		t.Fatal(got)
     63 	}
     64 }
     65 
     66 func TestSamplesStartup(t *testing.T) {
     67 	// A concurrent process creates the coupon after our GET. The pass lookup
     68 	// then fails once. Neither event should require restarting the landing page.
     69 	stored := make(map[string]sampleFamily)
     70 	posts := make(map[string]int)
     71 	unavailable := make(chan struct{})
     72 	var failed bool
     73 	app := sampleApp(t, func(w http.ResponseWriter, r *http.Request) {
     74 		if r.Header.Get("Authorization") != "Bearer samples-key" {
     75 			t.Error("missing samples credential")
     76 		}
     77 		suffix := strings.TrimPrefix(r.URL.Path, "/instances/landing-samples/private/tokenfamilies")
     78 		switch r.Method {
     79 		case "GET":
     80 			slug := strings.TrimPrefix(suffix, "/")
     81 			if slug == passSlug && !failed {
     82 				failed = true
     83 				close(unavailable)
     84 				w.WriteHeader(503)
     85 				return
     86 			}
     87 			family, ok := stored[slug]
     88 			if !ok {
     89 				w.WriteHeader(404)
     90 				return
     91 			}
     92 			json.NewEncoder(w).Encode(struct {
     93 				sampleFamily
     94 				ValidBefore map[string]string `json:"valid_before"`
     95 			}{family, map[string]string{"t_s": "never"}})
     96 		case "POST":
     97 			if suffix != "" {
     98 				t.Errorf("unexpected POST %s", r.URL.Path)
     99 			}
    100 			var family sampleFamily
    101 			if err := json.NewDecoder(r.Body).Decode(&family); err != nil {
    102 				t.Error(err)
    103 			}
    104 			posts[family.Slug]++
    105 			stored[family.Slug] = family
    106 			if family.Slug == couponSlug {
    107 				w.WriteHeader(409)
    108 				return
    109 			}
    110 			w.WriteHeader(204)
    111 		default:
    112 			t.Errorf("unexpected request %s %s", r.Method, r.URL)
    113 		}
    114 	})
    115 	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    116 	defer cancel()
    117 	done := make(chan struct{})
    118 	go func() { app.ProvisionSamples(ctx); close(done) }()
    119 	select {
    120 	case <-unavailable:
    121 	case <-ctx.Done():
    122 		t.Fatal(ctx.Err())
    123 	}
    124 	page := sampleRequest(app, "GET", "/de/", "")
    125 	if page.Code != 200 || !strings.Contains(page.Body.String(), "/demo/de/merchant-samples") {
    126 		t.Fatal("main landing unavailable")
    127 	}
    128 	for _, r := range []*httptest.ResponseRecorder{sampleRequest(app, "GET", "/de/merchant-samples", ""), sampleRequest(app, "POST", "/de/merchant-samples/orders", "sample=earn")} {
    129 		if r.Code != 503 || r.Header().Get("Retry-After") == "" {
    130 			t.Fatalf("pending page status %d", r.Code)
    131 		}
    132 	}
    133 	select {
    134 	case <-done:
    135 	case <-ctx.Done():
    136 		t.Fatal(ctx.Err())
    137 	}
    138 	if !app.samplesReady.Load() {
    139 		t.Fatal("samples unavailable after retry")
    140 	}
    141 	// A fresh process reads the existing families and preserves issued tokens.
    142 	app.samplesReady.Store(false)
    143 	app.ProvisionSamples(ctx)
    144 	if !app.samplesReady.Load() || posts[couponSlug] != 1 || posts[passSlug] != 1 {
    145 		t.Fatalf("restart: posts %v", posts)
    146 	}
    147 	if stored[passSlug].Kind != "subscription" || stored[couponSlug].Kind != "discount" || stored[passSlug].Duration.Microseconds != (24*time.Hour).Microseconds() || stored[couponSlug].Duration.Microseconds != (30*24*time.Hour).Microseconds() {
    148 		t.Fatalf("wrong sample families: %v", stored)
    149 	}
    150 	wrong := stored[passSlug]
    151 	wrong.Kind = "discount"
    152 	if err := ensureSampleFamily(ctx, app.opts.SamplesBackend, wrong); err == nil {
    153 		t.Fatal("accepted incompatible family")
    154 	}
    155 	if got := sampleRequest(app, "GET", "/merchant-samples", "").Header().Get("Location"); got != "/demo/de/merchant-samples" {
    156 		t.Fatal(got)
    157 	}
    158 	page = sampleRequest(app, "GET", "/de/merchant-samples", "")
    159 	if page.Code != 200 || strings.Count(page.Body.String(), `name="sample"`) != 8 || !strings.Contains(page.Body.String(), `action="/demo/de/merchant-samples/orders"`) {
    160 		t.Fatal("missing sample actions")
    161 	}
    162 	for _, action := range []string{"coffee", "exhibition", "earn-multi", "redeem-multi"} {
    163 		if strings.Count(page.Body.String(), `name="sample" value="`+action+`"`) != 1 {
    164 			t.Errorf("expected one button for %s", action)
    165 		}
    166 	}
    167 }
    168 
    169 func TestSampleCheckouts(t *testing.T) {
    170 	// Capture real JSON requests through the normal HTTP entry point.
    171 	orders := make(chan backend.PostOrderRequest, 1)
    172 	statuses := make(chan backend.OrderStatusResponse, 1)
    173 	app := sampleApp(t, func(w http.ResponseWriter, r *http.Request) {
    174 		if r.Method == "POST" && r.URL.Path == "/instances/landing-samples/private/orders" {
    175 			var order backend.PostOrderRequest
    176 			if err := json.NewDecoder(r.Body).Decode(&order); err != nil {
    177 				t.Error(err)
    178 			}
    179 			orders <- order
    180 			json.NewEncoder(w).Encode(backend.PostOrderResponse{OrderID: order.Order.OrderID, Token: "claim"})
    181 		} else if r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/instances/landing-samples/private/orders/") {
    182 			json.NewEncoder(w).Encode(<-statuses)
    183 		} else {
    184 			t.Errorf("unexpected request %s %s", r.Method, r.URL)
    185 			w.WriteHeader(404)
    186 		}
    187 	})
    188 	app.samplesReady.Store(true)
    189 	coupon := []backend.OrderInput{{Type: "token", TokenFamilySlug: couponSlug}}
    190 	issueCoupon := []backend.OrderOutput{{Type: "token", TokenFamilySlug: couponSlug}}
    191 	pass := []backend.OrderOutput{{Type: "token", TokenFamilySlug: passSlug}}
    192 	const one = "TESTKUDOS:1"
    193 	const two = "TESTKUDOS:2"
    194 	coffee := []backend.OrderChoice{
    195 		{Amount: two, Description: "Without coupon", Outputs: issueCoupon},
    196 		{Amount: one, Description: "With one coupon", Inputs: coupon},
    197 		{Amount: "TESTKUDOS:0", Description: "With two coupons", Inputs: []backend.OrderInput{{Type: "token", TokenFamilySlug: couponSlug, Count: 2}}},
    198 	}
    199 	exhibition := []backend.OrderChoice{
    200 		{Amount: one, Description: "Single entry"},
    201 		{Amount: "TESTKUDOS:3", Description: "Day pass", Outputs: pass},
    202 		{Amount: "TESTKUDOS:0", Description: "Entry with pass", Inputs: []backend.OrderInput{{Type: "token", TokenFamilySlug: passSlug}}, Outputs: pass},
    203 	}
    204 	ids := map[string]bool{}
    205 	for _, tc := range []struct {
    206 		name    string
    207 		choices []backend.OrderChoice
    208 	}{
    209 		{"basket", []backend.OrderChoice{{Amount: "TESTKUDOS:7"}}},
    210 		{"pay-v0", nil}, {"pay-v1", []backend.OrderChoice{{Amount: one}}},
    211 		{"coffee", coffee}, {"earn", coffee}, {"redeem", coffee},
    212 		{"exhibition", exhibition}, {"pass", exhibition}, {"admission", exhibition},
    213 		{"postcard", []backend.OrderChoice{{Amount: one}, {Amount: "CHF:0.10"}}},
    214 		{"earn-multi", []backend.OrderChoice{{Amount: two, Outputs: issueCoupon}, {Amount: "CHF:0.20", Outputs: issueCoupon}}},
    215 		{"redeem-multi", []backend.OrderChoice{
    216 			{Amount: two, Description: "Full price"}, {Amount: one, Description: "Use a coupon", Inputs: coupon},
    217 			{Amount: "CHF:0.20", Description: "Full price"}, {Amount: "CHF:0.10", Description: "Use a coupon", Inputs: coupon},
    218 		}},
    219 	} {
    220 		t.Run(tc.name, func(t *testing.T) {
    221 			rec := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample="+tc.name)
    222 			if rec.Code != 303 {
    223 				t.Fatalf("checkout %d %s", rec.Code, rec.Body)
    224 			}
    225 			request := <-orders
    226 			order := request.Order
    227 			switch tc.name {
    228 			case "coffee", "earn", "redeem":
    229 				checkProducts(t, order.Products, []productSpec{{"Coffee", "1", two, "coffee.png"}})
    230 				if order.Products[0].Description != "Freshly brewed coffee" {
    231 					t.Error("wrong coffee description")
    232 				}
    233 			case "basket":
    234 				checkProducts(t, order.Products, []productSpec{
    235 					{"Coffee", "2", "TESTKUDOS:4", "coffee.png"},
    236 					{"Croissant", "1", two, "croissant.png"},
    237 					{"Tea", "1", one, ""},
    238 				})
    239 			default:
    240 				if len(order.Products) != 0 {
    241 					t.Fatalf("unexpected products for %s", tc.name)
    242 				}
    243 			}
    244 			id := order.OrderID
    245 			if !sampleOrderID.MatchString(id) || ids[id] {
    246 				t.Fatal("invalid or reused ID", id)
    247 			}
    248 			ids[id] = true
    249 			location, err := url.Parse(rec.Header().Get("Location"))
    250 			if err != nil || location.Path != "/instances/landing-samples/orders/"+id || location.Query().Get("token") != "claim" || !request.CreateToken {
    251 				t.Fatal(location)
    252 			}
    253 			receipt := "/en/merchant-samples/receipts/" + id
    254 			if order.FulfillmentURL != "https://public.example/samples-demo"+receipt || order.PublicReorderURL != "https://public.example/samples-demo/en/merchant-samples" || order.Summary == "" {
    255 				t.Fatal(order)
    256 			}
    257 			if !reflect.DeepEqual(order.Choices, tc.choices) {
    258 				t.Fatalf("choices %+v, want %+v", order.Choices, tc.choices)
    259 			}
    260 			status := backend.OrderStatusResponse{OrderStatus: "paid", ContractTerms: backend.ContractTerms{Version: order.Version, Amount: order.Amount, Choices: order.Choices}}
    261 			amount := one
    262 			if tc.choices == nil {
    263 				if order.Version != 0 || order.Amount != one {
    264 					t.Fatal(order)
    265 				}
    266 			} else {
    267 				if order.Version != 1 || order.Amount != "" {
    268 					t.Fatal(order)
    269 				}
    270 				last := len(tc.choices) - 1
    271 				status.ChoiceIndex = &last
    272 				amount = tc.choices[last].Amount
    273 			}
    274 			statuses <- status
    275 			page := sampleRequest(app, "GET", receipt, "")
    276 			if page.Code != 200 || !strings.Contains(page.Body.String(), "Paid "+amount) {
    277 				t.Fatalf("receipt for %s: %d", amount, page.Code)
    278 			}
    279 		})
    280 	}
    281 	if got := sampleRequest(app, "POST", "/en/merchant-samples/orders", "sample=unknown").Code; got != 400 {
    282 		t.Fatalf("unknown sample %d", got)
    283 	}
    284 }
    285 
    286 type productSpec struct{ name, quantity, price, imageFile string }
    287 
    288 func checkProducts(t *testing.T, products []backend.Product, want []productSpec) {
    289 	t.Helper()
    290 	if len(products) != len(want) {
    291 		t.Fatalf("got %d products, want %d", len(products), len(want))
    292 	}
    293 	for i, item := range want {
    294 		p := products[i]
    295 		if p.Name != item.name || p.UnitQuantity != item.quantity || !reflect.DeepEqual(p.Prices, []string{item.price}) || p.Description == "" || p.PricesAreNet {
    296 			t.Errorf("invalid line item %d: %s, quantity %s, prices %v", i, p.Name, p.UnitQuantity, p.Prices)
    297 		}
    298 		if item.imageFile == "" {
    299 			if p.Image != "" {
    300 				t.Errorf("unexpected image for %s", p.Name)
    301 			}
    302 			continue
    303 		}
    304 		encoded, ok := strings.CutPrefix(p.Image, "data:image/png;base64,")
    305 		data, err := base64.StdEncoding.DecodeString(encoded)
    306 		if !ok || err != nil {
    307 			t.Fatalf("invalid image URL for %s", p.Name)
    308 		}
    309 		if _, err := png.Decode(bytes.NewReader(data)); err != nil {
    310 			t.Fatal(err)
    311 		}
    312 		preview, err := Assets.ReadFile("assets/static/" + item.imageFile)
    313 		if err != nil || !bytes.Equal(preview, data) {
    314 			t.Errorf("image for %s differs from preview", p.Name)
    315 		}
    316 	}
    317 }