Files
ai_academy/internal/agent/tools/xlsx_translate_test.go
T
runny c6088aeb4b
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
fix(翻译):修复(工具与沙箱解耦,双通道自适应)
2026-11-30 21:09:02 +08:00

300 lines
9.7 KiB
Go

package tools
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"testing"
"academy/internal/models/chat"
"academy/internal/sandbox"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// fakeTranslateStore is an in-memory SessionFileSink + dir ensurer.
type fakeTranslateStore struct {
files map[string][]byte
ensured []string
writePath string
}
func (s *fakeTranslateStore) EnsureSessionDir(_ context.Context, _, dir string) error {
s.ensured = append(s.ensured, dir)
return nil
}
func (s *fakeTranslateStore) StatSessionFile(_ context.Context, _, _ string) (*sandbox.RemoteStatEntry, error) {
return nil, fmt.Errorf("not implemented")
}
func (s *fakeTranslateStore) ReadSessionFile(_ context.Context, _, path string) ([]byte, error) {
if data, ok := s.files[path]; ok {
return data, nil
}
return nil, fmt.Errorf("no such file: %s", path)
}
func (s *fakeTranslateStore) WriteSessionWorkspaceFile(_ context.Context, _, path string, content []byte) error {
s.files[path] = content
s.writePath = path
return nil
}
// fakeTranslateTempDoc is an in-memory TemporaryDocumentService covering the
// surface xlsx_translate uses. Unimplemented methods panic via the embedded
// nil interface — the tool must not call them.
type fakeTranslateTempDoc struct {
interfaces.TemporaryDocumentService
docs []*types.TemporaryDocument
created []*types.TemporaryDocument
createdBytes map[string][]byte
openBytes map[string][]byte
}
func (s *fakeTranslateTempDoc) List(_ context.Context, _ uint64, _ string) ([]*types.TemporaryDocument, error) {
return s.docs, nil
}
func (s *fakeTranslateTempDoc) OpenFile(_ context.Context, _ uint64, _ string, documentID string) (io.ReadCloser, string, error) {
if data, ok := s.openBytes[documentID]; ok {
return io.NopCloser(bytes.NewReader(data)), "part.xlsx", nil
}
return nil, "", fmt.Errorf("no such document: %s", documentID)
}
func (s *fakeTranslateTempDoc) Create(_ context.Context, _ uint64, _ string, fileName, _ string, fileSize int64, reader io.Reader, _ types.TemporaryDocumentCreateOptions) (*types.TemporaryDocument, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
if int64(len(data)) != fileSize {
return nil, fmt.Errorf("size mismatch")
}
doc := &types.TemporaryDocument{ID: fmt.Sprintf("doc-%d", len(s.created)+1), FileName: fileName, FileSize: fileSize}
if s.createdBytes == nil {
s.createdBytes = map[string][]byte{}
}
s.createdBytes[doc.ID] = data
s.created = append(s.created, doc)
return doc, nil
}
// fakeTranslateChat answers every batch with the requested array translated
// deterministically: CJK runs become " EN ".
type fakeTranslateChat struct {
prompts []string
}
func (f *fakeTranslateChat) Chat(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
f.prompts = append(f.prompts, messages[len(messages)-1].Content)
content := messages[len(messages)-1].Content
start := strings.IndexByte(content, '[')
end := strings.LastIndexByte(content, ']')
var texts []string
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
return nil, err
}
out := make([]string, 0, len(texts))
for _, t := range texts {
out = append(out, replaceCJKRuns(t))
}
b, _ := json.Marshal(out)
return &types.ChatResponse{Content: string(b)}, nil
}
func (f *fakeTranslateChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
return nil, fmt.Errorf("not implemented")
}
func (f *fakeTranslateChat) GetModelName() string { return "fake" }
func (f *fakeTranslateChat) GetModelID() string { return "fake-id" }
// replaceCJKRuns mirrors the engine-test stub: CJK runs become a single space.
func replaceCJKRuns(s string) string {
var b strings.Builder
inCJK := false
for _, r := range s {
if (r >= 0x3400 && r <= 0x9FFF) || (r >= 0xF900 && r <= 0xFAFF) ||
(r >= 0x3000 && r <= 0x303F) || (r >= 0xFF01 && r <= 0xFF5E) {
inCJK = true
continue
}
if inCJK {
b.WriteByte(' ')
inCJK = false
}
b.WriteRune(r)
}
if inCJK {
b.WriteByte(' ')
}
return b.String()
}
func buildToolFixture(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, f := range []struct{ name, body string }{
{"[Content_Types].xml", "<Types/>"},
{"xl/sharedStrings.xml", `<sst xmlns="x"><si><t>螺母 M8</t></si><si><t>Assembly Process</t></si></sst>`},
} {
w, _ := zw.Create(f.name)
w.Write([]byte(f.body))
}
zw.Close()
return buf.Bytes()
}
func toolExecContext(sessionID string) context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: sessionID})
}
func sharedStringsFrom(t *testing.T, data []byte) string {
t.Helper()
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
for _, f := range r.File {
if f.Name == "xl/sharedStrings.xml" {
rc, _ := f.Open()
raw, _ := io.ReadAll(rc)
rc.Close()
return string(raw)
}
}
t.Fatalf("no sharedStrings.xml in output")
return ""
}
func TestXlsxTranslateToolEndToEndSandbox(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xlsx": buildToolFixture(t),
}}
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if store.writePath != "/workspace/output/part_EN.xlsx" {
t.Fatalf("unexpected output path: %s", store.writePath)
}
if len(result.OutputFiles) != 1 || !strings.Contains(result.OutputFiles[0], "part_EN.xlsx") {
t.Fatalf("missing output link: %v", result.OutputFiles)
}
if !strings.Contains(result.Output, "part_EN.xlsx") {
t.Fatalf("output does not name the deliverable: %s", result.Output)
}
ss := sharedStringsFrom(t, store.files[store.writePath])
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("output still contains Chinese: %s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("English string lost: %s", ss)
}
}
// TestXlsxTranslateToolWithoutSandbox covers the 192 deployment failure mode:
// no workspace sandbox anywhere in the session, so input comes from the
// uploaded session attachment and the deliverable is a preview URL.
func TestXlsxTranslateToolWithoutSandbox(t *testing.T) {
tempDoc := &fakeTranslateTempDoc{
openBytes: map[string][]byte{"doc-1": buildToolFixture(t)},
}
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
ID: "doc-1", FileName: "D4-A08AR12000002-A3-SIP.xlsx", FileType: "xlsx",
})
tool := NewXlsxTranslateTool(nil, nil, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "D4-A08AR12000002-A3-SIP.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if len(tempDoc.created) != 1 {
t.Fatalf("expected one delivered attachment, got %d", len(tempDoc.created))
}
created := tempDoc.created[0]
if created.FileName != "D4-A08AR12000002-A3-SIP_EN.xlsx" {
t.Fatalf("unexpected deliverable name: %s", created.FileName)
}
wantURL := "/api/v1/sessions/sess-1/attachments/" + created.ID + "/preview"
if !strings.Contains(result.Output, wantURL) {
t.Fatalf("output missing preview URL %s: %s", wantURL, result.Output)
}
ss := sharedStringsFrom(t, tempDoc.createdBytes[created.ID])
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("delivered workbook still contains Chinese: %s", ss)
}
}
// TestXlsxTranslateToolSandboxReadFallsBackToAttachment covers a mixed
// session: a sandbox exists but the named file is not staged there, so the
// upload is read from the attachment service while the deliverable still
// goes to the sandbox output directory.
func TestXlsxTranslateToolSandboxReadFallsBackToAttachment(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tempDoc := &fakeTranslateTempDoc{
openBytes: map[string][]byte{"doc-1": buildToolFixture(t)},
}
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
ID: "doc-1", FileName: "part.xlsx", FileType: "xlsx",
})
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if store.writePath != "/workspace/output/part_EN.xlsx" {
t.Fatalf("unexpected output path: %s", store.writePath)
}
}
func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xls": {0xD0, 0xCF, 0x11, 0xE0},
}}
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("legacy .xls should be rejected")
}
if !strings.Contains(result.Error, ".xlsx") {
t.Fatalf("unhelpful error: %s", result.Error)
}
}
func TestXlsxTranslateToolMissingFile(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tempDoc := &fakeTranslateTempDoc{}
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("missing file should fail")
}
}