4me-sdk 2.0.4 → 2.0.6

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,620 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe Sdk4me::Client do
4
- def client(authentication, options = {})
5
- (@client ||= {})["#{authentication}-#{options}"] ||= begin
6
- options = { max_retry_time: -1 }.merge(options)
7
- options = if authentication == :api_token
8
- { api_token: 'secret' }.merge(options)
9
- else
10
- { access_token: 'secret' }.merge(options)
11
- end
12
- Sdk4me::Client.new(options)
13
- end
14
- end
15
-
16
- def credentials(authentication)
17
- if authentication == :api_token
18
- { basic_auth: %w[secret x] }
19
- else
20
- { headers: { 'Authorization' => 'Bearer secret' } }
21
- end
22
- end
23
-
24
- %i[api_token access_token].each do |authentication|
25
- context 'Sdk4me.config' do
26
- before(:each) do
27
- Sdk4me.configure do |config|
28
- config.max_retry_time = 120 # override default value (5400)
29
- if authentication == :api_token
30
- config.api_token = 'secret' # set value
31
- else
32
- config.access_token = 'secret'
33
- end
34
- end
35
- end
36
-
37
- it 'should define the MAX_PAGE_SIZE' do
38
- expect(Sdk4me::Client::MAX_PAGE_SIZE).to eq(100)
39
- end
40
-
41
- it 'should use the Sdk4me configuration' do
42
- client = Sdk4me::Client.new
43
- expect(client.option(:host)).to eq('https://api.4me.com') # default value
44
- if authentication == :api_token
45
- expect(client.option(:api_token)).to eq('secret') # value set using Sdk4me.config
46
- else
47
- expect(client.option(:access_token)).to eq('secret') # value set using Sdk4me.config
48
- end
49
- expect(client.option(:max_retry_time)).to eq(120) # value overridden in Sdk4me.config
50
- end
51
-
52
- it 'should override the Sdk4me configuration' do
53
- client = Sdk4me::Client.new(host: 'https://demo.4me.com', api_token: 'unknown', block_at_rate_limit: true)
54
- expect(client.option(:read_timeout)).to eq(25) # default value
55
- expect(client.option(:host)).to eq('https://demo.4me.com') # default value overridden in Client.new
56
- expect(client.option(:api_token)).to eq('unknown') # value set using Sdk4me.config and overridden in Client.new
57
- expect(client.option(:max_retry_time)).to eq(120) # value overridden in Sdk4me.config
58
- expect(client.option(:block_at_rate_limit)).to eq(true) # value overridden in Client.new
59
- end
60
-
61
- %i[host api_version].each do |required_option|
62
- it "should require option #{required_option}" do
63
- expect { Sdk4me::Client.new(required_option => '') }.to raise_error("Missing required configuration option #{required_option}")
64
- end
65
- end
66
-
67
- it 'should require access_token' do
68
- expect { Sdk4me::Client.new(access_token: '', api_token: '') }.to raise_error('Missing required configuration option access_token')
69
- end
70
-
71
- [['https://api.4me.com', true, 'api.4me.com', 443],
72
- ['https://api.example.com:777', true, 'api.example.com', 777],
73
- ['http://sdk4me.example.com', false, 'sdk4me.example.com', 80],
74
- ['http://sdk4me.example.com:777', false, 'sdk4me.example.com', 777]].each do |host, ssl, domain, port|
75
- it 'should parse ssl, host and port' do
76
- client = Sdk4me::Client.new(host: host)
77
- expect(client.instance_variable_get(:@ssl)).to eq(ssl)
78
- expect(client.instance_variable_get(:@domain)).to eq(domain)
79
- expect(client.instance_variable_get(:@port)).to eq(port)
80
- end
81
- end
82
- end
83
-
84
- it 'should set the ca-bundle.crt file' do
85
- http = Net::HTTP.new('https://api.4me.com')
86
- http.use_ssl = true
87
-
88
- on_disk = `ls #{http.ca_file}`
89
- expect(on_disk).not_to match(/cannot access/)
90
- expect(on_disk).to match(%r{/ca-bundle.crt$})
91
- end
92
-
93
- describe 'headers' do
94
- it 'should set the content type header' do
95
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'Content-Type' => 'application/json' }).to_return(body: { name: 'my name' }.to_json)
96
- client(authentication).get('me')
97
- expect(stub).to have_been_requested
98
- end
99
-
100
- it 'should add the X-4me-Account header' do
101
- client = client(authentication, account: 'test')
102
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'X-4me-Account' => 'test' }).to_return(body: { name: 'my name' }.to_json)
103
- client.get('me')
104
- expect(stub).to have_been_requested
105
- end
106
-
107
- it 'should add the X-4me-Source header' do
108
- client = client(authentication, source: 'myapp')
109
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'X-4me-Source' => 'myapp' }).to_return(body: { name: 'my name' }.to_json)
110
- client.get('me')
111
- expect(stub).to have_been_requested
112
- end
113
-
114
- it 'should add a default User-Agent header' do
115
- client = client(authentication)
116
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'User-Agent' => "4me-sdk-ruby/#{Sdk4me::Client::VERSION}" }).to_return(body: { name: 'my name' }.to_json)
117
- client.get('me')
118
- expect(stub).to have_been_requested
119
- end
120
-
121
- it 'should override the default User-Agent header' do
122
- client = client(authentication, user_agent: 'Foo/1.0')
123
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'User-Agent' => 'Foo/1.0' }).to_return(body: { name: 'my name' }.to_json)
124
- client.get('me')
125
- expect(stub).to have_been_requested
126
- end
127
-
128
- it 'should be able to override default headers' do
129
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'Content-Type' => 'application/x-www-form-urlencoded' }).to_return(body: { name: 'my name' }.to_json)
130
- client(authentication).get('me', {}, { 'Content-Type' => 'application/x-www-form-urlencoded' })
131
- expect(stub).to have_been_requested
132
- end
133
-
134
- it 'should be able to override option headers' do
135
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'X-4me-Source' => 'foo' }).to_return(body: { name: 'my name' }.to_json)
136
- client(authentication, source: 'myapp').get('me', {}, { 'X-4me-Source' => 'foo' })
137
- expect(stub).to have_been_requested
138
- end
139
-
140
- it 'should set the other headers' do
141
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).with(headers: { 'X-4me-Other' => 'value' }).to_return(body: { name: 'my name' }.to_json)
142
- client(authentication).get('me', {}, { 'X-4me-Other' => 'value' })
143
- expect(stub).to have_been_requested
144
- end
145
-
146
- it 'should accept headers in the each call' do
147
- stub = stub_request(:get, 'https://api.4me.com/v1/requests?fields=subject&page=1&per_page=100').with(credentials(authentication)).with(headers: { 'X-4me-Secret' => 'special' }).to_return(body: [{ id: 1, subject: 'Subject 1' }, { id: 2, subject: 'Subject 2' }, { id: 3, subject: 'Subject 3' }].to_json)
148
- client(authentication).each('requests', { fields: 'subject' }, { 'X-4me-Secret' => 'special' }) do |request|
149
- expect(request[:subject]).to eq("Subject #{request[:id]}")
150
- end
151
- expect(stub).to have_been_requested
152
- end
153
- end
154
-
155
- context 'each' do
156
- it 'should yield each result' do
157
- stub_request(:get, 'https://api.4me.com/v1/requests?fields=subject&page=1&per_page=100').with(credentials(authentication)).to_return(body: [{ id: 1, subject: 'Subject 1' }, { id: 2, subject: 'Subject 2' }, { id: 3, subject: 'Subject 3' }].to_json)
158
- nr_of_requests = client(authentication).each('requests', { fields: 'subject' }) do |request|
159
- expect(request[:subject]).to eq("Subject #{request[:id]}")
160
- end
161
- expect(nr_of_requests).to eq(3)
162
- end
163
-
164
- it 'should retrieve multiple pages' do
165
- stub_page1 = stub_request(:get, 'https://api.4me.com/v1/requests?page=1&per_page=2').with(credentials(authentication)).to_return(body: [{ id: 1, subject: 'Subject 1' }, { id: 2, subject: 'Subject 2' }].to_json, headers: { 'Link' => '<https://api.4me.com/v1/requests?page=1&per_page=2>; rel="first",<https://api.4me.com/v1/requests?page=2&per_page=2>; rel="next",<https://api.4me.com/v1/requests?page=2&per_page=2>; rel="last"' })
166
- stub_page2 = stub_request(:get, 'https://api.4me.com/v1/requests?page=2&per_page=2').with(credentials(authentication)).to_return(body: [{ id: 3, subject: 'Subject 3' }].to_json, headers: { 'Link' => '<https://api.4me.com/v1/requests?page=1&per_page=2>; rel="first",<https://api.4me.com/v1/requests?page=1&per_page=2>; rel="prev",<https://api.4me.com/v1/requests?page=2&per_page=2>; rel="last"' })
167
- nr_of_requests = client(authentication).each('requests', { per_page: 2 }) do |request|
168
- expect(request[:subject]).to eq("Subject #{request[:id]}")
169
- end
170
- expect(nr_of_requests).to eq(3)
171
- expect(stub_page1).to have_been_requested
172
- expect(stub_page2).to have_been_requested
173
- end
174
- end
175
-
176
- context 'get' do
177
- it 'should return a response' do
178
- stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(body: { name: 'my name' }.to_json)
179
- response = client(authentication).get('me')
180
- expect(response[:name]).to eq('my name')
181
- end
182
-
183
- describe 'parameters' do
184
- [[nil, ''],
185
- %w[normal normal],
186
- ['hello;<', 'hello%3B%3C'],
187
- [true, 'true'],
188
- [false, 'false'],
189
- [DateTime.now, DateTime.now.new_offset(0).iso8601.gsub('+', '%2B')],
190
- [Date.new, Date.new.strftime('%Y-%m-%d')],
191
- [Time.now, Time.now.strftime('%H:%M')],
192
- [['first', 'second;<', true], 'first,second%3B%3C,true']].each do |param_value, url_value|
193
- it "should cast #{param_value.class.name}: '#{param_value}' to '#{url_value}'" do
194
- stub = stub_request(:get, "https://api.4me.com/v1/me?value=#{url_value}").with(credentials(authentication)).to_return(body: { name: 'my name' }.to_json)
195
- client(authentication).get('me', { value: param_value })
196
- expect(stub).to have_been_requested
197
- end
198
- end
199
-
200
- it 'should not cast arrays in post and put calls' do
201
- stub = stub_request(:post, 'https://api.4me.com/v1/people').with(credentials(authentication)).with(body: { user_ids: [1, 2, 3] }, headers: { 'X-4me-Custom' => 'custom' }).to_return(body: { id: 101 }.to_json)
202
- client(authentication).post('people', { user_ids: [1, 2, 3] }, { 'X-4me-Custom' => 'custom' })
203
- expect(stub).to have_been_requested
204
- end
205
-
206
- it 'should not cast hashes in post and put calls' do
207
- stub = stub_request(:patch, 'https://api.4me.com/v1/people/55').with(credentials(authentication)).with(body: '{"contacts_attributes":{"0":{"protocol":"email","label":"work","uri":"work@example.com"}}}', headers: { 'X-4me-Custom' => 'custom' }).to_return(body: { id: 101 }.to_json)
208
- client(authentication).put('people/55', { contacts_attributes: { 0 => { protocol: :email, label: :work, uri: 'work@example.com' } } }, { 'X-4me-Custom' => 'custom' })
209
- expect(stub).to have_been_requested
210
- end
211
-
212
- it 'should not double escape symbols' do
213
- stub = stub_request(:patch, 'https://api.4me.com/v1/people/55').with(credentials(authentication)).with(body: '{"status":"waiting_for"}').to_return(body: { id: 101 }.to_json)
214
- client(authentication).put('people/55', { status: :waiting_for })
215
- expect(stub).to have_been_requested
216
- end
217
-
218
- it 'should handle fancy filter operations' do
219
- now = DateTime.now
220
- stub = stub_request(:get, "https://api.4me.com/v1/people?created_at=>#{now.new_offset(0).iso8601.gsub('+', '%2B')}&id!=15").with(credentials(authentication)).to_return(body: { name: 'my name' }.to_json)
221
- client(authentication).get('people', { 'created_at=>' => now, 'id!=' => 15 })
222
- expect(stub).to have_been_requested
223
- end
224
-
225
- it 'should append parameters' do
226
- stub = stub_request(:get, 'https://api.4me.com/v1/people?id!=15&primary_email=me@example.com').with(credentials(authentication)).to_return(body: { name: 'my name' }.to_json)
227
- client(authentication).get('people?id!=15', { primary_email: 'me@example.com' })
228
- expect(stub).to have_been_requested
229
- end
230
- end
231
- end
232
-
233
- context 'patch' do
234
- %i[put patch].each do |method|
235
- it "should send patch requests with parameters and headers for #{method} calls" do
236
- stub = stub_request(:patch, 'https://api.4me.com/v1/people/1').with(credentials(authentication)).with(body: { name: 'New Name' }, headers: { 'X-4me-Custom' => 'custom' }).to_return(body: { id: 1 }.to_json)
237
- client(authentication).send(method, 'people/1', { name: 'New Name' }, { 'X-4me-Custom' => 'custom' })
238
- expect(stub).to have_been_requested
239
- end
240
- end
241
- end
242
-
243
- context 'post' do
244
- it 'should send post requests with parameters and headers' do
245
- stub = stub_request(:post, 'https://api.4me.com/v1/people').with(credentials(authentication)).with(body: { name: 'New Name' }, headers: { 'X-4me-Custom' => 'custom' }).to_return(body: { id: 101 }.to_json)
246
- client(authentication).post('people', { name: 'New Name' }, { 'X-4me-Custom' => 'custom' })
247
- expect(stub).to have_been_requested
248
- end
249
- end
250
-
251
- context 'delete' do
252
- it 'should send delete requests with parameters and headers' do
253
- stub = stub_request(:delete, 'https://api.4me.com/v1/people?id=value').with(credentials(authentication)).with(headers: { 'X-4me-Custom' => 'custom' }).to_return(body: '', status: 204)
254
- response = client(authentication).delete('people', { id: 'value' }, { 'X-4me-Custom' => 'custom' })
255
- expect(stub).to have_been_requested
256
- expect(response.valid?).to be_truthy
257
- expect(response.json).to eq({})
258
- end
259
- end
260
-
261
- context 'attachments' do
262
- it 'should not log an error for XML responses' do
263
- xml = %(<?xml version="1.0" encoding="UTF-8"?>\n<details>some info</details>)
264
- stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(body: xml)
265
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
266
- expect_log("XML response:\n#{xml}", :debug)
267
- response = client(authentication).get('me')
268
- expect(response.valid?).to be_falsey
269
- expect(response.raw.body).to eq(xml)
270
- end
271
-
272
- it 'should not log an error for redirects' do
273
- stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(body: '', status: 303, headers: { 'Location' => 'http://redirect.example.com/to/here' })
274
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
275
- expect_log('Redirect: http://redirect.example.com/to/here', :debug)
276
- response = client(authentication).get('me')
277
- expect(response.valid?).to be_falsey
278
- expect(response.raw.body).to eq('')
279
- end
280
-
281
- it 'should not parse attachments for get requests' do
282
- expect(Sdk4me::Attachments).not_to receive(:new)
283
- stub_request(:get, 'https://api.4me.com/v1/requests/777?note_attachments=/tmp/first.png,/tmp/second.zip&note=note%20%5Battachment:/tmp/third.gif%5D').with(credentials(authentication)).to_return(body: { id: 777, upload_called: false }.to_json)
284
-
285
- response = client(authentication).get('/requests/777', { note: 'note [attachment:/tmp/third.gif]', note_attachments: ['/tmp/first.png', '/tmp/second.zip'] })
286
- expect(response.valid?).to be_truthy
287
- expect(response[:upload_called]).to be_falsey
288
- end
289
-
290
- %i[post patch].each do |method|
291
- it "should parse attachments for #{method} requests" do
292
- attachments = double('Sdk4me::Attachments')
293
- expect(attachments).to receive(:upload_attachments!) do |data|
294
- expect(data[:note_attachments]).to eq(['/tmp/first.png', '/tmp/second.zip'])
295
- data[:note_attachments] = 'processed'
296
- end
297
- expect(Sdk4me::Attachments).to receive(:new).with(client(authentication), '/requests/777') { attachments }
298
- stub_request(method, 'https://api.4me.com/v1/requests/777').with(credentials(authentication)).with(body: { note: 'note', note_attachments: 'processed' }).to_return(body: { id: 777, upload_called: true }.to_json)
299
-
300
- response = client(authentication).send(method, '/requests/777', { note: 'note', note_attachments: ['/tmp/first.png', '/tmp/second.zip'] })
301
- expect(response.valid?).to be_truthy
302
- expect(response[:upload_called]).to be_truthy
303
- end
304
- end
305
- end
306
-
307
- context 'import' do
308
- before(:each) do
309
- csv_mime_type = ['text/csv', 'text/comma-separated-values'].detect { |t| MIME::Types[t].any? } # which mime type is used depends on version of mime-types gem
310
- @multi_part_body = "--0123456789ABLEWASIEREISAWELBA9876543210\r\nContent-Disposition: form-data; name=\"type\"\r\n\r\npeople\r\n--0123456789ABLEWASIEREISAWELBA9876543210\r\nContent-Disposition: form-data; name=\"file\"; filename=\"#{@fixture_dir}/people.csv\"\r\nContent-Type: #{csv_mime_type}\r\n\r\nPrimary Email,Name\nchess.cole@example.com,Chess Cole\ned.turner@example.com,Ed Turner\r\n--0123456789ABLEWASIEREISAWELBA9876543210--"
311
- @multi_part_headers = { 'Accept' => '*/*', 'Content-Type' => 'multipart/form-data; boundary=0123456789ABLEWASIEREISAWELBA9876543210', 'User-Agent' => "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/523.10.6 (KHTML, like Gecko) Version/3.0.4 Safari/523.10.6 4me/#{Sdk4me::Client::VERSION}" }
312
-
313
- @import_queued_response = { body: { state: 'queued' }.to_json }
314
- @import_processing_response = { body: { state: 'processing' }.to_json }
315
- @import_done_response = { body: { state: 'done', results: { errors: 0, updated: 1, created: 1, failures: 0, unchanged: 0, deleted: 0 } }.to_json }
316
- @import_failed_response = { body: { state: 'error', message: 'Invalid byte sequence in UTF-8 on line 2', results: { errors: 1, updated: 1, created: 0, failures: 1, unchanged: 0, deleted: 0 } }.to_json }
317
- allow(client(authentication)).to receive(:sleep)
318
- WebMock.disable_net_connect!
319
- end
320
-
321
- it 'should import a CSV file' do
322
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
323
- expect_log("Import file '#{@fixture_dir}/people.csv' successfully uploaded with token '68ef5ef0f64c0'.")
324
-
325
- response = client(authentication).import(File.new("#{@fixture_dir}/people.csv"), 'people')
326
- expect(response[:token]).to eq('68ef5ef0f64c0')
327
- end
328
-
329
- it 'should import a CSV file by filename' do
330
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
331
- response = client(authentication).import("#{@fixture_dir}/people.csv", 'people')
332
- expect(response[:token]).to eq('68ef5ef0f64c0')
333
- end
334
-
335
- it 'should wait for the import to complete' do
336
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
337
- progress_stub = stub_request(:get, 'https://api.4me.com/v1/import/68ef5ef0f64c0').with(credentials(authentication))
338
- .to_return(@import_queued_response, @import_processing_response)
339
- .then.to_raise(StandardError.new('network error'))
340
- .then.to_return(@import_done_response)
341
-
342
- # verify the correct log statement are made
343
- expect_log('Sending POST request to api.4me.com:443/v1/import', :debug)
344
- expect_log("Response:\n{\n \"token\": \"68ef5ef0f64c0\"\n}", :debug)
345
- expect_log("Import file '#{@fixture_dir}/people.csv' successfully uploaded with token '68ef5ef0f64c0'.")
346
- expect_log('Sending GET request to api.4me.com:443/v1/import/68ef5ef0f64c0', :debug)
347
- expect_log("Response:\n{\n \"state\": \"queued\"\n}", :debug)
348
- expect_log("Import of '#{@fixture_dir}/people.csv' is queued. Checking again in 30 seconds.", :debug)
349
- expect_log('Sending GET request to api.4me.com:443/v1/import/68ef5ef0f64c0', :debug)
350
- expect_log("Response:\n{\n \"state\": \"processing\"\n}", :debug)
351
- expect_log("Import of '#{@fixture_dir}/people.csv' is processing. Checking again in 30 seconds.", :debug)
352
- expect_log('Sending GET request to api.4me.com:443/v1/import/68ef5ef0f64c0', :debug)
353
- expect_log("GET request to api.4me.com:443/v1/import/68ef5ef0f64c0 failed: 500: No Response from Server - network error for 'api.4me.com:443/v1/import/68ef5ef0f64c0'", :error)
354
- expect_log('Sending GET request to api.4me.com:443/v1/import/68ef5ef0f64c0', :debug)
355
- expect_log("Response:\n{\n \"state\": \"done\",\n \"results\": {\n \"errors\": 0,\n \"updated\": 1,\n \"created\": 1,\n \"failures\": 0,\n \"unchanged\": 0,\n \"deleted\": 0\n }\n}", :debug)
356
-
357
- response = client(authentication).import("#{@fixture_dir}/people.csv", 'people', true)
358
- expect(response[:state]).to eq('done')
359
- expect(response[:results][:updated]).to eq(1)
360
- expect(progress_stub).to have_been_requested.times(4)
361
- end
362
-
363
- it 'should wait for the import to fail' do
364
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
365
- progress_stub = stub_request(:get, 'https://api.4me.com/v1/import/68ef5ef0f64c0').with(credentials(authentication)).to_return(@import_queued_response, @import_processing_response, @import_failed_response)
366
-
367
- response = client(authentication).import("#{@fixture_dir}/people.csv", 'people', true)
368
- expect(response.valid?).to be_falsey
369
- expect(response[:message]).to eq('Invalid byte sequence in UTF-8 on line 2')
370
- expect(progress_stub).to have_been_requested.times(3)
371
- end
372
-
373
- it 'should not continue when there is an error connecting to 4me' do
374
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
375
- progress_stub = stub_request(:get, 'https://api.4me.com/v1/import/68ef5ef0f64c0').with(credentials(authentication))
376
- .to_return(@import_queued_response, @import_processing_response)
377
- .then.to_raise(StandardError.new('network error')) # twice
378
-
379
- expect { client(authentication).import("#{@fixture_dir}/people.csv", 'people', true) }.to raise_error(Sdk4me::Exception, "Unable to monitor progress for people import. 500: No Response from Server - network error for 'api.4me.com:443/v1/import/68ef5ef0f64c0'")
380
- expect(progress_stub).to have_been_requested.times(4)
381
- end
382
-
383
- it 'should return an invalid response in case waiting for progress is false' do
384
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { message: 'oops!' }.to_json)
385
- response = client(authentication).import("#{@fixture_dir}/people.csv", 'people', false)
386
- expect(response.valid?).to be_falsey
387
- expect(response.message).to eq('oops!')
388
- end
389
-
390
- it 'should raise an UploadFailed exception in case waiting for progress is true' do
391
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { message: 'oops!' }.to_json)
392
- expect { client(authentication).import("#{@fixture_dir}/people.csv", 'people', true) }.to raise_error(Sdk4me::UploadFailed, 'Failed to queue people import. oops!')
393
- end
394
-
395
- it 'should return the error response when the import state is set to error' do
396
- stub_request(:post, 'https://api.4me.com/v1/import').with(credentials(authentication)).with(body: @multi_part_body, headers: @multi_part_headers).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
397
- stub_request(:get, 'https://api.4me.com/v1/import/68ef5ef0f64c0').with(credentials(authentication)).to_return(body: { state: 'error', message: 'Too many import failures', logfile: 'foo' }.to_json)
398
-
399
- response = client(authentication).import("#{@fixture_dir}/people.csv", 'people', true)
400
- expect(response.valid?).to be_falsey
401
- expect(response[:message]).to eq('Too many import failures')
402
- expect(response[:logfile]).to eq('foo')
403
- end
404
- end
405
-
406
- context 'export' do
407
- before(:each) do
408
- @export_queued_response = { body: { state: 'queued' }.to_json }
409
- @export_processing_response = { body: { state: 'processing' }.to_json }
410
- @export_done_response = { body: { state: 'done', url: 'https://download.example.com/export.zip?AWSAccessKeyId=12345' }.to_json }
411
- allow(client(authentication)).to receive(:sleep)
412
- end
413
-
414
- it 'should export multiple types' do
415
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people,people_contact_details' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
416
- expect_log("Export for 'people,people_contact_details' successfully queued with token '68ef5ef0f64c0'.")
417
-
418
- response = client(authentication).export(%w[people people_contact_details])
419
- expect(response[:token]).to eq('68ef5ef0f64c0')
420
- end
421
-
422
- it 'should indicate when nothing is exported' do
423
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people', from: '2012-03-30T23:00:00+00:00' }).to_return(status: 204)
424
- expect_log("No changed records for 'people' since 2012-03-30T23:00:00+00:00.")
425
-
426
- response = client(authentication).export('people', DateTime.new(2012, 0o3, 30, 23, 0o0, 0o0))
427
- expect(response[:token]).to be_nil
428
- end
429
-
430
- it 'should export since a certain time' do
431
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people', from: '2012-03-30T23:00:00+00:00' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
432
- expect_log("Export for 'people' successfully queued with token '68ef5ef0f64c0'.")
433
-
434
- response = client(authentication).export('people', DateTime.new(2012, 0o3, 30, 23, 0o0, 0o0))
435
- expect(response[:token]).to eq('68ef5ef0f64c0')
436
- end
437
-
438
- it 'should export with locale' do
439
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'translations', locale: 'nl' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
440
- expect_log("Export for 'translations' successfully queued with token '68ef5ef0f64c0'.")
441
-
442
- response = client(authentication).export('translations', nil, nil, 'nl')
443
- expect(response[:token]).to eq('68ef5ef0f64c0')
444
- end
445
-
446
- it 'should wait for the export to complete' do
447
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
448
- progress_stub = stub_request(:get, 'https://api.4me.com/v1/export/68ef5ef0f64c0').with(credentials(authentication))
449
- .to_return(@export_queued_response, @export_processing_response)
450
- .then.to_raise(StandardError.new('network error'))
451
- .then.to_return(@export_done_response)
452
-
453
- # verify the correct log statement are made
454
- expect_log('Sending POST request to api.4me.com:443/v1/export', :debug)
455
- expect_log(%(Response:\n{\n "token": "68ef5ef0f64c0"\n}), :debug)
456
- expect_log("Export for 'people' successfully queued with token '68ef5ef0f64c0'.")
457
- expect_log('Sending GET request to api.4me.com:443/v1/export/68ef5ef0f64c0', :debug)
458
- expect_log(%(Response:\n{\n "state": "queued"\n}), :debug)
459
- expect_log("Export of 'people' is queued. Checking again in 30 seconds.", :debug)
460
- expect_log('Sending GET request to api.4me.com:443/v1/export/68ef5ef0f64c0', :debug)
461
- expect_log(%(Response:\n{\n "state": "processing"\n}), :debug)
462
- expect_log("Export of 'people' is processing. Checking again in 30 seconds.", :debug)
463
- expect_log('Sending GET request to api.4me.com:443/v1/export/68ef5ef0f64c0', :debug)
464
- expect_log("GET request to api.4me.com:443/v1/export/68ef5ef0f64c0 failed: 500: No Response from Server - network error for 'api.4me.com:443/v1/export/68ef5ef0f64c0'", :error)
465
- expect_log('Sending GET request to api.4me.com:443/v1/export/68ef5ef0f64c0', :debug)
466
- expect_log(%(Response:\n{\n "state": "done",\n "url": "https://download.example.com/export.zip?AWSAccessKeyId=12345"\n}), :debug)
467
-
468
- response = client(authentication).export('people', nil, true)
469
- expect(response[:state]).to eq('done')
470
- expect(response[:url]).to eq('https://download.example.com/export.zip?AWSAccessKeyId=12345')
471
- expect(progress_stub).to have_been_requested.times(4)
472
- end
473
-
474
- it 'should not continue when there is an error connecting to 4me' do
475
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
476
- progress_stub = stub_request(:get, 'https://api.4me.com/v1/export/68ef5ef0f64c0').with(credentials(authentication))
477
- .to_return(@export_queued_response, @export_processing_response)
478
- .then.to_raise(StandardError.new('network error')) # twice
479
-
480
- expect { client(authentication).export('people', nil, true) }.to raise_error(Sdk4me::Exception, "Unable to monitor progress for 'people' export. 500: No Response from Server - network error for 'api.4me.com:443/v1/export/68ef5ef0f64c0'")
481
- expect(progress_stub).to have_been_requested.times(4)
482
- end
483
-
484
- it 'should return an invalid response in case waiting for progress is false' do
485
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people' }).to_return(body: { message: 'oops!' }.to_json)
486
- response = client(authentication).export('people')
487
- expect(response.valid?).to be_falsey
488
- expect(response.message).to eq('oops!')
489
- end
490
-
491
- it 'should raise an UploadFailed exception in case waiting for progress is true' do
492
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people' }).to_return(body: { message: 'oops!' }.to_json)
493
- expect { client(authentication).export('people', nil, true) }.to raise_error(Sdk4me::UploadFailed, "Failed to queue 'people' export. oops!")
494
- end
495
-
496
- it 'should return the error response when the export state is set to error' do
497
- stub_request(:post, 'https://api.4me.com/v1/export').with(credentials(authentication)).with(body: { type: 'people' }).to_return(body: { token: '68ef5ef0f64c0' }.to_json)
498
- stub_request(:get, 'https://api.4me.com/v1/export/68ef5ef0f64c0').with(credentials(authentication)).to_return(body: { state: 'error', message: 'Too many export failures', logfile: 'foo' }.to_json)
499
-
500
- response = client(authentication).export('people', nil, true)
501
- expect(response.valid?).to be_falsey
502
- expect(response[:message]).to eq('Too many export failures')
503
- expect(response[:logfile]).to eq('foo')
504
- end
505
- end
506
-
507
- context 'retry' do
508
- it 'should not retry when max_retry_time = -1' do
509
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_raise(StandardError.new('network error'))
510
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
511
- expect_log("GET request to api.4me.com:443/v1/me failed: 500: No Response from Server - network error for 'api.4me.com:443/v1/me'", :error)
512
-
513
- response = client(authentication).get('me')
514
- expect(stub).to have_been_requested.times(1)
515
- expect(response.valid?).to be_falsey
516
- expect(response.message).to eq("500: No Response from Server - network error for 'api.4me.com:443/v1/me'")
517
- end
518
-
519
- it 'should not retry 4 times when max_retry_time = 16' do
520
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_raise(StandardError.new('network error'))
521
- [2, 4, 8].each_with_index do |secs, i|
522
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
523
- expect_log("Request failed, retry ##{i + 1} in #{secs} seconds: 500: No Response from Server - network error for 'api.4me.com:443/v1/me'", :warn)
524
- end
525
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
526
-
527
- retry_client = client(authentication, max_retry_time: 16)
528
- allow(retry_client).to receive(:sleep)
529
- response = retry_client.get('me')
530
- expect(stub).to have_been_requested.times(4)
531
- expect(response.valid?).to be_falsey
532
- expect(response.message).to eq("500: No Response from Server - network error for 'api.4me.com:443/v1/me'")
533
- end
534
-
535
- it 'should return the response after retry succeeds' do
536
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_raise(StandardError.new('network error')).then.to_return(body: { name: 'my name' }.to_json)
537
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
538
- expect_log("Request failed, retry #1 in 2 seconds: 500: No Response from Server - network error for 'api.4me.com:443/v1/me'", :warn)
539
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
540
- expect_log(%(Response:\n{\n "name": "my name"\n}), :debug)
541
-
542
- retry_client = client(authentication, max_retry_time: 16)
543
- allow(retry_client).to receive(:sleep)
544
- response = retry_client.get('me')
545
- expect(stub).to have_been_requested.times(2)
546
- expect(response.valid?).to be_truthy
547
- expect(response[:name]).to eq('my name')
548
- end
549
- end
550
-
551
- context 'rate limiting' do
552
- it 'should not block on rate limit when block_at_rate_limit is false' do
553
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(status: 429, body: { message: 'Too Many Requests' }.to_json)
554
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
555
- expect_log('GET request to api.4me.com:443/v1/me failed: 429: Too Many Requests', :error)
556
-
557
- response = client(authentication, block_at_rate_limit: false).get('me')
558
- expect(stub).to have_been_requested.times(1)
559
- expect(response.valid?).to be_falsey
560
- expect(response.message).to eq('429: Too Many Requests')
561
- end
562
-
563
- it 'should block on rate limit when block_at_rate_limit is true' do
564
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(status: 429, body: { message: 'Too Many Requests' }.to_json).then.to_return(body: { name: 'my name' }.to_json)
565
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
566
- expect_log('Request throttled, trying again in 300 seconds: 429: Too Many Requests', :warn)
567
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
568
- expect_log(%(Response:\n{\n "name": "my name"\n}), :debug)
569
-
570
- block_client = client(authentication, block_at_rate_limit: true, max_retry_time: 500)
571
- allow(block_client).to receive(:sleep)
572
- response = block_client.get('me')
573
- expect(stub).to have_been_requested.times(2)
574
- expect(response.valid?).to be_truthy
575
- expect(response[:name]).to eq('my name')
576
- end
577
-
578
- it 'should block on rate limit using Retry-After when block_at_rate_limit is true' do
579
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(status: 429, body: { message: 'Too Many Requests' }.to_json, headers: { 'Retry-After' => '20' }).then.to_return(body: { name: 'my name' }.to_json)
580
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
581
- expect_log('Request throttled, trying again in 20 seconds: 429: Too Many Requests', :warn)
582
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
583
- expect_log(%(Response:\n{\n "name": "my name"\n}), :debug)
584
-
585
- block_client = client(authentication, block_at_rate_limit: true)
586
- allow(block_client).to receive(:sleep)
587
- response = block_client.get('me')
588
- expect(stub).to have_been_requested.times(2)
589
- expect(response.valid?).to be_truthy
590
- expect(response[:name]).to eq('my name')
591
- end
592
-
593
- it 'should block on rate limit using Retry-After with minimum of 2 seconds when block_at_rate_limit is true' do
594
- stub = stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(status: 429, body: { message: 'Too Many Requests' }.to_json, headers: { 'Retry-After' => '1' }).then.to_return(body: { name: 'my name' }.to_json)
595
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
596
- expect_log('Request throttled, trying again in 2 seconds: 429: Too Many Requests', :warn)
597
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug)
598
- expect_log(%(Response:\n{\n "name": "my name"\n}), :debug)
599
-
600
- block_client = client(authentication, block_at_rate_limit: true)
601
- allow(block_client).to receive(:sleep)
602
- response = block_client.get('me')
603
- expect(stub).to have_been_requested.times(2)
604
- expect(response.valid?).to be_truthy
605
- expect(response[:name]).to eq('my name')
606
- end
607
- end
608
-
609
- context 'logger' do
610
- it 'should be possible to override the default logger' do
611
- logger = Logger.new($stdout)
612
- logger_client = client(authentication, max_retry_time: -1, logger: logger)
613
- stub_request(:get, 'https://api.4me.com/v1/me').with(credentials(authentication)).to_return(body: { name: 'my name' }.to_json)
614
- expect_log('Sending GET request to api.4me.com:443/v1/me', :debug, logger)
615
- expect_log(%(Response:\n{\n "name": "my name"\n}), :debug, logger)
616
- logger_client.get('me')
617
- end
618
- end
619
- end
620
- end