| 1 | package calls |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "testing" |
| 6 | ) |
| 7 | |
| 8 | func TestSqidUsesOnlyTheReadableAlphabet(t *testing.T) { |
| 9 | for i := 0; i < 50; i++ { |
| 10 | s, err := newSqid() |
| 11 | if err != nil { |
| 12 | t.Fatal(err) |
| 13 | } |
| 14 | if len(s) != sqidLength || strings.Trim(s, sqidAlphabet) != "" { |
| 15 | t.Fatalf("bad sqid %q", s) |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | // validSqid is what stands between a room id straight off the request |
| 21 | // line and a rate-limiter key, a hub lookup and a log line (review Task |
| 22 | // 5 item 1), so both of its branches are worth a table: the length, and |
| 23 | // the alphabet. The alphabet branch is the one no other test reaches — |
| 24 | // every id newSqid produces is in it by construction. |
| 25 | func TestValidSqidChecksLengthAndAlphabet(t *testing.T) { |
| 26 | good, err := newSqid() |
| 27 | if err != nil { |
| 28 | t.Fatal(err) |
| 29 | } |
| 30 | table := []struct { |
| 31 | name string |
| 32 | in string |
| 33 | want bool |
| 34 | }{ |
| 35 | {"a minted id", good, true}, |
| 36 | {"ten from the alphabet", "23456789ab", true}, |
| 37 | {"the last character of the alphabet", "zzzzzzzzzz", true}, |
| 38 | {"empty", "", false}, |
| 39 | {"nine characters", "23456789a", false}, |
| 40 | {"eleven characters", "23456789abc", false}, |
| 41 | {"the letter o, which the alphabet drops", "2345678oab", false}, |
| 42 | {"the letter l, which the alphabet drops", "2345678lab", false}, |
| 43 | {"the digit one, which the alphabet drops", "23456781ab", false}, |
| 44 | {"the digit zero, which the alphabet drops", "23456780ab", false}, |
| 45 | {"uppercase", "23456789AB", false}, |
| 46 | {"a hyphen", "2345678-ab", false}, |
| 47 | {"a dot", "23456789.b", false}, |
| 48 | {"a space", "23456789 b", false}, |
| 49 | {"ten bytes of five multi-byte runes", strings.Repeat("é", 5), false}, |
| 50 | } |
| 51 | for _, tc := range table { |
| 52 | t.Run(tc.name, func(t *testing.T) { |
| 53 | if got := validSqid(tc.in); got != tc.want { |
| 54 | t.Fatalf("validSqid(%q) = %v, want %v", tc.in, got, tc.want) |
| 55 | } |
| 56 | }) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func TestLinkTokenHashIsSHA256Hex(t *testing.T) { |
| 61 | tok, hash, err := newLinkToken() |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | if len(hash) != 64 || hashLinkToken(tok) != hash { |
| 66 | t.Fatalf("hash %q does not match token", hash) |
| 67 | } |
| 68 | } |
| 69 | |