github.com/Psiphon-Inc/goarista@v0.0.0-20160825065156-d002785f4c67/test/panic.go (about)

     1  // Copyright (C) 2015  Arista Networks, Inc.
     2  // Use of this source code is governed by the Apache License 2.0
     3  // that can be found in the COPYING file.
     4  
     5  package test
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  	"testing"
    11  )
    12  
    13  // ShouldPanic will test is a function is panicking
    14  func ShouldPanic(t *testing.T, fn func()) {
    15  	defer func() {
    16  		if r := recover(); r == nil {
    17  			t.Errorf("%sThe function %p should have panicked",
    18  				getCallerInfo(), fn)
    19  		}
    20  	}()
    21  
    22  	fn()
    23  }
    24  
    25  // ShouldPanicWith will test is a function is panicking with a specific message
    26  func ShouldPanicWith(t *testing.T, msg interface{}, fn func()) {
    27  	defer func() {
    28  		if r := recover(); r == nil {
    29  			t.Errorf("%sThe function %p should have panicked",
    30  				getCallerInfo(), fn)
    31  		} else if d := Diff(msg, r); len(d) != 0 {
    32  			t.Errorf("%sThe function %p panicked with the wrong message.\n"+
    33  				"Expected: %#v\nReceived: %#v\nDiff:%s",
    34  				getCallerInfo(), fn, msg, r, d)
    35  		}
    36  	}()
    37  
    38  	fn()
    39  }
    40  
    41  func getCallerInfo() string {
    42  	_, file, line, ok := runtime.Caller(4)
    43  	if !ok {
    44  		return ""
    45  	}
    46  	return fmt.Sprintf("%s:%d\n", file, line)
    47  }