Add application name to client, update style of assigning client to match other recen...
[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 repeated parameters are passed' do
218       pending("This is caused by Faraday's encoding of query parameters.")
219       conn = stub_connection do |stub|
220          stub.post('/prediction/v1.2/training?data=1&data=2') do |env|
221            env[:params]['data'].should include('1', '2')
222          end
223        end
224       request = CLIENT.execute(
225         :api_method => @prediction.training.insert,
226         :parameters => [['data', '1'], ['data','2']],
227         :connection => conn
228       )
229       conn.verify
230     end
231
232     it 'should generate requests against the correct URIs' do
233       conn = stub_connection do |stub|
234          stub.post('/prediction/v1.2/training?data=12345') do |env|
235          end
236        end
237       request = CLIENT.execute(
238         :api_method => @prediction.training.insert,
239         :parameters => {'data' => '12345'},
240         :connection => conn
241       )
242       conn.verify
243     end
244
245     it 'should generate requests against the correct URIs' do
246       conn = stub_connection do |stub|
247         stub.post('/prediction/v1.2/training?data=12345') do |env|
248         end
249       end
250       request = CLIENT.execute(
251         :api_method => @prediction.training.insert,
252         :parameters => {'data' => '12345'},
253         :connection => conn
254       )
255       conn.verify
256     end
257
258     it 'should allow modification to the base URIs for testing purposes' do
259       # Using a new client instance here to avoid caching rebased discovery doc
260       prediction_rebase =
261         Google::APIClient.new(:application_name => 'API Client Tests').discovered_api('prediction', 'v1.2')
262       prediction_rebase.method_base =
263         'https://testing-domain.example.com/prediction/v1.2/'
264
265       conn = stub_connection do |stub|
266         stub.post('/prediction/v1.2/training') do |env|
267           env[:url].host.should == 'testing-domain.example.com'
268         end
269       end
270         
271       request = CLIENT.execute(
272         :api_method => prediction_rebase.training.insert,
273         :parameters => {'data' => '123'},
274         :connection => conn
275       )
276       conn.verify
277     end
278
279     it 'should generate OAuth 1 requests' do
280       CLIENT.authorization = :oauth_1
281       CLIENT.authorization.token_credential_key = '12345'
282       CLIENT.authorization.token_credential_secret = '12345'
283
284       conn = stub_connection do |stub|
285         stub.post('/prediction/v1.2/training?data=12345') do |env|
286           env[:request_headers].should have_key('Authorization')
287           env[:request_headers]['Authorization'].should =~ /^OAuth/
288         end
289       end
290
291       request = CLIENT.execute(
292         :api_method => @prediction.training.insert,
293         :parameters => {'data' => '12345'},
294         :connection => conn
295       )
296       conn.verify
297     end
298
299     it 'should generate OAuth 2 requests' do
300       CLIENT.authorization = :oauth_2
301       CLIENT.authorization.access_token = '12345'
302
303       conn = stub_connection do |stub|
304         stub.post('/prediction/v1.2/training?data=12345') do |env|
305           env[:request_headers].should have_key('Authorization')
306           env[:request_headers]['Authorization'].should =~ /^Bearer/
307         end
308       end
309
310       request = CLIENT.execute(
311         :api_method => @prediction.training.insert,
312         :parameters => {'data' => '12345'},
313         :connection => conn
314       )
315       conn.verify
316     end
317
318     it 'should not be able to execute improperly authorized requests' do
319       CLIENT.authorization = :oauth_1
320       CLIENT.authorization.token_credential_key = '12345'
321       CLIENT.authorization.token_credential_secret = '12345'
322       result = CLIENT.execute(
323         @prediction.training.insert,
324         {'data' => '12345'}
325       )
326       result.response.status.should == 401
327     end
328
329     it 'should not be able to execute improperly authorized requests' do
330       CLIENT.authorization = :oauth_2
331       CLIENT.authorization.access_token = '12345'
332       result = CLIENT.execute(
333         @prediction.training.insert,
334         {'data' => '12345'}
335       )
336       result.response.status.should == 401
337     end
338
339     it 'should not be able to execute improperly authorized requests' do
340       (lambda do
341         CLIENT.authorization = :oauth_1
342         CLIENT.authorization.token_credential_key = '12345'
343         CLIENT.authorization.token_credential_secret = '12345'
344         result = CLIENT.execute!(
345           @prediction.training.insert,
346           {'data' => '12345'}
347         )
348       end).should raise_error(Google::APIClient::ClientError)
349     end
350
351     it 'should not be able to execute improperly authorized requests' do
352       (lambda do
353         CLIENT.authorization = :oauth_2
354         CLIENT.authorization.access_token = '12345'
355         result = CLIENT.execute!(
356           @prediction.training.insert,
357           {'data' => '12345'}
358         )
359       end).should raise_error(Google::APIClient::ClientError)
360     end
361
362     it 'should correctly handle unnamed parameters' do
363       conn = stub_connection do |stub|
364         stub.post('/prediction/v1.2/training') do |env|
365           env[:request_headers].should have_key('Content-Type')
366           env[:request_headers]['Content-Type'].should == 'application/json'
367         end
368       end
369       CLIENT.authorization = :oauth_2
370       CLIENT.authorization.access_token = '12345'
371       CLIENT.execute(
372         :api_method => @prediction.training.insert,
373         :body => MultiJson.dump({"id" => "bucket/object"}),
374         :headers => {'Content-Type' => 'application/json'},
375         :connection => conn
376       )
377       conn.verify
378     end
379   end
380
381   describe 'with the plus API' do
382     before do
383       CLIENT.authorization = nil
384       @plus = CLIENT.discovered_api('plus')
385     end
386
387     it 'should correctly determine the discovery URI' do
388       CLIENT.discovery_uri('plus').should ===
389         'https://www.googleapis.com/discovery/v1/apis/plus/v1/rest'
390     end
391
392     it 'should find APIs that are in the discovery document' do
393       CLIENT.discovered_api('plus').name.should == 'plus'
394       CLIENT.discovered_api('plus').version.should == 'v1'
395       CLIENT.discovered_api(:plus).name.should == 'plus'
396       CLIENT.discovered_api(:plus).version.should == 'v1'
397     end
398
399     it 'should find methods that are in the discovery document' do
400       # TODO(bobaman) Fix this when the RPC names are correct
401       CLIENT.discovered_method(
402         'plus.activities.list', 'plus'
403       ).name.should == 'list'
404     end
405
406     it 'should define the origin API in discovered methods' do
407       CLIENT.discovered_method(
408         'plus.activities.list', 'plus'
409       ).api.name.should == 'plus'
410     end
411
412     it 'should not find methods that are not in the discovery document' do
413       CLIENT.discovered_method('plus.bogus', 'plus').should == nil
414     end
415
416     it 'should generate requests against the correct URIs' do
417       conn = stub_connection do |stub|
418         stub.get('/plus/v1/people/107807692475771887386/activities/public' +
419                   '?collection=public&userId=107807692475771887386') do |env|
420         end
421       end
422       
423       request = CLIENT.execute(
424         :api_method => @plus.activities.list,
425         :parameters => {
426           'userId' => '107807692475771887386', 'collection' => 'public'
427         },
428         :authenticated => false,
429         :connection => conn
430       )
431       conn.verify
432     end
433
434     it 'should correctly validate parameters' do
435       (lambda do
436         CLIENT.execute(
437           :api_method => @plus.activities.list,
438           :parameters => {'alt' => 'json'},
439           :authenticated => false
440         )
441       end).should raise_error(ArgumentError)
442     end
443
444     it 'should correctly validate parameters' do
445       (lambda do
446         CLIENT.execute(
447           :api_method => @plus.activities.list,
448           :parameters => {
449             'userId' => '107807692475771887386', 'collection' => 'bogus'
450           },
451           :authenticated => false
452         ).to_env(Faraday.default_connection)
453       end).should raise_error(ArgumentError)
454     end
455   end
456   
457 =begin
458   describe 'with the latitude API' do
459     before do
460       CLIENT.authorization = nil
461       @latitude = CLIENT.discovered_api('latitude')
462     end
463
464     it 'should correctly determine the discovery URI' do
465       CLIENT.discovery_uri('latitude').should ===
466         'https://www.googleapis.com/discovery/v1/apis/latitude/v1/rest'
467     end
468
469     it 'should find APIs that are in the discovery document' do
470       CLIENT.discovered_api('latitude').name.should == 'latitude'
471       CLIENT.discovered_api('latitude').version.should == 'v1'
472     end
473
474     it 'should return a batch path' do
475       CLIENT.discovered_api('latitude').batch_path.should_not be_nil
476     end
477
478     it 'should find methods that are in the discovery document' do
479       CLIENT.discovered_method(
480         'latitude.currentLocation.get', 'latitude'
481       ).name.should == 'get'
482     end
483
484     it 'should define the origin API in discovered methods' do
485       CLIENT.discovered_method(
486         'latitude.currentLocation.get', 'latitude'
487       ).api.name.should == 'latitude'
488     end
489
490     it 'should not find methods that are not in the discovery document' do
491       CLIENT.discovered_method('latitude.bogus', 'latitude').should == nil
492     end
493
494     it 'should generate requests against the correct URIs' do
495       request = CLIENT.generate_request(
496         :api_method => 'latitude.currentLocation.get',
497         :authenticated => false
498       )
499       request.to_env(Faraday.default_connection)[:url].to_s.should ===
500         'https://www.googleapis.com/latitude/v1/currentLocation'
501     end
502
503     it 'should generate requests against the correct URIs' do
504       request = CLIENT.generate_request(
505         :api_method => @latitude.current_location.get,
506         :authenticated => false
507       )
508       request.to_env(Faraday.default_connection)[:url].to_s.should ===
509         'https://www.googleapis.com/latitude/v1/currentLocation'
510     end
511
512     it 'should not be able to execute requests without authorization' do
513       result = CLIENT.execute(
514         :api_method => 'latitude.currentLocation.get',
515         :authenticated => false
516       )
517       result.response.status.should == 401
518     end
519   end
520 =end
521
522   describe 'with the moderator API' do
523     before do
524       CLIENT.authorization = nil
525       @moderator = CLIENT.discovered_api('moderator')
526     end
527
528     it 'should correctly determine the discovery URI' do
529       CLIENT.discovery_uri('moderator').should ===
530         'https://www.googleapis.com/discovery/v1/apis/moderator/v1/rest'
531     end
532
533     it 'should find APIs that are in the discovery document' do
534       CLIENT.discovered_api('moderator').name.should == 'moderator'
535       CLIENT.discovered_api('moderator').version.should == 'v1'
536     end
537
538     it 'should find methods that are in the discovery document' do
539       CLIENT.discovered_method(
540         'moderator.profiles.get', 'moderator'
541       ).name.should == 'get'
542     end
543
544     it 'should define the origin API in discovered methods' do
545       CLIENT.discovered_method(
546         'moderator.profiles.get', 'moderator'
547       ).api.name.should == 'moderator'
548     end
549
550     it 'should not find methods that are not in the discovery document' do
551       CLIENT.discovered_method('moderator.bogus', 'moderator').should == nil
552     end
553
554     it 'should return a batch path' do
555       CLIENT.discovered_api('moderator').batch_path.should_not be_nil
556     end
557
558     it 'should generate requests against the correct URIs' do
559       conn = stub_connection do |stub|
560         stub.get('/moderator/v1/profiles/@me') do |env|
561         end
562       end
563       request = CLIENT.execute(
564         :api_method => @moderator.profiles.get,
565         :authenticated => false,
566         :connection => conn
567       )
568       conn.verify
569     end
570
571     it 'should not be able to execute requests without authorization' do
572       result = CLIENT.execute(
573         @moderator.profiles.get,
574         {},
575         '',
576         [],
577         {:authenticated => false}
578       )
579       result.response.status.should == 401
580     end
581   end
582
583   describe 'with the adsense API' do
584     before do
585       CLIENT.authorization = nil
586       @adsense = CLIENT.discovered_api('adsense', 'v1')
587     end
588
589     it 'should correctly determine the discovery URI' do
590       CLIENT.discovery_uri('adsense').should ===
591         'https://www.googleapis.com/discovery/v1/apis/adsense/v1/rest'
592     end
593
594     it 'should find APIs that are in the discovery document' do
595       CLIENT.discovered_api('adsense').name.should == 'adsense'
596       CLIENT.discovered_api('adsense').version.should == 'v1'
597     end
598
599     it 'should return a batch path' do
600       CLIENT.discovered_api('adsense').batch_path.should_not be_nil
601     end
602
603     it 'should find methods that are in the discovery document' do
604       CLIENT.discovered_method(
605         'adsense.reports.generate', 'adsense'
606       ).name.should == 'generate'
607     end
608
609     it 'should not find methods that are not in the discovery document' do
610       CLIENT.discovered_method('adsense.bogus', 'adsense').should == nil
611     end
612
613     it 'should generate requests against the correct URIs' do
614       conn = stub_connection do |stub|
615         stub.get('/adsense/v1/adclients') do |env|
616         end
617       end
618       request = CLIENT.execute(
619         :api_method => @adsense.adclients.list,
620         :authenticated => false,
621         :connection => conn
622       )
623       conn.verify
624     end
625
626     it 'should not be able to execute requests without authorization' do
627       result = CLIENT.execute(
628         :api_method => @adsense.adclients.list,
629         :authenticated => false
630       )
631       result.response.status.should == 401
632     end
633
634     it 'should fail when validating missing required parameters' do
635       (lambda do
636         CLIENT.execute(
637           :api_method => @adsense.reports.generate,
638           :authenticated => false
639         )
640       end).should raise_error(ArgumentError)
641     end
642
643     it 'should succeed when validating parameters in a correct call' do
644       conn = stub_connection do |stub|
645         stub.get('/adsense/v1/reports?dimension=DATE&endDate=2010-01-01&metric=PAGE_VIEWS&startDate=2000-01-01') do |env|
646         end
647       end
648       (lambda do
649         CLIENT.execute(
650           :api_method => @adsense.reports.generate,
651           :parameters => {
652             'startDate' => '2000-01-01',
653             'endDate' => '2010-01-01',
654             'dimension' => 'DATE',
655             'metric' => 'PAGE_VIEWS'
656           },
657           :authenticated => false,
658           :connection => conn
659         )
660       end).should_not raise_error
661       conn.verify
662     end
663
664     it 'should fail when validating parameters with invalid values' do
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' => 'BAD_CHARACTERS=-&*(£&',
672             'metric' => 'PAGE_VIEWS'
673           },
674           :authenticated => false
675         )
676       end).should raise_error(ArgumentError)
677     end
678
679     it 'should succeed when validating repeated parameters in a correct call' do
680       conn = stub_connection do |stub|
681         stub.get('/adsense/v1/reports?dimension%5B%5D=DATE&dimension%5B%5D=PRODUCT_CODE'+
682                  '&endDate=2010-01-01&metric%5B%5D=CLICKS&metric%5B%5D=PAGE_VIEWS&'+
683                  'startDate=2000-01-01') do |env|
684         end
685       end
686       (lambda do
687         CLIENT.execute(
688           :api_method => @adsense.reports.generate,
689           :parameters => {
690             'startDate' => '2000-01-01',
691             'endDate' => '2010-01-01',
692             'dimension' => ['DATE', 'PRODUCT_CODE'],
693             'metric' => ['PAGE_VIEWS', 'CLICKS']
694           },
695           :authenticated => false,
696           :connection => conn
697         )
698       end).should_not raise_error
699       conn.verify
700     end
701
702     it 'should fail when validating incorrect repeated parameters' do
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', 'BAD_CHARACTERS=-&*(£&'],
710             'metric' => ['PAGE_VIEWS', 'CLICKS']
711           },
712           :authenticated => false
713         )
714       end).should raise_error(ArgumentError)
715     end
716   end
717
718   describe 'with the Drive API' do
719     before do
720       CLIENT.authorization = nil
721       @drive = CLIENT.discovered_api('drive', 'v1')
722     end
723
724     it 'should include media upload info methods' do
725       @drive.files.insert.media_upload.should_not == nil
726     end
727
728     it 'should include accepted media types' do
729       @drive.files.insert.media_upload.accepted_types.should_not be_empty
730     end
731
732     it 'should have an upload path' do
733       @drive.files.insert.media_upload.uri_template.should_not == nil
734     end
735
736     it 'should have a max file size' do
737       @drive.files.insert.media_upload.max_size.should_not == nil
738     end
739   end
740 end