dtm/common/utils_test.go
hitzhangjie cc66ceb484 refactor-*: improve code readability
- use clearer method names, comments;
- define dtm usage info;
- determine action by switch-case instead of if-else, because only
  os.Args[1] needs to be checked;
- use time layout '2006-01-02 15:04:05.999' to format milliseconds;
- change filenames dtmsvr/main.go to dtmsvr/dtmsvr.go;
- simplify code;
- use `()` to think less about operator precedence;

xxx
2021-09-23 23:05:42 +08:00

42 lines
1.0 KiB
Go

package common
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/go-playground/assert/v2"
)
func TestGin(t *testing.T) {
app := GetGinApp()
app.GET("/api/sample", WrapHandler(func(c *gin.Context) (interface{}, error) {
return 1, nil
}))
app.GET("/api/error", WrapHandler(func(c *gin.Context) (interface{}, error) {
return nil, errors.New("err1")
}))
getResultString := func(api string, body io.Reader) string {
req, _ := http.NewRequest("GET", api, body)
w := httptest.NewRecorder()
app.ServeHTTP(w, req)
return string(w.Body.Bytes())
}
assert.Equal(t, "{\"msg\":\"pong\"}", getResultString("/api/ping", nil))
assert.Equal(t, "1", getResultString("/api/sample", nil))
assert.Equal(t, "{\"code\":500,\"message\":\"err1\"}", getResultString("/api/error", strings.NewReader("{}")))
}
func TestFuncs(t *testing.T) {
wd := MustGetwd()
assert.NotEqual(t, "", wd)
dir1 := GetCallerCodeDir()
assert.Equal(t, true, strings.HasSuffix(dir1, "common"))
}