diff --git a/app/services/discourse_translator/libre_translate.rb b/app/services/discourse_translator/libre_translate.rb index 4ee81fa3..73e53c87 100644 --- a/app/services/discourse_translator/libre_translate.rb +++ b/app/services/discourse_translator/libre_translate.rb @@ -104,7 +104,7 @@ def self.translate!(translatable, target_locale_sym = I18n.locale) translate_uri, q: text_for_translation(translatable), source: detected_lang, - target: SUPPORTED_LANG_MAPPING[target_locale], + target: SUPPORTED_LANG_MAPPING[target_locale_sym], format: "html", ) res["translatedText"] diff --git a/spec/services/libre_translate_spec.rb b/spec/services/libre_translate_spec.rb index ae316e18..536fb4a3 100644 --- a/spec/services/libre_translate_spec.rb +++ b/spec/services/libre_translate_spec.rb @@ -4,6 +4,9 @@ RSpec.describe DiscourseTranslator::LibreTranslate do let(:mock_response) { Struct.new(:status, :body) } + let(:api_key) { "12345" } + + before { SiteSetting.translator_libretranslate_endpoint = "http://localhost:5000" } describe ".access_token" do describe "when set" do @@ -17,7 +20,6 @@ describe ".translate_supported?" do it "should equate source language to target" do - SiteSetting.translator_libretranslate_endpoint = "http://localhost:5000" source = "en" target = :fr @@ -27,4 +29,38 @@ expect(described_class.translate_supported?(source, target)).to be true end end + + describe ".translate" do + fab!(:post) + + before do + SiteSetting.translator_libretranslate_api_key = api_key + Excon + .expects(:get) + .with(SiteSetting.translator_libretranslate_endpoint + "/languages") + .returns(mock_response.new(200, [{ code: "de" }, { code: "en" }].to_json)) + end + + it "truncates text for translation to max_characters_per_translation setting" do + SiteSetting.max_characters_per_translation = 50 + post.set_detected_locale("de") + body = { q: post.cooked, source: "de", target: "en", format: "html", api_key: api_key } + + translated_text = "hur dur hur dur" + # https://publicapi.dev/libre-translate-api + Excon + .expects(:post) + .with( + SiteSetting.translator_libretranslate_endpoint + "/translate", + body: URI.encode_www_form(body), + headers: { + "Content-Type" => "application/x-www-form-urlencoded", + }, + ) + .returns(mock_response.new(200, %{ { "translatedText": "#{translated_text}"} })) + .once + + expect(described_class.translate(post)).to eq(["de", translated_text]) + end + end end