package main

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func errPanic(writer http.ResponseWriter, request *http.Request) error {
	fmt.Println(" this is an panic testing .....")
	panic(6789)
	//return nil
}

func errUserErr(writer http.ResponseWriter, request *http.Request) error {
	//panic(6789)
	fmt.Println(" this is an testing .....")
	return testingUserError("user error")
}

type testingUserError string

func (e testingUserError) Error() string {
	return e.Message()
}

func (e testingUserError) Message() string {
	return string(e)
}

var tests = []struct {
	h       appHandler
	code    int
	message string
}{
	//	{errPanic,500,"Internal Server Error"},
	{errUserErr, 400, "user error"},
}

func TestErrWrapper(t *testing.T) {

	for _, tt := range tests {
		f := errWrapper(tt.h)

		response := httptest.NewRecorder()
		request := httptest.NewRequest(http.MethodGet, "http:/www.baidu.com", bytes.NewBufferString("this is custome str "))
		f(response, request)
		b, _ := ioutil.ReadAll(response.Body)
		body := strings.Trim(string(b), "\n")
		if response.Code != tt.code || body != tt.message {
			t.Errorf(" expect (%d ,%s) ; got (%d ,%s)", tt.code, tt.message, response.Code, body)

		}

	}

}
