package xlsxtranslate
import (
"archive/zip"
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// stripCJK replaces every run of CJK ideographs and CJK/full-width
// punctuation with a single space, keeping placeholders, numbers and ASCII
// text intact at their original token boundaries — the deterministic
// behaviour the real LLM is asked for by the system prompt.
func stripCJK(s string) string {
var b strings.Builder
inCJK := false
for _, r := range s {
if isCJKOrFullWidth(r) {
inCJK = true
continue
}
if inCJK {
b.WriteByte(' ')
inCJK = false
}
b.WriteRune(r)
}
if inCJK {
b.WriteByte(' ')
}
return b.String()
}
// isCJKOrFullWidth reports whether r is a CJK ideograph or a CJK punctuation
// / full-width form that a translation would replace.
func isCJKOrFullWidth(r rune) bool {
switch {
case r >= 0x3400 && r <= 0x9FFF, r >= 0xF900 && r <= 0xFAFF:
return true
case r >= 0x3000 && r <= 0x303F, r >= 0xFF01 && r <= 0xFF5E:
return true
case r >= 0x2018 && r <= 0x201D, r == 0x2026:
return true
}
return false
}
// fakeTranslator is a deterministic Translator stub.
type fakeTranslator struct {
calls int
fail error
respond func(masked string, seq int) string
}
func (f *fakeTranslator) TranslateBatch(_ context.Context, texts []string) ([]string, error) {
if f.fail != nil {
return nil, f.fail
}
out := make([]string, len(texts))
for i, m := range texts {
if f.respond != nil {
out[i] = f.respond(m, f.calls*1000+i)
} else {
out[i] = stripCJK(m)
}
}
f.calls++
return out, nil
}
const fixtureSharedStrings = `
螺母
接地区域铜箔纸取消
Assembly Process
底板平面度 <1.0mm
螺母
检查 & 包装 <OK>
`
const fixtureDrawing = `
万向轮
Caster
`
const fixtureSheet = `
检验工具
`
// buildTestXlsx assembles a minimal but structurally faithful workbook.
func buildTestXlsx(t *testing.T) []byte {
t.Helper()
files := map[string][]byte{
"[Content_Types].xml": []byte(``),
"_rels/.rels": []byte(``),
"xl/workbook.xml": []byte(``),
"xl/sharedStrings.xml": []byte(fixtureSharedStrings),
"xl/worksheets/sheet1.xml": []byte(fixtureSheet),
"xl/drawings/drawing1.xml": []byte(fixtureDrawing),
"xl/media/image1.png": {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xDE, 0xAD, 0xBE, 0xEF},
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
names := []string{
"[Content_Types].xml", "_rels/.rels", "xl/workbook.xml",
"xl/sharedStrings.xml", "xl/worksheets/sheet1.xml",
"xl/drawings/drawing1.xml", "xl/media/image1.png",
}
for _, name := range names {
w, err := zw.Create(name)
if err != nil {
t.Fatalf("zip create: %v", err)
}
if _, err := w.Write(files[name]); err != nil {
t.Fatalf("zip write: %v", err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("zip close: %v", err)
}
return buf.Bytes()
}
func zipEntry(t *testing.T, data []byte, name string) []byte {
t.Helper()
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open zip: %v", err)
}
for _, f := range r.File {
if f.Name == name {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
return raw
}
}
t.Fatalf("entry %s not found", name)
return nil
}
func TestTranslateSharedStringsDrawingsAndInline(t *testing.T) {
in := buildTestXlsx(t)
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), in, &Options{BatchSize: 2}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if tr.calls == 0 {
t.Fatalf("expected LLM batches to run")
}
// Structure: entry count and media bytes unchanged.
rIn, _ := zip.NewReader(bytes.NewReader(in), int64(len(in)))
rOut, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output not a valid zip: %v", err)
}
if len(rIn.File) != len(rOut.File) {
t.Fatalf("entry count changed: %d -> %d", len(rIn.File), len(rOut.File))
}
inMedia := zipEntry(t, in, "xl/media/image1.png")
outMedia := zipEntry(t, out, "xl/media/image1.png")
if !bytes.Equal(inMedia, outMedia) {
t.Fatalf("media bytes altered")
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if hasCJK(ss) {
t.Fatalf("sharedStrings still contains CJK:\n%s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("non-CJK shared string was altered:\n%s", ss)
}
// Both duplicate 螺母 blocks must be rewritten.
if got := strings.Count(ss, "xml:space=\"preserve\""); got != 5 {
t.Fatalf("expected 5 carrier rewrites, got %d:\n%s", got, ss)
}
// Entity content round-trips: unescaped before translation, correctly
// re-escaped on write-back.
if !strings.Contains(ss, "&") || !strings.Contains(ss, "<OK>") {
t.Fatalf("translated text not re-escaped for XML:\n%s", ss)
}
// Numbers inside a translated unit survive (placeholder protection).
if !strings.Contains(ss, "1.0mm") {
t.Fatalf("numeric token lost in translation:\n%s", ss)
}
// Rich-text sibling run cleared, style run preserved in the sibling.
if !strings.Contains(ss, "") {
t.Fatalf("rich text run structure dropped:\n%s", ss)
}
dw := string(zipEntry(t, out, "xl/drawings/drawing1.xml"))
if hasCJK(dw) {
t.Fatalf("drawing still contains CJK:\n%s", dw)
}
// Split runs joined into the first run's translation.
if !strings.Contains(dw, "") {
t.Fatalf("carrier a:t not written:\n%s", dw)
}
if strings.Contains(dw, ">Caster<") == false {
t.Fatalf("non-CJK paragraph altered:\n%s", dw)
}
sh := string(zipEntry(t, out, "xl/worksheets/sheet1.xml"))
if hasCJK(sh) {
t.Fatalf("inline string not translated:\n%s", sh)
}
if report.ResidualCJKCount != 0 {
t.Fatalf("residual CJK reported: %d %v", report.ResidualCJKCount, report.ResidualCJKSamples)
}
if len(report.NumberMismatches) != 0 || len(report.PartMismatches) != 0 {
t.Fatalf("integrity check failed: %v %v", report.NumberMismatches, report.PartMismatches)
}
if report.TranslatedUnits == 0 || report.GlossaryHits == 0 {
t.Fatalf("unexpected counts: units=%d glossary=%d", report.TranslatedUnits, report.GlossaryHits)
}
// 螺母 is a glossary hit; the LLM must not have been asked for it — the
// glossary value must appear verbatim.
if !strings.Contains(ss, "NUT") {
t.Fatalf("glossary hit not applied:\n%s", ss)
}
}
func TestTranslateNoCJKLeavesPackageUntouched(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, f := range []struct{ name, body string }{
{"[Content_Types].xml", ""},
{"xl/sharedStrings.xml", `Assembly Process`},
} {
w, _ := zw.Create(f.name)
w.Write([]byte(f.body))
}
zw.Close()
in := buf.Bytes()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), in, nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if tr.calls != 0 || report.TranslatedUnits != 0 {
t.Fatalf("unexpected work: calls=%d units=%d", tr.calls, report.TranslatedUnits)
}
// Repackaging may differ at the container level (compression, header
// flags), but every entry's content must be byte-identical.
inR, err := zip.NewReader(bytes.NewReader(in), int64(len(in)))
if err != nil {
t.Fatalf("input zip: %v", err)
}
outR, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
if len(inR.File) != len(outR.File) {
t.Fatalf("entry count changed: %d -> %d", len(inR.File), len(outR.File))
}
for i, f := range inR.File {
inRaw, err := readZip(f)
if err != nil {
t.Fatalf("read input %s: %v", f.Name, err)
}
outRaw, err := readZip(outR.File[i])
if err != nil {
t.Fatalf("read output %s: %v", f.Name, err)
}
if !bytes.Equal(inRaw, outRaw) {
t.Fatalf("entry %s was modified although it contains no CJK", f.Name)
}
}
}
func TestTranslateNormalizesFullWidthPunctuation(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
w.Write([]byte(`重点检验:`))
zw.Close()
tr := &fakeTranslator{respond: func(masked string, _ int) string {
return "Key inspection:" // deliberately full-width from the "LLM"
}}
out, _, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if !strings.Contains(ss, "Key inspection:") || strings.Contains(ss, ":") {
t.Fatalf("full-width punctuation not normalized: %s", ss)
}
}
func TestTranslateOversizedUnitIsSkippedAndReported(t *testing.T) {
long := strings.Repeat("长", 6000)
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
fmt.Fprintf(w, `%s短文本`, long)
zw.Close()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), buf.Bytes(), &Options{MaxUnitRunes: 100}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if !strings.Contains(ss, long) {
t.Fatalf("oversized unit was modified")
}
if report.RemainingCJKUnits != 1 || report.ResidualCJKCount != 1 {
t.Fatalf("oversized unit not reported: %+v", report)
}
if !strings.Contains(ss, stripCJK("短文本")) {
t.Fatalf("short unit not translated alongside skipped unit:\n%s", truncate(ss, 200))
}
}
func TestVerifyReportsBadTranslator(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
w.Write([]byte(`螺母 M8 检查 573.5`))
zw.Close()
// Translator that "forgets" to translate: residual must be reported.
tr := &fakeTranslator{respond: func(m string, _ int) string { return m }}
out, report, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if report.ResidualCJKCount != 1 {
t.Fatalf("residual not detected: %+v", report)
}
_ = out
}
func TestRealSIPRegression(t *testing.T) {
root := os.Getenv("ACADEMY_REPO_ROOT")
if root == "" {
root = "../.."
}
path := filepath.Join(root, "docs", "D4-A08AR12000002-A3-SIP.xlsx")
data, err := os.ReadFile(path)
if err != nil {
t.Skipf("real SIP file not available: %v", err)
}
if len(data) < 10<<20 {
t.Fatalf("unexpectedly small SIP file: %d bytes", len(data))
}
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), data, &Options{BatchSize: 50}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
rIn, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("input zip: %v", err)
}
rOut, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
if len(rIn.File) != len(rOut.File) {
t.Fatalf("entry count changed: %d -> %d", len(rIn.File), len(rOut.File))
}
// Every media byte must be identical.
inBytName := map[string][]byte{}
for _, f := range rIn.File {
if strings.HasPrefix(f.Name, "xl/media/") {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read media: %v", err)
}
inBytName[f.Name] = raw
}
}
for _, f := range rOut.File {
if strings.HasPrefix(f.Name, "xl/media/") {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read media out: %v", err)
}
if !bytes.Equal(inBytName[f.Name], raw) {
t.Fatalf("media %s altered", f.Name)
}
}
}
// Merged-cell structure of the sheets must be untouched.
countMerges := func(d []byte) int { return strings.Count(string(d), " %d", f.Name, countMerges(rawIn), countMerges(rawOut))
}
}
}
if report.ResidualCJKCount != 0 {
t.Fatalf("residual CJK in real SIP: %d samples=%v", report.ResidualCJKCount, report.ResidualCJKSamples)
}
if len(report.NumberMismatches) != 0 || len(report.PartMismatches) != 0 {
t.Fatalf("integrity check failed on real SIP: numbers=%v parts=%v",
report.NumberMismatches[:min(5, len(report.NumberMismatches))],
report.PartMismatches[:min(5, len(report.PartMismatches))])
}
if report.TranslatedUnits < 200 {
t.Fatalf("unexpectedly few units translated: %d", report.TranslatedUnits)
}
t.Logf("real SIP regression OK: %s", report.Markdown())
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// TestTranslateCollapsesWhitespaceVariants covers the positional-protocol
// desync: whitespace-padded variants of one term must collapse into a single
// translation unit, or a batch containing both loses an answer (19 of 20).
func TestTranslateCollapsesWhitespaceVariants(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
w.Write([]byte(`` +
`客 戶` +
`客 戶` +
`客户资料清单` +
``))
zw.Close()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if report.TranslatedUnits != 2 {
t.Fatalf("expected 2 canonical units after whitespace collapse, got %d", report.TranslatedUnits)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if hasCJK(ss) {
t.Fatalf("variants left untranslated:\n%s", ss)
}
if strings.Count(ss, "Customer") != 2 {
t.Fatalf("both whitespace variants should carry the glossary translation:\n%s", ss)
}
}