discourse-translator/spec/services/discourse_ai_spec.rb
Natalie Tay 346d47cde9
FIX: Normalize languages within Discourse AI translator (#194)
The criteria to allow a post to be translated is if the user's locale is different from the site's default locale.

For each translator (e.g. Google, Amazon, Azure), we maintain a list of mappings `SUPPORTED_LANG_MAPPING` for each locale. On top of that, this mapping is also used to define what language the post should be translated to. When using most translators available in the plugin, "en_GB" forums will translate text to "en" due to these mappings. This is not a problem for Discourse AI provider, since there are no restrictions on language.

This PR normalizes locales within Discourse AI translator, so that it sees "ar" to be the same as "ar_SA".
2025-01-13 17:13:26 +08:00

57 lines
1.8 KiB
Ruby

# frozen_string_literal: true
require "rails_helper"
describe DiscourseTranslator::DiscourseAi do
fab!(:post)
before do
Fabricate(:fake_model).tap do |fake_llm|
SiteSetting.public_send("ai_helper_model=", "custom:#{fake_llm.id}")
end
SiteSetting.ai_helper_enabled = true
SiteSetting.translator_enabled = true
SiteSetting.translator = "DiscourseAi"
end
describe ".language_supported?" do
it "returns true when detected language is different from i18n locale" do
I18n.stubs(:locale).returns(:xx)
expect(described_class.language_supported?("any-language")).to eq(true)
end
it "returns false when detected language is same base language as i18n locale" do
I18n.stubs(:locale).returns(:en_GB)
expect(described_class.language_supported?("en")).to eq(false)
end
end
describe ".detect" do
it "stores the detected language in a custom field" do
locale = "de"
DiscourseAi::Completions::Llm.with_prepared_responses(["<language>de</language>"]) do
DiscourseTranslator::DiscourseAi.detect(post)
post.save_custom_fields
end
expect(post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD]).to eq locale
end
end
describe ".translate" do
before do
post.custom_fields[DiscourseTranslator::DETECTED_LANG_CUSTOM_FIELD] = "de"
post.save_custom_fields
end
it "translates the post and returns [locale, translated_text]" do
DiscourseAi::Completions::Llm.with_prepared_responses(
["<translation>some translated text</translation>"],
) do
locale, translated_text = DiscourseTranslator::DiscourseAi.translate(post)
expect(locale).to eq "de"
expect(translated_text).to eq "some translated text"
end
end
end
end