175 lines
6.6 KiB
Go
175 lines
6.6 KiB
Go
package upstreamimpl
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"git.5iot.com/iotlcm-public/iotlcm-upstream-chan/internal/model"
|
|
"git.5iot.com/iotlcm-public/iotlcm-upstream-chan/internal/model/entity"
|
|
)
|
|
|
|
func TestTibiotAPNWriteResponseLossIsUncertain(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
body string
|
|
drop bool
|
|
uncertain bool
|
|
wantCode int
|
|
}{
|
|
{"已办理后断响应", "", true, true, 9999},
|
|
{"响应损坏", "{", false, true, 9999},
|
|
{"缺status", `{}`, false, true, 9999},
|
|
{"畸形status", `{"status":true}`, false, true, 9999},
|
|
{"小数status", `{"status":0.5}`, false, true, 9999},
|
|
{"明确拒绝", `{"status":9999,"message":"拒绝"}`, false, false, 9999},
|
|
{"明确成功", `{"status":0,"message":"成功"}`, false, false, 0},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
var writes atomic.Int32
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != "/api/v1/card/cardNetWork" {
|
|
t.Errorf("错误路由:%s", r.URL.Path)
|
|
}
|
|
writes.Add(1)
|
|
if tc.drop {
|
|
conn, _, err := w.(http.Hijacker).Hijack()
|
|
if err != nil {
|
|
t.Error(err)
|
|
return
|
|
}
|
|
_ = conn.Close()
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(tc.body))
|
|
}))
|
|
defer server.Close()
|
|
client := &sSimTibiot{baseURL: server.URL, userName: "tester", password: "fake", http: server.Client()}
|
|
out, err := client.ChangeSimApnFunction(context.Background(), &model.SimCardOperateChangeApnInput{
|
|
SimKeys: []*model.SimKey{{ICCID: "fake-card"}},
|
|
ReqData: model.SimCardOperateChangeApnInputItem{OperType: "0", SubmitOnly: true},
|
|
})
|
|
if err != nil || len(out) != 1 || writes.Load() != 1 || out[0].Code != tc.wantCode || out[0].ResData.Uncertain != tc.uncertain || out[0].ResData.Pending {
|
|
t.Fatalf("写后语义错误:out=%+v writes=%d err=%v", out, writes.Load(), err)
|
|
}
|
|
t.Logf("writes=%d uncertain=%v code=%d", writes.Load(), out[0].ResData.Uncertain, out[0].Code)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTibiotAPNRedirectDoesNotReplayAndReadUnchanged(t *testing.T) {
|
|
for _, status := range []int{307, 308} {
|
|
t.Run(http.StatusText(status), func(t *testing.T) {
|
|
var writes, targets atomic.Int32
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
t.Errorf("方法改变:%s", r.Method)
|
|
}
|
|
writes.Add(1)
|
|
if r.URL.Path == "/target" {
|
|
targets.Add(1)
|
|
_, _ = w.Write([]byte(`{"status":0}`))
|
|
return
|
|
}
|
|
w.Header().Set("Location", "/target")
|
|
w.WriteHeader(status)
|
|
}))
|
|
defer server.Close()
|
|
client := &sSimTibiot{baseURL: server.URL, userName: "tester", password: "fake", http: server.Client()}
|
|
out, err := client.ChangeSimApnFunction(context.Background(), &model.SimCardOperateChangeApnInput{SimKeys: []*model.SimKey{{ICCID: "fake"}}, ReqData: model.SimCardOperateChangeApnInputItem{OperType: "0"}})
|
|
if err != nil || len(out) != 1 || writes.Load() != 1 || targets.Load() != 0 || out[0].Code == 0 || !out[0].ResData.Uncertain {
|
|
t.Fatalf("跳转重放/分类错误:out=%+v writes=%d targets=%d err=%v", out, writes.Load(), targets.Load(), err)
|
|
}
|
|
t.Logf("APN writes=%d targetWrites=%d uncertain=%v", writes.Load(), targets.Load(), out[0].ResData.Uncertain)
|
|
resp, err := client.post(context.Background(), "/read-endpoint", map[string]any{})
|
|
if err != nil || !tibiotSuccess(resp) || writes.Load() != 3 || targets.Load() != 1 {
|
|
t.Fatalf("只读跳转改变:%+v %v calls=%d targets=%d", resp, err, writes.Load(), targets.Load())
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTibiotRateLimiterSpacesRequestsAndHonorsCancellation(t *testing.T) {
|
|
limiter := newTibiotRateLimiter(25 * time.Millisecond)
|
|
if err := limiter.wait(context.Background()); err != nil {
|
|
t.Fatalf("first wait failed: %v", err)
|
|
}
|
|
|
|
started := time.Now()
|
|
if err := limiter.wait(context.Background()); err != nil {
|
|
t.Fatalf("second wait failed: %v", err)
|
|
}
|
|
if elapsed := time.Since(started); elapsed < 20*time.Millisecond {
|
|
t.Fatalf("second slot was granted too early: %s", elapsed)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
|
|
defer cancel()
|
|
reservedBeforeCancel := limiter.next
|
|
if err := limiter.wait(ctx); err == nil {
|
|
t.Fatal("expected cancellation while waiting for a slot")
|
|
}
|
|
if !limiter.next.Equal(reservedBeforeCancel) {
|
|
t.Fatalf("canceled waiter reserved a slot: before=%s after=%s", reservedBeforeCancel, limiter.next)
|
|
}
|
|
}
|
|
|
|
func TestTibiotQuerySimDataUsageRetriesOnceAfterUpstreamFailure(t *testing.T) {
|
|
previousLimiter := tibiotSimDataMarginLimiter
|
|
tibiotSimDataMarginLimiter = newTibiotRateLimiter(time.Millisecond)
|
|
defer func() { tibiotSimDataMarginLimiter = previousLimiter }()
|
|
|
|
var calls atomic.Int32
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var body map[string]any
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
t.Fatalf("decode request: %v", err)
|
|
}
|
|
if body["flowUnit"] != "MB" {
|
|
t.Fatalf("flowUnit missing: %#v", body)
|
|
}
|
|
if calls.Add(1) == 1 {
|
|
_, _ = w.Write([]byte(`{"status":10049,"message":"too many requests","data":null}`))
|
|
return
|
|
}
|
|
_, _ = w.Write([]byte(`{"status":0,"message":"ok","data":"2MB"}`))
|
|
}))
|
|
defer server.Close()
|
|
|
|
client := NewSimTibiot().NewTemp(context.Background(), &model.SimChannelConfigItemCache{
|
|
Template: &entity.TSimChannelTemplate{
|
|
TempConfig: `{"api":{"baseUrl":"` + server.URL + `"},"http":{"timeout":"2s"}}`,
|
|
},
|
|
Channel: &entity.TSimChannels{ChanConfig: `{"userName":"tester","password":"secret"}`},
|
|
}).(*sSimTibiot)
|
|
items, err := client.QuerySimDataUsage(context.Background(), &model.SimDataUsageInput{
|
|
SimKeys: []*model.SimKey{{ICCID: "8986000000000000001"}},
|
|
})
|
|
if err != nil || len(items) != 1 {
|
|
t.Fatalf("unexpected query result: items=%#v err=%v", items, err)
|
|
}
|
|
if calls.Load() != 2 {
|
|
t.Fatalf("upstream calls = %d, want one retry", calls.Load())
|
|
}
|
|
if items[0].Code != 0 || items[0].ResData.DataUsage != 2 {
|
|
t.Fatalf("unexpected successful retry result: %#v", items[0])
|
|
}
|
|
|
|
cachedItems, err := client.QuerySimDataUsage(context.Background(), &model.SimDataUsageInput{
|
|
SimKeys: []*model.SimKey{{ICCID: "8986000000000000001"}},
|
|
})
|
|
if err != nil || len(cachedItems) != 1 {
|
|
t.Fatalf("unexpected cached query result: items=%#v err=%v", cachedItems, err)
|
|
}
|
|
if calls.Load() != 2 {
|
|
t.Fatalf("cached query called upstream again: calls=%d", calls.Load())
|
|
}
|
|
if !cachedItems[0].Cached || cachedItems[0].UpdatedAt == "" {
|
|
t.Fatalf("cached query metadata missing: %#v", cachedItems[0])
|
|
}
|
|
}
|