test(json): 锁定 REST WebSocket MTR 与 MCP 输出合同

This commit is contained in:
tsosunchia committed 2026-09-05 13:50:52 +08:00
1 parent 939167e400
commit d70a8665e0
9 files changed
+466 -84

No files matched your search

+129
View File
@@ -0,0 +1,129 @@
package service
import (
"bytes"
"encoding/json"
"os"
"reflect"
"testing"
"github.com/nxtrace/NTrace-core/ipgeo"
"github.com/nxtrace/NTrace-core/trace"
)
type serviceJSONContracts struct {
Trace TraceResponse `json:"trace"`
MTRReport MTRReportResponse `json:"mtr_report"`
MTRRaw MTRRawResponse `json:"mtr_raw"`
}
func TestServiceJSONContractsGolden(t *testing.T) {
contracts := serviceJSONContracts{
Trace: TraceResponse{
Target: "escape <&>\u2028 target",
ResolvedIP: "2001:db8::10",
Protocol: "udp",
DataProvider: ipgeo.NextTraceAPIProvider,
Language: "en",
Hops: []Hop{{
TTL: 1,
Attempts: []Attempt{
{Success: true, IP: "192.0.2.1", Hostname: "edge.example", RTTMs: 1.25},
{Success: false, Error: "timeout\nsecond line"},
},
}},
DurationMs: 1250,
Parameters: ParameterBoundaries{Supported: []string{"target", "protocol"}},
},
MTRReport: MTRReportResponse{
Target: "example.test",
ResolvedIP: "192.0.2.9",
Protocol: "icmp",
Stats: []trace.MTRHopStat{{
TTL: 1,
Host: "edge.example",
IP: "192.0.2.1",
Loss: 33.333333333333336,
Snt: 3,
Last: 1.25,
Avg: 1.5,
Best: 1.25,
Wrst: 1.75,
StDev: 0.25,
Received: 2,
MPLS: []string{"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"},
Response: &trace.MTRProbeResponse{
Kind: trace.MTRResponseTransit,
Description: "ICMP Time Exceeded",
},
}},
DurationMs: 30000,
Parameters: ParameterBoundaries{
Supported: []string{"target", "hop_interval_ms"},
NotApplicable: []string{"queries"},
NotYetSupported: []string{"future_option"},
},
PathEnd: &TraceStopReason{
Hop: 3,
Reason: trace.StopReasonUnreachable,
Responses: []string{"ICMP Host Unreachable"},
Markers: []string{"!H"},
},
},
MTRRaw: MTRRawResponse{
Target: "raw.example",
ResolvedIP: "2001:db8::20",
Protocol: "tcp",
Records: []trace.MTRRawRecord{{
Iteration: 2,
TTL: 4,
Success: true,
IP: "2001:db8::4",
Host: "router <&>\u2028 name",
RTTMs: 12.75,
ASN: "AS64512",
Country: "ZZ",
City: "Example City",
Owner: "Example Network",
Lat: -0.125,
Lng: 179.999,
Response: &trace.MTRProbeResponse{
Kind: trace.MTRResponseDestination,
Marker: "!X",
},
}},
DurationMs: 5000,
Warnings: []string{"first line\nsecond line", ""},
Parameters: ParameterBoundaries{Supported: []string{"target", "duration_ms"}},
},
}
got, err := json.MarshalIndent(contracts, "", " ")
if err != nil {
t.Fatalf("marshal service JSON contracts: %v", err)
}
got = append(got, '\n')
assertServiceJSONGolden(t, got, "testdata/json_responses.golden.json")
}
func assertServiceJSONGolden(t *testing.T, got []byte, path string) {
t.Helper()
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read JSON golden: %v", err)
}
var gotValue any
if err := json.Unmarshal(got, &gotValue); err != nil {
t.Fatalf("decode generated JSON: %v", err)
}
var wantValue any
if err := json.Unmarshal(want, &wantValue); err != nil {
t.Fatalf("decode JSON golden: %v", err)
}
if !reflect.DeepEqual(gotValue, wantValue) {
t.Fatalf("JSON semantics changed\n--- got ---\n%s\n--- want ---\n%s", got, want)
}
if !bytes.Equal(got, want) {
t.Fatalf("JSON bytes changed while semantics remain equal\n--- got ---\n%s\n--- want ---\n%s", got, want)
}
}
+119
View File
@@ -0,0 +1,119 @@
{
"trace": {
"target": "escape \u003c\u0026\u003e\u2028 target",
"resolved_ip": "2001:db8::10",
"protocol": "udp",
"data_provider": "NextTrace-API",
"language": "en",
"hops": [
{
"ttl": 1,
"attempts": [
{
"success": true,
"ip": "192.0.2.1",
"hostname": "edge.example",
"rtt_ms": 1.25
},
{
"success": false,
"error": "timeout\nsecond line"
}
]
}
],
"duration_ms": 1250,
"parameters": {
"supported": [
"target",
"protocol"
]
}
},
"mtr_report": {
"target": "example.test",
"resolved_ip": "192.0.2.9",
"protocol": "icmp",
"stats": [
{
"ttl": 1,
"host": "edge.example",
"ip": "192.0.2.1",
"loss_percent": 33.333333333333336,
"snt": 3,
"last_ms": 1.25,
"avg_ms": 1.5,
"best_ms": 1.25,
"wrst_ms": 1.75,
"stdev_ms": 0.25,
"mpls": [
"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"
],
"received": 2,
"response": {
"kind": "transit",
"description": "ICMP Time Exceeded"
}
}
],
"duration_ms": 30000,
"parameters": {
"supported": [
"target",
"hop_interval_ms"
],
"not_applicable": [
"queries"
],
"not_yet_supported": [
"future_option"
]
},
"path_end": {
"hop": 3,
"reason": "unreachable",
"responses": [
"ICMP Host Unreachable"
],
"markers": [
"!H"
]
}
},
"mtr_raw": {
"target": "raw.example",
"resolved_ip": "2001:db8::20",
"protocol": "tcp",
"records": [
{
"iteration": 2,
"ttl": 4,
"success": true,
"ip": "2001:db8::4",
"host": "router \u003c\u0026\u003e\u2028 name",
"rtt_ms": 12.75,
"asn": "AS64512",
"country": "ZZ",
"city": "Example City",
"owner": "Example Network",
"lat": -0.125,
"lng": 179.999,
"response": {
"kind": "destination",
"marker": "!X"
}
}
],
"duration_ms": 5000,
"warnings": [
"first line\nsecond line",
""
],
"parameters": {
"supported": [
"target",
"duration_ms"
]
}
}
}
+83
View File
@@ -0,0 +1,83 @@
package server
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"reflect"
"testing"
"github.com/gin-gonic/gin"
"github.com/nxtrace/NTrace-core/internal/service"
"github.com/nxtrace/NTrace-core/ipgeo"
"github.com/nxtrace/NTrace-core/trace"
)
func TestRESTTraceResponseGolden(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.JSON(http.StatusOK, traceResponse{
Target: "escape <&>\u2028 target",
ResolvedIP: "2001:db8::9",
Protocol: "UDP",
DataProvider: ipgeo.NextTraceAPIProvider,
Language: "en",
Hops: []hopResponse{{
TTL: 1,
Attempts: []hopAttempt{
{Success: true, IP: "2001:db8::1", Hostname: "edge.example", RTT: 12.5},
{Success: false, Error: "timeout\nretry"},
},
}},
DurationMs: 250,
StopReason: &service.TraceStopReason{
Hop: 3,
Reason: trace.StopReasonUnreachable,
Responses: []string{"ICMP Host Unreachable"},
},
})
if got := recorder.Header().Get("Content-Type"); got != "application/json; charset=utf-8" {
t.Fatalf("Content-Type = %q", got)
}
body := recorder.Body.Bytes()
if bytes.HasSuffix(body, []byte{'\n'}) {
t.Fatal("REST JSON response unexpectedly ends with a newline")
}
got := append(append([]byte(nil), body...), '\n')
assertJSONGolden(t, got, "testdata/rest_trace_response.golden.json")
}
func assertJSONGolden(t *testing.T, got []byte, path string) {
t.Helper()
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read JSON golden: %v", err)
}
if !reflect.DeepEqual(decodeJSONSequence(t, got), decodeJSONSequence(t, want)) {
t.Fatalf("JSON semantics changed\n--- got ---\n%s\n--- want ---\n%s", got, want)
}
if !bytes.Equal(got, want) {
t.Fatalf("JSON bytes changed while semantics remain equal\n--- got ---\n%s\n--- want ---\n%s", got, want)
}
}
func decodeJSONSequence(t *testing.T, data []byte) []any {
t.Helper()
decoder := json.NewDecoder(bytes.NewReader(data))
values := make([]any, 0, 1)
for {
var value any
if err := decoder.Decode(&value); err != nil {
if err == io.EOF {
return values
}
t.Fatalf("decode JSON contract: %v", err)
}
values = append(values, value)
}
}
+35
View File
@@ -371,6 +371,41 @@ func TestMCPHandlerCallsEveryToolWithStructuredContent(t *testing.T) {
}
}
func TestMCPStructuredContentGolden(t *testing.T) {
session, cleanup := newTestMCPSession(t, newRecordingMCPService())
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
type contract struct {
Tool string `json:"tool"`
StructuredContent json.RawMessage `json:"structured_content"`
}
contracts := make([]contract, 0, 3)
for _, name := range []string{"nexttrace_traceroute", "nexttrace_mtr_report", "nexttrace_mtr_raw"} {
result, err := session.CallTool(ctx, &mcp.CallToolParams{
Name: name,
Arguments: map[string]any{"target": "example.com"},
})
if err != nil {
t.Fatalf("CallTool(%s): %v", name, err)
}
payload, err := json.Marshal(result.StructuredContent)
if err != nil {
t.Fatalf("marshal structuredContent for %s: %v", name, err)
}
contracts = append(contracts, contract{Tool: name, StructuredContent: payload})
}
got, err := json.MarshalIndent(contracts, "", " ")
if err != nil {
t.Fatalf("marshal MCP JSON contracts: %v", err)
}
got = append(got, '\n')
assertJSONGolden(t, got, "testdata/mcp_structured_content.golden.json")
}
func TestMCPHandlerReturnsServiceErrorsAsToolErrors(t *testing.T) {
svc := newRecordingMCPService()
svc.failTool = "nexttrace_geo_lookup"
+87
View File
@@ -0,0 +1,87 @@
[
{
"tool": "nexttrace_traceroute",
"structured_content": {
"data_provider": "",
"duration_ms": 0,
"hops": null,
"language": "",
"parameters": {
"supported": null
},
"protocol": "icmp",
"resolved_ip": "93.184.216.34",
"stop_reason": {
"hop": 4,
"reason": "destination_reached"
},
"target": "example.com"
}
},
{
"tool": "nexttrace_mtr_report",
"structured_content": {
"duration_ms": 0,
"parameters": {
"supported": null
},
"path_end": {
"hop": 4,
"reason": "destination_reached"
},
"protocol": "icmp",
"resolved_ip": "93.184.216.34",
"stats": [
{
"avg_ms": 0,
"best_ms": 0,
"geo": {
"asnumber": "",
"city": "",
"city_en": "",
"country": "",
"country_en": "",
"district": "",
"domain": "",
"ip": "",
"isp": "",
"lat": 0,
"lng": 0,
"owner": "",
"prefix": "",
"prov": "",
"prov_en": "",
"router": {},
"source": "",
"whois": ""
},
"last_ms": 0,
"loss_percent": 0,
"received": 0,
"snt": 0,
"stdev_ms": 0,
"ttl": 1,
"wrst_ms": 0
}
],
"target": "example.com"
}
},
{
"tool": "nexttrace_mtr_raw",
"structured_content": {
"duration_ms": 0,
"parameters": {
"supported": null
},
"path_end": {
"hop": 3,
"reason": "unreachable"
},
"protocol": "icmp",
"records": null,
"resolved_ip": "93.184.216.34",
"target": "example.com"
}
}
]
+1
View File
@@ -0,0 +1 @@
{"target":"escape \u003c\u0026\u003e\u2028 target","resolved_ip":"2001:db8::9","protocol":"UDP","data_provider":"NextTrace-API","language":"en","hops":[{"ttl":1,"attempts":[{"success":true,"ip":"2001:db8::1","hostname":"edge.example","rtt_ms":12.5},{"success":false,"error":"timeout\nretry"}]}],"duration_ms":250,"stop_reason":{"hop":3,"reason":"unreachable","responses":["ICMP Host Unreachable"]}}
-62
View File
@@ -1,62 +0,0 @@
[
{
"type": "start",
"data": {
"data_provider": "NextTrace-API",
"language": "en",
"protocol": "UDP",
"resolved_ip": "2001:db8::9",
"target": "example.test"
}
},
{
"type": "mtr_raw",
"data": {
"iteration": 1,
"ttl": 2,
"success": true,
"ip": "2001:db8::2",
"host": "router.example",
"rtt_ms": 12.5,
"lat": 0,
"lng": 0,
"mpls": [
"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"
],
"response": {
"kind": "unreachable",
"description": "ICMP Host Unreachable",
"marker": "!H"
}
}
},
{
"type": "path_end",
"data": {
"hop": 2,
"reason": "unreachable",
"responses": [
"ICMP Host Unreachable"
],
"markers": [
"!H"
]
}
},
{
"type": "complete",
"data": {
"iteration": 1,
"path_end": {
"hop": 2,
"reason": "unreachable",
"responses": [
"ICMP Host Unreachable"
],
"markers": [
"!H"
]
}
}
}
]
+4
View File
@@ -0,0 +1,4 @@
{"type":"start","data":{"data_provider":"NextTrace-API","language":"en","protocol":"UDP","resolved_ip":"2001:db8::9","target":"example.test"}}
{"type":"mtr_raw","data":{"iteration":1,"ttl":2,"success":true,"ip":"2001:db8::2","host":"router.example","rtt_ms":12.5,"lat":0,"lng":0,"mpls":["[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"],"response":{"kind":"unreachable","description":"ICMP Host Unreachable","marker":"!H"}}}
{"type":"path_end","data":{"hop":2,"reason":"unreachable","responses":["ICMP Host Unreachable"],"markers":["!H"]}}
{"type":"complete","data":{"iteration":1,"path_end":{"hop":2,"reason":"unreachable","responses":["ICMP Host Unreachable"],"markers":["!H"]}}}
+8 -22
View File
@@ -1,9 +1,8 @@
package server
import (
"bytes"
"encoding/json"
"os"
"reflect"
"testing"
"github.com/gin-gonic/gin"
@@ -51,25 +50,12 @@ func TestWebSocketEnvelopeGolden(t *testing.T) {
{Type: "complete", Data: gin.H{"iteration": 1, "path_end": pathEnd}},
}
gotJSON, err := json.Marshal(envelopes)
if err != nil {
t.Fatalf("marshal websocket envelopes: %v", err)
}
wantJSON, err := os.ReadFile("testdata/ws_envelopes.golden.json")
if err != nil {
t.Fatalf("read websocket envelope golden: %v", err)
}
var got any
if err := json.Unmarshal(gotJSON, &got); err != nil {
t.Fatalf("decode generated websocket envelopes: %v", err)
}
var want any
if err := json.Unmarshal(wantJSON, &want); err != nil {
t.Fatalf("decode websocket envelope golden: %v", err)
}
if !reflect.DeepEqual(got, want) {
formatted, _ := json.MarshalIndent(got, "", " ")
t.Fatalf("websocket envelope schema changed\n--- got ---\n%s\n--- want ---\n%s", formatted, wantJSON)
var encoded bytes.Buffer
encoder := json.NewEncoder(&encoded)
for _, envelope := range envelopes {
if err := encoder.Encode(envelope); err != nil {
t.Fatalf("encode websocket envelope: %v", err)
}
}
assertJSONGolden(t, encoded.Bytes(), "testdata/ws_envelopes.golden.jsonl")
}