github.com/go-swagger/go-swagger@v0.31.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 "os" 19 "sync" 20 "testing" 21 22 "github.com/stretchr/testify/assert" 23 ) 24 25 // mutex for -race because this test alters a global 26 var logMutex = &sync.Mutex{} 27 28 func TestDebugLog(t *testing.T) { 29 tmpFile, _ := os.CreateTemp("", "debug-test") 30 tmpName := tmpFile.Name() 31 logMutex.Lock() 32 defer func() { 33 Debug = false 34 // mutex for -race 35 logMutex.Unlock() 36 _ = os.Remove(tmpName) 37 }() 38 39 // mutex for -race 40 Debug = true 41 debugOptions() 42 defer func() { 43 generatorLogger.SetOutput(os.Stdout) 44 }() 45 generatorLogger.SetOutput(tmpFile) 46 47 debugLog("A debug") 48 _ = tmpFile.Close() 49 50 flushed, _ := os.Open(tmpName) 51 buf := make([]byte, 500) 52 _, _ = flushed.Read(buf) 53 assert.Contains(t, string(buf), "A debug") 54 _ = flushed.Close() 55 56 // test debugLogAsJSON() 57 tmpJSONFile, _ := os.CreateTemp("", "debug-test") 58 tmpJSONName := tmpJSONFile.Name() 59 defer func() { 60 _ = os.Remove(tmpJSONName) 61 }() 62 generatorLogger.SetOutput(tmpJSONFile) 63 debugLogAsJSON("A short debug") 64 65 sch := struct { 66 FieldOne string `json:"fieldOne"` 67 }{ 68 FieldOne: "content", 69 } 70 debugLogAsJSON("A long debug:%t", true, sch) 71 _ = tmpJSONFile.Close() 72 73 flushed, _ = os.Open(tmpJSONName) 74 buf2 := make([]byte, 500) 75 _, _ = flushed.Read(buf2) 76 _ = flushed.Close() 77 assert.Contains(t, string(buf2), "A short debug") 78 assert.Contains(t, string(buf2), "A long debug:true") 79 assert.Contains(t, string(buf2), `"fieldOne":`) 80 assert.Contains(t, string(buf2), `"content"`) 81 } 82 83 func TestDebugLogAsJSON(t *testing.T) { 84 t.SkipNow() 85 86 var body struct { 87 A string `json:"a"` 88 B int `json:"b"` 89 } 90 Debug = true 91 body.A = "abc" 92 body.B = 123 93 debugLogAsJSON("No arg") 94 debugLogAsJSON("With arg:%t", true, body) 95 }