github.com/djarvur/go-swagger@v0.18.0/generator/debug_test.go (about) 1 // Copyright 2015 go-swagger maintainers 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package generator 16 17 import ( 18 "io/ioutil" 19 "os" 20 "sync" 21 "testing" 22 23 "github.com/stretchr/testify/assert" 24 ) 25 26 var ( 27 logMutex = &sync.Mutex{} 28 ) 29 30 func TestDebug(t *testing.T) { 31 // test debugLog() 32 tmpFile, _ := ioutil.TempFile("", "debug-test") 33 tmpName := tmpFile.Name() 34 defer func() { 35 Debug = false 36 // mutex for -race 37 logMutex.Unlock() 38 _ = os.Remove(tmpName) 39 }() 40 41 // mutex for -race 42 logMutex.Lock() 43 Debug = true 44 debugOptions() 45 defer func() { 46 generatorLogger.SetOutput(os.Stdout) 47 }() 48 generatorLogger.SetOutput(tmpFile) 49 50 debugLog("A debug") 51 _ = tmpFile.Close() 52 53 flushed, _ := os.Open(tmpName) 54 buf := make([]byte, 500) 55 _, _ = flushed.Read(buf) 56 assert.Contains(t, string(buf), "A debug") 57 _ = flushed.Close() 58 59 // test debugLogAsJSON() 60 tmpJSONFile, _ := ioutil.TempFile("", "debug-test") 61 tmpJSONName := tmpJSONFile.Name() 62 defer func() { 63 _ = os.Remove(tmpJSONName) 64 }() 65 generatorLogger.SetOutput(tmpJSONFile) 66 debugLogAsJSON("A short debug") 67 68 sch := struct { 69 FieldOne string `json:"fieldOne"` 70 }{ 71 FieldOne: "content", 72 } 73 debugLogAsJSON("A long debug:%t", true, sch) 74 _ = tmpJSONFile.Close() 75 76 flushed, _ = os.Open(tmpJSONName) 77 buf2 := make([]byte, 500) 78 _, _ = flushed.Read(buf2) 79 _ = flushed.Close() 80 assert.Contains(t, string(buf2), "A short debug") 81 assert.Contains(t, string(buf2), "A long debug:true") 82 assert.Contains(t, string(buf2), `"fieldOne":`) 83 assert.Contains(t, string(buf2), `"content"`) 84 } 85 86 func TestDebugAsJSON(t *testing.T) { 87 t.SkipNow() 88 var body struct { 89 A string `json:"a"` 90 B int `json:"b"` 91 } 92 Debug = true 93 body.A = "abc" 94 body.B = 123 95 debugLogAsJSON("No arg") 96 debugLogAsJSON("With arg:%t", true, body) 97 }