deepl-rb 3.10.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +1 -1
  3. data/CHANGELOG.md +313 -1
  4. data/README.md +225 -309
  5. data/Rakefile +17 -8
  6. data/VERSION +1 -1
  7. data/deepl-rb.gemspec +73 -86
  8. data/lib/deepl/admin_client.rb +39 -14
  9. data/lib/deepl/api.rb +3 -17
  10. data/lib/deepl/app_info.rb +0 -1
  11. data/lib/deepl/client.rb +399 -84
  12. data/lib/deepl/configuration.rb +19 -70
  13. data/lib/deepl/exceptions/authorization_failed.rb +1 -1
  14. data/lib/deepl/exceptions/connection_error.rb +10 -7
  15. data/lib/deepl/exceptions/limit_exceeded.rb +1 -1
  16. data/lib/deepl/exceptions/quota_exceeded.rb +1 -1
  17. data/lib/deepl/exceptions/request_entity_too_large.rb +1 -2
  18. data/lib/deepl/exceptions/request_error.rb +7 -0
  19. data/lib/deepl/exceptions/server_error.rb +2 -1
  20. data/lib/deepl/exceptions/translation_memory_job_error.rb +32 -0
  21. data/lib/deepl/exceptions/validation_error.rb +3 -2
  22. data/lib/deepl/requests/base.rb +129 -51
  23. data/lib/deepl/requests/correct.rb +2 -8
  24. data/lib/deepl/requests/document/upload.rb +29 -26
  25. data/lib/deepl/requests/glossary/base.rb +30 -0
  26. data/lib/deepl/requests/glossary/create.rb +18 -22
  27. data/lib/deepl/requests/glossary/destroy.rb +4 -16
  28. data/lib/deepl/requests/glossary/entries.rb +6 -14
  29. data/lib/deepl/requests/glossary/find.rb +3 -13
  30. data/lib/deepl/requests/glossary/language_pairs.rb +2 -2
  31. data/lib/deepl/requests/glossary/list.rb +2 -2
  32. data/lib/deepl/requests/languages.rb +6 -11
  33. data/lib/deepl/requests/languages_for_resource.rb +2 -0
  34. data/lib/deepl/requests/multilingual_glossary/create.rb +8 -0
  35. data/lib/deepl/requests/multilingual_glossary/destroy_dictionary.rb +4 -0
  36. data/lib/deepl/requests/multilingual_glossary/entries.rb +5 -3
  37. data/lib/deepl/requests/multilingual_glossary/helpers.rb +22 -14
  38. data/lib/deepl/requests/rephrase.rb +3 -1
  39. data/lib/deepl/requests/spoken_terms/create.rb +5 -0
  40. data/lib/deepl/requests/spoken_terms/destroy_term_list.rb +1 -0
  41. data/lib/deepl/requests/spoken_terms/entries.rb +1 -0
  42. data/lib/deepl/requests/spoken_terms/helpers.rb +9 -2
  43. data/lib/deepl/requests/style_profile/create.rb +5 -0
  44. data/lib/deepl/requests/style_profile/list.rb +2 -2
  45. data/lib/deepl/requests/style_rule/create.rb +25 -1
  46. data/lib/deepl/requests/style_rule/create_custom_instruction.rb +7 -0
  47. data/lib/deepl/requests/style_rule/helpers.rb +13 -4
  48. data/lib/deepl/requests/style_rule/list.rb +2 -0
  49. data/lib/deepl/requests/style_rule/update.rb +1 -0
  50. data/lib/deepl/requests/style_rule/update_custom_instruction.rb +2 -0
  51. data/lib/deepl/requests/translate.rb +20 -36
  52. data/lib/deepl/requests/translation_memory/create_export.rb +6 -1
  53. data/lib/deepl/requests/translation_memory/create_import.rb +10 -0
  54. data/lib/deepl/requests/translation_memory/download_export.rb +0 -4
  55. data/lib/deepl/requests/translation_memory/list.rb +2 -2
  56. data/lib/deepl/requests/translation_memory/segments.rb +2 -2
  57. data/lib/deepl/requests/translation_memory/storage_base.rb +5 -9
  58. data/lib/deepl/requests/write_improvements.rb +7 -0
  59. data/lib/deepl/resources/document_handle.rb +1 -26
  60. data/lib/deepl/resources/document_translation_status.rb +0 -12
  61. data/lib/deepl/resources/language.rb +4 -10
  62. data/lib/deepl/resources/multilingual_glossary.rb +4 -4
  63. data/lib/deepl/resources/style_rule.rb +1 -23
  64. data/lib/deepl/resources/translation_memory_job.rb +3 -4
  65. data/lib/deepl/resources/usage.rb +5 -38
  66. data/lib/deepl/utils/client_builder.rb +44 -9
  67. data/lib/deepl/utils/glossary_entries.rb +30 -0
  68. data/lib/deepl/utils/http_client_builder.rb +50 -13
  69. data/lib/deepl/utils/output_path.rb +25 -0
  70. data/lib/deepl/utils/term_validator.rb +3 -3
  71. data/lib/deepl/utils/translation_memory_operations.rb +230 -0
  72. data/lib/deepl.rb +6 -171
  73. data/lib/http_client_options.rb +2 -2
  74. data/lib/version.rb +1 -1
  75. data/upgrading_to_v4.md +374 -0
  76. metadata +9 -50
  77. data/.gitlab-ci.yml +0 -197
  78. data/lib/deepl/deprecation.rb +0 -42
  79. data/lib/deepl/document_api.rb +0 -150
  80. data/lib/deepl/exceptions/not_supported.rb +0 -20
  81. data/lib/deepl/glossary_api.rb +0 -38
  82. data/lib/deepl/style_rule_api.rb +0 -72
  83. data/lib/deepl/translation_memory_api.rb +0 -389
  84. data/license_checker.sh +0 -8
  85. data/spec/fixtures.rb +0 -33
  86. data/spec/offline/admin_client_spec.rb +0 -551
  87. data/spec/offline/client_spec.rb +0 -273
  88. data/spec/offline/configuration_spec.rb +0 -164
  89. data/spec/offline/constants_spec.rb +0 -180
  90. data/spec/offline/correct_text_spec.rb +0 -50
  91. data/spec/offline/deprecation_spec.rb +0 -32
  92. data/spec/offline/errors_spec.rb +0 -92
  93. data/spec/offline/glossaries_spec.rb +0 -98
  94. data/spec/offline/http_client_spec.rb +0 -319
  95. data/spec/offline/languages_spec.rb +0 -155
  96. data/spec/offline/module_methods_spec.rb +0 -13
  97. data/spec/offline/multilingual_glossaries_spec.rb +0 -358
  98. data/spec/offline/offline_helper.rb +0 -71
  99. data/spec/offline/rephrase_text_spec.rb +0 -73
  100. data/spec/offline/spoken_terms_spec.rb +0 -215
  101. data/spec/offline/style_profiles_spec.rb +0 -266
  102. data/spec/offline/style_rules_spec.rb +0 -318
  103. data/spec/offline/translate_document_spec.rb +0 -606
  104. data/spec/offline/translate_text_spec.rb +0 -286
  105. data/spec/offline/translation_memories_client_spec.rb +0 -256
  106. data/spec/offline/translation_memories_spec.rb +0 -463
  107. data/spec/offline/usage_spec.rb +0 -151
  108. data/spec/real_api/admin_client_spec.rb +0 -77
  109. data/spec/real_api/correct_text_spec.rb +0 -20
  110. data/spec/real_api/glossaries_spec.rb +0 -28
  111. data/spec/real_api/languages_spec.rb +0 -27
  112. data/spec/real_api/multilingual_glossaries_spec.rb +0 -53
  113. data/spec/real_api/proxy_spec.rb +0 -41
  114. data/spec/real_api/real_api_helper.rb +0 -65
  115. data/spec/real_api/rephrase_text_spec.rb +0 -16
  116. data/spec/real_api/spoken_terms_spec.rb +0 -56
  117. data/spec/real_api/style_profiles_spec.rb +0 -46
  118. data/spec/real_api/style_rules_spec.rb +0 -46
  119. data/spec/real_api/translate_document_spec.rb +0 -18
  120. data/spec/real_api/translate_text_spec.rb +0 -16
  121. data/spec/real_api/translation_memories_spec.rb +0 -56
  122. data/spec/real_api/usage_spec.rb +0 -20
  123. data/spec/spec_helper.rb +0 -13
@@ -1,32 +0,0 @@
1
- # Copyright 2026 DeepL SE (https://www.deepl.com)
2
- # Use of this source code is governed by an MIT
3
- # license that can be found in the LICENSE file.
4
- # frozen_string_literal: true
5
-
6
- require_relative 'offline_helper'
7
-
8
- describe DeepL::Deprecation do
9
- around do |example|
10
- enabled = Warning[:deprecated]
11
- example.run
12
- ensure
13
- Warning[:deprecated] = enabled
14
- end
15
-
16
- it "prints nothing while Ruby's deprecation warnings are off" do
17
- Warning[:deprecated] = false
18
-
19
- expect { described_class.warn_once('spec-off', 'm') }.not_to output.to_stderr
20
- end
21
-
22
- it 'warns in the deprecated category when they are on' do
23
- Warning[:deprecated] = true
24
-
25
- if RUBY_VERSION >= '3.0'
26
- expect(Warning).to receive(:warn).with(/m/, category: :deprecated)
27
- described_class.warn_once('spec-on', 'm')
28
- else
29
- expect { described_class.warn_once('spec-on', 'm') }.to output(/m/).to_stderr
30
- end
31
- end
32
- end
@@ -1,92 +0,0 @@
1
- # Copyright 2026 DeepL SE (https://www.deepl.com)
2
- # Use of this source code is governed by an MIT
3
- # license that can be found in the LICENSE file.
4
- # frozen_string_literal: true
5
-
6
- require_relative 'offline_helper'
7
-
8
- describe 'DeepL error mapping' do
9
- {
10
- 401 => [DeepL::Exceptions::AuthorizationFailed, /Authorization failed/],
11
- 403 => [DeepL::Exceptions::AuthorizationFailed, /Authorization failed/],
12
- 456 => [DeepL::Exceptions::QuotaExceeded, /Quota exceeded/],
13
- 413 => [DeepL::Exceptions::RequestEntityTooLarge,
14
- /request size has reached the supported limit/],
15
- 418 => [DeepL::Exceptions::RequestError, 'Request failed with HTTP status 418: m']
16
- }.each do |status, (error_class, message)|
17
- it "raises #{error_class.name.split('::').last} for status #{status} without retrying" do
18
- stub = stub_request(:get, url('/v2/usage')).to_return(status: status, body: '{"message":"m"}')
19
-
20
- expect { DeepL.usage }.to raise_error(error_class, message)
21
- expect(stub).to have_been_requested.once
22
- end
23
- end
24
-
25
- {
26
- 400 => DeepL::Exceptions::BadRequest,
27
- 404 => DeepL::Exceptions::NotFound
28
- }.each do |status, error_class|
29
- it "raises #{error_class.name.split('::').last} with the API message for status #{status}" do
30
- stub = stub_request(:get,
31
- url('/v2/usage')).to_return(reply({ message: 'Value for x invalid' },
32
- status))
33
-
34
- expect { DeepL.usage }.to raise_error(error_class, 'Value for x invalid')
35
- expect(stub).to have_been_requested.once
36
- end
37
-
38
- it "raises #{error_class.name.split('::').last} with a plain-text body as the message" do
39
- stub_request(:get, url('/v2/usage')).to_return(status: status, body: 'plain text')
40
-
41
- expect { DeepL.usage }.to raise_error(error_class, 'plain text')
42
- end
43
- end
44
-
45
- it 'retries a 503 reply and raises ServerError with its status' do
46
- stub = stub_request(:get, url('/v2/usage')).to_return(status: 503, body: '')
47
-
48
- expect { DeepL.usage }
49
- .to raise_error(DeepL::Exceptions::ServerError) { |e| expect(e.http_status_code).to eq(503) }
50
- expect(stub).to have_been_requested.times(3)
51
- end
52
-
53
- it 'keeps the status code and the failed request on the raised error' do
54
- stub_request(:get, url('/v2/usage')).to_return(status: 418, body: '')
55
-
56
- expect { DeepL.usage }.to(raise_error(DeepL::Exceptions::RequestError) do |error|
57
- expect([error.http_status_code, error.request.path, error.message])
58
- .to eq([418, '/v2/usage', 'Request failed with HTTP status 418.'])
59
- end)
60
- end
61
-
62
- it 'uses the raw body as the message of a 400 reply with a JSON array' do
63
- stub_request(:get, url('/v2/usage')).to_return(status: 400, body: '["x"]')
64
-
65
- expect { DeepL.usage }.to raise_error(DeepL::Exceptions::BadRequest, '["x"]')
66
- end
67
-
68
- ['not json', '[]', '{"translations":[1]}'].each do |body|
69
- it "raises DeepL::Exceptions::Error for the malformed response #{body}" do
70
- stub_request(:post, url('/v2/translate')).to_return(status: 200, body: body)
71
-
72
- expect { DeepL.translate('a', nil, 'DE') }
73
- .to raise_error(an_instance_of(DeepL::Exceptions::Error), /Unexpected response/)
74
- end
75
- end
76
-
77
- it 'keeps the response on the raised error' do
78
- stub_request(:get, url('/v2/usage')).to_return(status: 456, body: 'quota')
79
-
80
- expect { DeepL.usage }.to(raise_error { |error| expect(error.response.body).to eq('quota') })
81
- end
82
-
83
- it 'raises the errors of every endpoint family the same way' do
84
- stub_request(:post, %r{/v2/(translate|write/rephrase)}).to_return(status: 403)
85
- stub_request(:delete, url('/v2/glossaries/g-1')).to_return(status: 404,
86
- body: '{"message":"gone"}')
87
-
88
- expect { DeepL.translate('a', nil, 'DE') }.to raise_error(DeepL::Exceptions::AuthorizationFailed)
89
- expect { DeepL.rephrase('a') }.to raise_error(DeepL::Exceptions::AuthorizationFailed)
90
- expect { DeepL.glossaries.destroy('g-1') }.to raise_error(DeepL::Exceptions::NotFound, 'gone')
91
- end
92
- end
@@ -1,98 +0,0 @@
1
- # Copyright 2026 DeepL SE (https://www.deepl.com)
2
- # Use of this source code is governed by an MIT
3
- # license that can be found in the LICENSE file.
4
- # frozen_string_literal: true
5
-
6
- require_relative 'offline_helper'
7
-
8
- describe DeepL::GlossaryApi do
9
- let(:glossaries) { DeepL.glossaries }
10
- let(:glossary_json) do
11
- { glossary_id: 'g-1', name: 'terms', ready: true, source_lang: 'en', target_lang: 'de',
12
- creation_time: '2026-01-02T03:04:05.678Z', entry_count: 2 }
13
- end
14
-
15
- describe '#create' do
16
- it 'sends the entries of an array as TSV' do
17
- stub_request(:post, url('/v2/glossaries')).with(
18
- body: { name: 'terms', source_lang: 'EN', target_lang: 'DE',
19
- entries: "Apple\tApfel\nBanana\tBanane\n", entries_format: 'tsv' },
20
- headers: json_headers
21
- ).to_return(reply(glossary_json, 201))
22
-
23
- glossaries.create('terms', 'EN', 'DE', [%w[Apple Apfel], %w[Banana Banane]])
24
- end
25
-
26
- it 'sends a string of entries and the entries format as given' do
27
- stub_request(:post, url('/v2/glossaries')).with(
28
- body: { name: 'terms', source_lang: 'EN', target_lang: 'DE', entries: "Apple,Apfel\n",
29
- entries_format: 'csv' }
30
- ).to_return(reply(glossary_json, 201))
31
-
32
- glossaries.create('terms', 'EN', 'DE', "Apple,Apfel\n", entries_format: 'csv')
33
- end
34
-
35
- it 'strips surrounding whitespace from the terms of an array' do
36
- stub_request(:post, url('/v2/glossaries'))
37
- .with(body: hash_including(entries: "Apple\tApfel\n"))
38
- .to_return(reply(glossary_json, 201))
39
-
40
- glossaries.create('terms', 'EN', 'DE', [[' Apple ', "Apfel\n"]])
41
- end
42
-
43
- it 'returns a glossary' do
44
- stub_request(:post, url('/v2/glossaries')).to_return(reply(glossary_json, 201))
45
-
46
- expect(glossaries.create('terms', 'EN', 'DE', [%w[a b]])).to be_a(DeepL::Resources::Glossary)
47
- end
48
- end
49
-
50
- describe '#create with invalid terms' do
51
- [[%W[Apple\tPie Apfel]], [%W[Apple Apfel\nKuchen]], [['Apple', ' ']]].each do |entries|
52
- it "raises ValidationError for #{entries.inspect} and sends no request" do
53
- expect { glossaries.create('terms', 'EN', 'DE', entries) }
54
- .to raise_error(DeepL::Exceptions::ValidationError)
55
- expect(a_request(:any, /.*/)).not_to have_been_made
56
- end
57
- end
58
- end
59
-
60
- describe '#find' do
61
- it 'sends a GET without a body' do
62
- stub_request(:get, url('/v2/glossaries/g-1')).with(headers: auth_headers) { bodyless?(_1) }
63
- .to_return(reply(glossary_json))
64
-
65
- glossaries.find('g-1')
66
- end
67
- end
68
-
69
- describe '#list' do
70
- it 'returns one glossary per entry of the reply' do
71
- second = glossary_json.merge(glossary_id: 'g-2')
72
- stub_request(:get, url('/v2/glossaries'))
73
- .with(headers: auth_headers) { bodyless?(_1) }
74
- .to_return(reply(glossaries: [glossary_json, second]))
75
-
76
- expect(glossaries.list.size).to eq(2)
77
- end
78
- end
79
-
80
- describe '#entries' do
81
- it 'parses the TSV reply into pairs' do
82
- stub_request(:get, url('/v2/glossaries/g-1/entries'))
83
- .with(headers: auth_headers) { bodyless?(_1) }
84
- .to_return(status: 200, body: "Apple\tApfel\nBanana\tBanane")
85
-
86
- expect(glossaries.entries('g-1')).to eq([%w[Apple Apfel], %w[Banana Banane]])
87
- end
88
- end
89
-
90
- describe '#destroy' do
91
- it 'sends a DELETE without a body and returns the ID' do
92
- stub_request(:delete, url('/v2/glossaries/g-1')).with(headers: auth_headers) { bodyless?(_1) }
93
- .to_return(status: 204)
94
-
95
- expect(glossaries.destroy('g-1')).to eq('g-1')
96
- end
97
- end
98
- end
@@ -1,319 +0,0 @@
1
- # Copyright 2026 DeepL SE (https://www.deepl.com)
2
- # Use of this source code is governed by an MIT
3
- # license that can be found in the LICENSE file.
4
- # frozen_string_literal: true
5
-
6
- require 'logger'
7
- require 'stringio'
8
- require_relative 'offline_helper'
9
-
10
- describe 'DeepL HTTP client' do
11
- def stub_usage(*replies)
12
- stub_request(:get, url('/v2/usage')).to_return(*replies)
13
- end
14
-
15
- describe 'retries' do
16
- it 'retries a 429 reply' do
17
- stub = stub_usage(reply({}, 429), usage_reply)
18
-
19
- DeepL.usage
20
- expect(stub).to have_been_requested.twice
21
- end
22
-
23
- it 'retries a 500 reply' do
24
- stub = stub_usage(reply({}, 500), usage_reply)
25
-
26
- DeepL.usage
27
-
28
- expect(stub).to have_been_requested.twice
29
- end
30
-
31
- it 'retries a 503 reply' do
32
- stub = stub_usage(reply({}, 503), usage_reply)
33
-
34
- DeepL.usage
35
-
36
- expect(stub).to have_been_requested.twice
37
- end
38
-
39
- it 'retries refused and reset connections, broken pipes and EOF' do
40
- [Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EPIPE, EOFError].each do |error|
41
- WebMock.reset!
42
- stub = stub_request(:get, url('/v2/usage')).to_raise(error).then.to_return(usage_reply)
43
-
44
- DeepL.usage
45
-
46
- expect(stub).to have_been_requested.twice
47
- end
48
- end
49
-
50
- it 'does not retry a TLS failure or a malformed response' do
51
- [OpenSSL::SSL::SSLError, Net::HTTPBadResponse].each do |error|
52
- WebMock.reset!
53
- stub = stub_request(:get, url('/v2/usage')).to_raise(error).then.to_return(usage_reply)
54
-
55
- expect { DeepL.usage }.to raise_error(error)
56
- expect(stub).to have_been_requested.once
57
- end
58
- end
59
-
60
- it 'raises a failed proxy CONNECT without retrying' do
61
- error = Net::HTTPClientException.new('407 "Proxy Authentication Required"', nil)
62
- stub = stub_request(:get, url('/v2/usage')).to_raise(error).then.to_return(usage_reply)
63
-
64
- expect { DeepL.usage }.to raise_error(Net::HTTPClientException)
65
- expect(stub).to have_been_requested.once
66
- end
67
-
68
- it 'retries a body shorter than its Content-Length and raises EOFError' do
69
- short = { status: 200, body: '{"char', headers: { 'Content-Length' => '46' } }
70
- stub = stub_usage(short)
71
-
72
- expect { DeepL.usage }.to raise_error(EOFError)
73
- expect(stub).to have_been_requested.times(3)
74
- end
75
-
76
- it 'does not let Net::HTTP re-send a request or accept a short body' do # rubocop:disable RSpec/ExampleLength
77
- clients = []
78
- allow(Net::HTTP).to receive(:new).and_wrap_original do |new, *args|
79
- new.call(*args).tap { clients << _1 }
80
- end
81
- upload_url = 'https://storage.example.test/upload?sig=abc'
82
- stub_request(:put, upload_url).to_return(status: 200)
83
-
84
- [nil, DeepL::HTTPClientOptions.new({})].each do |options|
85
- client = DeepL::Client.new('abc', http_client_options: options)
86
- client.upload_translation_memory_file(upload_url, 'tmx')
87
- end
88
-
89
- expect(clients.map(&:max_retries)).to eq([0, 0, 0, 0])
90
- # Net::HTTP#ignore_eof= exists from net-http 0.3 (Ruby 3.2).
91
- next unless Net::HTTP.method_defined?(:ignore_eof=)
92
-
93
- expect(clients.map(&:ignore_eof)).to eq([false, false, false, false])
94
- end
95
-
96
- it 'trims the auth key' do
97
- DeepL.configuration.auth_key = " k \n"
98
- stub_request(:get, url('/v2/usage')).with(headers: auth_headers).to_return(usage_reply)
99
-
100
- DeepL.usage
101
- end
102
-
103
- it 'retries a network error' do
104
- stub = stub_request(:get, url('/v2/usage')).to_raise(SocketError).then.to_return(usage_reply)
105
-
106
- DeepL.usage
107
-
108
- expect(stub).to have_been_requested.twice
109
- end
110
-
111
- it 'retries a timeout' do
112
- stub = stub_request(:get, url('/v2/usage')).to_timeout.then.to_return(usage_reply)
113
-
114
- DeepL.usage
115
-
116
- expect(stub).to have_been_requested.twice
117
- end
118
-
119
- it 'raises the network error after max_network_retries retries' do
120
- stub = stub_request(:get, url('/v2/usage')).to_timeout
121
-
122
- expect { DeepL.usage }.to raise_error(Net::OpenTimeout)
123
- expect(stub).to have_been_requested.times(3)
124
- end
125
-
126
- it 'raises LimitExceeded after max_network_retries retries' do
127
- stub = stub_usage(reply({}, 429))
128
-
129
- expect { DeepL.usage }.to raise_error(DeepL::Exceptions::LimitExceeded)
130
- expect(stub).to have_been_requested.times(3)
131
- end
132
-
133
- it 'does not retry when max_network_retries is 0' do
134
- DeepL.configuration.max_network_retries = 0
135
- stub = stub_usage(reply({}, 429))
136
-
137
- expect { DeepL.usage }.to raise_error(DeepL::Exceptions::LimitExceeded)
138
- expect(stub).to have_been_requested.once
139
- end
140
- end
141
-
142
- describe '.with_session' do
143
- it 'runs the block without client options' do
144
- stub = stub_usage(usage_reply)
145
-
146
- DeepL.with_session { DeepL.usage }
147
-
148
- expect(stub).to have_been_requested.once
149
- end
150
-
151
- it 'raises ArgumentError without a block' do
152
- expect { DeepL.with_session }.to raise_error(ArgumentError, /requires a block/)
153
- end
154
-
155
- it 'applies the proxy and the timeouts to the client inside the block' do
156
- options = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'proxy.example.test',
157
- 'proxy_port' => 8080 },
158
- nil, open_timeout: 3, read_timeout: 4)
159
- stub_usage(usage_reply)
160
-
161
- client = DeepL.with_session(options) do
162
- DeepL.usage
163
- DeepL.api.http_client
164
- end
165
-
166
- expect([client.proxy_address, client.proxy_port, client.open_timeout, client.read_timeout])
167
- .to eq(['proxy.example.test', 8080, 3, 4])
168
- end
169
-
170
- it 'enables SSL from the URL scheme and verifies certificates unless disabled' do
171
- session_client = lambda do |host, verify|
172
- DeepL.configuration.host = host
173
- options = DeepL::HTTPClientOptions.new({}, nil, enable_ssl_verification: verify)
174
- DeepL.with_session(options) { DeepL.api.http_client }
175
- end
176
-
177
- expect(session_client.call('http://localhost:3000', true)).to have_attributes(use_ssl?: false)
178
- expect(session_client.call('https://api.deepl.com', false))
179
- .to have_attributes(use_ssl?: true, verify_mode: OpenSSL::SSL::VERIFY_NONE)
180
- end
181
-
182
- it 'uses no proxy when only the proxy address is given' do
183
- options = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'proxy.example.test' })
184
-
185
- expect(DeepL.with_session(options) { DeepL.api.http_client }.proxy_address).to be_nil
186
- end
187
-
188
- it 'raises SocketError when the session cannot connect' do
189
- http = Net::HTTP.new('unresolvable.invalid', 443)
190
- allow(http).to receive(:start).and_raise(SocketError, 'getaddrinfo: Name not known')
191
- allow(DeepL::Utils::HTTPClientBuilder).to receive(:build).and_return(http)
192
-
193
- expect { DeepL.with_session { nil } }.to raise_error(SocketError)
194
- end
195
-
196
- it 'opens the session connection with the configured timeout' do
197
- DeepL.configuration.timeout = 4
198
- options = DeepL::HTTPClientOptions.new({}, nil, read_timeout: 7)
199
-
200
- client = DeepL.with_session(options) { DeepL.api.http_client }
201
-
202
- expect([client.open_timeout, client.read_timeout]).to eq([4, 7])
203
- end
204
-
205
- it 'restores the previous client when the block ends' do
206
- previous = DeepL.api.http_client
207
- options = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'proxy.example.test',
208
- 'proxy_port' => 8080 })
209
- stub_usage(usage_reply)
210
-
211
- DeepL.with_session(options) { DeepL.usage }
212
-
213
- expect(DeepL.api.http_client).to equal(previous)
214
- expect(DeepL.api.http_client.proxy_address).to be_nil
215
- expect(DeepL.http_client).to be_nil
216
- end
217
-
218
- it 'restores the previous client when the block raises' do
219
- previous = DeepL.api.http_client
220
-
221
- expect { DeepL.with_session { raise 'boom' } }.to raise_error('boom')
222
- expect(DeepL.api.http_client).to equal(previous)
223
- end
224
- end
225
-
226
- describe 'logging' do
227
- let(:log) { StringIO.new }
228
-
229
- it 'logs the request and the retry' do
230
- DeepL.configuration.logger = Logger.new(log)
231
- stub_usage(reply({}, 429), usage_reply)
232
-
233
- DeepL.usage
234
-
235
- expect(log.string).to include('Request to the DeepL API: GET /v2/usage')
236
- .and include('Starting retry 1 for request GET /v2/usage')
237
- end
238
-
239
- context 'with a debug logger' do
240
- before do
241
- DeepL.configuration.auth_key = 'sdktest-secret-key'
242
- DeepL.configuration.logger = Logger.new(log, level: Logger::DEBUG)
243
- end
244
-
245
- def expect_key_redacted
246
- expect(log.string).not_to include('sdktest-secret-key')
247
- expect(log.string).to include('DeepL-Auth-Key [REDACTED]')
248
- end
249
-
250
- it 'redacts the auth key in the request details' do
251
- stub_usage(usage_reply)
252
-
253
- DeepL.usage
254
-
255
- expect_key_redacted
256
- end
257
-
258
- it 'redacts the auth key in the details of a request type that overrides them' do
259
- stub_request(:post, url('/v2/translate'))
260
- .to_return(reply(translations: [{ text: 'Hallo' }]))
261
-
262
- DeepL.translate('Hello', nil, 'DE')
263
-
264
- expect_key_redacted
265
- end
266
-
267
- it 'redacts an Authorization header given with another casing' do
268
- stub_request(:post, url('/v2/translate'))
269
- .to_return(reply(translations: [{ text: 'Hallo' }]))
270
-
271
- other = { 'authorization' => 'DeepL-Auth-Key sdktest-other-key' }
272
- DeepL.translate('Hello', nil, 'DE', {}, other)
273
-
274
- expect(log.string).not_to include('sdktest-other-key')
275
- end
276
- end
277
- end
278
-
279
- describe 'headers' do
280
- it 'lets per-call headers replace the Authorization header in any casing' do
281
- stub_request(:post, url('/v2/translate'))
282
- .with(headers: { 'Authorization' => 'DeepL-Auth-Key other', 'X-Custom' => 'v' })
283
- .to_return(reply(translations: [{ text: 'Hallo' }]))
284
-
285
- DeepL.translate('Hello', nil, 'DE', {}, { 'authorization' => 'DeepL-Auth-Key other',
286
- 'X-Custom' => 'v' })
287
- end
288
-
289
- it "keeps the SDK's Host and Content-Type over per-call headers" do
290
- sdk_host = ->(request) { [nil, 'api.deepl.com'].include?(request.headers['Host']) }
291
- stub_request(:post, 'https://api.deepl.com/v2/translate')
292
- .with(headers: { 'Content-Type' => 'application/json' }, &sdk_host)
293
- .to_return(reply(translations: [{ text: 'Hallo' }]))
294
-
295
- DeepL.translate('Hello', nil, 'DE', {}, { 'host' => 'other.example.test',
296
- 'content-type' => 'text/plain' })
297
- end
298
-
299
- it 'sends no caller Content-Type with a request without a body' do
300
- DeepL.configuration.headers = { 'content-type' => 'text/plain' }
301
- stub_request(:get, url('/v2/usage'))
302
- .with { |request| !request.headers.key?('Content-Type') }.to_return(usage_reply)
303
-
304
- DeepL.usage
305
- end
306
- end
307
-
308
- describe 'HTTPClientBuilder' do
309
- it 'uses the proxy only when both address and port are given' do
310
- partial = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'proxy.example.test' })
311
- full = DeepL::HTTPClientOptions.new({ 'proxy_addr' => 'proxy.example.test',
312
- 'proxy_port' => 8080 })
313
- build = ->(options) { DeepL::Utils::HTTPClientBuilder.build('https://api.deepl.com', options) }
314
-
315
- expect(build.call(partial).proxy_address).to be_nil
316
- expect(build.call(full).proxy_address).to eq('proxy.example.test')
317
- end
318
- end
319
- end