...
1 package playground
2
3 import (
4 "fmt"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "regexp"
9 "testing"
10 )
11
12 func TestHandler_createsAbsoluteURLs(t *testing.T) {
13 rec := httptest.NewRecorder()
14 req := httptest.NewRequest(http.MethodGet, "https://example.org/query", nil)
15 h := Handler("example.org API", "https://example.org/query")
16 h.ServeHTTP(rec, req)
17
18 res := rec.Result()
19 defer res.Body.Close()
20 if res.StatusCode != http.StatusOK {
21 t.Errorf("res.StatusCode = %d; want %d", res.StatusCode, http.StatusOK)
22 }
23
24 b, err := io.ReadAll(res.Body)
25 if err != nil {
26 panic(fmt.Errorf("reading res.Body: %w", err))
27 }
28
29 want := regexp.MustCompile(`(?m)^.*url\s*=\s*['"]https:\/\/example\.org\/query["'].*$`)
30 if !want.Match(b) {
31 t.Errorf("no match for %s in response body", want.String())
32 }
33
34 wantSubURL := regexp.MustCompile(`(?m)^.*subscriptionUrl\s*=\s*['"]wss:\/\/example\.org\/query["'].*$`)
35 if !wantSubURL.Match(b) {
36 t.Errorf("no match for %s in response body", wantSubURL.String())
37 }
38
39 wantMetaCharsetElement := regexp.MustCompile(`<head>\n\s{0,}<meta charset="utf-8">\n\s{0,}.*<title>`)
40 if !wantMetaCharsetElement.Match(b) {
41 t.Errorf("no match for %s in response body", wantMetaCharsetElement.String())
42 }
43 }
44
45 func TestHandler_createsRelativeURLs(t *testing.T) {
46 rec := httptest.NewRecorder()
47 req := httptest.NewRequest(http.MethodGet, "http://localhost:8080/query", nil)
48 h := Handler("example.org API", "/customquery")
49 h.ServeHTTP(rec, req)
50
51 res := rec.Result()
52 defer res.Body.Close()
53 if res.StatusCode != http.StatusOK {
54 t.Errorf("res.StatusCode = %d; want %d", res.StatusCode, http.StatusOK)
55 }
56 if res.Header.Get("Content-Type") != "text/html; charset=UTF-8" {
57 t.Errorf("res.Header.Get(\"Content-Type\") = %q; want %q", res.Header.Get("Content-Type"), "text/html; charset=UTF-8")
58 }
59
60 b, err := io.ReadAll(res.Body)
61 if err != nil {
62 panic(fmt.Errorf("reading res.Body: %w", err))
63 }
64
65 wantURL := regexp.MustCompile(`(?m)^.*url\s*=\s*location\.protocol.*$`)
66 if !wantURL.Match(b) {
67 t.Errorf("no match for %s in response body", wantURL.String())
68 }
69 wantSubURL := regexp.MustCompile(`(?m)^.*subscriptionUrl\s*=\s*wsProto.*['"]\/customquery['"].*$`)
70 if !wantSubURL.Match(b) {
71 t.Errorf("no match for %s in response body", wantSubURL.String())
72 }
73 }
74
75 func TestHandler_Integrity(t *testing.T) {
76 testResourceIntegrity(t, Handler)
77 }
78
View as plain text