github.com/googollee/clic@v0.1.5/source/file_codec_test.go (about) 1 package source 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "testing" 8 9 "github.com/google/go-cmp/cmp" 10 ) 11 12 func TestCodec(t *testing.T) { 13 tests := []struct { 14 codec FileCodec 15 content string 16 wantTag string 17 wantExt string 18 }{ 19 {JSON{}, "{\"int\":1,\"str\":\"str\"}\n", "json", "json"}, 20 } 21 22 for _, tc := range tests { 23 t.Run(fmt.Sprintf("%T", tc.codec), func(t *testing.T) { 24 if got, want := tc.codec.TagName(), tc.wantTag; got != want { 25 t.Errorf("codec.TagName() = %q, want: %q", got, want) 26 } 27 28 if got, want := tc.codec.ExtName(), tc.wantExt; got != want { 29 t.Errorf("codec.ExtName() = %q, want: %q", got, want) 30 } 31 32 fname := filepath.Join(t.TempDir(), "config."+tc.codec.ExtName()) 33 f, err := os.Create(fname) 34 if err != nil { 35 t.Fatalf("can't create temp file %q: %v", fname, err) 36 } 37 _, _ = f.WriteString(tc.content) 38 f.Close() 39 40 var value map[string]any 41 if err := tc.codec.Decode(fname, &value); err != nil { 42 t.Fatalf("tc.codec.Decode() returns error: %v", err) 43 } 44 45 if err := tc.codec.Encode(fname, &value); err != nil { 46 t.Fatalf("tc.codec.Encode() returns error: %v", err) 47 } 48 49 gotContent, err := os.ReadFile(fname) 50 if err != nil { 51 t.Fatalf("os.ReadFile(%q) error: %v", fname, err) 52 } 53 54 if diff := cmp.Diff(string(gotContent), tc.content); diff != "" { 55 t.Errorf("the diff content after decoding and encoding:\n%s", diff) 56 } 57 }) 58 59 t.Run(fmt.Sprintf("%TInvalidFile", tc.codec), func(t *testing.T) { 60 i := 1 61 fname := "/nonexist/file" 62 63 if err := tc.codec.Decode(fname, &i); err == nil { 64 t.Fatalf("tc.codec.Decode() should return an error, which is not") 65 } 66 67 if err := tc.codec.Encode(fname, &i); err == nil { 68 t.Fatalf("tc.codec.Encode() should return an error, which is not") 69 } 70 }) 71 } 72 }