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