|
1 | 1 | package main
|
2 | 2 |
|
3 |
| -import "fmt" |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "testing" |
| 6 | +) |
4 | 7 |
|
5 |
| -func Example_validateID() { |
6 |
| - fmt.Println(validateID("D9L6MbPfE4")) |
7 |
| - fmt.Println(validateID("ABZdez09-_")) |
8 |
| - fmt.Println(validateID("N_M_YelfGeR")) |
9 |
| - fmt.Println(validateID("Abc")) |
10 |
| - fmt.Println(validateID("Abc?q=1235")) |
11 |
| - fmt.Println(validateID("../../file")) |
12 |
| - fmt.Println(validateID("Heya世界")) |
| 8 | +func TestValidateID(t *testing.T) { |
| 9 | + for _, tc := range []struct { |
| 10 | + in string |
| 11 | + want error |
| 12 | + }{ |
| 13 | + { |
| 14 | + in: "D9L6MbPfE4", |
| 15 | + want: nil, |
| 16 | + }, |
| 17 | + { |
| 18 | + in: "ABZdez09-_", |
| 19 | + want: nil, |
| 20 | + }, |
| 21 | + { |
| 22 | + in: "N_M_YelfGeR", |
| 23 | + want: nil, |
| 24 | + }, |
| 25 | + { |
| 26 | + in: "Abc", |
| 27 | + want: fmt.Errorf("id length is 3 instead of 10 or 11"), |
| 28 | + }, |
| 29 | + { |
| 30 | + in: "Abc?q=1235", |
| 31 | + want: fmt.Errorf("id contains unexpected character '?'"), |
| 32 | + }, |
| 33 | + { |
| 34 | + in: "../../file", |
| 35 | + want: fmt.Errorf("id contains unexpected character '.'"), |
| 36 | + }, |
| 37 | + { |
| 38 | + in: "Heya世界", |
| 39 | + want: fmt.Errorf(`id contains unexpected character '\u00e4'`), |
| 40 | + }, |
| 41 | + } { |
| 42 | + got := validateID(tc.in) |
| 43 | + if !equalError(got, tc.want) { |
| 44 | + t.Errorf("validateID(%q) error doesn't match:\n got: %v\nwant: %v", tc.in, got, tc.want) |
| 45 | + } |
| 46 | + } |
| 47 | +} |
13 | 48 |
|
14 |
| - // Output: |
15 |
| - // <nil> |
16 |
| - // <nil> |
17 |
| - // <nil> |
18 |
| - // id length is 3 instead of 10 or 11 |
19 |
| - // id contains unexpected character '?' |
20 |
| - // id contains unexpected character '.' |
21 |
| - // id contains unexpected character '\u00e4' |
| 49 | +// equalError reports whether errors a and b are considered equal. |
| 50 | +// They're equal if both are nil, or both are not nil and a.Error() == b.Error(). |
| 51 | +func equalError(a, b error) bool { |
| 52 | + return a == nil && b == nil || a != nil && b != nil && a.Error() == b.Error() |
22 | 53 | }
|
0 commit comments