github.com/lyft/flytestdlib@v0.3.12-0.20210213045714-8cdd111ecda1/cli/pflags/api/generator_test.go (about) 1 package api 2 3 import ( 4 "context" 5 "flag" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 "reflect" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 ) 14 15 // Make sure existing config file(s) parse correctly before overriding them with this flag! 16 var update = flag.Bool("update", false, "Updates testdata") 17 18 // If v is a pointer, it will get its element value or the zero value of the element type. 19 // If v is not a pointer, it will return it as is. 20 func elemValueOrNil(v interface{}) interface{} { 21 if t := reflect.TypeOf(v); t.Kind() == reflect.Ptr { 22 if reflect.ValueOf(v).IsNil() { 23 return reflect.Zero(t.Elem()).Interface() 24 } 25 26 return reflect.ValueOf(v).Interface() 27 } else if v == nil { 28 return reflect.Zero(t).Interface() 29 } 30 31 return v 32 } 33 34 func TestElemValueOrNil(t *testing.T) { 35 var iPtr *int 36 assert.Equal(t, 0, elemValueOrNil(iPtr)) 37 var sPtr *string 38 assert.Equal(t, "", elemValueOrNil(sPtr)) 39 var i int 40 assert.Equal(t, 0, elemValueOrNil(i)) 41 var s string 42 assert.Equal(t, "", elemValueOrNil(s)) 43 var arr []string 44 assert.Equal(t, arr, elemValueOrNil(arr)) 45 } 46 47 func TestNewGenerator(t *testing.T) { 48 g, err := NewGenerator("github.com/lyft/flytestdlib/cli/pflags/api", "TestType", "DefaultTestType") 49 if !assert.NoError(t, err) { 50 t.FailNow() 51 } 52 53 ctx := context.Background() 54 p, err := g.Generate(ctx) 55 if !assert.NoError(t, err) { 56 t.FailNow() 57 } 58 59 codeOutput, err := ioutil.TempFile("", "output-*.go") 60 if !assert.NoError(t, err) { 61 t.FailNow() 62 } 63 64 defer func() { assert.NoError(t, os.Remove(codeOutput.Name())) }() 65 66 testOutput, err := ioutil.TempFile("", "output-*_test.go") 67 if !assert.NoError(t, err) { 68 t.FailNow() 69 } 70 71 defer func() { assert.NoError(t, os.Remove(testOutput.Name())) }() 72 73 assert.NoError(t, p.WriteCodeFile(codeOutput.Name())) 74 assert.NoError(t, p.WriteTestFile(testOutput.Name())) 75 76 codeBytes, err := ioutil.ReadFile(codeOutput.Name()) 77 assert.NoError(t, err) 78 79 testBytes, err := ioutil.ReadFile(testOutput.Name()) 80 assert.NoError(t, err) 81 82 goldenFilePath := filepath.Join("testdata", "testtype.go") 83 goldenTestFilePath := filepath.Join("testdata", "testtype_test.go") 84 if *update { 85 assert.NoError(t, ioutil.WriteFile(goldenFilePath, codeBytes, os.ModePerm)) 86 assert.NoError(t, ioutil.WriteFile(goldenTestFilePath, testBytes, os.ModePerm)) 87 } 88 89 goldenOutput, err := ioutil.ReadFile(filepath.Clean(goldenFilePath)) 90 assert.NoError(t, err) 91 assert.Equal(t, string(goldenOutput), string(codeBytes)) 92 93 goldenTestOutput, err := ioutil.ReadFile(filepath.Clean(goldenTestFilePath)) 94 assert.NoError(t, err) 95 assert.Equal(t, string(goldenTestOutput), string(testBytes)) 96 }