| 8 | ) |
| 9 | |
| 10 | func TestTry(t *testing.T) { |
| 11 | t.Parallel() |
| 12 | |
| 13 | t.Run("panics", func(t *testing.T) { |
| 14 | t.Parallel() |
| 15 | |
| 16 | err := errors.New("SOS") |
| 17 | recovered := Try(func() { panic(err) }) |
| 18 | require.ErrorIs(t, recovered.AsError(), err) |
| 19 | require.ErrorAs(t, recovered.AsError(), &err) |
| 20 | // The exact contents aren't tested because the stacktrace contains local file paths |
| 21 | // and even the structure of the stacktrace is bound to be unstable over time. Just |
| 22 | // test a couple of basics. |
| 23 | require.Contains(t, recovered.String(), "SOS", "formatted panic should contain the panic message") |
| 24 | require.Contains(t, recovered.String(), "panics.(*Catcher).Try", recovered.String(), "formatted panic should contain the stack trace") |
| 25 | }) |
| 26 | |
| 27 | t.Run("no panic", func(t *testing.T) { |
| 28 | t.Parallel() |
| 29 | |
| 30 | recovered := Try(func() {}) |
| 31 | require.Nil(t, recovered) |
| 32 | }) |
| 33 | } |