package machinelearning import ( "strings" "testing" ) func policyFixture() Policy { return Policy{Generation: "33333333-3333-4333-8333-333333333333", Enabled: true, ScopeUUID: fixture().ScopeUUID, Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, Exclude: []string{"/lab/private"}, MaxBatchBytes: 12000} } func TestPolicyPaths(t *testing.T) { p := policyFixture() for _, tc := range []struct { path string allow bool }{ {"/lab", true}, {"/lab/文書", true}, {"/labs", false}, {"/lab/private", false}, {"/lab/private/child", false}, {"/lab/private-other", true}, {"/lab/../secret", false}, {"/lab/%70rivate", false}, {"/lab//a", false}, {"https://example.com/lab", false}, {"/lab/a?b", false}, } { if p.Allows(tc.path, p.Generation) != tc.allow { t.Errorf("path %q", tc.path) } } p.Prefixes = []string{"/"} if !p.Allows("/other", p.Generation) || p.Allows("/lab/private/x", p.Generation) { t.Fatal("root/exclusion") } if p.Allows("/lab", "stale") { t.Fatal("stale generation accepted") } p.Enabled = false if p.Allows("/lab", p.Generation) { t.Fatal("disabled scope accepted") } } func TestPolicyValidationAndPrepare(t *testing.T) { for _, mutate := range []func(*Policy){ func(p *Policy) { p.Prefixes = []string{"/lab/"} }, func(p *Policy) { p.Exclude = []string{"relative"} }, func(p *Policy) { p.AllowExternal = true }, func(p *Policy) { p.MaxBatchBytes = 0 }, func(p *Policy) { p.Provider = "openai"; p.Model = "text-embedding-3-small" }, } { p := policyFixture() mutate(&p) if p.Validate() == nil { t.Fatal("invalid policy accepted") } } p := policyFixture() inputs := []Input{{ID: "chunk:0", Text: "合成文書"}} req, err := p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs) if err != nil { t.Fatal(err) } inputs[0].Text = "changed" if req.Inputs[0].Text == "changed" || req.AllowExternal { t.Fatal("input/consent binding") } p.MaxBatchBytes = 2 if _, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs); err == nil { t.Fatal("batch budget") } p = policyFixture() p.Provider = "openai" p.Model = "text-embedding-3-small" p.AllowExternal = true req, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs) if err != nil || !req.AllowExternal { t.Fatalf("explicit external policy: %v", err) } }