droboticflow-new/internal/api/annotation_source_validation_browser_test.go

103 lines
4.2 KiB
Go

package api
import (
"context"
"droboticflow/internal/config"
"droboticflow/internal/domain"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
)
func TestSourceValidationBrowserReplica(t *testing.T) {
if os.Getenv("SOURCE_VALIDATION_BROWSER_TEST") != "1" {
t.Skip("local browser opt-in")
}
t.Setenv("ANNOTATION_PROCESSOR_MODE", "external")
t.Setenv("ANNOTATION_PROCESSOR_ROLE", "validation")
f, root := annotationProcessorFixture(t)
batch, _ := f.store.GetHumanBatch(f.ctx, f.item.BatchID)
batch.ProcessingProfile = domain.ProcessingProfileRawHuman
if err := f.store.UpsertHumanBatch(f.ctx, *batch); err != nil {
t.Fatal(err)
}
if err := f.store.UpsertOrganizationPlugin(f.ctx, domain.OrganizationPluginRecord{OrganizationID: domain.DefaultOrganizationID, PluginID: "annotation-qa", Enabled: true, Config: defaultAnnotationPluginConfig()}); err != nil {
t.Fatal(err)
}
draft := f.request(http.MethodPut, "/api/plugins/annotation-qa/tasks/"+f.task.ID+"/drafts", f.annotator, map[string]any{
"version": f.item.Version, "sliceSegments": []map[string]any{{"id": "source-draft-slice", "name": "测试切片", "start": 0., "end": 4.}},
"segments": []map[string]any{{"id": "source-draft-action", "start": 0., "end": 4., "description": "已保存的测试标注", "status": "described", "source": "manual", "confidence": 1.}},
"operations": []any{}, "statuses": map[string]string{},
})
if draft.Code != 200 {
t.Fatalf("seed draft: %d %s", draft.Code, draft.Body.String())
}
before, _ := f.store.GetHumanItem(f.ctx, f.item.ID)
now := time.Now().UTC()
job, err := f.store.ClaimAnnotationIndex(f.ctx, "browser-invalid-source", now.Format(time.RFC3339Nano), now.Add(time.Minute).Format(time.RFC3339Nano))
if err != nil || job == nil {
t.Fatal("missing index job", err)
}
job.Status, job.Error, job.Attempt = "failed", "IMU row 418451 invalid type gyr", 5
if ok, err := f.store.FinishAnnotationIndex(f.ctx, *job); err != nil || !ok {
t.Fatal("seed invalid job", err)
}
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
var start sync.Once
var processes sync.WaitGroup
defer processes.Wait()
defer cancel()
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/__fixture/validate" && r.Method == http.MethodPost {
start.Do(func() {
processes.Add(1)
go func() {
defer processes.Done()
_ = RunAnnotationProcessor(ctx, f.store, config.AppConfig{WorkspaceMountPath: root}, 1, false)
}()
})
renderJSON(w, 202, map[string]bool{"started": true})
return
}
user := f.annotator
if cookie, err := r.Cookie("source-fixture-role"); err == nil && cookie.Value == "admin" {
user = f.admin
}
if r.URL.Path == "/api/auth/me" {
renderJSON(w, 200, map[string]any{"user": sanitizeUser(&user), "organization": domain.OrganizationRecord{ID: domain.DefaultOrganizationID, Status: domain.OrganizationStatusActive}})
return
}
if r.Method != "GET" && r.Method != "HEAD" && !strings.HasSuffix(r.URL.Path, "/source-validation-retries") {
renderJSON(w, 403, map[string]string{"error": "fixture read-only"})
return
}
csrf := "source-fixture-csrf"
r.AddCookie(&http.Cookie{Name: csrfCookieName, Value: csrf})
r.Header.Set(csrfHeaderName, csrf)
r = r.WithContext(context.WithValue(r.Context(), authContextKey{}, &authenticatedPrincipal{User: user, Organization: domain.OrganizationRecord{ID: domain.DefaultOrganizationID, Status: domain.OrganizationStatusActive}}))
f.handler.ServeHTTP(w, r)
}))
defer api.Close()
commandCtx, done := context.WithTimeout(t.Context(), 3*time.Minute)
defer done()
cmd := exec.CommandContext(commandCtx, "node", "tests/browser/annotation-source-validation-replica.mjs")
cmd.WaitDelay = 5 * time.Second
cmd.Dir = "../.."
cmd.Env = append(os.Environ(), "SOURCE_VALIDATION_API="+api.URL)
out, err := cmd.CombinedOutput()
t.Log(string(out))
if err != nil {
t.Fatal(err)
}
after, _ := f.store.GetHumanItem(f.ctx, f.item.ID)
if after.Version != before.Version || after.AssignedUserID != before.AssignedUserID || string(mustJSON(t, after.Subject.Payload)) != string(mustJSON(t, before.Subject.Payload)) {
t.Fatal("source validation altered annotation ownership or saved content")
}
}