func (c *C) logCaller(skip int, issue string) { // This is a bit heavier than it ought to be. skip += 1 // Our own frame. if pc, callerFile, callerLine, ok := runtime.Caller(skip); ok { var testFile string var testLine int testFunc := runtime.FuncForPC(c.method.Get()) if runtime.FuncForPC(pc) != testFunc { for { skip += 1 if pc, file, line, ok := runtime.Caller(skip); ok { // Note that the test line may be different on // distinct calls for the same test. Showing // the "internal" line is helpful when debugging. if runtime.FuncForPC(pc) == testFunc { testFile, testLine = file, line break } } else { break } } } if testFile != "" && (testFile != callerFile || testLine != callerLine) { c.logf("%s:%d > %s:%d:\n... %s", nicePath(testFile), testLine, nicePath(callerFile), callerLine, issue) } else { c.logf("%s:%d:\n... %s", nicePath(callerFile), callerLine, issue) } } }
// This function wraps Fatalf in order to provide a functional stack trace // on failures rather than just a line number of the failing check. This // helps if you have a test that fails in a loop since it will show // the path to get there as well as the error directly. func Fatalf(l Logger, f string, args ...interface{}) { lines := make([]string, 0, 100) msg := fmt.Sprintf(f, args...) lines = append(lines, msg) // Get the directory of testtool in order to ensure that we don't show // it in the stack traces (it can be spammy). _, myfile, _, _ := runtime.Caller(0) mydir := path.Dir(myfile) // Generate the Stack of callers: for i := 0; true; i++ { _, file, line, ok := runtime.Caller(i) if ok == false { break } // Don't print the stack line if its within testtool since its // annoying to see the testtool internals. if path.Dir(file) == mydir { continue } msg := fmt.Sprintf("%d - %s:%d", i, file, line) lines = append(lines, msg) } l.Fatalf("%s", strings.Join(lines, "\n")) }
func caller() { //FIXME add a test to make sure file, pc from Callers matches // the equivalent from Caller. for i := 0; i < 2; i++ { _, _, _, ok := runtime.Caller(i) if !ok { panic(i) } } _, _, _, ok := runtime.Caller(20) if ok { panic(3) } pcA := make([]uintptr, 6, 6) count := runtime.Callers(0, pcA) pcB := make([]uintptr, 6, 6) countM1 := runtime.Callers(1, pcB) if count-1 != countM1 { panic(5) } for i := 1; i < countM1-1; i++ { if pcA[i+1] != pcB[i] { panic(100 + i) } } }
// callerPkgDir returns a pathname containing the build-time location of the // deepest calling function that is not within this package. If that cannot be // found, ok will be false and dir will be empty. func callerPkgDir() (dir string, ok bool) { _, thisFile, _, c*k := runtime.Caller(0) // /home/me/workspace/src/fastly/go-utils/tls/tls.go if !c*k { return } thisDir := filepath.Dir(thisFile) // /home/me/workspace/src/fastly/go-utils/tls sep := fmt.Sprintf("%csrc%c", os.PathSeparator, os.PathSeparator) // /src/ p := strings.SplitN(thisDir, sep, 2) if len(p) < 2 { return } thisPkg := p[1] // fastly/go-utils/tls/ for i := 1; ; i++ { if i > 10 { // typical stack is tls.ConfigureServer -> tls.GenerateConfig -> // tls.LoadPackagedKeypair -> tls.LocatePackagedPEMFile -> // tls.LocatePackagedPEMDir -> tls.searchUpwards panic("excessive recursion inside tls package") } _, file, _, c*k := runtime.Caller(i) // /home/me/workspace/src/foo/bar/subpkg/thing.go if !c*k { return } if !strings.Contains(file, thisPkg) { return filepath.Dir(file), true // /home/me/workspace/src/foo/bar/subpkg } } }
func setCaller(entry *logrus.Entry, skip int) { _, file, line, ok := runtime.Caller(skip) if !ok { file = "???" line = 0 } else { i := 1 for strings.Contains(file, "logrus/") { _, fileHigher, lineHigher, okHigher := runtime.Caller(skip + i) if okHigher { file = fileHigher line = lineHigher } i++ } lastSlash := strings.LastIndex(file, "/") if lastSlash >= 0 { folderSlash := strings.LastIndex(file[:lastSlash], "/") if folderSlash >= 0 { file = file[folderSlash+1:] } else { file = file[lastSlash+1:] } } } entry.Data["caller"] = fmt.Sprintf("%s:%d", file, line) }
// decorate prefixes the string with the file and line of the call site // and inserts the final newline if needed and indentation tabs for formatting. func decorate(s string) string { _, file, line, ok := runtime.Caller(3) if strings.Contains(file, "testing") { _, file, line, ok = runtime.Caller(4) } if ok { // Truncate file name at last file name separator. if index := strings.LastIndex(file, "/"); index >= 0 { file = file[index+1:] } else if index = strings.LastIndex(file, "\\"); index >= 0 { file = file[index+1:] } } else { file = "???" line = 1 } buf := new(bytes.Buffer) // Every line is indented at least one tab. buf.WriteString(" ") fmt.Fprintf(buf, "%s:%d: ", file, line) lines := strings.Split(s, "\n") if l := len(lines); l > 1 && lines[l-1] == "" { lines = lines[:l-1] } for i, line := range lines { if i > 0 { // Second and subsequent lines are indented an extra tab. buf.WriteString("\n\t\t") } buf.WriteString(line) } buf.WriteByte('\n') return buf.String() }
func getActualCaller() (file string, line int, ok bool) { cpc, _, _, ok := runtime.Caller(2) if !ok { return } callerFunPtr := runtime.FuncForPC(cpc) if callerFunPtr == nil { ok = false return } var pc uintptr for callLevel := 3; callLevel < 5; callLevel++ { pc, file, line, ok = runtime.Caller(callLevel) if !ok { return } funcPtr := runtime.FuncForPC(pc) if funcPtr == nil { ok = false return } if getFuncNameWithoutPackage(funcPtr.Name()) != getFuncNameWithoutPackage(callerFunPtr.Name()) { return } } ok = false return }
// computeErrorLocation implements a heuristic to find the location in the user // code where the error occurred. It walks back the callstack until the file // doesn't match "/goa/design/*.go" or one of the DSL package paths. // When successful it returns the file name and line number, empty string and // 0 otherwise. func computeErrorLocation() (file string, line int) { skipFunc := func(file string) bool { if strings.HasSuffix(file, "_test.go") { // Be nice with tests return false } file = filepath.ToSlash(file) for pkg := range dslPackages { if strings.Contains(file, pkg) { return true } } return false } depth := 2 _, file, line, _ = runtime.Caller(depth) for skipFunc(file) { depth++ _, file, line, _ = runtime.Caller(depth) } wd, err := os.Getwd() if err != nil { return } wd, err = filepath.Abs(wd) if err != nil { return } f, err := filepath.Rel(wd, file) if err != nil { return } file = f return }
func test2() { pc, file, line, ok := runtime.Caller(2) log.Println(pc) log.Println(file) log.Println(line) log.Println(ok) f := runtime.FuncForPC(pc) log.Println(f.Name()) pc, file, line, ok = runtime.Caller(0) log.Println(pc) log.Println(file) log.Println(line) log.Println(ok) f = runtime.FuncForPC(pc) log.Println(f.Name()) pc, file, line, ok = runtime.Caller(1) log.Println(pc) log.Println(file) log.Println(line) log.Println(ok) f = runtime.FuncForPC(pc) log.Println(f.Name()) }
// computeErrorLocation implements a heuristic to find the location in the user // code where the error occurred. It walks back the callstack until the file // doesn't match "/goa/design/*.go". // When successful it returns the file name and line number, empty string and // 0 otherwise. func computeErrorLocation() (file string, line int) { depth := 2 _, file, line, _ = runtime.Caller(depth) ok := strings.HasSuffix(file, "_test.go") // Be nice with tests if !ok { nok, _ := regexp.MatchString(`/goa/design/.+\.go$`, file) ok = !nok } for !ok { depth++ _, file, line, _ = runtime.Caller(depth) ok = strings.HasSuffix(file, "_test.go") if !ok { nok, _ := regexp.MatchString(`/goa/design/.+\.go$`, file) ok = !nok } } wd, err := os.Getwd() if err != nil { return } wd, err = filepath.Abs(wd) if err != nil { return } f, err := filepath.Rel(wd, file) if err != nil { return } file = f return }
func (c *C) logCaller(skip int) { // This is a bit heavier than it ought to be. skip += 1 // Our own frame. pc, callerFile, callerLine, ok := runtime.Caller(skip) if !ok { return } var testFile string var testLine int testFunc := runtime.FuncForPC(c.method.PC()) if runtime.FuncForPC(pc) != testFunc { for { skip += 1 if pc, file, line, ok := runtime.Caller(skip); ok { // Note that the test line may be different on // distinct calls for the same test. Showing // the "internal" line is helpful when debugging. if runtime.FuncForPC(pc) == testFunc { testFile, testLine = file, line break } } else { break } } } if testFile != "" && (testFile != callerFile || testLine != callerLine) { c.logCode(testFile, testLine) } c.logCode(callerFile, callerLine) }
// break func Break(format bool, v ...interface{}) { fmt.Println("Variables:") Fdump(os.Stdout, format, v...) var pc, file, line, ok = runtime.Caller(1) if ok { fmt.Printf("\n\n[Debug] %s() [%s:%d]\n[Stack]\n", runtime.FuncForPC(pc).Name(), file, line) } for i := 2; ; i++ { pc, file, line, ok := runtime.Caller(i) if !ok { break } fn := runtime.FuncForPC(pc).Name() if 0 != len(file) { // /usr/local/go/src/pkg/runtime/proc.c:1223 (0x173d0) fmt.Printf("%s(...)\n%s:%d (0x%x)\n", fn, file, line, pc) } else { // runtime.goexit(...) // L1223: runtime.goexit(...) (0x173d0) fmt.Printf("L%d: %s(...) (0x%x)\n", line, fn, pc) } } fmt.Println("\nPress Enter to Continue") fmt.Scanln() fmt.Println("Break End...") }
func TestFrameLine(t *testing.T) { var tests = []struct { Frame want int }{{ Frame(initpc), 9, }, { func() Frame { var pc, _, _, _ = runtime.Caller(0) return Frame(pc) }(), 20, }, { func() Frame { var pc, _, _, _ = runtime.Caller(1) return Frame(pc) }(), 28, }, { Frame(0), // invalid PC 0, }} for _, tt := range tests { got := tt.Frame.line() want := tt.want if want != got { t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) } } }
func (self *Tester) findDepth() int { height := 1 // Skip us for { pc, _, _, ok := runtime.Caller(height) function := runtime.FuncForPC(pc) if !ok { // Got too close to the sun if false { for ; height > 0; height-- { pc, _, _, ok := runtime.Caller(height) fmt.Printf("[%d %v %v]", height, pc, ok) if ok { function := runtime.FuncForPC(pc) fmt.Printf(" => [%s]", function.Name()) } fmt.Printf("\n") } } return 1 } functionEntry := function.Entry() if functionEntry == self.focusEntry || functionEntry == self.testEntry { return height - 1 // Not the surrounding test function, but within it } height += 1 } return 1 }
func (p *Parser) debug(value string) { if p.Logdebug { _, _, line1, _ := runtime.Caller(1) _, _, line2, _ := runtime.Caller(2) fmt.Println(fmt.Sprintf("debug: %s (%d from %d)", value, line1, line2)) } }
func getFailingLine() (failingLine, error) { _, filename, ln, _ := runtime.Caller(3) // TODO: this is really hacky, need to find a way of not using magic numbers for runtime.Caller // If we are not in a test file, we must still be inside this package, // so we need to go up one more stack frame to get to the test file if !strings.HasSuffix(filename, "_test.go") { _, filename, ln, _ = runtime.Caller(4) } bf, err := ioutil.ReadFile(filename) if err != nil { return failingLine{}, fmt.Errorf("Failed to open %s", filename) } lines := strings.Split(string(bf), "\n")[ln-2 : ln+2] return failingLine{ softTabs(lines[1]), filename, softTabs(lines[2]), int(ln), softTabs(lines[0]), }, nil }
// assertSoftForkStatus retrieves the current blockchain info from the given // test harness and ensures the provided soft fork key is both available and its // status is the equivalent of the passed state. func assertSoftForkStatus(r *rpctest.Harness, t *testing.T, forkKey string, state blockchain.ThresholdState) { // Convert the expected threshold state into the equivalent // getblockchaininfo RPC status string. status, err := thresholdStateToStatus(state) if err != nil { _, _, line, _ := runtime.Caller(1) t.Fatalf("assertion failed at line %d: unable to convert "+ "threshold state %v to string", line, state) } info, err := r.Node.GetBlockChainInfo() if err != nil { t.Fatalf("failed to retrieve chain info: %v", err) } // Ensure the key is available. desc, ok := info.Bip9SoftForks[forkKey] if !ok { _, _, line, _ := runtime.Caller(1) t.Fatalf("assertion failed at line %d: softfork status for %q "+ "is not in getblockchaininfo results", line, forkKey) } // Ensure the status it the expected value. if desc.Status != status { _, _, line, _ := runtime.Caller(1) t.Fatalf("assertion failed at line %d: softfork status for %q "+ "is %v instead of expected %v", line, forkKey, desc.Status, status) } }
func FakeHoistLaunchableForDir(dirName string) (*Launchable, *runit.ServiceBuilder) { tempDir, _ := ioutil.TempDir("", "fakeenv") launchableInstallDir := util.From(runtime.Caller(0)).ExpandPath(dirName) launchable := &Launchable{ Location: "testLaunchable.tar.gz", Id: "testPod__testLaunchable", RunAs: "testPod", PodEnvDir: tempDir, Fetcher: uri.DefaultFetcher, RootDir: launchableInstallDir, P2Exec: util.From(runtime.Caller(0)).ExpandPath("fake_p2-exec"), } curUser, err := user.Current() if err == nil { launchable.RunAs = curUser.Username } sbTemp, _ := ioutil.TempDir("", "fakesvdir") sb := &runit.ServiceBuilder{ RunitRoot: sbTemp, } executables, _ := launchable.Executables(sb) for _, exe := range executables { os.MkdirAll(exe.Service.Path, 0644) } return launchable, sb }
func TestValidateTemplate(t *testing.T) { shouldPass := func(template *api.Template) { errs := ValidateTemplate(template) if len(errs) != 0 { _, _, line, _ := goruntime.Caller(1) t.Errorf("line %v: Unexpected non-zero error list: %#v", line, errs) } } shouldFail := func(template *api.Template) { if len(ValidateTemplate(template)) == 0 { _, _, line, _ := goruntime.Caller(1) t.Errorf("line %v: Expected non-zero error list", line) } } // Test empty Template, should fail on empty ID template := &api.Template{} shouldFail(template) // Set ID, should pass template.JSONBase.ID = "templateId" shouldPass(template) // Add invalid Parameter, should fail on Parameter name template.Parameters = []api.Parameter{{Name: "", Value: "1"}} shouldFail(template) // Fix Parameter name, should pass template.Parameters[0].Name = "VALID_NAME" shouldPass(template) // Add invalid Item, should fail on Object.kind template.Items = []runtime.Object{{}} shouldFail(template) }
func getCurrentFile() string { _, filename, _, _ := runtime.Caller(1) //hack: not sure why Caller is inconsistent between test and run if strings.Contains(filename, "recovery/_test") { _, filename, _, _ = runtime.Caller(3) } return filename }
func cl(s string) string { _, thisFile, _, _ := runtime.Caller(1) _, testFile, line, ok := runtime.Caller(2) if ok && thisFile == testFile { return fmt.Sprintf("%d: %s", line, s) } return s }
func getFuncInfo() (funcName, fileName string, lineNo int) { var pc uintptr pc, fileName, lineNo, _ = runtime.Caller(1) pc, _, _, _ = runtime.Caller(1) f := runtime.FuncForPC(pc) funcName = f.Name() return }
func (p *ControllerRegistor) recoverPanic(context *beecontext.Context) { if err := recover(); err != nil { if err == USERSTOPRUN { return } if RunMode == "dev" { if !RecoverPanic { panic(err) } else { if ErrorsShow { if handler, ok := ErrorMaps[fmt.Sprint(err)]; ok { executeError(handler, context) return } } var stack string Critical("the request url is ", context.Input.Url()) Critical("Handler crashed with error", err) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } Critical(fmt.Sprintf("%s:%d", file, line)) stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d", file, line)) } showErr(err, context, stack) } } else { if !RecoverPanic { panic(err) } else { // in production model show all infomation if ErrorsShow { if handler, ok := ErrorMaps[fmt.Sprint(err)]; ok { executeError(handler, context) return } else if handler, ok := ErrorMaps["503"]; ok { executeError(handler, context) return } else { context.WriteString(fmt.Sprint(err)) } } else { Critical("the request url is ", context.Input.Url()) Critical("Handler crashed with error", err) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } Critical(fmt.Sprintf("%s:%d", file, line)) } } } } } }
func caller(s string, va ...interface{}) { _, fn, fl, _ := runtime.Caller(2) fmt.Printf("caller: %s:%d: ", path.Base(fn), fl) fmt.Printf(s, va...) fmt.Println() _, fn, fl, _ = runtime.Caller(1) fmt.Printf("\tcallee: %s:%d: ", path.Base(fn), fl) fmt.Println() }
func caller(s string, va ...interface{}) { _, fn, fl, _ := runtime.Caller(2) fmt.Fprintf(os.Stderr, "caller: %s:%d: ", path.Base(fn), fl) fmt.Fprintf(os.Stderr, s, va...) fmt.Fprintln(os.Stderr) _, fn, fl, _ = runtime.Caller(1) fmt.Fprintf(os.Stderr, "\tcallee: %s:%d: ", path.Base(fn), fl) fmt.Fprintln(os.Stderr) }
func (f *stringFormatter) Format(calldepth int, r *Record, output io.Writer) error { for _, part := range f.parts { if part.verb == fmtVerbStatic { output.Write([]byte(part.layout)) } else if part.verb == fmtVerbTime { output.Write([]byte(r.Time.Format(part.layout))) } else if part.verb == fmtVerbLevelColor { doFmtVerbLevelColor(part.layout, r.Level, output) } else { var v interface{} switch part.verb { case fmtVerbLevel: v = r.Level break case fmtVerbID: v = r.Id break case fmtVerbPid: v = pid break case fmtVerbProgram: v = program break case fmtVerbModule: v = r.Module break case fmtVerbMessage: v = r.Message() break case fmtVerbLongfile, fmtVerbShortfile: _, file, line, ok := runtime.Caller(calldepth + 1) if !ok { file = "???" line = 0 } else if part.verb == fmtVerbShortfile { file = filepath.Base(file) } v = fmt.Sprintf("%s:%d", file, line) case fmtVerbLongfunc, fmtVerbShortfunc, fmtVerbLongpkg, fmtVerbShortpkg: // TODO cache pc v = "???" if pc, _, _, ok := runtime.Caller(calldepth + 1); ok { if f := runtime.FuncForPC(pc); f != nil { v = formatFuncName(part.verb, f.Name()) } } case fmtVerbCallpath: v = formatCallpath(calldepth + 1) default: panic("unhandled format part") } fmt.Fprintf(output, part.layout, v) } } return nil }
func fatalf(t TestingT, fmtStr string, v ...interface{}) { // Backspace (delete) the file and line that t.Fatalf will add // that points to *this* invocation and replace it with that of // invocation of the webDriverT/webElementT method. _, thisFile, thisLine, _ := runtime.Caller(1) undoThisPrefix := strings.Repeat("\x08", len(fmt.Sprintf("%s:%d: ", filepath.Base(thisFile), thisLine))) _, file, line, _ := runtime.Caller(5) t.Fatalf(undoThisPrefix+filepath.Base(file)+":"+strconv.Itoa(line)+": "+fmtStr, v...) }
func (p *ControllerRegistor) recoverPanic(rw http.ResponseWriter, r *http.Request) { if err := recover(); err != nil { if err == USERSTOPRUN { return } if _, ok := err.(middleware.HTTPException); ok { // catch intented errors, only for HTTP 4XX and 5XX } else { if RunMode == "dev" { if !RecoverPanic { panic(err) } else { if ErrorsShow { if handler, ok := middleware.ErrorMaps[fmt.Sprint(err)]; ok { handler(rw, r) return } } var stack string Critical("the request url is ", r.URL.Path) Critical("Handler crashed with error", err) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } Critical(file, line) stack = stack + fmt.Sprintln(file, line) } middleware.ShowErr(err, rw, r, stack) } } else { if !RecoverPanic { panic(err) } else { // in production model show all infomation if ErrorsShow { handler := p.getErrorHandler(fmt.Sprint(err)) handler(rw, r) return } else { Critical("the request url is ", r.URL.Path) Critical("Handler crashed with error", err) for i := 1; ; i++ { _, file, line, ok := runtime.Caller(i) if !ok { break } Critical(file, line) } } } } } } }
func signBuild(artifactPath string) error { sigLoc := fmt.Sprintf("%s.sig", artifactPath) return exec.Command("gpg", "--no-default-keyring", "--keyring", util.From(runtime.Caller(0)).ExpandPath("pubring.gpg"), "--secret-keyring", util.From(runtime.Caller(0)).ExpandPath("secring.gpg"), "-u", "p2universe", "--out", sigLoc, "--detach-sign", artifactPath).Run() }
func signManifest(manifestPath string, workdir string) (string, error) { signedManifestPath := fmt.Sprintf("%s.asc", manifestPath) return signedManifestPath, exec.Command("gpg", "--no-default-keyring", "--keyring", util.From(runtime.Caller(0)).ExpandPath("pubring.gpg"), "--secret-keyring", util.From(runtime.Caller(0)).ExpandPath("secring.gpg"), "-u", "p2universe", "--output", signedManifestPath, "--clearsign", manifestPath).Run() }