fix: use exact MyMemory matches when top translation is blank

This commit is contained in:
Valdemar Lorenzen
2026-10-15 10:52:17 +02:00
parent d0a66c29a8
commit c31424b217
3 changed files with 55 additions and 4 deletions
+32
View File
@@ -28,3 +28,35 @@ import Testing
}
}
}
@Test func myMemoryUsesNonblankExactMatchWhenPrimaryTranslationIsEmpty() async throws {
// MyMemory's live response for "hello" has a blank top translation and a valid exact match.
let body = #"{"responseStatus":200,"quotaFinished":false,"responseData":{"translatedText":""},"matches":[{"segment":"hello","translation":"","source":"en-GB","target":"ja-JP"},{"segment":"hello there","translation":"近似","source":"en","target":"ja"},{"segment":"hello","translation":"bonjour","source":"en","target":"fr"},{"segment":"hello","translation":"こんにちは","source":"en-GB","target":"ja-JP"}]}"#
let translation = try await MyMemoryAPI.translate("hello") { request in
(Data(body.utf8), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
#expect(translation == "こんにちは")
}
@Test func myMemoryNeverUsesMatchesToBypassFailureOrReplacePrimaryTranslation() async throws {
let matches = #""matches":[{"segment":"hello","translation":"こんにちは","source":"en","target":"ja"}]"#
for metadata in [#""responseStatus":403"#, #""responseStatus":200,"quotaFinished":true"#] {
await #expect(throws: (any Error).self) {
try await MyMemoryAPI.translate("hello") { request in
(Data("{\(metadata),\(matches)}".utf8),
HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
}
}
let primary = try await MyMemoryAPI.translate("hello") { request in
(Data("{\"responseStatus\":200,\"responseData\":{\"translatedText\":\"どうも\"},\(matches)}".utf8),
HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
#expect(primary == "どうも")
await #expect(throws: (any Error).self) {
try await MyMemoryAPI.translate("unrelated") { request in
(Data("{\"responseStatus\":200,\(matches)}".utf8),
HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
}
}
}