Skip to content

Commit 142902a

Browse files
authored
FIX: Incorrect lang mapping using non-symbols (#238)
Also adds test coverage for /translate endpoint
1 parent 1c4e532 commit 142902a

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

app/services/discourse_translator/libre_translate.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def self.translate!(translatable, target_locale_sym = I18n.locale)
104104
translate_uri,
105105
q: text_for_translation(translatable),
106106
source: detected_lang,
107-
target: SUPPORTED_LANG_MAPPING[target_locale],
107+
target: SUPPORTED_LANG_MAPPING[target_locale_sym],
108108
format: "html",
109109
)
110110
res["translatedText"]

spec/services/libre_translate_spec.rb

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
RSpec.describe DiscourseTranslator::LibreTranslate do
66
let(:mock_response) { Struct.new(:status, :body) }
7+
let(:api_key) { "12345" }
8+
9+
before { SiteSetting.translator_libretranslate_endpoint = "http://localhost:5000" }
710

811
describe ".access_token" do
912
describe "when set" do
@@ -17,7 +20,6 @@
1720

1821
describe ".translate_supported?" do
1922
it "should equate source language to target" do
20-
SiteSetting.translator_libretranslate_endpoint = "http://localhost:5000"
2123
source = "en"
2224
target = :fr
2325

@@ -27,4 +29,38 @@
2729
expect(described_class.translate_supported?(source, target)).to be true
2830
end
2931
end
32+
33+
describe ".translate" do
34+
fab!(:post)
35+
36+
before do
37+
SiteSetting.translator_libretranslate_api_key = api_key
38+
Excon
39+
.expects(:get)
40+
.with(SiteSetting.translator_libretranslate_endpoint + "/languages")
41+
.returns(mock_response.new(200, [{ code: "de" }, { code: "en" }].to_json))
42+
end
43+
44+
it "truncates text for translation to max_characters_per_translation setting" do
45+
SiteSetting.max_characters_per_translation = 50
46+
post.set_detected_locale("de")
47+
body = { q: post.cooked, source: "de", target: "en", format: "html", api_key: api_key }
48+
49+
translated_text = "hur dur hur dur"
50+
# https://publicapi.dev/libre-translate-api
51+
Excon
52+
.expects(:post)
53+
.with(
54+
SiteSetting.translator_libretranslate_endpoint + "/translate",
55+
body: URI.encode_www_form(body),
56+
headers: {
57+
"Content-Type" => "application/x-www-form-urlencoded",
58+
},
59+
)
60+
.returns(mock_response.new(200, %{ { "translatedText": "#{translated_text}"} }))
61+
.once
62+
63+
expect(described_class.translate(post)).to eq(["de", translated_text])
64+
end
65+
end
3066
end

0 commit comments

Comments
 (0)