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