| 1 |
package storage |
| 2 |
|
| 3 |
import ( |
| 4 |
"os" |
| 5 |
"path" |
| 6 |
"reflect" |
| 7 |
"testing" |
| 8 |
|
| 9 |
"golang.org/x/text/language" |
| 10 |
) |
| 11 |
|
| 12 |
func TestStoreFromFile(t *testing.T) { |
| 13 |
for _, tc := range []struct { |
| 14 |
name string |
| 15 |
pathToFile string |
| 16 |
content string |
| 17 |
want UserStore |
| 18 |
wantErr bool |
| 19 |
}{ |
| 20 |
{ |
| 21 |
name: "normal user file", |
| 22 |
pathToFile: "userfile.json", |
| 23 |
content: `{ |
| 24 |
"id1": { |
| 25 |
"ID": "id1", |
| 26 |
"EmailVerified": true, |
| 27 |
"PreferredLanguage": "DE" |
| 28 |
} |
| 29 |
}`, |
| 30 |
want: userStore{map[string]*User{ |
| 31 |
"id1": { |
| 32 |
ID: "id1", |
| 33 |
EmailVerified: true, |
| 34 |
PreferredLanguage: language.German, |
| 35 |
}, |
| 36 |
}}, |
| 37 |
}, |
| 38 |
{ |
| 39 |
name: "malformed file", |
| 40 |
pathToFile: "whatever", |
| 41 |
content: "not a json just a text", |
| 42 |
wantErr: true, |
| 43 |
}, |
| 44 |
{ |
| 45 |
name: "not existing file", |
| 46 |
pathToFile: "what/ever/file", |
| 47 |
wantErr: true, |
| 48 |
}, |
| 49 |
} { |
| 50 |
t.Run(tc.name, func(t *testing.T) { |
| 51 |
actualPath := path.Join(t.TempDir(), tc.pathToFile) |
| 52 |
|
| 53 |
if tc.content != "" && tc.pathToFile != "" { |
| 54 |
if err := os.WriteFile(actualPath, []byte(tc.content), 0666); err != nil { |
| 55 |
t.Fatalf("cannot create file with test content: %q", tc.content) |
| 56 |
} |
| 57 |
} |
| 58 |
result, err := StoreFromFile(actualPath) |
| 59 |
if err != nil && !tc.wantErr { |
| 60 |
t.Errorf("StoreFromFile(%q) returned unexpected error %q", tc.pathToFile, err) |
| 61 |
} else if err == nil && tc.wantErr { |
| 62 |
t.Errorf("StoreFromFile(%q) did not return an expected error", tc.pathToFile) |
| 63 |
} |
| 64 |
if !tc.wantErr && !reflect.DeepEqual(tc.want, result.(userStore)) { |
| 65 |
t.Errorf("expected StoreFromFile(%q) = %v, but got %v", |
| 66 |
tc.pathToFile, tc.want, result) |
| 67 |
} |
| 68 |
}) |
| 69 |
} |
| 70 |
} |