github.com/joomcode/pegomock@v2.9.2-0.20220414140958-14f53b6b2a6c+incompatible/testing_t_support.go (about) 1 // Copyright (c) 2013-2014 Onsi Fakhouri 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining 4 // a copy of this software and associated documentation files (the 5 // "Software"), to deal in the Software without restriction, including 6 // without limitation the rights to use, copy, modify, merge, publish, 7 // distribute, sublicense, and/or sell copies of the Software, and to 8 // permit persons to whom the Software is furnished to do so, subject to 9 // the following conditions: 10 // 11 // The above copyright notice and this permission notice shall be 12 // included in all copies or substantial portions of the Software. 13 // 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 22 package pegomock 23 24 import ( 25 "regexp" 26 "runtime/debug" 27 "strings" 28 ) 29 30 type testingT interface { 31 Errorf(format string, args ...interface{}) 32 } 33 34 func BuildTestingTFailHandler(t testingT) FailHandler { 35 return func(message string, callerSkip ...int) { 36 skip := 1 37 if len(callerSkip) > 0 { 38 skip = callerSkip[0] 39 } 40 stackTrace := pruneStack(string(debug.Stack()), skip) 41 t.Errorf("\n%s\n%s", stackTrace, message) 42 } 43 } 44 45 func pruneStack(fullStackTrace string, skip int) string { 46 stack := strings.Split(fullStackTrace, "\n") 47 if len(stack) > 2*(skip+1) { 48 stack = stack[2*(skip+1):] 49 } 50 prunedStack := []string{} 51 re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) 52 for i := 0; i < len(stack)/2; i++ { 53 if !re.Match([]byte(stack[i*2])) { 54 prunedStack = append(prunedStack, stack[i*2]) 55 prunedStack = append(prunedStack, stack[i*2+1]) 56 } 57 } 58 return strings.Join(prunedStack, "\n") 59 } 60 61 func WithT(t testingT) Option { 62 return WithFailHandler(BuildTestingTFailHandler(t)) 63 }