// server_test.go Day 47:SMPP 服务端测试——smpp.Client(现有客户端)回环连接: // bind 鉴权(通过/拒绝)/submit_sm 受理/UCS2 解码。 package smpp import ( "context" "testing" "time" ) // fakeHandler 测试回调。 type fakeHandler struct { password string submits chan *submitRecord } type submitRecord struct { src, dest, content string regDel uint8 } func (h *fakeHandler) Bind(systemID, password, clientIP string) Status { if password != h.password { return StatusBindFail } return StatusOK } func (h *fakeHandler) SubmitSM(systemID, srcAddr, destAddr, content string, registeredDelivery uint8) (string, Status) { h.submits <- &submitRecord{src: srcAddr, dest: destAddr, content: content, regDel: registeredDelivery} return "mid-001", StatusOK } func startTestServer(t *testing.T, h *fakeHandler) *Server { t.Helper() srv := NewServer(ServerConfig{Addr: "127.0.0.1:0", IdleTimeout: 5 * time.Second}, h) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(func() { cancel(); srv.Close() }) go func() { _ = srv.ListenAndServe(ctx) }() for i := 0; i < 50 && srv.Addr() == ""; i++ { time.Sleep(10 * time.Millisecond) } if srv.Addr() == "" { t.Fatal("server 未监听") } return srv } // TestServer_BindAndSubmit bind 通过+submit_sm 受理(ASCII)。 func TestServer_BindAndSubmit(t *testing.T) { h := &fakeHandler{password: "pw123", submits: make(chan *submitRecord, 1)} srv := startTestServer(t, h) c := NewClient(Config{Addr: srv.Addr(), SystemID: "user1", Password: "pw123"}) if err := c.Connect(context.Background()); err != nil { t.Fatalf("bind: %v", err) } defer c.Close() id, st, err := c.Submit(&SubmitReq{ Source: Addr{Ton: 0, Npi: 0, Address: "UT0012"}, Dest: Addr{Ton: 1, Npi: 1, Address: "13800138000"}, RegisteredDelivery: 1, ShortMessage: []byte("hello"), }) if err != nil || st != StatusOK { t.Fatalf("submit: st=%v err=%v", st, err) } if id != "mid-001" { t.Fatalf("message_id=%s", id) } select { case rec := <-h.submits: if rec.src != "UT0012" || rec.dest != "13800138000" || rec.content != "hello" || rec.regDel != 1 { t.Fatalf("受理字段错误: %+v", rec) } case <-time.After(2 * time.Second): t.Fatal("服务端未收到 submit_sm") } } // TestServer_BindRejected 错误密码:bind_resp status=13,客户端报被拒。 func TestServer_BindRejected(t *testing.T) { h := &fakeHandler{password: "pw123", submits: make(chan *submitRecord, 1)} srv := startTestServer(t, h) c := NewClient(Config{Addr: srv.Addr(), SystemID: "user1", Password: "bad"}) if err := c.Connect(context.Background()); err == nil { c.Close() t.Fatal("期望 bind 被拒") } }