| 1 | package busy |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/hex" |
| 6 | "encoding/json" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "os" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | ) |
| 13 | |
| 14 | // The three files are copies, and a copy that drifts is a fork nobody |
| 15 | // chose: each must be the bytes provenance.json records. |
| 16 | func TestFilesAreTheRecordedCopies(t *testing.T) { |
| 17 | raw, err := os.ReadFile("provenance.json") |
| 18 | if err != nil { |
| 19 | t.Fatal(err) |
| 20 | } |
| 21 | var record struct { |
| 22 | Files map[string]struct { |
| 23 | SHA256 string `json:"sha256"` |
| 24 | Bytes int `json:"bytes"` |
| 25 | } `json:"files"` |
| 26 | } |
| 27 | if err := json.Unmarshal(raw, &record); err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | for name, body := range map[string][]byte{"rastrillo.js": ShimJS(), "busy.js": JS(), "busy.css": CSS()} { |
| 31 | want, ok := record.Files[name] |
| 32 | sum := sha256.Sum256(body) |
| 33 | if !ok || want.SHA256 != hex.EncodeToString(sum[:]) || want.Bytes != len(body) { |
| 34 | t.Errorf("%s is not the copy provenance.json records", name) |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | // The point of the package: the shim it hands out has no busy rule left in |
| 40 | // it (or it would fight busy.js), and busy.js has the minimum. |
| 41 | func TestTheShimLeftTheRuleToBusyJS(t *testing.T) { |
| 42 | if strings.Contains(string(ShimJS()), "busySubmit") || strings.Contains(string(ShimJS()), `"submit"`) { |
| 43 | t.Error("the shim still carries a busy rule; two on one page fight over every submit") |
| 44 | } |
| 45 | for _, want := range []string{"HOLD_MS = 650", "busySubmit", "pageshow", "pagehide"} { |
| 46 | if !strings.Contains(string(JS()), want) { |
| 47 | t.Errorf("busy.js lacks %q", want) |
| 48 | } |
| 49 | } |
| 50 | if !strings.Contains(string(CSS()), `:not([data-idle-label]):has(> [rst-spin])`) { |
| 51 | t.Error("busy.css lacks the spinner-in-place rule") |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | func TestHandlerServesOnlyItsTwoFiles(t *testing.T) { |
| 56 | h := Handler() |
| 57 | for path, want := range map[string]int{ |
| 58 | Prefix + "busy.js": 200, |
| 59 | Prefix + "busy.css": 200, |
| 60 | Prefix + "rastrillo.js": 404, |
| 61 | Prefix + "../busy.go": 404, |
| 62 | Prefix: 404, |
| 63 | "/static/busy.js": 404, |
| 64 | "/static/estilo/busy/v1/busy.js": 404, // the version is the digest, not a counter |
| 65 | } { |
| 66 | rec := httptest.NewRecorder() |
| 67 | h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil)) |
| 68 | if rec.Code != want { |
| 69 | t.Errorf("GET %s = %d, want %d", path, rec.Code, want) |
| 70 | } |
| 71 | } |
| 72 | rec := httptest.NewRecorder() |
| 73 | h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, Prefix+"busy.js", nil)) |
| 74 | if rec.Code != http.StatusMethodNotAllowed { |
| 75 | t.Errorf("POST = %d", rec.Code) |
| 76 | } |
| 77 | } |
| 78 | |