github.com/rzurga/go-swagger@v0.28.1-0.20211109195225-5d1f453ffa3a/generator/utils_test.go (about) 1 package generator 2 3 import ( 4 "io/ioutil" 5 "log" 6 "os" 7 "os/exec" 8 "regexp" 9 "testing" 10 11 "github.com/stretchr/testify/assert" 12 "github.com/stretchr/testify/require" 13 ) 14 15 // testing utilities for codegen assertions 16 17 func reqm(str string) *regexp.Regexp { 18 return regexp.MustCompile(regexp.QuoteMeta(str)) 19 } 20 21 func reqOri(str string) *regexp.Regexp { 22 return regexp.MustCompile(str) 23 } 24 25 func assertInCode(t testing.TB, expr, code string) bool { 26 return assert.Regexp(t, reqm(expr), code) 27 } 28 29 func assertRegexpInCode(t testing.TB, expr, code string) bool { 30 return assert.Regexp(t, reqOri(expr), code) 31 } 32 33 func assertNotInCode(t testing.TB, expr, code string) bool { 34 return assert.NotRegexp(t, reqm(expr), code) 35 } 36 37 // Unused 38 // func assertRegexpNotInCode(t testing.TB, expr, code string) bool { 39 // return assert.NotRegexp(t, reqOri(expr), code) 40 // } 41 42 func requireValidation(t testing.TB, pth, expr string, gm GenSchema) { 43 if !assertValidation(t, pth, expr, gm) { 44 t.FailNow() 45 } 46 } 47 48 func assertValidation(t testing.TB, pth, expr string, gm GenSchema) bool { 49 if !assert.True(t, gm.HasValidations, "expected the schema to have validations") { 50 return false 51 } 52 if !assert.Equal(t, pth, gm.Path, "paths don't match") { 53 return false 54 } 55 if !assert.Equal(t, expr, gm.ValueExpression, "expressions don't match") { 56 return false 57 } 58 return true 59 } 60 61 func funcBody(code string, signature string) string { 62 submatches := regexp.MustCompile( 63 "\\nfunc \\([a-zA-Z_][a-zA-Z0-9_]* " + regexp.QuoteMeta(signature) + " {\\n" + // function signature 64 "((([^}\\n][^\\n]*)?\\n)*)}\\n", // function body 65 ).FindStringSubmatch(code) 66 67 if submatches == nil { 68 return "" 69 } 70 return submatches[1] 71 } 72 73 // testing utilities for codegen build 74 75 func goExecInDir(t testing.TB, target string, args ...string) { 76 cmd := exec.Command("go", args...) 77 cmd.Dir = target 78 p, err := cmd.CombinedOutput() 79 require.NoErrorf(t, err, "unexpected error: %s: %v\n%s", cmd.String(), err, string(p)) 80 } 81 82 func testCwd(t testing.TB) string { 83 cwd, err := os.Getwd() 84 require.NoError(t, err) 85 return cwd 86 } 87 88 func discardOutput() func() { 89 // discards log output then sends a function to set it back to stdout 90 log.SetOutput(ioutil.Discard) 91 92 return func() { 93 log.SetOutput(os.Stdout) 94 } 95 }