Files
lingniu-vehicle-ingest/vehicle-data-platform/apps/api/internal/platform/handler_test.go
2026-07-04 17:53:03 +08:00

1061 lines
45 KiB
Go

package platform
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestHandlerDashboardSummary(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/dashboard/summary", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "onlineVehicles") {
t.Fatalf("response missing onlineVehicles: %s", rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "serviceStatuses") || !strings.Contains(rec.Body.String(), "degraded") {
t.Fatalf("response missing vehicle service status distribution: %s", rec.Body.String())
}
}
func TestHandlerVehicles(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles?limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("response missing vehicle: %s", rec.Body.String())
}
var body struct {
Data Page[VehicleRow] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
t.Fatalf("vehicle row should include canonical vehicle service status: %s", rec.Body.String())
}
if body.Data.Items[0].ServiceStatus.Status != "degraded" {
t.Fatalf("vehicle row should expose degraded status, got %+v", body.Data.Items[0].ServiceStatus)
}
}
func TestHandlerVehiclesFiltersServiceStatus(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles?limit=10&serviceStatus=degraded", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("degraded vehicles should include partially online vehicle: %s", rec.Body.String())
}
if strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
t.Fatalf("degraded vehicles should exclude healthy vehicle: %s", rec.Body.String())
}
}
func TestHandlerVehicleCoverage(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&coverage=multi&online=online&bindingStatus=bound", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
for _, want := range []string{"sourceCount", "onlineSourceCount", "protocols", "LB9A32A24R0LS1426"} {
if !strings.Contains(rec.Body.String(), want) {
t.Fatalf("response missing %q: %s", want, rec.Body.String())
}
}
var body struct {
Data Page[VehicleCoverageRow] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
t.Fatalf("coverage row should include canonical vehicle service status: %s", rec.Body.String())
}
if body.Data.Items[0].ServiceStatus.Status != "degraded" {
t.Fatalf("coverage row should expose degraded status, got %+v", body.Data.Items[0].ServiceStatus)
}
var rawBody struct {
Data Page[struct {
VIN string `json:"vin"`
MissingProtocols []string `json:"missingProtocols"`
SourceStatus []VehicleSourceStatus `json:"sourceStatus"`
SourceConsistency *VehicleSourceConsistency `json:"sourceConsistency"`
}] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &rawBody); err != nil {
t.Fatalf("response JSON should decode missing source evidence: %v body=%s", err, rec.Body.String())
}
if len(rawBody.Data.Items) == 0 || !containsString(rawBody.Data.Items[0].MissingProtocols, "YUTONG_MQTT") {
t.Fatalf("coverage row should expose missing canonical protocols, got %+v body=%s", rawBody.Data.Items, rec.Body.String())
}
if len(rawBody.Data.Items) == 0 || rawBody.Data.Items[0].SourceConsistency == nil {
t.Fatalf("coverage row should expose vehicle-level source consistency: %s", rec.Body.String())
}
if rawBody.Data.Items[0].SourceConsistency.Status != "degraded" || !containsString(rawBody.Data.Items[0].SourceConsistency.MissingProtocols, "YUTONG_MQTT") {
t.Fatalf("coverage source consistency should diagnose missing source evidence, got %+v body=%s", rawBody.Data.Items[0].SourceConsistency, rec.Body.String())
}
byProtocol := map[string]VehicleSourceStatus{}
for _, source := range rawBody.Data.Items[0].SourceStatus {
byProtocol[source.Protocol] = source
}
for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
if _, ok := byProtocol[protocol]; !ok {
t.Fatalf("coverage row should expose canonical source slot %s, got %+v body=%s", protocol, rawBody.Data.Items[0].SourceStatus, rec.Body.String())
}
}
if !byProtocol["JT808"].Online || byProtocol["YUTONG_MQTT"].Online || byProtocol["YUTONG_MQTT"].HasRealtime {
t.Fatalf("coverage source slots should expose online and missing evidence, got %+v", byProtocol)
}
}
func TestHandlerVehicleCoverageFiltersServiceStatus(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&serviceStatus=degraded", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("degraded coverage should include partially online multi-source vehicle: %s", rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
t.Fatalf("degraded coverage should include online single-source vehicle that misses canonical sources: %s", rec.Body.String())
}
}
func TestHandlerVehicleCoverageFiltersMissingProtocol(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&missingProtocol=YUTONG_MQTT", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("missing MQTT coverage should include vehicle without MQTT source: %s", rec.Body.String())
}
if strings.Contains(rec.Body.String(), "LMRKH9AC2R1004087") {
t.Fatalf("missing MQTT coverage should exclude vehicle with MQTT source: %s", rec.Body.String())
}
}
func TestHandlerVehicleCoverageTreatsMissingCanonicalSourceAsDegraded(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage?limit=10&missingProtocol=YUTONG_MQTT&online=online", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data Page[VehicleCoverageRow] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) == 0 {
t.Fatalf("missing source query should return online vehicles with missing canonical source: %s", rec.Body.String())
}
for _, row := range body.Data.Items {
if row.ServiceStatus == nil || row.ServiceStatus.Status != "degraded" {
t.Fatalf("missing canonical source should degrade vehicle service, got row=%+v body=%s", row, rec.Body.String())
}
if row.ServiceStatus.Title != "来源不完整" {
t.Fatalf("missing canonical source should use explicit incomplete-source title, got row=%+v body=%s", row, rec.Body.String())
}
}
}
func TestHandlerVehicleCoverageSummary(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/coverage/summary?coverage=multi", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleCoverageSummary `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.TotalVehicles != 1 || body.Data.MultiSourceVehicles != 1 {
t.Fatalf("coverage summary should honor filters, got %+v body=%s", body.Data, rec.Body.String())
}
if body.Data.OnlineVehicles != 1 || body.Data.UnboundVehicles != 0 {
t.Fatalf("coverage summary should expose filtered online and binding totals, got %+v", body.Data)
}
if len(body.Data.MissingSources) == 0 {
t.Fatalf("coverage summary should expose missing source counts, got %+v", body.Data)
}
if len(body.Data.ArchiveMissingFields) == 0 {
t.Fatalf("coverage summary should expose archive missing-field counts, got %+v", body.Data)
}
}
func TestSplitCSVEmptyReturnsEmptySlice(t *testing.T) {
values := splitCSV("")
if values == nil {
t.Fatalf("empty CSV should encode as [] instead of JSON null")
}
if len(values) != 0 {
t.Fatalf("empty CSV should have no values, got %#v", values)
}
}
func TestHandlerVehicleDetail(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?vin=LB9A32A24R0LS1426", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
for _, want := range []string{"lookupKey", "lookupResolved", "identity", "realtimeSummary", "realtime", "history", "raw", "mileage", "quality", "sources", "sourceStatus"} {
if !strings.Contains(rec.Body.String(), want) {
t.Fatalf("response missing %q: %s", want, rec.Body.String())
}
}
}
func TestHandlerVehicleServiceCanonicalEndpoint(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312&protocol=JT808", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Resolution == nil || body.Data.Resolution.VIN != "LB9A32A24R0LS1426" {
t.Fatalf("vehicle service should resolve canonical vehicle identity, got %+v body=%s", body.Data.Resolution, rec.Body.String())
}
for _, row := range body.Data.Realtime {
if row.Protocol != "JT808" {
t.Fatalf("vehicle service should keep source filter, got realtime row %+v body=%s", row, rec.Body.String())
}
}
}
func TestHandlerVehicleServiceIncludesVehicleLevelStatus(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.ServiceStatus == nil {
t.Fatalf("vehicle service should include serviceStatus: %s", rec.Body.String())
}
if body.Data.ServiceStatus.Status != "degraded" || body.Data.ServiceStatus.Title != "来源不完整" {
t.Fatalf("vehicle service should prioritize missing source evidence, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
}
if body.Data.ServiceStatus.OnlineSourceCount != 1 || body.Data.ServiceStatus.SourceCount != 3 {
t.Fatalf("vehicle service should expose source counts, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
}
if body.Data.Resolution == nil || body.Data.Resolution.ServiceStatus == nil || body.Data.Resolution.ServiceStatus.Title != body.Data.ServiceStatus.Title {
t.Fatalf("resolution should reuse canonical vehicle service status, resolution=%+v service=%+v", body.Data.Resolution, body.Data.ServiceStatus)
}
if body.Data.Identity == nil || body.Data.Identity.ServiceStatus == nil || body.Data.Identity.ServiceStatus.Title != body.Data.ServiceStatus.Title {
t.Fatalf("identity should reuse canonical vehicle service status, identity=%+v service=%+v", body.Data.Identity, body.Data.ServiceStatus)
}
if body.Data.RealtimeSummary == nil || body.Data.RealtimeSummary.ServiceStatus == nil || body.Data.RealtimeSummary.ServiceStatus.Title != body.Data.ServiceStatus.Title {
t.Fatalf("realtime summary should reuse canonical vehicle service status, summary=%+v service=%+v", body.Data.RealtimeSummary, body.Data.ServiceStatus)
}
}
func TestHandlerVehicleServiceIncludesUnifiedOverview(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.ServiceOverview == nil {
t.Fatalf("vehicle service should include serviceOverview: %s", rec.Body.String())
}
overview := body.Data.ServiceOverview
if overview.VIN != "LB9A32A24R0LS1426" || overview.Plate != "粤AG18312" {
t.Fatalf("overview should expose canonical vehicle identity, got %+v", overview)
}
if overview.SourceCount != 3 || overview.OnlineSourceCount != 1 || overview.CoverageStatus != "partial" {
t.Fatalf("overview should summarize source coverage, got %+v", overview)
}
if overview.LastSeen == "" || overview.PrimaryProtocol == "" {
t.Fatalf("overview should expose latest service time and primary source, got %+v", overview)
}
if overview.RealtimeCount == 0 || overview.HistoryCount == 0 || overview.RawCount == 0 || overview.MileageCount == 0 {
t.Fatalf("overview should expose available data counts, got %+v", overview)
}
}
func TestHandlerVehicleServiceIncludesSourceConsistency(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.SourceConsistency == nil {
t.Fatalf("vehicle service should include sourceConsistency: %s", rec.Body.String())
}
consistency := body.Data.SourceConsistency
if consistency.SourceCount != 3 || consistency.OnlineSourceCount != 1 || consistency.LocatedSourceCount != 2 {
t.Fatalf("sourceConsistency should summarize source coverage, got %+v", consistency)
}
if consistency.MileageDeltaKm <= 0 || consistency.SourceTimeDeltaSeconds <= 0 {
t.Fatalf("sourceConsistency should expose mileage and source time deltas, got %+v", consistency)
}
if consistency.Status == "" || consistency.Severity == "" || consistency.Title == "" || consistency.Detail == "" {
t.Fatalf("sourceConsistency should expose actionable diagnosis, got %+v", consistency)
}
if consistency.Status != "degraded" || consistency.Title != "来源不完整" {
t.Fatalf("sourceConsistency should diagnose missing source evidence before offline evidence, got %+v", consistency)
}
}
func TestHandlerVehicleServiceExposesMissingSourceSlots(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
byProtocol := map[string]VehicleSourceStatus{}
for _, source := range body.Data.SourceStatus {
byProtocol[source.Protocol] = source
}
for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
if _, ok := byProtocol[protocol]; !ok {
t.Fatalf("vehicle service should expose expected source slot %s, got %+v", protocol, body.Data.SourceStatus)
}
}
mqtt := byProtocol["YUTONG_MQTT"]
if mqtt.Online || mqtt.HasRealtime || mqtt.HasHistory || mqtt.HasRaw || mqtt.HasMileage || mqtt.LastSeen != "" {
t.Fatalf("missing MQTT source should be an empty coverage slot, got %+v", mqtt)
}
}
func TestHandlerVehicleServiceConsistencyExposesMissingProtocols(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data struct {
SourceConsistency struct {
MissingProtocols []string `json:"missingProtocols"`
} `json:"sourceConsistency"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if !containsString(body.Data.SourceConsistency.MissingProtocols, "YUTONG_MQTT") {
t.Fatalf("sourceConsistency should expose missing source evidence, got %+v body=%s", body.Data.SourceConsistency.MissingProtocols, rec.Body.String())
}
}
func TestHandlerVehicleServiceOverviewEndpoint(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service/overview?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleServiceOverview `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.VIN != "LB9A32A24R0LS1426" || body.Data.Plate != "粤AG18312" {
t.Fatalf("overview endpoint should resolve canonical vehicle identity, got %+v", body.Data)
}
if body.Data.SourceCount != 2 || body.Data.OnlineSourceCount != 1 || body.Data.CoverageStatus != "partial" {
t.Fatalf("overview endpoint should summarize vehicle service coverage, got %+v", body.Data)
}
if body.Data.ServiceStatus == nil || body.Data.ServiceStatus.Status != "degraded" || body.Data.ServiceStatus.Title != "来源不完整" {
t.Fatalf("overview endpoint should expose canonical service status, got %+v", body.Data.ServiceStatus)
}
if body.Data.SourceConsistency == nil || body.Data.SourceConsistency.SourceCount != 2 || body.Data.SourceConsistency.OnlineSourceCount != 1 {
t.Fatalf("overview endpoint should expose source consistency, got %+v", body.Data.SourceConsistency)
}
if body.Data.SourceConsistency.Status != "degraded" || body.Data.SourceConsistency.Title != "来源不完整" {
t.Fatalf("overview source consistency should expose diagnosis, got %+v", body.Data.SourceConsistency)
}
if strings.Contains(rec.Body.String(), `"raw"`) || strings.Contains(rec.Body.String(), `"history"`) {
t.Fatalf("overview endpoint should not return heavy detail pages: %s", rec.Body.String())
}
}
func TestHandlerVehicleServiceSummaryEndpoint(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicle-service/summary", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleServiceSummary `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.TotalVehicles < 4 || body.Data.OnlineVehicles < 1 {
t.Fatalf("summary should expose vehicle-level totals, got %+v", body.Data)
}
if body.Data.MultiSourceVehicles < 1 || body.Data.SingleSourceVehicles < 1 {
t.Fatalf("summary should expose source coverage distribution, got %+v", body.Data)
}
if body.Data.ArchiveIncompleteVehicles < 1 {
t.Fatalf("summary should expose incomplete archive vehicles, got %+v", body.Data)
}
if len(body.Data.ServiceStatuses) == 0 || len(body.Data.Protocols) == 0 {
t.Fatalf("summary should expose service status and protocol distributions, got %+v", body.Data)
}
noDataStatusFound := false
for _, status := range body.Data.ServiceStatuses {
if status.Status == "degraded" && status.Title != "来源不完整" {
t.Fatalf("summary degraded status should use vehicle-service missing source title, got %+v", status)
}
if status.Status == "no_data" {
noDataStatusFound = true
if status.Title != "暂无数据来源" || status.Count != body.Data.NoDataVehicles {
t.Fatalf("no_data service status should mirror noDataVehicles, got status=%+v summary=%+v", status, body.Data)
}
}
}
if !noDataStatusFound {
t.Fatalf("summary service status distribution should include no_data, got %+v", body.Data.ServiceStatuses)
}
var rawBody struct {
Data struct {
MissingSources []struct {
Protocol string `json:"protocol"`
Count int `json:"count"`
} `json:"missingSources"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &rawBody); err != nil {
t.Fatalf("response JSON should decode raw summary: %v body=%s", err, rec.Body.String())
}
missing := map[string]int{}
for _, source := range rawBody.Data.MissingSources {
missing[source.Protocol] = source.Count
}
if missing["GB32960"] != 2 || missing["JT808"] != 2 || missing["YUTONG_MQTT"] != 3 {
t.Fatalf("summary should expose canonical missing source counts, got %+v body=%s", missing, rec.Body.String())
}
}
func TestHandlerVehicleServiceOverviewsEndpoint(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/vehicle-service/overviews", bytes.NewBufferString(`{"keywords":["粤AG18312","LMRKH9AC2R1004087"]}`))
req.Header.Set("Content-Type", "application/json")
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data Page[VehicleServiceOverview] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Total != 2 || len(body.Data.Items) != 2 {
t.Fatalf("batch overview should return two items, got %+v body=%s", body.Data, rec.Body.String())
}
if body.Data.Items[0].VIN != "LB9A32A24R0LS1426" || body.Data.Items[1].VIN != "LMRKH9AC2R1004087" {
t.Fatalf("batch overview should preserve request order, got %+v", body.Data.Items)
}
if body.Data.Items[0].ServiceStatus == nil || body.Data.Items[1].ServiceStatus == nil {
t.Fatalf("batch overview should include canonical status for every vehicle, got %+v", body.Data.Items)
}
if body.Data.Items[0].SourceConsistency == nil || body.Data.Items[0].SourceConsistency.SourceCount != 2 {
t.Fatalf("batch overview should include source consistency, got %+v", body.Data.Items[0].SourceConsistency)
}
if strings.Contains(rec.Body.String(), `"raw"`) || strings.Contains(rec.Body.String(), `"history"`) {
t.Fatalf("batch overview should not return heavy detail pages: %s", rec.Body.String())
}
}
func TestHandlerVehicleDetailResolvesPlateToVIN(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?vin=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), `"vin":"LB9A32A24R0LS1426"`) {
t.Fatalf("response should resolve plate to VIN: %s", rec.Body.String())
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Resolution == nil || !body.Data.Resolution.Resolved || body.Data.Resolution.VIN != "LB9A32A24R0LS1426" {
t.Fatalf("vehicle detail should include canonical identity resolution, got %+v body=%s", body.Data.Resolution, rec.Body.String())
}
if len(body.Data.Resolution.Protocols) < 2 {
t.Fatalf("vehicle detail resolution should include source protocols, got %+v", body.Data.Resolution.Protocols)
}
}
func TestHandlerVehicleDetailAcceptsKeyword(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), `"vin":"LB9A32A24R0LS1426"`) {
t.Fatalf("response should resolve keyword to VIN: %s", rec.Body.String())
}
}
func TestHandlerVehicleDetailKeepsUnresolvedLookupOutOfVIN(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/detail?keyword=64646848247", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
for _, want := range []string{`"lookupKey":"64646848247"`, `"lookupResolved":false`, `"vin":""`} {
if !strings.Contains(rec.Body.String(), want) {
t.Fatalf("response missing %q: %s", want, rec.Body.String())
}
}
var body struct {
Data VehicleDetail `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.VIN == "64646848247" {
t.Fatalf("unresolved lookup should not be returned as top-level VIN: %s", rec.Body.String())
}
if len(body.Data.Sources) != 0 || len(body.Data.SourceStatus) != 0 || len(body.Data.Raw.Items) != 0 || len(body.Data.History.Items) != 0 || len(body.Data.Mileage.Items) != 0 {
t.Fatalf("unresolved lookup should not return vehicle data sections: %+v", body.Data)
}
}
func TestHandlerVehicleResolveReturnsCanonicalIdentity(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/resolve?keyword=粤AG18312", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleIdentityResolution `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if !body.Data.Resolved || body.Data.VIN != "LB9A32A24R0LS1426" || body.Data.Plate != "粤AG18312" {
t.Fatalf("resolve should return canonical identity, got %+v body=%s", body.Data, rec.Body.String())
}
if len(body.Data.Protocols) < 2 {
t.Fatalf("resolve should include available source protocols, got %+v", body.Data.Protocols)
}
if body.Data.ServiceStatus == nil || body.Data.ServiceStatus.Status != "degraded" {
t.Fatalf("resolve should include canonical service status, got %+v body=%s", body.Data.ServiceStatus, rec.Body.String())
}
}
func TestHandlerVehicleResolveKeepsUnresolvedKeyword(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/vehicles/resolve?keyword=64646848247", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data VehicleIdentityResolution `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Resolved || body.Data.VIN != "" || body.Data.LookupKey != "64646848247" {
t.Fatalf("unresolved keyword should not fabricate identity, got %+v body=%s", body.Data, rec.Body.String())
}
}
func TestHandlerRealtimeLocations(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/realtime/locations?limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("response missing vehicle: %s", rec.Body.String())
}
}
func TestHandlerVehicleRealtime(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
for _, want := range []string{"protocols", "sourceCount", "primaryProtocol", "LB9A32A24R0LS1426"} {
if !strings.Contains(rec.Body.String(), want) {
t.Fatalf("response missing %q: %s", want, rec.Body.String())
}
}
var body struct {
Data struct {
Items []VehicleRealtimeRow `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) == 0 || body.Data.Items[0].ServiceStatus == nil {
t.Fatalf("realtime vehicle row should include canonical serviceStatus: %s", rec.Body.String())
}
byProtocol := map[string]VehicleSourceStatus{}
for _, source := range body.Data.Items[0].SourceStatus {
byProtocol[source.Protocol] = source
}
for _, protocol := range []string{"GB32960", "JT808", "YUTONG_MQTT"} {
if _, ok := byProtocol[protocol]; !ok {
t.Fatalf("realtime row should expose canonical source slot %s, got %+v body=%s", protocol, body.Data.Items[0].SourceStatus, rec.Body.String())
}
}
if !byProtocol["JT808"].Online || byProtocol["YUTONG_MQTT"].Online || byProtocol["YUTONG_MQTT"].HasRealtime {
t.Fatalf("realtime source slots should expose online and missing evidence, got %+v", byProtocol)
}
}
func TestHandlerVehicleRealtimeFiltersServiceStatus(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?serviceStatus=degraded&limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LB9A32A24R0LS1426") {
t.Fatalf("degraded realtime should include partially online vehicle: %s", rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "LNXNEGRR7SR318212") {
t.Fatalf("degraded realtime should include online single-source vehicle that misses canonical sources: %s", rec.Body.String())
}
}
func TestHandlerVehicleRealtimeAcceptsKeyword(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/realtime/vehicles?keyword=川AHTWO1&limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data struct {
Items []VehicleRealtimeRow `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) != 1 || body.Data.Items[0].VIN != "LNXNEGRR7SR318212" {
t.Fatalf("realtime vehicles should accept vehicle keyword, got %+v body=%s", body.Data.Items, rec.Body.String())
}
}
func TestHandlerHistoryMileageQualityOps(t *testing.T) {
cases := []struct {
path string
want string
}{
{"/api/history/locations?limit=10", "totalMileageKm"},
{"/api/history/raw-frames?protocol=GB32960&vin=LB9A32A24R0LS1426&limit=1&includeFields=true", "plate"},
{"/api/mileage/summary?limit=10", "totalMileageKm"},
{"/api/mileage/daily?limit=10", "dailyMileageKm"},
{"/api/statistics/online-summary?limit=10", "onlineRatePercent"},
{"/api/statistics/online-vehicles?limit=10", "offlineDurationMinutes"},
{"/api/quality/summary?limit=10", "issueVehicleCount"},
{"/api/quality/issues?limit=10", "sourceEndpoint"},
{"/api/ops/health", "linkHealth"},
}
handler := NewHandler(NewService(NewMockStore()))
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), tc.want) {
t.Fatalf("response missing %q: %s", tc.want, rec.Body.String())
}
})
}
}
func TestHandlerQualityIncludesNoSourceVehicles(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/quality/issues?limit=20", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data Page[QualityIssueRow] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
found := false
for _, item := range body.Data.Items {
if item.IssueType == "NO_SOURCE" {
found = true
if item.VIN == "" || item.Plate == "" || item.Protocol != "VEHICLE_SERVICE" {
t.Fatalf("NO_SOURCE issue should identify bound vehicle service, got %+v", item)
}
}
}
if !found {
t.Fatalf("quality issues should include NO_SOURCE vehicles, got %+v", body.Data.Items)
}
}
func TestHandlerQualitySummaryIncludesNoSourceBucket(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/quality/summary?limit=20", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data QualitySummary `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
found := false
for _, item := range body.Data.IssueTypes {
if item.Name == "NO_SOURCE" {
found = true
}
}
if !found {
t.Fatalf("quality summary should include NO_SOURCE bucket, got %+v", body.Data.IssueTypes)
}
}
func TestBuildQualityIssueWhereUsesMatchingArgs(t *testing.T) {
fromSQL, args := buildQualityIssueWhere(url.Values{"vin": {"VIN001"}, "protocol": {"VEHICLE_SERVICE"}, "keyword": {"粤A"}})
if strings.Count(fromSQL, "?") != len(args) {
t.Fatalf("quality issue SQL placeholders should match args: placeholders=%d args=%d sql=%s args=%#v", strings.Count(fromSQL, "?"), len(args), fromSQL, args)
}
}
func TestBuildQualityIssueWhereFiltersIssueType(t *testing.T) {
fromSQL, args := buildQualityIssueWhere(url.Values{"issueType": {"NO_SOURCE"}})
if !strings.Contains(fromSQL, "q.issue_type = ?") {
t.Fatalf("quality issue SQL should filter issue type: %s", fromSQL)
}
if len(args) != 1 || args[0] != "NO_SOURCE" {
t.Fatalf("args = %#v", args)
}
}
func TestHandlerQualityIssuesFiltersIssueType(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/quality/issues?issueType=NO_SOURCE&limit=20", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data Page[QualityIssueRow] `json:"data"`
}
if err := json.NewDecoder(rec.Body).Decode(&body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Total == 0 {
t.Fatalf("expected at least one NO_SOURCE issue")
}
for _, item := range body.Data.Items {
if item.IssueType != "NO_SOURCE" {
t.Fatalf("expected only NO_SOURCE issues, got %+v", body.Data.Items)
}
}
}
func TestHandlerQualityNotificationPlan(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/quality/notification-plan?limit=10", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data QualityNotificationPlan `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.ActiveRuleCount == 0 || body.Data.P0RuleCount == 0 {
t.Fatalf("notification plan should expose active P0 rules, got %+v", body.Data)
}
if len(body.Data.Rules) == 0 || len(body.Data.Policies) == 0 || len(body.Data.PriorityIssues) == 0 {
t.Fatalf("notification plan should include rules, policies and priority issues: %+v", body.Data)
}
firstPolicy := body.Data.Policies[0]
if firstPolicy.EscalationMinutes <= 0 || firstPolicy.AcceptanceCriteria == "" {
t.Fatalf("notification policies should expose escalation minutes and acceptance criteria: %+v", firstPolicy)
}
first := body.Data.PriorityIssues[0]
if first.Priority != "P0" || first.ActionLabel == "" || first.SLA == "" || first.VehicleLabel == "" {
t.Fatalf("priority issue should be enriched for notification: %+v", first)
}
if !strings.Contains(first.NotificationText, "实时定位") || !strings.Contains(first.NotificationText, "#/history") {
t.Fatalf("priority issue should include evidence links, got %q", first.NotificationText)
}
}
func TestHandlerOpsHealthIncludesVehicleServiceRuntime(t *testing.T) {
handler := NewHandler(NewServiceWithRuntime(NewMockStore(), RuntimeInfo{
RequestTimeoutMs: 1500,
AMapWebJSConfigured: true,
AMapAPIConfigured: true,
AMapSecurityProxyEnabled: true,
AMapSecurityCodeExposed: false,
AMapSecurityServiceHost: "/_AMapService",
PlatformRelease: "platform-20260704153005",
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/ops/health", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data OpsHealth `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Runtime.RequestTimeoutMs != 1500 {
t.Fatalf("ops health should include request timeout runtime, got %+v body=%s", body.Data.Runtime, rec.Body.String())
}
if !body.Data.Runtime.AMapWebJSConfigured || !body.Data.Runtime.AMapSecurityProxyEnabled {
t.Fatalf("ops health should expose AMap runtime readiness, got %+v body=%s", body.Data.Runtime, rec.Body.String())
}
if !body.Data.Runtime.AMapAPIConfigured {
t.Fatalf("ops health should expose server-side AMap API readiness, got %+v body=%s", body.Data.Runtime, rec.Body.String())
}
if body.Data.Runtime.AMapSecurityCodeExposed {
t.Fatalf("ops health should show that AMap security code is not exposed when proxy is enabled: %+v", body.Data.Runtime)
}
if body.Data.Runtime.AMapSecurityServiceHost != "/_AMapService" {
t.Fatalf("ops health should include AMap security service host, got %+v", body.Data.Runtime)
}
if body.Data.Runtime.PlatformRelease != "platform-20260704153005" {
t.Fatalf("ops health should include platform release, got %+v", body.Data.Runtime)
}
}
func TestHandlerVehicleDataAPIsResolveVehicleKeyword(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
cases := []struct {
name string
path string
wantVIN string
}{
{name: "history locations vin alias", path: "/api/history/locations?vin=粤AG18312&limit=10", wantVIN: "LB9A32A24R0LS1426"},
{name: "raw frames vin alias", path: "/api/history/raw-frames?vin=粤AG18312&limit=1", wantVIN: "LB9A32A24R0LS1426"},
{name: "daily mileage vin alias", path: "/api/mileage/daily?vin=粤AG18312&limit=10", wantVIN: "LB9A32A24R0LS1426"},
{name: "history locations keyword", path: "/api/history/locations?keyword=川AHTWO1&limit=10", wantVIN: "LNXNEGRR7SR318212"},
{name: "raw frames keyword", path: "/api/history/raw-frames?keyword=川AHTWO1&limit=1", wantVIN: "LNXNEGRR7SR318212"},
{name: "daily mileage keyword", path: "/api/mileage/daily?keyword=川AHTWO1&limit=10", wantVIN: "LNXNEGRR7SR318212"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data struct {
Items []struct {
VIN string `json:"vin"`
} `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) == 0 {
t.Fatalf("vehicle data API should return rows for resolved keyword: %s", rec.Body.String())
}
if body.Data.Items[0].VIN != tc.wantVIN {
t.Fatalf("vehicle data API should resolve keyword to VIN %s, got %s body=%s", tc.wantVIN, body.Data.Items[0].VIN, rec.Body.String())
}
})
}
}
func TestHandlerRawFramesPostAcceptsKeyword(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/history/raw-frames/query", strings.NewReader(`{"keyword":"川AHTWO1","limit":1}`))
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data struct {
Items []RawFrameRow `json:"items"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if len(body.Data.Items) != 1 || body.Data.Items[0].VIN != "LNXNEGRR7SR318212" {
t.Fatalf("raw POST should resolve keyword to VIN, got %+v body=%s", body.Data.Items, rec.Body.String())
}
}
func TestHandlerRawFramesRejectsUnscopedIncludeFields(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
cases := []struct {
name string
req *http.Request
}{
{
name: "get",
req: httptest.NewRequest(http.MethodGet, "/api/history/raw-frames?limit=1&includeFields=true", nil),
},
{
name: "post",
req: httptest.NewRequest(http.MethodPost, "/api/history/raw-frames/query", strings.NewReader(`{"limit":1,"includeFields":true}`)),
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, tc.req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Error.Code != "RAW_FRAME_SCOPE_REQUIRED" {
t.Fatalf("error code = %q body=%s", body.Error.Code, rec.Body.String())
}
if !strings.Contains(body.Error.Message, "车辆或时间范围") {
t.Fatalf("error message should explain required scope: %s", rec.Body.String())
}
})
}
}
func TestHandlerRawFramesKeepsUnresolvedKeywordEmpty(t *testing.T) {
handler := NewHandler(NewService(NewMockStore()))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/history/raw-frames?keyword=64646848247&limit=1", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d body=%s", rec.Code, rec.Body.String())
}
var body struct {
Data Page[RawFrameRow] `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response JSON should decode: %v body=%s", err, rec.Body.String())
}
if body.Data.Total != 0 || len(body.Data.Items) != 0 {
t.Fatalf("unresolved keyword should not fabricate raw rows: %+v body=%s", body.Data, rec.Body.String())
}
}