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 =begin
475   describe 'with the latitude API' do
476     before do
477       CLIENT.authorization = nil
478       @latitude = CLIENT.discovered_api('latitude')
479     end
480
481     it 'should correctly determine the discovery URI' do
482       CLIENT.discovery_uri('latitude').should ===
483         'https://www.googleapis.com/discovery/v1/apis/latitude/v1/rest'
484     end
485
486     it 'should find APIs that are in the discovery document' do
487       CLIENT.discovered_api('latitude').name.should == 'latitude'
488       CLIENT.discovered_api('latitude').version.should == 'v1'
489     end
490
491     it 'should return a batch path' do
492       CLIENT.discovered_api('latitude').batch_path.should_not be_nil
493     end
494
495     it 'should find methods that are in the discovery document' do
496       CLIENT.discovered_method(
497         'latitude.currentLocation.get', 'latitude'
498       ).name.should == 'get'
499     end
500
501     it 'should define the origin API in discovered methods' do
502       CLIENT.discovered_method(
503         'latitude.currentLocation.get', 'latitude'
504       ).api.name.should == 'latitude'
505     end
506
507     it 'should not find methods that are not in the discovery document' do
508       CLIENT.discovered_method('latitude.bogus', 'latitude').should == nil
509     end
510
511     it 'should generate requests against the correct URIs' do
512       request = CLIENT.generate_request(
513         :api_method => 'latitude.currentLocation.get',
514         :authenticated => false
515       )
516       request.to_env(Faraday.default_connection)[:url].to_s.should ===
517         'https://www.googleapis.com/latitude/v1/currentLocation'
518     end
519
520     it 'should generate requests against the correct URIs' do
521       request = CLIENT.generate_request(
522         :api_method => @latitude.current_location.get,
523         :authenticated => false
524       )
525       request.to_env(Faraday.default_connection)[:url].to_s.should ===
526         'https://www.googleapis.com/latitude/v1/currentLocation'
527     end
528
529     it 'should not be able to execute requests without authorization' do
530       result = CLIENT.execute(
531         :api_method => 'latitude.currentLocation.get',
532         :authenticated => false
533       )
534       result.response.status.should == 401
535     end
536   end
537 =end
538
539   describe 'with the moderator API' do
540     before do
541       CLIENT.authorization = nil
542       @moderator = CLIENT.discovered_api('moderator')
543     end
544
545     it 'should correctly determine the discovery URI' do
546       CLIENT.discovery_uri('moderator').should ===
547         'https://www.googleapis.com/discovery/v1/apis/moderator/v1/rest'
548     end
549
550     it 'should find APIs that are in the discovery document' do
551       CLIENT.discovered_api('moderator').name.should == 'moderator'
552       CLIENT.discovered_api('moderator').version.should == 'v1'
553     end
554
555     it 'should find methods that are in the discovery document' do
556       CLIENT.discovered_method(
557         'moderator.profiles.get', 'moderator'
558       ).name.should == 'get'
559     end
560
561     it 'should define the origin API in discovered methods' do
562       CLIENT.discovered_method(
563         'moderator.profiles.get', 'moderator'
564       ).api.name.should == 'moderator'
565     end
566
567     it 'should not find methods that are not in the discovery document' do
568       CLIENT.discovered_method('moderator.bogus', 'moderator').should == nil
569     end
570
571     it 'should return a batch path' do
572       CLIENT.discovered_api('moderator').batch_path.should_not be_nil
573     end
574
575     it 'should generate requests against the correct URIs' do
576       conn = stub_connection do |stub|
577         stub.get('/moderator/v1/profiles/@me') do |env|
578         end
579       end
580       request = CLIENT.execute(
581         :api_method => @moderator.profiles.get,
582         :authenticated => false,
583         :connection => conn
584       )
585       conn.verify
586     end
587
588     it 'should not be able to execute requests without authorization' do
589       result = CLIENT.execute(
590         @moderator.profiles.get,
591         {},
592         '',
593         [],
594         {:authenticated => false}
595       )
596       result.response.status.should == 401
597     end
598   end
599
600   describe 'with the adsense API' do
601     before do
602       CLIENT.authorization = nil
603       @adsense = CLIENT.discovered_api('adsense', 'v1')
604     end
605
606     it 'should correctly determine the discovery URI' do
607       CLIENT.discovery_uri('adsense').should ===
608         'https://www.googleapis.com/discovery/v1/apis/adsense/v1/rest'
609     end
610
611     it 'should find APIs that are in the discovery document' do
612       CLIENT.discovered_api('adsense').name.should == 'adsense'
613       CLIENT.discovered_api('adsense').version.should == 'v1'
614     end
615
616     it 'should return a batch path' do
617       CLIENT.discovered_api('adsense').batch_path.should_not be_nil
618     end
619
620     it 'should find methods that are in the discovery document' do
621       CLIENT.discovered_method(
622         'adsense.reports.generate', 'adsense'
623       ).name.should == 'generate'
624     end
625
626     it 'should not find methods that are not in the discovery document' do
627       CLIENT.discovered_method('adsense.bogus', 'adsense').should == nil
628     end
629
630     it 'should generate requests against the correct URIs' do
631       conn = stub_connection do |stub|
632         stub.get('/adsense/v1/adclients') do |env|
633         end
634       end
635       request = CLIENT.execute(
636         :api_method => @adsense.adclients.list,
637         :authenticated => false,
638         :connection => conn
639       )
640       conn.verify
641     end
642
643     it 'should not be able to execute requests without authorization' do
644       result = CLIENT.execute(
645         :api_method => @adsense.adclients.list,
646         :authenticated => false
647       )
648       result.response.status.should == 401
649     end
650
651     it 'should fail when validating missing required parameters' do
652       (lambda do
653         CLIENT.execute(
654           :api_method => @adsense.reports.generate,
655           :authenticated => false
656         )
657       end).should raise_error(ArgumentError)
658     end
659
660     it 'should succeed when validating parameters in a correct call' do
661       conn = stub_connection do |stub|
662         stub.get('/adsense/v1/reports?dimension=DATE&endDate=2010-01-01&metric=PAGE_VIEWS&startDate=2000-01-01') do |env|
663         end
664       end
665       (lambda do
666         CLIENT.execute(
667           :api_method => @adsense.reports.generate,
668           :parameters => {
669             'startDate' => '2000-01-01',
670             'endDate' => '2010-01-01',
671             'dimension' => 'DATE',
672             'metric' => 'PAGE_VIEWS'
673           },
674           :authenticated => false,
675           :connection => conn
676         )
677       end).should_not raise_error
678       conn.verify
679     end
680
681     it 'should fail when validating parameters with invalid values' do
682       (lambda do
683         CLIENT.execute(
684           :api_method => @adsense.reports.generate,
685           :parameters => {
686             'startDate' => '2000-01-01',
687             'endDate' => '2010-01-01',
688             'dimension' => 'BAD_CHARACTERS=-&*(£&',
689             'metric' => 'PAGE_VIEWS'
690           },
691           :authenticated => false
692         )
693       end).should raise_error(ArgumentError)
694     end
695
696     it 'should succeed when validating repeated parameters in a correct call' do
697       conn = stub_connection do |stub|
698         stub.get('/adsense/v1/reports?dimension%5B%5D=DATE&dimension%5B%5D=PRODUCT_CODE'+
699                  '&endDate=2010-01-01&metric%5B%5D=CLICKS&metric%5B%5D=PAGE_VIEWS&'+
700                  'startDate=2000-01-01') do |env|
701         end
702       end
703       (lambda do
704         CLIENT.execute(
705           :api_method => @adsense.reports.generate,
706           :parameters => {
707             'startDate' => '2000-01-01',
708             'endDate' => '2010-01-01',
709             'dimension' => ['DATE', 'PRODUCT_CODE'],
710             'metric' => ['PAGE_VIEWS', 'CLICKS']
711           },
712           :authenticated => false,
713           :connection => conn
714         )
715       end).should_not raise_error
716       conn.verify
717     end
718
719     it 'should fail when validating incorrect repeated parameters' do
720       (lambda do
721         CLIENT.execute(
722           :api_method => @adsense.reports.generate,
723           :parameters => {
724             'startDate' => '2000-01-01',
725             'endDate' => '2010-01-01',
726             'dimension' => ['DATE', 'BAD_CHARACTERS=-&*(£&'],
727             'metric' => ['PAGE_VIEWS', 'CLICKS']
728           },
729           :authenticated => false
730         )
731       end).should raise_error(ArgumentError)
732     end
733   end
734
735   describe 'with the Drive API' do
736     before do
737       CLIENT.authorization = nil
738       @drive = CLIENT.discovered_api('drive', 'v1')
739     end
740
741     it 'should include media upload info methods' do
742       @drive.files.insert.media_upload.should_not == nil
743     end
744
745     it 'should include accepted media types' do
746       @drive.files.insert.media_upload.accepted_types.should_not be_empty
747     end
748
749     it 'should have an upload path' do
750       @drive.files.insert.media_upload.uri_template.should_not == nil
751     end
752
753     it 'should have a max file size' do
754       @drive.files.insert.media_upload.max_size.should_not == nil
755     end
756   end
757 end