154 lines
4.9 KiB
Go
154 lines
4.9 KiB
Go
// adapter_test.go Day 33:HTTP 上游适配器——鉴权/方法/解析全分支。
|
|
package httpadapter
|
|
|
|
import (
|
|
"context"
|
|
"crypto/hmac"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// upstream 模拟上游:校验鉴权并按统一契约回包。
|
|
type upstream struct {
|
|
appKey string
|
|
secret string
|
|
}
|
|
|
|
func (u upstream) handler(t *testing.T) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
switch {
|
|
case u.appKey != "":
|
|
if r.Header.Get("X-App-Key") != u.appKey {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_, _ = w.Write([]byte(`{"code":401,"msg":"appkey 错误"}`))
|
|
return
|
|
}
|
|
case u.secret != "":
|
|
ts := r.Header.Get("X-Timestamp")
|
|
sign := r.Header.Get("X-Sign")
|
|
payload := r.URL.RawQuery
|
|
if r.Method == http.MethodPost {
|
|
raw := make([]byte, r.ContentLength)
|
|
_, _ = r.Body.Read(raw)
|
|
payload = string(raw)
|
|
}
|
|
mac := hmac.New(sha256.New, []byte(u.secret))
|
|
mac.Write([]byte(ts + "." + payload))
|
|
want := hex.EncodeToString(mac.Sum(nil))
|
|
if sign != want {
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_, _ = w.Write([]byte(`{"code":401,"msg":"签名错误"}`))
|
|
return
|
|
}
|
|
}
|
|
resp := map[string]any{"code": 0, "msg": "ok",
|
|
"data": map[string]string{"message_id": "up-12345"}}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(resp)
|
|
}
|
|
}
|
|
|
|
// TestAdapter_PostAppKey 验收:POST + appkey 鉴权命中,解析 message_id;错 key 被拒。
|
|
func TestAdapter_PostAppKey(t *testing.T) {
|
|
up := upstream{appKey: "k1"}
|
|
srv := httptest.NewServer(up.handler(t))
|
|
defer srv.Close()
|
|
|
|
a := New(Config{Endpoint: srv.URL, Method: "POST", AuthType: AuthAppKey, AppKey: "k1"})
|
|
resp, err := a.Send(context.Background(), &SendReq{Mobile: "13800001111", Content: "hi"})
|
|
if err != nil {
|
|
t.Fatalf("发送: %v", err)
|
|
}
|
|
if resp.MessageID != "up-12345" {
|
|
t.Fatalf("message_id = %q", resp.MessageID)
|
|
}
|
|
// 错 key
|
|
bad := New(Config{Endpoint: srv.URL, Method: "POST", AuthType: AuthAppKey, AppKey: "wrong"})
|
|
if _, err := bad.Send(context.Background(), &SendReq{Mobile: "13800001111", Content: "hi"}); err == nil {
|
|
t.Fatal("错 appkey 应被拒")
|
|
}
|
|
}
|
|
|
|
// TestAdapter_GetSign 验收:GET + sign(HMAC-SHA256)鉴权命中。
|
|
func TestAdapter_GetSign(t *testing.T) {
|
|
up := upstream{secret: "s3cr3t"}
|
|
srv := httptest.NewServer(up.handler(t))
|
|
defer srv.Close()
|
|
|
|
a := New(Config{Endpoint: srv.URL, Method: "GET", AuthType: AuthSign, Secret: "s3cr3t"})
|
|
resp, err := a.Send(context.Background(), &SendReq{Mobile: "13800001111", Content: "yo", SrcID: "1001"})
|
|
if err != nil {
|
|
t.Fatalf("GET+sign: %v", err)
|
|
}
|
|
if resp.MessageID == "" {
|
|
t.Fatal("message_id 为空")
|
|
}
|
|
// 错密钥 → 签名不符
|
|
bad := New(Config{Endpoint: srv.URL, Method: "GET", AuthType: AuthSign, Secret: "nope"})
|
|
if _, err := bad.Send(context.Background(), &SendReq{Mobile: "13800001111", Content: "yo"}); err == nil {
|
|
t.Fatal("错密钥应被拒")
|
|
}
|
|
}
|
|
|
|
// TestAdapter_PostNone 无鉴权 POST(JSON body 携带全字段)。
|
|
func TestAdapter_PostNone(t *testing.T) {
|
|
var gotBody map[string]string
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_ = json.NewDecoder(r.Body).Decode(&gotBody)
|
|
_, _ = w.Write([]byte(`{"code":0,"data":{"message_id":"m-9"}}`))
|
|
}))
|
|
defer srv.Close()
|
|
|
|
a := New(Config{Endpoint: srv.URL}) // 默认 POST + none
|
|
if _, err := a.Send(context.Background(), &SendReq{Mobile: "13900002222", Content: "c", TaskID: "T1"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if gotBody["mobile"] != "13900002222" || gotBody["task_id"] != "T1" {
|
|
t.Fatalf("POST 体: %v", gotBody)
|
|
}
|
|
}
|
|
|
|
// TestAdapter_ErrorBranches 上游 5xx / 业务 code!=0 / 非法 JSON。
|
|
func TestAdapter_ErrorBranches(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
taskID := ""
|
|
if r.Method == http.MethodPost { // 分支开关在 POST body 的 task_id
|
|
var req struct {
|
|
TaskID string `json:"task_id"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&req)
|
|
taskID = req.TaskID
|
|
} else {
|
|
taskID = r.URL.Query().Get("task_id")
|
|
}
|
|
switch taskID {
|
|
case "5xx":
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
_, _ = w.Write([]byte("boom"))
|
|
case "biz":
|
|
_, _ = w.Write([]byte(`{"code":13,"msg":"余额不足"}`))
|
|
default:
|
|
_, _ = w.Write([]byte("not-json"))
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
a := New(Config{Endpoint: srv.URL, Timeout: 2 * time.Second})
|
|
if _, err := a.Send(context.Background(), &SendReq{Mobile: "1", Content: "x", TaskID: "5xx"}); err == nil ||
|
|
!strings.Contains(err.Error(), "500") {
|
|
t.Fatalf("5xx: %v", err)
|
|
}
|
|
if _, err := a.Send(context.Background(), &SendReq{Mobile: "1", Content: "x", TaskID: "biz"}); err == nil ||
|
|
!strings.Contains(err.Error(), "余额不足") {
|
|
t.Fatalf("业务失败: %v", err)
|
|
}
|
|
if _, err := a.Send(context.Background(), &SendReq{Mobile: "1", Content: "x"}); err == nil {
|
|
t.Fatal("非法 JSON 应报错")
|
|
}
|
|
}
|