286d21d3ef2d72787d06c3782cfef266ca02b6c2
[akkoma] / test / pleroma / translators / deepl_test.exs
1 defmodule Pleroma.Akkoma.Translators.DeepLTest do
2 use Pleroma.DataCase, async: true
3
4 alias Pleroma.Akkoma.Translators.DeepL
5
6 describe "translating with deepl" do
7 setup do
8 clear_config([:deepl, :api_key], "deepl_api_key")
9 end
10
11 test "should work with the free tier" do
12 clear_config([:deepl, :tier], :free)
13
14 Tesla.Mock.mock(fn
15 %{method: :post, url: "https://api-free.deepl.com/v2/translate"} = env ->
16 auth_header = Enum.find(env.headers, fn {k, _v} -> k == "authorization" end)
17 assert {"authorization", "DeepL-Auth-Key deepl_api_key"} = auth_header
18
19 %Tesla.Env{
20 status: 200,
21 body:
22 Jason.encode!(%{
23 translations: [
24 %{
25 "text" => "I will crush you",
26 "detected_source_language" => "ja"
27 }
28 ]
29 })
30 }
31 end)
32
33 assert {:ok, "ja", "I will crush you"} = DeepL.translate("ギュギュ握りつぶしちゃうぞ", "en")
34 end
35
36 test "should work with the pro tier" do
37 clear_config([:deepl, :tier], :pro)
38
39 Tesla.Mock.mock(fn
40 %{method: :post, url: "https://api.deepl.com/v2/translate"} = env ->
41 auth_header = Enum.find(env.headers, fn {k, _v} -> k == "authorization" end)
42 assert {"authorization", "DeepL-Auth-Key deepl_api_key"} = auth_header
43
44 %Tesla.Env{
45 status: 200,
46 body:
47 Jason.encode!(%{
48 translations: [
49 %{
50 "text" => "I will crush you",
51 "detected_source_language" => "ja"
52 }
53 ]
54 })
55 }
56 end)
57
58 assert {:ok, "ja", "I will crush you"} = DeepL.translate("ギュギュ握りつぶしちゃうぞ", "en")
59 end
60
61 test "should gracefully fail if the API errors" do
62 clear_config([:deepl, :tier], :free)
63
64 Tesla.Mock.mock(fn
65 %{method: :post, url: "https://api-free.deepl.com/v2/translate"} ->
66 %Tesla.Env{
67 status: 403,
68 body: ""
69 }
70 end)
71
72 assert {:error, "DeepL request failed (code 403)"} = DeepL.translate("ギュギュ握りつぶしちゃうぞ", "en")
73 end
74 end
75 end