49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package httpx
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestWriteOKWrapsData(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
WriteOK(rec, "trace-1", map[string]any{"online": 12})
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status = %d", rec.Code)
|
|
}
|
|
var body map[string]any
|
|
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body["traceId"] != "trace-1" {
|
|
t.Fatalf("traceId = %#v", body["traceId"])
|
|
}
|
|
data := body["data"].(map[string]any)
|
|
if data["online"].(float64) != 12 {
|
|
t.Fatalf("data = %#v", data)
|
|
}
|
|
}
|
|
|
|
func TestWriteErrorWrapsError(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
WriteError(rec, http.StatusBadRequest, "BAD_QUERY", "查询失败", "vin required", "trace-2")
|
|
if rec.Code != http.StatusBadRequest {
|
|
t.Fatalf("status = %d", rec.Code)
|
|
}
|
|
if got := rec.Body.String(); !containsAll(got, []string{"BAD_QUERY", "查询失败", "vin required", "trace-2"}) {
|
|
t.Fatalf("body = %s", got)
|
|
}
|
|
}
|
|
|
|
func containsAll(value string, parts []string) bool {
|
|
for _, part := range parts {
|
|
if !strings.Contains(value, part) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|