github.com/jaredpalmer/terraform@v1.1.0-alpha20210908.0.20210911170307-88705c943a03/internal/logging/panic_test.go (about) 1 package logging 2 3 import ( 4 "bytes" 5 "fmt" 6 "strings" 7 "testing" 8 9 "github.com/hashicorp/go-hclog" 10 ) 11 12 func TestPanicRecorder(t *testing.T) { 13 rec := panics.registerPlugin("test") 14 15 output := []string{ 16 "panic: test", 17 " stack info", 18 } 19 20 for _, line := range output { 21 rec(line) 22 } 23 24 expected := fmt.Sprintf(pluginPanicOutput, "test", strings.Join(output, "\n")) 25 26 res := PluginPanics() 27 if len(res) == 0 { 28 t.Fatal("no output") 29 } 30 31 if res[0] != expected { 32 t.Fatalf("expected: %q\ngot: %q", expected, res[0]) 33 } 34 } 35 36 func TestPanicLimit(t *testing.T) { 37 rec := panics.registerPlugin("test") 38 39 rec("panic: test") 40 41 for i := 0; i < 200; i++ { 42 rec(fmt.Sprintf("LINE: %d", i)) 43 } 44 45 res := PluginPanics() 46 // take the extra content into account 47 max := strings.Count(pluginPanicOutput, "\n") + panics.maxLines 48 for _, out := range res { 49 found := strings.Count(out, "\n") 50 if found > max { 51 t.Fatalf("expected no more than %d lines, got: %d", max, found) 52 } 53 } 54 } 55 56 func TestLogPanicWrapper(t *testing.T) { 57 var buf bytes.Buffer 58 logger := hclog.NewInterceptLogger(&hclog.LoggerOptions{ 59 Name: "test", 60 Level: hclog.Debug, 61 Output: &buf, 62 DisableTime: true, 63 }) 64 65 wrapped := (&logPanicWrapper{ 66 Logger: logger, 67 }).Named("test") 68 69 wrapped.Debug("panic: invalid foo of bar") 70 wrapped.Debug("\tstack trace") 71 72 expected := `[DEBUG] test.test: PANIC: invalid foo of bar 73 [DEBUG] test.test: stack trace 74 ` 75 76 got := buf.String() 77 78 if expected != got { 79 t.Fatalf("Expected:\n%q\nGot:\n%q", expected, got) 80 } 81 82 }