package machinelearning import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "net/http" "net/http/httptest" "os" "strings" "testing" ) func fixture() Request { return Request{Protocol: "1", DomainUUID: "11111111-1111-4111-8111-111111111111", ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 2, Inputs: []Input{{ID: "page:chunk0", Text: "合成文書 library books"}}} } func resultFor(req Request) Result { r := Result{Protocol: req.Protocol, DomainUUID: req.DomainUUID, ScopeUUID: req.ScopeUUID, Provider: req.Provider, Model: req.Model, ModelRevision: req.Model, Dimensions: req.Dimensions, Tokenizer: "unicode-cjk-bigram-v1"} for _, item := range req.Inputs { hash := sha256.Sum256([]byte(item.Text)) r.Outputs = append(r.Outputs, Output{ID: item.ID, InputSHA256: hex.EncodeToString(hash[:]), Vector: []float64{0.5, -0.2}}) } return r } func TestClient(t *testing.T) { req := fixture() for _, test := range []struct { name string mutate func(*Result) wantErr bool }{ {"valid", func(*Result) {}, false}, {"wrong-domain", func(r *Result) { r.DomainUUID = req.ScopeUUID }, true}, {"wrong-scope", func(r *Result) { r.ScopeUUID = req.DomainUUID }, true}, {"wrong-hash", func(r *Result) { r.Outputs[0].InputSHA256 = "wrong" }, true}, {"wrong-dimensions", func(r *Result) { r.Outputs[0].Vector = []float64{1} }, true}, {"wrong-model", func(r *Result) { r.ModelRevision = "other" }, true}, {"wrong-tokenizer", func(r *Result) { r.Tokenizer = "other" }, true}, {"zero", func(r *Result) { r.Outputs[0].Vector = []float64{0, 0} }, true}, } { t.Run(test.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/v1/embeddings" || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 40) { t.Error("request contract") } var sent Request if err := json.NewDecoder(r.Body).Decode(&sent); err != nil || sent.Inputs[0].Text != req.Inputs[0].Text { t.Error("input changed") } result := resultFor(req) test.mutate(&result) _ = json.NewEncoder(w).Encode(result) })) defer server.Close() client, err := NewClient(server.URL, strings.Repeat("t", 40)) if err != nil { t.Fatal(err) } _, err = client.Embed(context.Background(), req) if (err != nil) != test.wantErr { t.Fatalf("unexpected error: %v", err) } }) } } func TestNoRedirectRetryOrSecretErrors(t *testing.T) { calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ w.Header().Set("Location", "/secret") w.WriteHeader(307) _, _ = w.Write([]byte("secret provider body")) })) defer server.Close() client, _ := NewClient(server.URL, strings.Repeat("t", 40)) _, err := client.Embed(context.Background(), fixture()) var status *StatusError if !errors.As(err, &status) || status.Status != 307 || calls != 1 || strings.Contains(err.Error(), "secret") { t.Fatalf("redirect/error handling: %v calls=%d", err, calls) } ctx, cancel := context.WithCancel(context.Background()) cancel() _, err = client.Embed(ctx, fixture()) if !errors.Is(err, context.Canceled) { t.Fatal(err) } } func TestRequestValidation(t *testing.T) { for _, mutate := range []func(*Request){ func(r *Request) { r.DomainUUID = "../" }, func(r *Request) { r.Inputs[0].Text = strings.Repeat("x", 6001) }, func(r *Request) { r.Provider = "openai"; r.Model = "text-embedding-3-small" }, func(r *Request) { r.Inputs = append(r.Inputs, r.Inputs[0]) }, func(r *Request) { r.Dimensions = 1537 }, } { req := fixture() mutate(&req) if validate(req) == nil { t.Fatal("accepted invalid request") } } for _, origin := range []string{"file:///tmp/x", "http://user:pass@localhost", "https://ml.invalid/path", "https://ml.invalid?x=1"} { if _, err := NewClient(origin, strings.Repeat("t", 40)); err == nil { t.Fatal("accepted origin", origin) } } } // Optional end-to-end contract test against a local synthetic fixture service. // No real Pages documents, credentials, or paid OpenAI requests are used. func TestLocalDoc2VecService(t *testing.T) { origin := os.Getenv("PAGES_ML_TEST_ORIGIN") if origin == "" { t.Skip("set PAGES_ML_TEST_ORIGIN for synthetic service integration") } client, err := NewClient(origin, strings.Repeat("t", 40)) if err != nil { t.Fatal(err) } req := fixture() req.Model = os.Getenv("PAGES_ML_TEST_MODEL") req.Dimensions = 8 result, err := client.Embed(context.Background(), req) if err != nil { t.Fatal(err) } if len(result.Outputs) != 1 || len(result.Outputs[0].Vector) != 8 { t.Fatal("wrong result shape") } }