Merge pull request #71 from twelvelabs/master
[arvados.git] / spec / google / api_client / discovery_spec.rb
1 # encoding:utf-8
2
3 # Copyright 2010 Google Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #      http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17
18 require 'spec_helper'
19
20 require 'faraday'
21 require 'multi_json'
22 require 'compat/multi_json'
23 require 'signet/oauth_1/client'
24 require 'google/api_client'
25 require 'google/api_client/version'
26
27 describe Google::APIClient do
28   include ConnectionHelpers
29   CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
30
31   after do
32     # Reset client to not-quite-pristine state
33     CLIENT.key = nil
34     CLIENT.user_ip = nil
35   end
36
37   it 'should raise a type error for bogus authorization' do
38     (lambda do
39       Google::APIClient.new(:application_name => 'API Client Tests', :authorization => 42)
40     end).should raise_error(TypeError)
41   end
42
43   it 'should not be able to retrieve the discovery document for a bogus API' do
44     (lambda do
45       CLIENT.discovery_document('bogus')
46     end).should raise_error(Google::APIClient::TransmissionError)
47     (lambda do
48       CLIENT.discovered_api('bogus')
49     end).should raise_error(Google::APIClient::TransmissionError)
50   end
51
52   it 'should raise an error for bogus services' do
53     (lambda do
54       CLIENT.discovered_api(42)
55     end).should raise_error(TypeError)
56   end
57
58   it 'should raise an error for bogus services' do
59     (lambda do
60       CLIENT.preferred_version(42)
61     end).should raise_error(TypeError)
62   end
63
64   it 'should raise an error for bogus methods' do
65     (lambda do
66       CLIENT.execute(42)
67     end).should raise_error(TypeError)
68   end
69
70   it 'should not return a preferred version for bogus service names' do
71     CLIENT.preferred_version('bogus').should == nil
72   end
73
74   describe 'with the prediction API' do
75     before do
76       CLIENT.authorization = nil
77       # The prediction API no longer exposes a v1, so we have to be
78       # careful about looking up the wrong API version.
79       @prediction = CLIENT.discovered_api('prediction', 'v1.2')
80     end
81
82     it 'should correctly determine the discovery URI' do
83       CLIENT.discovery_uri('prediction').should ===
84         'https://www.googleapis.com/discovery/v1/apis/prediction/v1/rest'
85     end
86
87     it 'should correctly determine the discovery URI if :user_ip is set' do
88       CLIENT.user_ip = '127.0.0.1'
89       
90       conn = stub_connection do |stub|
91         stub.get('/discovery/v1/apis/prediction/v1.2/rest?userIp=127.0.0.1') do |env|
92         end
93       end
94       CLIENT.execute(
95         :http_method => 'GET',
96         :uri => CLIENT.discovery_uri('prediction', 'v1.2'),
97         :authenticated => false,
98         :connection => conn
99       )
100       conn.verify
101     end
102
103     it 'should correctly determine the discovery URI if :key is set' do
104       CLIENT.key = 'qwerty'
105       conn = stub_connection do |stub|
106         stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty') do |env|
107         end
108       end
109       request = CLIENT.execute(
110         :http_method => 'GET',
111         :uri => CLIENT.discovery_uri('prediction', 'v1.2'),
112         :authenticated => false,
113         :connection => conn
114         )
115         conn.verify
116     end
117
118     it 'should correctly determine the discovery URI if both are set' do
119       CLIENT.key = 'qwerty'
120       CLIENT.user_ip = '127.0.0.1'
121       conn = stub_connection do |stub|
122         stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty&userIp=127.0.0.1') do |env|
123         end
124       end
125       request = CLIENT.execute(
126         :http_method => 'GET',
127         :uri => CLIENT.discovery_uri('prediction', 'v1.2'),
128         :authenticated => false,
129         :connection => conn
130         )
131         conn.verify
132     end
133
134     it 'should correctly generate API objects' do
135       CLIENT.discovered_api('prediction', 'v1.2').name.should == 'prediction'
136       CLIENT.discovered_api('prediction', 'v1.2').version.should == 'v1.2'
137       CLIENT.discovered_api(:prediction, 'v1.2').name.should == 'prediction'
138       CLIENT.discovered_api(:prediction, 'v1.2').version.should == 'v1.2'
139     end
140
141     it 'should discover methods' do
142       CLIENT.discovered_method(
143         'prediction.training.insert', 'prediction', 'v1.2'
144       ).name.should == 'insert'
145       CLIENT.discovered_method(
146         :'prediction.training.insert', :prediction, 'v1.2'
147       ).name.should == 'insert'
148       CLIENT.discovered_method(
149         'prediction.training.delete', 'prediction', 'v1.2'
150       ).name.should == 'delete'
151     end
152
153     it 'should define the origin API in discovered methods' do
154       CLIENT.discovered_method(
155         'prediction.training.insert', 'prediction', 'v1.2'
156       ).api.name.should == 'prediction'
157     end
158
159     it 'should not find methods that are not in the discovery document' do
160       CLIENT.discovered_method(
161         'prediction.bogus', 'prediction', 'v1.2'
162       ).should == nil
163     end
164
165     it 'should raise an error for bogus methods' do
166       (lambda do
167         CLIENT.discovered_method(42, 'prediction', 'v1.2')
168       end).should raise_error(TypeError)
169     end
170
171     it 'should raise an error for bogus methods' do
172       (lambda do
173         CLIENT.execute(:api_method => CLIENT.discovered_api('prediction', 'v1.2'))
174       end).should raise_error(TypeError)
175     end
176
177     it 'should correctly determine the preferred version' do
178       CLIENT.preferred_version('prediction').version.should_not == 'v1'
179       CLIENT.preferred_version(:prediction).version.should_not == 'v1'
180     end
181
182     it 'should return a batch path' do
183       CLIENT.discovered_api('prediction', 'v1.2').batch_path.should_not be_nil
184     end
185
186     it 'should generate valid requests' do
187       conn = stub_connection do |stub|
188         stub.post('/prediction/v1.2/training?data=12345') do |env|
189           env[:body].should == ''
190         end
191       end
192       request = CLIENT.execute(
193         :api_method => @prediction.training.insert,
194         :parameters => {'data' => '12345'},
195         :connection => conn
196       )
197       conn.verify
198     end
199
200     it 'should generate valid requests when parameter value includes semicolon' do
201       conn = stub_connection do |stub|
202         # semicolon (;) in parameter value was being converted to 
203         # bare ampersand (&) in 0.4.7. ensure that it gets converted 
204         # to a CGI-escaped semicolon (%3B) instead.
205         stub.post('/prediction/v1.2/training?data=12345%3B67890') do |env|
206           env[:body].should == ''
207         end
208       end
209       request = CLIENT.execute(
210         :api_method => @prediction.training.insert,
211         :parameters => {'data' => '12345;67890'},
212         :connection => conn
213       )
214       conn.verify
215     end
216
217     it 'should generate valid requests when multivalued parameters are passed' do
218       conn = stub_connection do |stub|
219          stub.post('/prediction/v1.2/training?data=1&data=2') do |env|
220            env.params['data'].should include('1', '2')
221          end
222        end
223       request = CLIENT.execute(
224         :api_method => @prediction.training.insert,
225         :parameters => {'data' => ['1', '2']},
226         :connection => conn
227       )
228       conn.verify
229     end
230
231     it 'should generate requests against the correct URIs' do
232       conn = stub_connection do |stub|
233          stub.post('/prediction/v1.2/training?data=12345') do |env|
234          end
235        end
236       request = CLIENT.execute(
237         :api_method => @prediction.training.insert,
238         :parameters => {'data' => '12345'},
239         :connection => conn
240       )
241       conn.verify
242     end
243
244     it 'should generate requests against the correct URIs' do
245       conn = stub_connection do |stub|
246         stub.post('/prediction/v1.2/training?data=12345') do |env|
247         end
248       end
249       request = CLIENT.execute(
250         :api_method => @prediction.training.insert,
251         :parameters => {'data' => '12345'},
252         :connection => conn
253       )
254       conn.verify
255     end
256
257     it 'should allow modification to the base URIs for testing purposes' do
258       # Using a new client instance here to avoid caching rebased discovery doc
259       prediction_rebase =
260         Google::APIClient.new(:application_name => 'API Client Tests').discovered_api('prediction', 'v1.2')
261       prediction_rebase.method_base =
262         'https://testing-domain.example.com/prediction/v1.2/'
263
264       conn = stub_connection do |stub|
265         stub.post('/prediction/v1.2/training') do |env|
266           env[:url].host.should == 'testing-domain.example.com'
267         end
268       end
269         
270       request = CLIENT.execute(
271         :api_method => prediction_rebase.training.insert,
272         :parameters => {'data' => '123'},
273         :connection => conn
274       )
275       conn.verify
276     end
277
278     it 'should generate OAuth 1 requests' do
279       CLIENT.authorization = :oauth_1
280       CLIENT.authorization.token_credential_key = '12345'
281       CLIENT.authorization.token_credential_secret = '12345'
282
283       conn = stub_connection do |stub|
284         stub.post('/prediction/v1.2/training?data=12345') do |env|
285           env[:request_headers].should have_key('Authorization')
286           env[:request_headers]['Authorization'].should =~ /^OAuth/
287         end
288       end
289
290       request = CLIENT.execute(
291         :api_method => @prediction.training.insert,
292         :parameters => {'data' => '12345'},
293         :connection => conn
294       )
295       conn.verify
296     end
297
298     it 'should generate OAuth 2 requests' do
299       CLIENT.authorization = :oauth_2
300       CLIENT.authorization.access_token = '12345'
301
302       conn = stub_connection do |stub|
303         stub.post('/prediction/v1.2/training?data=12345') do |env|
304           env[:request_headers].should have_key('Authorization')
305           env[:request_headers]['Authorization'].should =~ /^Bearer/
306         end
307       end
308
309       request = CLIENT.execute(
310         :api_method => @prediction.training.insert,
311         :parameters => {'data' => '12345'},
312         :connection => conn
313       )
314       conn.verify
315     end
316
317     it 'should not be able to execute improperly authorized requests' do
318       CLIENT.authorization = :oauth_1
319       CLIENT.authorization.token_credential_key = '12345'
320       CLIENT.authorization.token_credential_secret = '12345'
321       result = CLIENT.execute(
322         @prediction.training.insert,
323         {'data' => '12345'}
324       )
325       result.response.status.should == 401
326     end
327
328     it 'should not be able to execute improperly authorized requests' do
329       CLIENT.authorization = :oauth_2
330       CLIENT.authorization.access_token = '12345'
331       result = CLIENT.execute(
332         @prediction.training.insert,
333         {'data' => '12345'}
334       )
335       result.response.status.should == 401
336     end
337
338     it 'should not be able to execute improperly authorized requests' do
339       (lambda do
340         CLIENT.authorization = :oauth_1
341         CLIENT.authorization.token_credential_key = '12345'
342         CLIENT.authorization.token_credential_secret = '12345'
343         result = CLIENT.execute!(
344           @prediction.training.insert,
345           {'data' => '12345'}
346         )
347       end).should raise_error(Google::APIClient::ClientError)
348     end
349
350     it 'should not be able to execute improperly authorized requests' do
351       (lambda do
352         CLIENT.authorization = :oauth_2
353         CLIENT.authorization.access_token = '12345'
354         result = CLIENT.execute!(
355           @prediction.training.insert,
356           {'data' => '12345'}
357         )
358       end).should raise_error(Google::APIClient::ClientError)
359     end
360
361     it 'should correctly handle unnamed parameters' do
362       conn = stub_connection do |stub|
363         stub.post('/prediction/v1.2/training') do |env|
364           env[:request_headers].should have_key('Content-Type')
365           env[:request_headers]['Content-Type'].should == 'application/json'
366         end
367       end
368       CLIENT.authorization = :oauth_2
369       CLIENT.authorization.access_token = '12345'
370       CLIENT.execute(
371         :api_method => @prediction.training.insert,
372         :body => MultiJson.dump({"id" => "bucket/object"}),
373         :headers => {'Content-Type' => 'application/json'},
374         :connection => conn
375       )
376       conn.verify
377     end
378   end
379
380   describe 'with the plus API' do
381     before do
382       CLIENT.authorization = nil
383       @plus = CLIENT.discovered_api('plus')
384     end
385
386     it 'should correctly determine the discovery URI' do
387       CLIENT.discovery_uri('plus').should ===
388         'https://www.googleapis.com/discovery/v1/apis/plus/v1/rest'
389     end
390
391     it 'should find APIs that are in the discovery document' do
392       CLIENT.discovered_api('plus').name.should == 'plus'
393       CLIENT.discovered_api('plus').version.should == 'v1'
394       CLIENT.discovered_api(:plus).name.should == 'plus'
395       CLIENT.discovered_api(:plus).version.should == 'v1'
396     end
397
398     it 'should find methods that are in the discovery document' do
399       # TODO(bobaman) Fix this when the RPC names are correct
400       CLIENT.discovered_method(
401         'plus.activities.list', 'plus'
402       ).name.should == 'list'
403     end
404
405     it 'should define the origin API in discovered methods' do
406       CLIENT.discovered_method(
407         'plus.activities.list', 'plus'
408       ).api.name.should == 'plus'
409     end
410
411     it 'should not find methods that are not in the discovery document' do
412       CLIENT.discovered_method('plus.bogus', 'plus').should == nil
413     end
414
415     it 'should generate requests against the correct URIs' do
416       conn = stub_connection do |stub|
417         stub.get('/plus/v1/people/107807692475771887386/activities/public') do |env|
418         end
419       end
420       
421       request = CLIENT.execute(
422         :api_method => @plus.activities.list,
423         :parameters => {
424           'userId' => '107807692475771887386', 'collection' => 'public'
425         },
426         :authenticated => false,
427         :connection => conn
428       )
429       conn.verify
430     end
431
432     it 'should correctly validate parameters' do
433       (lambda do
434         CLIENT.execute(
435           :api_method => @plus.activities.list,
436           :parameters => {'alt' => 'json'},
437           :authenticated => false
438         )
439       end).should raise_error(ArgumentError)
440     end
441
442     it 'should correctly validate parameters' do
443       (lambda do
444         CLIENT.execute(
445           :api_method => @plus.activities.list,
446           :parameters => {
447             'userId' => '107807692475771887386', 'collection' => 'bogus'
448           },
449           :authenticated => false
450         ).to_env(CLIENT.connection)
451       end).should raise_error(ArgumentError)
452     end
453   end
454
455   describe 'with the adsense API' do
456     before do
457       CLIENT.authorization = nil
458       @adsense = CLIENT.discovered_api('adsense', 'v1.3')
459     end
460
461     it 'should correctly determine the discovery URI' do
462       CLIENT.discovery_uri('adsense', 'v1.3').to_s.should ===
463         'https://www.googleapis.com/discovery/v1/apis/adsense/v1.3/rest'
464     end
465
466     it 'should find APIs that are in the discovery document' do
467       CLIENT.discovered_api('adsense', 'v1.3').name.should == 'adsense'
468       CLIENT.discovered_api('adsense', 'v1.3').version.should == 'v1.3'
469     end
470
471     it 'should return a batch path' do
472       CLIENT.discovered_api('adsense', 'v1.3').batch_path.should_not be_nil
473     end
474
475     it 'should find methods that are in the discovery document' do
476       CLIENT.discovered_method(
477         'adsense.reports.generate', 'adsense'
478       ).name.should == 'generate'
479     end
480
481     it 'should not find methods that are not in the discovery document' do
482       CLIENT.discovered_method('adsense.bogus', 'adsense').should == nil
483     end
484
485     it 'should generate requests against the correct URIs' do
486       conn = stub_connection do |stub|
487         stub.get('/adsense/v1.3/adclients') do |env|
488         end
489       end
490       request = CLIENT.execute(
491         :api_method => @adsense.adclients.list,
492         :authenticated => false,
493         :connection => conn
494       )
495       conn.verify
496     end
497
498     it 'should not be able to execute requests without authorization' do
499       result = CLIENT.execute(
500         :api_method => @adsense.adclients.list,
501         :authenticated => false
502       )
503       result.response.status.should == 401
504     end
505
506     it 'should fail when validating missing required parameters' do
507       (lambda do
508         CLIENT.execute(
509           :api_method => @adsense.reports.generate,
510           :authenticated => false
511         )
512       end).should raise_error(ArgumentError)
513     end
514
515     it 'should succeed when validating parameters in a correct call' do
516       conn = stub_connection do |stub|
517         stub.get('/adsense/v1.3/reports?dimension=DATE&endDate=2010-01-01&metric=PAGE_VIEWS&startDate=2000-01-01') do |env|
518         end
519       end
520       (lambda do
521         CLIENT.execute(
522           :api_method => @adsense.reports.generate,
523           :parameters => {
524             'startDate' => '2000-01-01',
525             'endDate' => '2010-01-01',
526             'dimension' => 'DATE',
527             'metric' => 'PAGE_VIEWS'
528           },
529           :authenticated => false,
530           :connection => conn
531         )
532       end).should_not raise_error
533       conn.verify
534     end
535
536     it 'should fail when validating parameters with invalid values' do
537       (lambda do
538         CLIENT.execute(
539           :api_method => @adsense.reports.generate,
540           :parameters => {
541             'startDate' => '2000-01-01',
542             'endDate' => '2010-01-01',
543             'dimension' => 'BAD_CHARACTERS=-&*(£&',
544             'metric' => 'PAGE_VIEWS'
545           },
546           :authenticated => false
547         )
548       end).should raise_error(ArgumentError)
549     end
550
551     it 'should succeed when validating repeated parameters in a correct call' do
552       conn = stub_connection do |stub|
553         stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
554                  '&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
555                  'startDate=2000-01-01') do |env|
556         end
557       end
558       (lambda do
559         CLIENT.execute(
560           :api_method => @adsense.reports.generate,
561           :parameters => {
562             'startDate' => '2000-01-01',
563             'endDate' => '2010-01-01',
564             'dimension' => ['DATE', 'PRODUCT_CODE'],
565             'metric' => ['PAGE_VIEWS', 'CLICKS']
566           },
567           :authenticated => false,
568           :connection => conn
569         )
570       end).should_not raise_error
571       conn.verify
572     end
573
574     it 'should fail when validating incorrect repeated parameters' do
575       (lambda do
576         CLIENT.execute(
577           :api_method => @adsense.reports.generate,
578           :parameters => {
579             'startDate' => '2000-01-01',
580             'endDate' => '2010-01-01',
581             'dimension' => ['DATE', 'BAD_CHARACTERS=-&*(£&'],
582             'metric' => ['PAGE_VIEWS', 'CLICKS']
583           },
584           :authenticated => false
585         )
586       end).should raise_error(ArgumentError)
587     end
588
589     it 'should generate valid requests when multivalued parameters are passed' do
590       conn = stub_connection do |stub|
591          stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
592                  '&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
593                  'startDate=2000-01-01') do |env|
594            env.params['dimension'].should include('DATE', 'PRODUCT_CODE')
595            env.params['metric'].should include('CLICKS', 'PAGE_VIEWS')
596          end
597        end
598       request = CLIENT.execute(
599         :api_method => @adsense.reports.generate,
600           :parameters => {
601             'startDate' => '2000-01-01',
602             'endDate' => '2010-01-01',
603             'dimension' => ['DATE', 'PRODUCT_CODE'],
604             'metric' => ['PAGE_VIEWS', 'CLICKS']
605           },
606           :authenticated => false,
607           :connection => conn
608       )
609       conn.verify
610     end
611   end
612
613   describe 'with the Drive API' do
614     before do
615       CLIENT.authorization = nil
616       @drive = CLIENT.discovered_api('drive', 'v1')
617     end
618
619     it 'should include media upload info methods' do
620       @drive.files.insert.media_upload.should_not == nil
621     end
622
623     it 'should include accepted media types' do
624       @drive.files.insert.media_upload.accepted_types.should_not be_empty
625     end
626
627     it 'should have an upload path' do
628       @drive.files.insert.media_upload.uri_template.should_not == nil
629     end
630
631     it 'should have a max file size' do
632       @drive.files.insert.media_upload.max_size.should_not == nil
633     end
634   end
635 end