Files
lingniu-vehicle-ingest/go/vehicle-gateway/internal/stats/source_test.go
2026-07-08 14:18:46 +08:00

80 lines
2.3 KiB
Go

package stats
import (
"context"
"strings"
"testing"
"time"
"lingniu-vehicle-ingest/go/vehicle-gateway/internal/envelope"
)
func TestNormalizeSourceIPDropsPort(t *testing.T) {
tests := map[string]string{
"115.231.168.135:20215": "115.231.168.135",
"115.231.168.135": "115.231.168.135",
" 115.159.85.149:28316 ": "115.159.85.149",
"": "",
}
for input, want := range tests {
if got := NormalizeSourceIP(input); got != want {
t.Fatalf("NormalizeSourceIP(%q) = %q, want %q", input, got, want)
}
}
}
func TestNewSourceIdentityRequiresSourceIP(t *testing.T) {
identity, ok := NewSourceIdentity(envelope.ProtocolJT808, "115.231.168.135:20215")
if !ok {
t.Fatal("NewSourceIdentity() ok = false")
}
if identity.Protocol != envelope.ProtocolJT808 {
t.Fatalf("protocol = %q", identity.Protocol)
}
if identity.SourceIP != "115.231.168.135" {
t.Fatalf("source ip = %q", identity.SourceIP)
}
if identity.SourceEndpoint != "115.231.168.135:20215" {
t.Fatalf("endpoint = %q", identity.SourceEndpoint)
}
if _, ok := NewSourceIdentity(envelope.ProtocolJT808, ""); ok {
t.Fatal("empty endpoint should not produce identity")
}
}
func TestUpsertDataSourcePreservesManualFields(t *testing.T) {
exec := &recordingExec{}
identity := SourceIdentity{
Protocol: envelope.ProtocolJT808,
SourceIP: "115.231.168.135",
SourceEndpoint: "115.231.168.135:20215",
}
if err := UpsertDataSource(context.Background(), exec, identity, time.Date(2026, 7, 8, 13, 0, 0, 0, time.UTC)); err != nil {
t.Fatalf("UpsertDataSource() error = %v", err)
}
if len(exec.calls) != 1 {
t.Fatalf("exec calls = %d", len(exec.calls))
}
sql := exec.calls[0].query
for _, want := range []string{
"INSERT INTO vehicle_data_source",
"latest_source_endpoint = VALUES(latest_source_endpoint)",
"latest_seen_at = VALUES(latest_seen_at)",
} {
if !strings.Contains(sql, want) {
t.Fatalf("source upsert missing %q: %s", want, sql)
}
}
for _, forbidden := range []string{
"platform_name = VALUES(platform_name)",
"trust_priority = VALUES(trust_priority)",
"enabled = VALUES(enabled)",
"remark = VALUES(remark)",
} {
if strings.Contains(sql, forbidden) {
t.Fatalf("source upsert should preserve manual field %q: %s", forbidden, sql)
}
}
}