Compare commits

..
7 Commits
Author SHA1 Message Date
Vincent Yang 0f2b50dd69 Merge pull request #245 from JounQin/feat/blank-text-passthrough
fix(translate): answer blank texts with themselves instead of failing the request
2026-10-11 00:54:20 +08:00
JounQin ee1114252e fix(service): treat a null text as no text, and read that from the field
UnmarshalJSON sent `null` down the string branch, where json.Unmarshal into a
string is a documented no-op, so `{"text":null}` decoded to `[""]` and was
indistinguishable from `{"text":""}` for the rest of the request. On main both
were an error, but this branch answers an empty text with itself, so null
quietly became a 200 instead.

A JSON null is a present key with no value, so it leaves the zero value now —
the same Texts == nil a body with no `text` key has — and the handler refuses
both with 400 Invalid request payload, testing the field directly instead of
re-deriving the decoder with `!Batch && len(Texts) == 0`. Every shape that
names text, including `"text": []`, still decodes to a non-nil Texts and is
answered rather than refused.

Refs #244.
2026-10-11 00:40:57 +08:00
JounQin b28dcd4958 fix(translate): answer an empty text list with an empty list, not 404
`"text": []` names a list that happens to be empty, and the response can
render that perfectly well, so rejecting it bought nothing: it was the
original "No text to translate" condition surviving for the one shape the
code had no answer to. It is answered with `{"data": []}` now — the same
rule as every other text, applied to none of them.

A body that never named `text` is a different thing, a payload without its
parameter: it answers 400 Invalid request payload instead of the 404 that
stood in for it, which is also what the endpoint answers for a body it
cannot bind. That is the only refusal left.

Refs #244.
2026-10-10 23:44:37 +08:00
JounQin 4fb2759d48 fix(translate): answer a request whose texts are all empty with 200 as well
Every text is answered now, blank or not, so the all-empty case needs no
rule of its own: "" and [""] are texts with nothing to translate in them,
and they are answered with themselves like any other blank text. A missing
or null `text` decodes to the one empty string and is answered the same
way.

The 404 is left for a request that names no text at all: `"text": []`, the
one shape there is nothing to answer with. Nothing else errors on
emptiness.

Refs #244.
2026-10-10 23:39:45 +08:00
JounQin 7269cf615a fix(translate): answer blank texts with themselves instead of failing the request
A request fails as a whole when any one of its texts is empty, so a document
split into lines cannot be translated at all if it has a blank line in it:
["", "Hello"] answers 404 "No text to translate" and nothing is translated.

A blank text — empty, or nothing but whitespace — carries nothing to
translate, so it is no longer sent, and its own text is the answer. That
keeps the response position-aligned, and it is the only thing that can work:
oneshot echoes an empty input, and the positional check would read that echo
as a failed translation and answer 503 instead. A whitespace-only text
survives today only because oneshot happens to echo it as well.

The 404 is now only for a request with no text at all — no texts, or every
text empty. A request that has text but nothing to translate, like ["   "],
is answered with its own texts, so no blank input errors any more and no
input that used to succeed fails now.

This matches the JavaScript client (@deeplx/core batchPayload and
restoreBlankSegments), which already drops text.trim() === '' segments and
puts them back, so the two sides agree on what a blank segment means.

Refs #240, #241, #244.
2026-10-10 23:35:19 +08:00
Vincent Yang 83f97d336d fix(translate): count the 1500-character cap in UTF-16 code units (#243)
fix(translate): count the 1500-character cap in UTF-16 code units
2026-10-10 22:54:51 +08:00
JounQin 10f66b9484 fix(translate): count the 1500-character cap in UTF-16 code units
The anonymous oneshot cap is 1500 UTF-16 code units — what
String.prototype.length reports in the extension and String.length in the
Kotlin iOS client this endpoint is modelled on. utf8.RuneCountInString
scores an astral character as one where oneshot scores it two, so 751
emoji (751 runes, 1502 units) passed the guard, travelled upstream and
came back as the generic 503 "request failed with status code: 400"
instead of the 413 the guard exists to produce.

Count the unit oneshot counts. BMP text is unaffected: runes and UTF-16
units agree everywhere except a surrogate pair, which is why the rune
count looked right.

Invalid UTF-8 is not part of this and needs no validation of its own:
encoding/json has already replaced every invalid byte with U+FFFD before
the guard runs, one unit each, exactly as a rune count scored them.

Measured against the live endpoint through a local build:
- 750 astral characters (1500 units) -> 200, 751 (1502 units) -> 400
- 800 CJK characters (800 units, 2400 bytes, 1600 columns) -> 200
- 1000 combining-mark pairs (2000 units, 1000 graphemes) -> 400
- 1500 ASCII -> 200, 1501 ASCII -> 413 from the guard

Refs #242
2026-10-10 21:39:05 +08:00
6 changed files with 358 additions and 49 deletions
+2 -2
View File
@@ -89,9 +89,9 @@ curl -X POST http://localhost:1188/translate \
Batch limits and failure modes:
- The anonymous limit is **1500 characters for the whole request**, counted in Unicode characters (runes) across every text in the array — not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts.
- The anonymous limit is **1500 characters for the whole request**, counted in UTF-16 code units — what JavaScript's `String.prototype.length` reports, so a CJK character costs 1 and an astral one (emoji, historic scripts) costs 2 — across every text in the array, not 1500 per text. A batch over that total is rejected with `413` and `text exceeds maximum length: N characters (anonymous oneshot limit is 1500)`, so a large batch has to be chunked by total length rather than by segment count. There is no separate cap on the number of texts.
- A blank text — empty, or nothing but whitespace — is answered with itself and never sent, so a blank line in a segmented document keeps its place instead of failing the request. `"text": []` is answered with `{"data": []}`; a body with no `text` field at all, or `"text": null`, is rejected with `400 {"code":400,"message":"Invalid request payload"}`.
- A batch is all-or-nothing: if DeepL returns a different number of translations or leaves one of them empty, the request fails with `503 {"code":503,"message":"Translation failed"}` instead of answering with placeholders or a shorter, misaligned array.
- `"text": []`, and any array containing an empty string, are rejected with the same `404 {"code":404,"message":"No text to translate"}` as `"text": ""`.
## Discussion Group
[Telegram Group](https://t.me/+8KDGHKJCxEVkNzll)
+19 -3
View File
@@ -91,8 +91,7 @@ type PayloadTranslate struct {
// Texts, and Batch records which shape the caller used so the response can
// mirror it. Any other shape (a number, an object, an array holding
// non-strings) fails the payload decode, which the handler reports as
// 400 Invalid request payload; null decodes to the empty string exactly as it
// did when text was a plain string.
// 400 Invalid request payload; null names no text, like a body without the key.
type PayloadText struct {
Texts []string
Batch bool
@@ -100,7 +99,8 @@ type PayloadText struct {
// UnmarshalJSON implements json.Unmarshaler.
func (p *PayloadText) UnmarshalJSON(data []byte) error {
if trimmed := bytes.TrimSpace(data); len(trimmed) > 0 && trimmed[0] == '[' {
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 && trimmed[0] == '[' {
var texts []string
if err := json.Unmarshal(trimmed, &texts); err != nil {
return err
@@ -109,6 +109,11 @@ func (p *PayloadText) UnmarshalJSON(data []byte) error {
return nil
}
// A JSON null names no text: leave the zero value, so Texts stays nil.
if string(trimmed) == "null" {
return nil
}
var text string
if err := json.Unmarshal(data, &text); err != nil {
return err
@@ -159,6 +164,17 @@ func Router(cfg *Config) *gin.Engine {
return
}
// A body without `text` never named a text to translate, which is a
// payload error. `"text": []` names a list that happens to be empty,
// and is answered with an empty list, so it is not caught here.
if req.Text.Texts == nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": http.StatusBadRequest,
"message": "Invalid request payload",
})
return
}
sourceLang := req.SourceLang
targetLang := req.TargetLang
texts := req.Text.Texts
+43 -1
View File
@@ -2,9 +2,13 @@ package service
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// The `text` field of POST /translate accepts either shape; decoding uses the
@@ -22,7 +26,8 @@ func TestPayloadTextUnmarshalJSON(t *testing.T) {
{name: "array", payload: `{"text":["Hello","Good morning"]}`, wantTexts: []string{"Hello", "Good morning"}, wantBatch: true},
{name: "single-element array", payload: `{"text":["Hello"]}`, wantTexts: []string{"Hello"}, wantBatch: true},
{name: "empty array", payload: `{"text":[]}`, wantTexts: []string{}, wantBatch: true},
{name: "null", payload: `{"text":null}`, wantTexts: []string{""}},
{name: "null", payload: `{"text":null}`, wantTexts: nil},
{name: "no text field", payload: `{}`, wantTexts: nil},
{name: "number", payload: `{"text":1}`, wantErr: true},
{name: "object", payload: `{"text":{}}`, wantErr: true},
{name: "mixed array", payload: `{"text":["Hello",1]}`, wantErr: true},
@@ -46,3 +51,40 @@ func TestPayloadTextUnmarshalJSON(t *testing.T) {
})
}
}
// POST /translate mirrors the shape it was given, and no shape that carries
// text is an error any more — an empty text is answered with itself and an
// empty array with an empty array. Every case here is answered (or refused)
// before a translation is attempted, so the test never reaches DeepL.
func TestTranslateHandlerAnswersEmptyText(t *testing.T) {
gin.SetMode(gin.TestMode)
router := Router(&Config{})
tests := []struct {
name string
payload string
wantCode int
wantInBody string
}{
{"empty array", `{"text":[],"target_lang":"EN"}`, http.StatusOK, `"data":[]`},
{"empty string", `{"text":"","target_lang":"EN"}`, http.StatusOK, `"data":""`},
{"null", `{"text":null,"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`},
{"array of empty", `{"text":[""],"target_lang":"EN"}`, http.StatusOK, `"data":[""]`},
{"no text field", `{"target_lang":"EN"}`, http.StatusBadRequest, `Invalid request payload`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/translate", strings.NewReader(tt.payload))
request.Header.Set("Content-Type", "application/json")
router.ServeHTTP(recorder, request)
if recorder.Code != tt.wantCode {
t.Fatalf("POST /translate %s = %d %s, want %d", tt.payload, recorder.Code, recorder.Body.String(), tt.wantCode)
}
if !strings.Contains(recorder.Body.String(), tt.wantInBody) {
t.Fatalf("POST /translate %s body = %s, want it to contain %s", tt.payload, recorder.Body.String(), tt.wantInBody)
}
})
}
}
+123
View File
@@ -0,0 +1,123 @@
package translate
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"unicode/utf8"
)
// The anonymous cap is a UTF-16 length, not a rune count: an astral character
// is a surrogate pair and costs two units, which is the only place the two
// disagree. A rune count understates such a request and lets oneshot answer it
// with a bare 400 instead.
func TestTextLength(t *testing.T) {
tests := []struct {
name string
text string
want int
}{
{"empty", "", 0},
{"ascii", "Hello, world!", 13},
{"BMP CJK", "你好", 2},
{"highest BMP code point", "\uFFFF", 1},
{"lowest astral code point", "\U00010000", 2},
{"astral character", "😀", 2},
{"astral characters", "😀😀", 4},
{"mixed", "a😀b", 4},
{"combining mark is two units, not one grapheme", "e\u0301", 2},
{"at the limit", strings.Repeat("a", maxFreeTextLength), maxFreeTextLength},
{"one past the limit", strings.Repeat("a", maxFreeTextLength+1), maxFreeTextLength + 1},
{"astral at the limit", strings.Repeat("😀", maxFreeTextLength/2), maxFreeTextLength},
{"astral past the limit", strings.Repeat("😀", maxFreeTextLength/2+1), maxFreeTextLength + 2},
{"combining at the limit", strings.Repeat("e\u0301", maxFreeTextLength/2), maxFreeTextLength},
{"combining past the limit", strings.Repeat("e\u0301", maxFreeTextLength/2+1), maxFreeTextLength + 2},
{"invalid UTF-8 counts one unit per byte", "\xf0\x90\x80", 3},
{"invalid UTF-8 mixed with ASCII", "a\xff\xfeb", 4},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := textLength(tt.text); got != tt.want {
t.Fatalf("textLength(%q) = %d, want %d", tt.text, got, tt.want)
}
})
}
}
// The guard counts JSON-decoded text, and encoding/json has already replaced
// every invalid byte with U+FFFD by then — json.Marshal would replace them
// again on the way upstream — so invalid UTF-8 never reaches textLength as
// invalid bytes, and the old rune count agreed with it exactly there. Invalid
// UTF-8 is therefore not what made the rune count wrong; an astral character
// is, which is the one case where the two columns below differ.
func TestTextLengthOnJSONDecodedText(t *testing.T) {
tests := []struct {
name string
body string
wantText string
wantUnits int
wantRunes int
}{
{"invalid UTF-8 in the body", "{\"text\":\"\xf0\x90\x80\"}", "\uFFFD\uFFFD\uFFFD", 3, 3},
{"paired surrogate escape", `{"text":"\ud83d\ude00"}`, "😀", 2, 1},
{"lone surrogate escape", `{"text":"\ud83d"}`, "\uFFFD", 1, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var payload struct {
Text string `json:"text"`
}
if err := json.Unmarshal([]byte(tt.body), &payload); err != nil {
t.Fatalf("json.Unmarshal(%q) error = %v", tt.body, err)
}
if payload.Text != tt.wantText {
t.Fatalf("decoded text = %q, want %q", payload.Text, tt.wantText)
}
if got := textLength(payload.Text); got != tt.wantUnits {
t.Fatalf("textLength(%q) = %d, want %d", payload.Text, got, tt.wantUnits)
}
if got := utf8.RuneCountInString(payload.Text); got != tt.wantRunes {
t.Fatalf("utf8.RuneCountInString(%q) = %d, want %d", payload.Text, got, tt.wantRunes)
}
})
}
}
// Rejected requests must fail before anything is sent upstream: every case
// below returns on validation alone, so the test never reaches DeepL. The
// astral cases are the regression — 751 runes, which the old rune count
// accepted, but 1502 UTF-16 units, which oneshot answers with 400.
func TestTranslateByDLXRejectsOversizedTextsBeforeUpstream(t *testing.T) {
tests := []struct {
name string
texts []string
}{
{"one ASCII past the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}},
{"astral characters past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2+1)}},
{"combining marks past the limit", []string{strings.Repeat("e\u0301", maxFreeTextLength/2+1)}},
{"invalid UTF-8 past the limit", []string{strings.Repeat("\xf0\x90\x80", maxFreeTextLength/3+1)}},
// 800 runes in total, but two units each: a batch the rune count let
// through in a single request.
{"batch of astral characters past the limit", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, length := textsToTranslate(tt.texts)
if length <= maxFreeTextLength {
t.Fatalf("textsToTranslate(%q) = %d, which is not over the limit", tt.texts, length)
}
result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "")
if err != nil {
t.Fatalf("TranslateByDLX() error = %v", err)
}
if result.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusRequestEntityTooLarge)
}
if want := fmt.Sprintf("%d", length); !strings.Contains(result.Message, want) {
t.Fatalf("TranslateByDLX() message = %q, want it to name %s", result.Message, want)
}
})
}
}
+79 -27
View File
@@ -29,7 +29,6 @@ import (
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/andybalholm/brotli"
"github.com/imroc/req/v3"
@@ -99,8 +98,10 @@ const (
// oneshot enforces a 1500-character hard cap on the total length of
// the `text` array for anonymous traffic (same limit the Chrome
// extension documents as G.notLoggedIn). Bail early to spare the
// upstream and give the caller a faster error.
// extension documents as G.notLoggedIn). A character there is a UTF-16
// code unit — what JavaScript's String.prototype.length and Kotlin's
// String.length report — so an astral character counts as two. Bail
// early to spare the upstream and give the caller a faster error.
maxFreeTextLength = 1500
// oneshotTimeout caps how long we wait on a single translate request.
@@ -416,21 +417,54 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL, appVersion
return gjson.ParseBytes(raw), resp.StatusCode, nil
}
// totalTextLength returns the total rune count of texts. ok is false when no
// text was requested or any of them is empty, which callers report as
// "No text to translate" — an empty element fails the batch as a whole rather
// than being skipped or translated as an empty segment.
func totalTextLength(texts []string) (total int, ok bool) {
if len(texts) == 0 {
return 0, false
}
for _, text := range texts {
if text == "" {
return 0, false
// textLength returns the length of text in UTF-16 code units — the unit
// oneshot's anonymous 1500-character cap counts, and the one the DeepL clients
// this profile mirrors report (the iOS app is Kotlin, the extension is
// JavaScript). An astral character is a surrogate pair and so counts as two,
// where a rune count scores it one and lets an oversized request travel
// upstream to be rejected there as a bare 400.
//
// Invalid UTF-8 needs no special case: the request body is decoded with
// encoding/json before this runs, which replaces every invalid byte with
// U+FFFD, and each replacement is one unit either way.
func textLength(text string) int {
n := 0
for _, r := range text {
if r > 0xFFFF {
n += 2
} else {
n++
}
total += utf8.RuneCountInString(text)
}
return total, true
return n
}
// textsToTranslate returns the positions of the texts that carry something to
// translate and their total length in UTF-16 code units. A blank text — empty,
// or nothing but whitespace — carries nothing to translate, so it is not sent:
// its own text is the answer, which keeps a segmented document position-aligned
// and lets an empty line pass through instead of failing the request.
func textsToTranslate(texts []string) (positions []int, total int) {
for i, text := range texts {
if strings.TrimSpace(text) == "" {
continue
}
positions = append(positions, i)
total += textLength(text)
}
return positions, total
}
// mergeTranslations puts the translations back at the positions they were asked
// for, leaving every text that was not sent — a blank one — exactly as it
// arrived.
func mergeTranslations(texts []string, positions []int, translations []string) []string {
merged := make([]string, len(texts))
copy(merged, texts)
for i, position := range positions {
merged[position] = translations[i]
}
return merged
}
// translationsFromResult extracts exactly count non-empty translations from
@@ -463,14 +497,8 @@ func translationsFromResult(result gjson.Result, count int) ([]string, error) {
func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling string, proxyURL string, dlSession string) (DLXTranslationResult, error) {
// oneshot charges its anonymous cap against the total length of the
// `text` array, and a batch is one upstream request, so the cap applies
// to the sum of the requested texts rather than to each text.
totalLength, ok := totalTextLength(texts)
if !ok {
return DLXTranslationResult{
Code: http.StatusNotFound,
Message: "No text to translate",
}, nil
}
// to the sum of the texts that are actually sent.
positions, totalLength := textsToTranslate(texts)
resolvedTarget, err := resolveTargetLang(targetLang)
if err != nil {
@@ -494,6 +522,22 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s
}, nil
}
// Nothing to translate: every text is blank, so none of them travels and
// the request is answered with its own texts — an empty list in, an empty
// list out — exactly as a blank element is inside a request that does have
// something to translate.
if len(positions) == 0 {
return DLXTranslationResult{
Code: http.StatusOK,
ID: time.Now().UnixMilli(),
Data: mergeTranslations(texts, positions, nil),
Alternatives: nil, // oneshot does not return alternatives
SourceLang: sourceLang,
TargetLang: targetLang,
Method: map[bool]string{true: "Pro", false: "Free"}[dlSession != ""],
}, nil
}
// tagHandling is accepted by the public DLX API for compatibility
// but oneshot does not expose html/xml tag handling the way the
// official v2 API does — ignored upstream.
@@ -503,8 +547,16 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s
// app_information always agree; the lookup itself is cached (appversion.go).
appVersion := currentIOSAppVersion()
// Blank texts stay here: oneshot echoes an empty input, and the positional
// check on the answer would read that echo as a failed translation and fail
// the batch, so there is nothing to gain by sending them.
requested := make([]string, 0, len(positions))
for _, position := range positions {
requested = append(requested, texts[position])
}
reqStruct := oneshotRequest{
Text: texts,
Text: requested,
TargetLang: resolvedTarget,
SourceLang: resolvedSource, // empty = autodetect; omitempty drops the field
// ItaClient.OneShotUsageType.translate (also: ocr, voiceforconversations)
@@ -576,7 +628,7 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s
}, nil
}
data, err := translationsFromResult(result, len(texts))
translations, err := translationsFromResult(result, len(requested))
if err != nil {
return DLXTranslationResult{
ID: id,
@@ -592,7 +644,7 @@ func TranslateByDLX(sourceLang, targetLang string, texts []string, tagHandling s
return DLXTranslationResult{
Code: http.StatusOK,
ID: id,
Data: data,
Data: mergeTranslations(texts, positions, translations),
Alternatives: nil, // oneshot does not return alternatives
SourceLang: sourceLang,
TargetLang: targetLang,
+92 -16
View File
@@ -9,27 +9,61 @@ import (
"github.com/tidwall/gjson"
)
func TestTotalTextLength(t *testing.T) {
func TestTextsToTranslate(t *testing.T) {
tests := []struct {
name string
texts []string
wantAt []int
wantTotal int
wantOK bool
}{
{"no texts", nil, 0, false},
{"empty array", []string{}, 0, false},
{"empty string", []string{""}, 0, false},
{"empty element in batch", []string{"Hello", ""}, 0, false},
{"single text", []string{"Hello"}, 5, true},
{"batch total", []string{"Hello", "Good morning"}, 17, true},
{"counts runes, not bytes", []string{"你好"}, 2, true},
{"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, maxFreeTextLength, true},
{"no texts", nil, nil, 0},
{"empty array", []string{}, nil, 0},
{"empty string", []string{""}, nil, 0},
{"every text empty", []string{"", ""}, nil, 0},
{"whitespace only", []string{" \t "}, nil, 0},
{"empty and blank", []string{"", " "}, nil, 0},
{"single text", []string{"Hello"}, []int{0}, 5},
{"empty element in batch", []string{"Hello", ""}, []int{0}, 5},
{"leading empty element in batch", []string{"", "Hello"}, []int{1}, 5},
{"blank elements around a batch", []string{"", "Hello", " ", "Good morning", "\n"}, []int{1, 3}, 17},
{"batch total", []string{"Hello", "Good morning"}, []int{0, 1}, 17},
{"counts UTF-16 units, not bytes", []string{"你好"}, []int{0}, 2},
{"astral character costs two units", []string{"😀"}, []int{0}, 2},
{"combining mark is two units, not one grapheme", []string{"e\u0301"}, []int{0}, 2},
{"invalid UTF-8 counts one unit per byte", []string{"\xf0\x90\x80"}, []int{0}, 3},
{"at the limit", []string{strings.Repeat("a", maxFreeTextLength)}, []int{0}, maxFreeTextLength},
{"astral at the limit", []string{strings.Repeat("😀", maxFreeTextLength/2)}, []int{0}, maxFreeTextLength},
{"astral past the limit", []string{strings.Repeat("😀", maxFreeTextLength/2), "😀"}, []int{0, 1}, maxFreeTextLength + 2},
{"astral batch sums units, not runes", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, []int{0, 1}, 1600},
{"blank texts are not charged", []string{" ", "Hello"}, []int{1}, 5},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
total, ok := totalTextLength(tt.texts)
if ok != tt.wantOK || total != tt.wantTotal {
t.Fatalf("totalTextLength(%q) = (%d, %v), want (%d, %v)", tt.texts, total, ok, tt.wantTotal, tt.wantOK)
at, total := textsToTranslate(tt.texts)
if total != tt.wantTotal || !reflect.DeepEqual(at, tt.wantAt) {
t.Fatalf("textsToTranslate(%q) = (%v, %d), want (%v, %d)", tt.texts, at, total, tt.wantAt, tt.wantTotal)
}
})
}
}
func TestMergeTranslations(t *testing.T) {
tests := []struct {
name string
texts []string
positions []int
translations []string
want []string
}{
{"no blanks", []string{"Hello"}, []int{0}, []string{"你好"}, []string{"你好"}},
{"leading blank", []string{"", "Hello"}, []int{1}, []string{"你好"}, []string{"", "你好"}},
{"blank keeps its exact text", []string{"", "Hello", " "}, []int{1}, []string{"你好"}, []string{"", "你好", " "}},
{"batch keeps order", []string{"Hello", " ", "Good morning"}, []int{0, 2}, []string{"你好", "早上好"}, []string{"你好", " ", "早上好"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := mergeTranslations(tt.texts, tt.positions, tt.translations); !reflect.DeepEqual(got, tt.want) {
t.Fatalf("mergeTranslations(%q, %v, %q) = %q, want %q", tt.texts, tt.positions, tt.translations, got, tt.want)
}
})
}
@@ -84,11 +118,12 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) {
texts []string
code int
}{
{"no texts", nil, http.StatusNotFound},
{"empty array", []string{}, http.StatusNotFound},
{"empty element in batch", []string{"Hello", ""}, http.StatusNotFound},
{"over the limit", []string{strings.Repeat("a", maxFreeTextLength+1)}, http.StatusRequestEntityTooLarge},
{"batch over the limit", []string{strings.Repeat("a", maxFreeTextLength), "b"}, http.StatusRequestEntityTooLarge},
// 751 runes in the batch, but 1502 UTF-16 units: the case a rune count
// let through to be rejected by oneshot instead.
{"astral batch over the unit limit", []string{strings.Repeat("😀", maxFreeTextLength/2+1)}, http.StatusRequestEntityTooLarge},
{"astral batch split over the unit limit", []string{strings.Repeat("😀", 400), strings.Repeat("😀", 400)}, http.StatusRequestEntityTooLarge},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -102,3 +137,44 @@ func TestTranslateByDLXValidationFailsBeforeUpstream(t *testing.T) {
})
}
}
// Every text is answered — translated when it carries something, returned as it
// is when it is blank — so nothing about emptiness is an error, and none of the
// cases below reaches DeepL. Data is always allocated, so an empty request
// marshals as `[]` rather than `null`.
func TestTranslateByDLXAnswersBlankTextsWithThemselves(t *testing.T) {
tests := []struct {
name string
texts []string
}{
{"no texts", nil},
{"empty array", []string{}},
{"single empty", []string{""}},
{"two empty", []string{"", ""}},
{"whitespace only", []string{" \t "}},
{"empty and whitespace", []string{"", " "}},
{"newlines and spaces", []string{"\n", "\t\n", " "}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := TranslateByDLX("", "ZH", tt.texts, "", "", "")
if err != nil {
t.Fatalf("TranslateByDLX() error = %v", err)
}
if result.Code != http.StatusOK {
t.Fatalf("TranslateByDLX() code = %d, want %d", result.Code, http.StatusOK)
}
if result.Data == nil {
t.Fatal("TranslateByDLX() data = nil, want an allocated slice so it marshals as []")
}
if len(result.Data) != len(tt.texts) {
t.Fatalf("TranslateByDLX() data = %q, want %d element(s)", result.Data, len(tt.texts))
}
for i, text := range tt.texts {
if result.Data[i] != text {
t.Fatalf("TranslateByDLX() data[%d] = %q, want %q", i, result.Data[i], text)
}
}
})
}
}