package web

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/valyala/fasthttp"
)

func TestRecoverError(t *testing.T) {
	t.Run("should write recover error to resp", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}

		defer func() {
			res := &ctx.Response
			assert.Equal(t, 500, res.StatusCode())
			assert.Equal(t, `{"detail":"We encountered an internal error"}`, string(res.Body()))
		}()

		defer recoverError("msg", &ctx)

		func() {
			panic("an error")
		}()
	})

	t.Run("should not write recover error if not panic", func(t *testing.T) {
		ctx := fasthttp.RequestCtx{}

		defer func() {
			res := &ctx.Response
			assert.Equal(t, 200, res.StatusCode())
		}()

		defer recoverError("msg", &ctx)

		defer func() {
			recover()
		}()

		func() {
			panic("an error")
		}()
	})
}
