Files
MeshPort/engines/singbox/cmd/meshport-singbox-ffi/main_test.go
T
2026-12-03 16:46:29 -08:00

62 lines
1.7 KiB
Go

package main
import (
"encoding/json"
"net"
"sync"
"testing"
)
func newTestContext() uint64 {
id := next.Add(1)
registry.Lock()
registry.contexts[id] = &engineContext{}
registry.Unlock()
return id
}
func TestABIRequestLifecycle(t *testing.T) {
id := newTestContext()
defer freeContext(id)
listener, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
listener.Close()
input, _ := json.Marshal(map[string]any{"op": "start", "config": map[string]any{"listen_port": port, "mesh_socks": "127.0.0.1:9", "mesh_cidrs": []string{"10.77.0.0/24"}}})
if _, err := dispatch(id, input); err != nil {
t.Fatal(err)
}
health, err := dispatch(id, []byte(`{"op":"health"}`))
if err != nil {
t.Fatal(err)
}
if state, ok := health.(map[string]string); !ok || len(state) != 1 || state["state"] != "Running" {
t.Fatalf("unexpected health payload: %#v", health)
}
if _, err := dispatch(id, input); err == nil {
t.Fatal("duplicate start accepted")
}
for _, bad := range []string{`{"op":"status","extra":true}`, `{"op":"status"} {}`, `{"op":"start"}`, `{"op":"wrong"}`} {
if _, err := dispatch(id, []byte(bad)); err == nil {
t.Fatal("bad request accepted", bad)
}
}
var wait sync.WaitGroup
for i := 0; i < 8; i++ {
wait.Add(1)
go func() { defer wait.Done(); _, _ = dispatch(id, []byte(`{"op":"status"}`)) }()
}
freeContext(id)
wait.Wait()
if _, err := dispatch(id, []byte(`{"op":"status"}`)); err == nil {
t.Fatal("freed context accepted")
}
probe, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", jsonNumber(port)))
if err != nil {
t.Fatal("listener leaked", err)
}
probe.Close()
}
func jsonNumber(port int) string { data, _ := json.Marshal(port); return string(data) }