|
| 1 | +package flagx_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "path" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/m-lab/go/flagx" |
| 9 | + "github.com/m-lab/go/testingx" |
| 10 | +) |
| 11 | + |
| 12 | +func TestStringFile(t *testing.T) { |
| 13 | + tests := []struct { |
| 14 | + name string |
| 15 | + value string |
| 16 | + useFile bool |
| 17 | + wantErr bool |
| 18 | + }{ |
| 19 | + { |
| 20 | + name: "success-string", |
| 21 | + value: "value12345", |
| 22 | + useFile: false, |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "success-file", |
| 26 | + value: "1234567890abcdef", |
| 27 | + useFile: true, |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "error-file", |
| 31 | + value: "@error-bad-filename", |
| 32 | + useFile: false, |
| 33 | + wantErr: true, |
| 34 | + }, |
| 35 | + } |
| 36 | + for _, tt := range tests { |
| 37 | + t.Run(tt.value, func(t *testing.T) { |
| 38 | + value := tt.value |
| 39 | + |
| 40 | + if !tt.wantErr && tt.useFile { |
| 41 | + // This is a file read - so create a file in a temp directory. |
| 42 | + dir := t.TempDir() |
| 43 | + name := path.Join(dir, "file.txt") |
| 44 | + testingx.Must(t, os.WriteFile(name, []byte(tt.value), 0664), "failed to write test file") |
| 45 | + defer os.Remove(name) |
| 46 | + value = "@" + name // reset name to include directory. |
| 47 | + } |
| 48 | + |
| 49 | + fb := &flagx.StringFile{} |
| 50 | + if err := fb.Set(value); (err != nil) != tt.wantErr { |
| 51 | + t.Errorf("StringFile.Set() error = %v, wantErr %v", err, tt.wantErr) |
| 52 | + } |
| 53 | + if tt.wantErr { |
| 54 | + return |
| 55 | + } |
| 56 | + if tt.value != fb.Get() { |
| 57 | + t.Errorf("StringFile.Get() want = %q, got %q", tt.value, fb.Get()) |
| 58 | + } |
| 59 | + if fb.String()[0] != '@' && tt.useFile { |
| 60 | + t.Errorf("StringFile.String() want = @<file>, got %q", fb.String()) |
| 61 | + } |
| 62 | + }) |
| 63 | + } |
| 64 | +} |
0 commit comments