Nuke it from orbit, it's the only way to be sure

This commit is contained in:
Steven Bazyl committed 2015-04-16 17:21:38 -07:00
1 parent 82f69445ad
commit 9b7809174d
72 files changed
-11948

No files matched your search

-122
View File
@@ -1,122 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::Storage do
let(:client) { Google::APIClient.new(:application_name => 'API Client Tests') }
let(:root_path) { File.expand_path(File.join(__FILE__, '..', '..', '..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:store) { double }
let(:client_stub) { double }
subject { Google::APIClient::Storage.new(store) }
describe 'authorize' do
it 'should authorize' do
expect(subject).to respond_to(:authorization)
expect(subject.store).to be == store
end
end
describe 'authorize' do
describe 'with credentials' do
it 'should initialize a new OAuth Client' do
expect(subject).to receive(:load_credentials).and_return({:first => 'a dummy'})
expect(client_stub).to receive(:issued_at=)
expect(client_stub).to receive(:expired?).and_return(false)
expect(Signet::OAuth2::Client).to receive(:new).and_return(client_stub)
expect(subject).not_to receive(:refresh_authorization)
subject.authorize
end
it 'should refresh authorization' do
expect(subject).to receive(:load_credentials).and_return({:first => 'a dummy'})
expect(client_stub).to receive(:issued_at=)
expect(client_stub).to receive(:expired?).and_return(true)
expect(Signet::OAuth2::Client).to receive(:new).and_return(client_stub)
expect(subject).to receive(:refresh_authorization)
auth = subject.authorize
expect(auth).to be == subject.authorization
expect(auth).not_to be_nil
end
end
describe 'without credentials' do
it 'should return nil' do
expect(subject.authorization).to be_nil
expect(subject).to receive(:load_credentials).and_return({})
expect(subject.authorize).to be_nil
expect(subject.authorization).to be_nil
end
end
end
describe 'write_credentials' do
it 'should call store to write credentials' do
authorization_stub = double
expect(authorization_stub).to receive(:refresh_token).and_return(true)
expect(subject).to receive(:credentials_hash)
expect(subject.store).to receive(:write_credentials)
subject.write_credentials(authorization_stub)
expect(subject.authorization).to be == authorization_stub
end
it 'should not call store to write credentials' do
expect(subject).not_to receive(:credentials_hash)
expect(subject.store).not_to receive(:write_credentials)
expect {
subject.write_credentials()
}.not_to raise_error
end
it 'should not call store to write credentials' do
expect(subject).not_to receive(:credentials_hash)
expect(subject.store).not_to receive(:write_credentials)
expect {
subject.write_credentials('something')
}.not_to raise_error
end
end
describe 'refresh_authorization' do
it 'should call refresh and write credentials' do
expect(subject).to receive(:write_credentials)
authorization_stub = double
expect(subject).to receive(:authorization).and_return(authorization_stub)
expect(authorization_stub).to receive(:refresh!).and_return(true)
subject.refresh_authorization
end
end
describe 'load_credentials' do
it 'should call store to load credentials' do
expect(subject.store).to receive(:load_credentials)
subject.send(:load_credentials)
end
end
describe 'credentials_hash' do
it 'should return an hash' do
authorization_stub = double
expect(authorization_stub).to receive(:access_token)
expect(authorization_stub).to receive(:client_id)
expect(authorization_stub).to receive(:client_secret)
expect(authorization_stub).to receive(:expires_in)
expect(authorization_stub).to receive(:refresh_token)
expect(authorization_stub).to receive(:issued_at).and_return('100')
allow(subject).to receive(:authorization).and_return(authorization_stub)
credentials = subject.send(:credentials_hash)
expect(credentials).to include(:access_token)
expect(credentials).to include(:authorization_uri)
expect(credentials).to include(:client_id)
expect(credentials).to include(:client_secret)
expect(credentials).to include(:expires_in)
expect(credentials).to include(:refresh_token)
expect(credentials).to include(:token_credential_uri)
expect(credentials).to include(:issued_at)
end
end
end
@@ -1,40 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::FileStore do
let(:root_path) { File.expand_path(File.join(__FILE__, '..','..','..', '..','..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:credentials_hash) {{
"access_token"=>"my_access_token",
"authorization_uri"=>"https://accounts.google.com/o/oauth2/auth",
"client_id"=>"123456_test_client_id@.apps.googleusercontent.com",
"client_secret"=>"123456_client_secret",
"expires_in"=>3600,
"refresh_token"=>"my_refresh_token",
"token_credential_uri"=>"https://accounts.google.com/o/oauth2/token",
"issued_at"=>1384440275
}}
subject{Google::APIClient::FileStore.new('a file path')}
it 'should have a path' do
expect(subject.path).to be == 'a file path'
subject.path = 'an other file path'
expect(subject.path).to be == 'an other file path'
end
it 'should load credentials' do
subject.path = json_file
credentials = subject.load_credentials
expect(credentials).to include('access_token', 'authorization_uri', 'refresh_token')
end
it 'should write credentials' do
io_stub = StringIO.new
expect(subject).to receive(:open).and_return(io_stub)
subject.write_credentials(credentials_hash)
end
end
@@ -1,70 +0,0 @@
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/version'
describe Google::APIClient::RedisStore do
let(:root_path) { File.expand_path(File.join(__FILE__, '..', '..', '..', '..', '..')) }
let(:json_file) { File.expand_path(File.join(root_path, 'fixtures', 'files', 'auth_stored_credentials.json')) }
let(:redis) {double}
let(:credentials_hash) { {
"access_token" => "my_access_token",
"authorization_uri" => "https://accounts.google.com/o/oauth2/auth",
"client_id" => "123456_test_client_id@.apps.googleusercontent.com",
"client_secret" => "123456_client_secret",
"expires_in" => 3600,
"refresh_token" => "my_refresh_token",
"token_credential_uri" => "https://accounts.google.com/o/oauth2/token",
"issued_at" => 1384440275
} }
subject { Google::APIClient::RedisStore.new('a redis instance') }
it 'should have a redis instance' do
expect(subject.redis).to be == 'a redis instance'
subject.redis = 'an other redis instance'
expect(subject.redis).to be == 'an other redis instance'
end
describe 'load_credentials' do
it 'should load credentials' do
subject.redis= redis
expect(redis).to receive(:get).and_return(credentials_hash.to_json)
expect(subject.load_credentials).to be == credentials_hash
end
it 'should return nil' do
subject.redis= redis
expect(redis).to receive(:get).and_return(nil)
expect(subject.load_credentials).to be_nil
end
end
describe 'redis_credentials_key' do
context 'without given key' do
it 'should return default key' do
expect(subject.redis_credentials_key).to be == "google_api_credentials"
end
end
context 'with given key' do
let(:redis_store) { Google::APIClient::RedisStore.new('a redis instance', 'another_google_api_credentials') }
it 'should use given key' do
expect(redis_store.redis_credentials_key).to be == "another_google_api_credentials"
end
end
end
describe 'write credentials' do
it 'should write credentials' do
subject.redis= redis
expect(redis).to receive(:set).and_return('ok')
expect(subject.write_credentials(credentials_hash)).to be_truthy
end
end
end
-248
View File
@@ -1,248 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::BatchRequest do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
it 'should raise an error if making an empty batch request' do
batch = Google::APIClient::BatchRequest.new
expect(lambda do
CLIENT.execute(batch)
end).to raise_error(Google::APIClient::BatchError)
end
it 'should allow query parameters in batch requests' do
batch = Google::APIClient::BatchRequest.new
batch.add(:uri => 'https://example.com', :parameters => {
'a' => '12345'
})
method, uri, headers, body = batch.to_http_request
expect(body.read).to include("/?a=12345")
end
describe 'with the discovery API' do
before do
CLIENT.authorization = nil
@discovery = CLIENT.discovered_api('discovery', 'v1')
end
describe 'with two valid requests' do
before do
@call1 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'plus',
'version' => 'v1'
}
}
@call2 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'discovery',
'version' => 'v1'
}
}
end
it 'should execute both when using a global callback' do
block_called = 0
ids = ['first_call', 'second_call']
expected_ids = ids.clone
batch = Google::APIClient::BatchRequest.new do |result|
block_called += 1
expect(result.status).to eq(200)
expect(expected_ids).to include(result.response.call_id)
expected_ids.delete(result.response.call_id)
end
batch.add(@call1, ids[0])
batch.add(@call2, ids[1])
CLIENT.execute(batch)
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
batch = Google::APIClient::BatchRequest.new
call1_returned, call2_returned = false, false
batch.add(@call1) do |result|
call1_returned = true
expect(result.status).to eq(200)
end
batch.add(@call2) do |result|
call2_returned = true
expect(result.status).to eq(200)
end
CLIENT.execute(batch)
expect(call1_returned).to be_truthy
expect(call2_returned).to be_truthy
end
it 'should raise an error if using the same call ID more than once' do
batch = Google::APIClient::BatchRequest.new
expect(lambda do
batch.add(@call1, 'my_id')
batch.add(@call2, 'my_id')
end).to raise_error(Google::APIClient::BatchError)
end
end
describe 'with a valid request and an invalid one' do
before do
@call1 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 'plus',
'version' => 'v1'
}
}
@call2 = {
:api_method => @discovery.apis.get_rest,
:parameters => {
'api' => 0,
'version' => 1
}
}
end
it 'should execute both when using a global callback' do
block_called = 0
ids = ['first_call', 'second_call']
expected_ids = ids.clone
batch = Google::APIClient::BatchRequest.new do |result|
block_called += 1
expect(expected_ids).to include(result.response.call_id)
expected_ids.delete(result.response.call_id)
if result.response.call_id == ids[0]
expect(result.status).to eq(200)
else
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
end
batch.add(@call1, ids[0])
batch.add(@call2, ids[1])
CLIENT.execute(batch)
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
batch = Google::APIClient::BatchRequest.new
call1_returned, call2_returned = false, false
batch.add(@call1) do |result|
call1_returned = true
expect(result.status).to eq(200)
end
batch.add(@call2) do |result|
call2_returned = true
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
CLIENT.execute(batch)
expect(call1_returned).to be_truthy
expect(call2_returned).to be_truthy
end
end
end
describe 'with the calendar API' do
before do
CLIENT.authorization = nil
@calendar = CLIENT.discovered_api('calendar', 'v3')
end
describe 'with two valid requests' do
before do
event1 = {
'summary' => 'Appointment 1',
'location' => 'Somewhere',
'start' => {
'dateTime' => '2011-01-01T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2011-01-01T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'myemail@mydomain.tld'
}
]
}
event2 = {
'summary' => 'Appointment 2',
'location' => 'Somewhere as well',
'start' => {
'dateTime' => '2011-01-02T10:00:00.000-07:00'
},
'end' => {
'dateTime' => '2011-01-02T10:25:00.000-07:00'
},
'attendees' => [
{
'email' => 'myemail@mydomain.tld'
}
]
}
@call1 = {
:api_method => @calendar.events.insert,
:parameters => {'calendarId' => 'myemail@mydomain.tld'},
:body => MultiJson.dump(event1),
:headers => {'Content-Type' => 'application/json'}
}
@call2 = {
:api_method => @calendar.events.insert,
:parameters => {'calendarId' => 'myemail@mydomain.tld'},
:body => MultiJson.dump(event2),
:headers => {'Content-Type' => 'application/json'}
}
end
it 'should convert to a correct HTTP request' do
batch = Google::APIClient::BatchRequest.new { |result| }
batch.add(@call1, '1').add(@call2, '2')
request = batch.to_env(CLIENT.connection)
boundary = Google::APIClient::BatchRequest::BATCH_BOUNDARY
expect(request[:method].to_s.downcase).to eq('post')
expect(request[:url].to_s).to eq('https://www.googleapis.com/batch')
expect(request[:request_headers]['Content-Type']).to eq("multipart/mixed;boundary=#{boundary}")
body = request[:body].read
expect(body).to include(@call1[:body])
expect(body).to include(@call2[:body])
end
end
end
end
@@ -1,53 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client/client_secrets'
FIXTURES_PATH = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::ClientSecrets do
context 'with JSON file' do
let(:file) { File.join(FIXTURES_PATH, 'files', 'client_secrets.json') }
subject(:secrets) { Google::APIClient::ClientSecrets.load(file)}
it 'should load the correct client ID' do
expect(secrets.client_id).to be == '898243283568.apps.googleusercontent.com'
end
it 'should load the correct client secret' do
expect(secrets.client_secret).to be == 'i8YaXdGgiQ4_KrTVNGsB7QP1'
end
context 'serialzed to hash' do
subject(:hash) { secrets.to_hash }
it 'should contain the flow as the first key' do
expect(hash).to have_key "installed"
end
it 'should contain the client ID' do
expect(hash["installed"]["client_id"]).to be == '898243283568.apps.googleusercontent.com'
end
it 'should contain the client secret' do
expect(hash["installed"]["client_secret"]).to be == 'i8YaXdGgiQ4_KrTVNGsB7QP1'
end
end
end
end
-708
View File
@@ -1,708 +0,0 @@
# encoding:utf-8
# Copyright 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'faraday'
require 'multi_json'
require 'compat/multi_json'
require 'signet/oauth_1/client'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient do
include ConnectionHelpers
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
it 'should raise a type error for bogus authorization' do
expect(lambda do
Google::APIClient.new(:application_name => 'API Client Tests', :authorization => 42)
end).to raise_error(TypeError)
end
it 'should not be able to retrieve the discovery document for a bogus API' do
expect(lambda do
CLIENT.discovery_document('bogus')
end).to raise_error(Google::APIClient::TransmissionError)
expect(lambda do
CLIENT.discovered_api('bogus')
end).to raise_error(Google::APIClient::TransmissionError)
end
it 'should raise an error for bogus services' do
expect(lambda do
CLIENT.discovered_api(42)
end).to raise_error(TypeError)
end
it 'should raise an error for bogus services' do
expect(lambda do
CLIENT.preferred_version(42)
end).to raise_error(TypeError)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.execute(42)
end).to raise_error(TypeError)
end
it 'should not return a preferred version for bogus service names' do
expect(CLIENT.preferred_version('bogus')).to eq(nil)
end
describe 'with zoo API' do
it 'should return API instance registered from file' do
zoo_json = File.join(fixtures_path, 'files', 'zoo.json')
contents = File.open(zoo_json, 'rb') { |io| io.read }
api = CLIENT.register_discovery_document('zoo', 'v1', contents)
expect(api).to be_kind_of(Google::APIClient::API)
end
end
describe 'with the prediction API' do
before do
CLIENT.authorization = nil
# The prediction API no longer exposes a v1, so we have to be
# careful about looking up the wrong API version.
@prediction = CLIENT.discovered_api('prediction', 'v1.2')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('prediction')).to be ===
'https://www.googleapis.com/discovery/v1/apis/prediction/v1/rest'
end
it 'should correctly determine the discovery URI if :user_ip is set' do
CLIENT.user_ip = '127.0.0.1'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?userIp=127.0.0.1') do |env|
[200, {}, '{}']
end
end
CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly determine the discovery URI if :key is set' do
CLIENT.key = 'qwerty'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly determine the discovery URI if both are set' do
CLIENT.key = 'qwerty'
CLIENT.user_ip = '127.0.0.1'
conn = stub_connection do |stub|
stub.get('/discovery/v1/apis/prediction/v1.2/rest?key=qwerty&userIp=127.0.0.1') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:http_method => 'GET',
:uri => CLIENT.discovery_uri('prediction', 'v1.2'),
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly generate API objects' do
expect(CLIENT.discovered_api('prediction', 'v1.2').name).to eq('prediction')
expect(CLIENT.discovered_api('prediction', 'v1.2').version).to eq('v1.2')
expect(CLIENT.discovered_api(:prediction, 'v1.2').name).to eq('prediction')
expect(CLIENT.discovered_api(:prediction, 'v1.2').version).to eq('v1.2')
end
it 'should discover methods' do
expect(CLIENT.discovered_method(
'prediction.training.insert', 'prediction', 'v1.2'
).name).to eq('insert')
expect(CLIENT.discovered_method(
:'prediction.training.insert', :prediction, 'v1.2'
).name).to eq('insert')
expect(CLIENT.discovered_method(
'prediction.training.delete', 'prediction', 'v1.2'
).name).to eq('delete')
end
it 'should define the origin API in discovered methods' do
expect(CLIENT.discovered_method(
'prediction.training.insert', 'prediction', 'v1.2'
).api.name).to eq('prediction')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method(
'prediction.bogus', 'prediction', 'v1.2'
)).to eq(nil)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.discovered_method(42, 'prediction', 'v1.2')
end).to raise_error(TypeError)
end
it 'should raise an error for bogus methods' do
expect(lambda do
CLIENT.execute(:api_method => CLIENT.discovered_api('prediction', 'v1.2'))
end).to raise_error(TypeError)
end
it 'should correctly determine the preferred version' do
expect(CLIENT.preferred_version('prediction').version).not_to eq('v1')
expect(CLIENT.preferred_version(:prediction).version).not_to eq('v1')
end
it 'should return a batch path' do
expect(CLIENT.discovered_api('prediction', 'v1.2').batch_path).not_to be_nil
end
it 'should generate valid requests' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:body]).to eq('')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate valid requests when parameter value includes semicolon' do
conn = stub_connection do |stub|
# semicolon (;) in parameter value was being converted to
# bare ampersand (&) in 0.4.7. ensure that it gets converted
# to a CGI-escaped semicolon (%3B) instead.
stub.post('/prediction/v1.2/training?data=12345%3B67890') do |env|
expect(env[:body]).to eq('')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345;67890'},
:connection => conn
)
conn.verify
end
it 'should generate valid requests when multivalued parameters are passed' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=1&data=2') do |env|
expect(env.params['data']).to include('1', '2')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => ['1', '2']},
:connection => conn
)
conn.verify
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should allow modification to the base URIs for testing purposes' do
# Using a new client instance here to avoid caching rebased discovery doc
prediction_rebase =
Google::APIClient.new(:application_name => 'API Client Tests').discovered_api('prediction', 'v1.2')
prediction_rebase.method_base =
'https://testing-domain.example.com/prediction/v1.2/'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training') do |env|
expect(env[:url].host).to eq('testing-domain.example.com')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => prediction_rebase.training.insert,
:parameters => {'data' => '123'},
:connection => conn
)
conn.verify
end
it 'should generate OAuth 1 requests' do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:request_headers]).to have_key('Authorization')
expect(env[:request_headers]['Authorization']).to match(/^OAuth/)
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should generate OAuth 2 requests' do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training?data=12345') do |env|
expect(env[:request_headers]).to have_key('Authorization')
expect(env[:request_headers]['Authorization']).to match(/^Bearer/)
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @prediction.training.insert,
:parameters => {'data' => '12345'},
:connection => conn
)
conn.verify
end
it 'should not be able to execute improperly authorized requests' do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
result = CLIENT.execute(
@prediction.training.insert,
{'data' => '12345'}
)
expect(result.response.status).to eq(401)
end
it 'should not be able to execute improperly authorized requests' do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
result = CLIENT.execute(
@prediction.training.insert,
{'data' => '12345'}
)
expect(result.response.status).to eq(401)
end
it 'should not be able to execute improperly authorized requests' do
expect(lambda do
CLIENT.authorization = :oauth_1
CLIENT.authorization.token_credential_key = '12345'
CLIENT.authorization.token_credential_secret = '12345'
result = CLIENT.execute!(
@prediction.training.insert,
{'data' => '12345'}
)
end).to raise_error(Google::APIClient::ClientError)
end
it 'should not be able to execute improperly authorized requests' do
expect(lambda do
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
result = CLIENT.execute!(
@prediction.training.insert,
{'data' => '12345'}
)
end).to raise_error(Google::APIClient::ClientError)
end
it 'should correctly handle unnamed parameters' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.2/training') do |env|
expect(env[:request_headers]).to have_key('Content-Type')
expect(env[:request_headers]['Content-Type']).to eq('application/json')
[200, {}, '{}']
end
end
CLIENT.authorization = :oauth_2
CLIENT.authorization.access_token = '12345'
CLIENT.execute(
:api_method => @prediction.training.insert,
:body => MultiJson.dump({"id" => "bucket/object"}),
:headers => {'Content-Type' => 'application/json'},
:connection => conn
)
conn.verify
end
end
describe 'with the plus API' do
before do
CLIENT.authorization = nil
@plus = CLIENT.discovered_api('plus')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('plus')).to be ===
'https://www.googleapis.com/discovery/v1/apis/plus/v1/rest'
end
it 'should find APIs that are in the discovery document' do
expect(CLIENT.discovered_api('plus').name).to eq('plus')
expect(CLIENT.discovered_api('plus').version).to eq('v1')
expect(CLIENT.discovered_api(:plus).name).to eq('plus')
expect(CLIENT.discovered_api(:plus).version).to eq('v1')
end
it 'should find methods that are in the discovery document' do
# TODO(bobaman) Fix this when the RPC names are correct
expect(CLIENT.discovered_method(
'plus.activities.list', 'plus'
).name).to eq('list')
end
it 'should define the origin API in discovered methods' do
expect(CLIENT.discovered_method(
'plus.activities.list', 'plus'
).api.name).to eq('plus')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method('plus.bogus', 'plus')).to eq(nil)
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/plus/v1/people/107807692475771887386/activities/public') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {
'userId' => '107807692475771887386', 'collection' => 'public'
},
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should correctly validate parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {'alt' => 'json'},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should correctly validate parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @plus.activities.list,
:parameters => {
'userId' => '107807692475771887386', 'collection' => 'bogus'
},
:authenticated => false
).to_env(CLIENT.connection)
end).to raise_error(ArgumentError)
end
it 'should correctly determine the service root_uri' do
expect(@plus.root_uri.to_s).to eq('https://www.googleapis.com/')
end
end
describe 'with the adsense API' do
before do
CLIENT.authorization = nil
@adsense = CLIENT.discovered_api('adsense', 'v1.3')
end
it 'should correctly determine the discovery URI' do
expect(CLIENT.discovery_uri('adsense', 'v1.3').to_s).to be ===
'https://www.googleapis.com/discovery/v1/apis/adsense/v1.3/rest'
end
it 'should find APIs that are in the discovery document' do
expect(CLIENT.discovered_api('adsense', 'v1.3').name).to eq('adsense')
expect(CLIENT.discovered_api('adsense', 'v1.3').version).to eq('v1.3')
end
it 'should return a batch path' do
expect(CLIENT.discovered_api('adsense', 'v1.3').batch_path).not_to be_nil
end
it 'should find methods that are in the discovery document' do
expect(CLIENT.discovered_method(
'adsense.reports.generate', 'adsense', 'v1.3'
).name).to eq('generate')
end
it 'should not find methods that are not in the discovery document' do
expect(CLIENT.discovered_method('adsense.bogus', 'adsense', 'v1.3')).to eq(nil)
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients') do |env|
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @adsense.adclients.list,
:authenticated => false,
:connection => conn
)
conn.verify
end
it 'should not be able to execute requests without authorization' do
result = CLIENT.execute(
:api_method => @adsense.adclients.list,
:authenticated => false
)
expect(result.response.status).to eq(401)
end
it 'should fail when validating missing required parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should succeed when validating parameters in a correct call' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&endDate=2010-01-01&metric=PAGE_VIEWS&startDate=2000-01-01') do |env|
[200, {}, '{}']
end
end
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => 'DATE',
'metric' => 'PAGE_VIEWS'
},
:authenticated => false,
:connection => conn
)
end).not_to raise_error
conn.verify
end
it 'should fail when validating parameters with invalid values' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => 'BAD_CHARACTERS=-&*(£&',
'metric' => 'PAGE_VIEWS'
},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should succeed when validating repeated parameters in a correct call' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
'&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
'startDate=2000-01-01') do |env|
[200, {}, '{}']
end
end
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'PRODUCT_CODE'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false,
:connection => conn
)
end).not_to raise_error
conn.verify
end
it 'should fail when validating incorrect repeated parameters' do
expect(lambda do
CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'BAD_CHARACTERS=-&*(£&'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false
)
end).to raise_error(ArgumentError)
end
it 'should generate valid requests when multivalued parameters are passed' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/reports?dimension=DATE&dimension=PRODUCT_CODE'+
'&endDate=2010-01-01&metric=CLICKS&metric=PAGE_VIEWS&'+
'startDate=2000-01-01') do |env|
expect(env.params['dimension']).to include('DATE', 'PRODUCT_CODE')
expect(env.params['metric']).to include('CLICKS', 'PAGE_VIEWS')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @adsense.reports.generate,
:parameters => {
'startDate' => '2000-01-01',
'endDate' => '2010-01-01',
'dimension' => ['DATE', 'PRODUCT_CODE'],
'metric' => ['PAGE_VIEWS', 'CLICKS']
},
:authenticated => false,
:connection => conn
)
conn.verify
end
end
describe 'with the Drive API' do
before do
CLIENT.authorization = nil
@drive = CLIENT.discovered_api('drive', 'v1')
end
it 'should include media upload info methods' do
expect(@drive.files.insert.media_upload).not_to eq(nil)
end
it 'should include accepted media types' do
expect(@drive.files.insert.media_upload.accepted_types).not_to be_empty
end
it 'should have an upload path' do
expect(@drive.files.insert.media_upload.uri_template).not_to eq(nil)
end
it 'should have a max file size' do
expect(@drive.files.insert.media_upload.max_size).not_to eq(nil)
end
end
describe 'with the Pub/Sub API' do
before do
CLIENT.authorization = nil
@pubsub = CLIENT.discovered_api('pubsub', 'v1beta2')
end
it 'should generate requests against the correct URIs' do
conn = stub_connection do |stub|
stub.get('/v1beta2/projects/12345/topics') do |env|
expect(env[:url].host).to eq('pubsub.googleapis.com')
[200, {}, '{}']
end
end
request = CLIENT.execute(
:api_method => @pubsub.projects.topics.list,
:parameters => {'project' => 'projects/12345'},
:connection => conn
)
conn.verify
end
it 'should correctly determine the service root_uri' do
expect(@pubsub.root_uri.to_s).to eq('https://pubsub.googleapis.com/')
end
it 'should discover correct method URIs' do
list = CLIENT.discovered_method(
"pubsub.projects.topics.list", "pubsub", "v1beta2"
)
expect(list.uri_template.pattern).to eq(
"https://pubsub.googleapis.com/v1beta2/{+project}/topics"
)
publish = CLIENT.discovered_method(
"pubsub.projects.topics.publish", "pubsub", "v1beta2"
)
expect(publish.uri_template.pattern).to eq(
"https://pubsub.googleapis.com/v1beta2/{+topic}:publish"
)
end
end
end
-98
View File
@@ -1,98 +0,0 @@
# Encoding: utf-8
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Gzip do
def create_connection(&block)
Faraday.new do |b|
b.response :charset
b.response :gzip
b.adapter :test do |stub|
stub.get '/', &block
end
end
end
it 'should ignore non-zipped content' do
conn = create_connection do |env|
[200, {}, 'Hello world']
end
result = conn.get('/')
expect(result.body).to eq("Hello world")
end
it 'should decompress gziped content' do
conn = create_connection do |env|
[200, { 'Content-Encoding' => 'gzip'}, Base64.decode64('H4sICLVGwlEAA3RtcADzSM3JyVcozy/KSeECANXgObcMAAAA')]
end
result = conn.get('/')
expect(result.body).to eq("Hello world\n")
end
it 'should inflate with the correct charset encoding' do
conn = create_connection do |env|
[200,
{ 'Content-Encoding' => 'deflate', 'Content-Type' => 'application/json;charset=BIG5'},
Base64.decode64('eJxb8nLp7t2VAA8fBCI=')]
end
result = conn.get('/')
expect(result.body.encoding).to eq(Encoding::BIG5)
expect(result.body).to eq('日本語'.encode("BIG5"))
end
describe 'with API Client' do
before do
@client = Google::APIClient.new(:application_name => 'test')
@client.authorization = nil
end
it 'should send gzip in user agent' do
conn = create_connection do |env|
agent = env[:request_headers]['User-Agent']
expect(agent).not_to be_nil
expect(agent).to include 'gzip'
[200, {}, 'Hello world']
end
@client.execute(:uri => 'http://www.example.com/', :connection => conn)
end
it 'should send gzip in accept-encoding' do
conn = create_connection do |env|
encoding = env[:request_headers]['Accept-Encoding']
expect(encoding).not_to be_nil
expect(encoding).to include 'gzip'
[200, {}, 'Hello world']
end
@client.execute(:uri => 'http://www.example.com/', :connection => conn)
end
it 'should not send gzip in accept-encoding if disabled for request' do
conn = create_connection do |env|
encoding = env[:request_headers]['Accept-Encoding']
expect(encoding).not_to include('gzip') unless encoding.nil?
[200, {}, 'Hello world']
end
response = @client.execute(:uri => 'http://www.example.com/', :gzip => false, :connection => conn)
puts response.status
end
end
end
-178
View File
@@ -1,178 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::UploadIO do
it 'should reject invalid file paths' do
expect(lambda do
media = Google::APIClient::UploadIO.new('doesnotexist', 'text/plain')
end).to raise_error
end
describe 'with a file' do
before do
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
end
it 'should report the correct file length' do
expect(@media.length).to eq(File.size(@file))
end
it 'should have a mime type' do
expect(@media.content_type).to eq('text/plain')
end
end
describe 'with StringIO' do
before do
@content = "hello world"
@media = Google::APIClient::UploadIO.new(StringIO.new(@content), 'text/plain', 'test.txt')
end
it 'should report the correct file length' do
expect(@media.length).to eq(@content.length)
end
it 'should have a mime type' do
expect(@media.content_type).to eq('text/plain')
end
end
end
RSpec.describe Google::APIClient::RangedIO do
before do
@source = StringIO.new("1234567890abcdef")
@io = Google::APIClient::RangedIO.new(@source, 1, 5)
end
it 'should return the correct range when read entirely' do
expect(@io.read).to eq("23456")
end
it 'should maintain position' do
expect(@io.read(1)).to eq('2')
expect(@io.read(2)).to eq('34')
expect(@io.read(2)).to eq('56')
end
it 'should allow rewinds' do
expect(@io.read(2)).to eq('23')
@io.rewind()
expect(@io.read(2)).to eq('23')
end
it 'should allow setting position' do
@io.pos = 3
expect(@io.read).to eq('56')
end
it 'should not allow position to be set beyond range' do
@io.pos = 10
expect(@io.read).to eq('')
end
it 'should return empty string when read amount is zero' do
expect(@io.read(0)).to eq('')
end
it 'should return empty string at EOF if amount is nil' do
@io.read
expect(@io.read).to eq('')
end
it 'should return nil at EOF if amount is positive int' do
@io.read
expect(@io.read(1)).to eq(nil)
end
end
RSpec.describe Google::APIClient::ResumableUpload do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
after do
# Reset client to not-quite-pristine state
CLIENT.key = nil
CLIENT.user_ip = nil
end
before do
@drive = CLIENT.discovered_api('drive', 'v1')
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
@uploader = Google::APIClient::ResumableUpload.new(
:media => @media,
:api_method => @drive.files.insert,
:uri => 'https://www.googleapis.com/upload/drive/v1/files/12345')
end
it 'should consider 20x status as complete' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(200))
expect(@uploader.complete?).to eq(true)
end
it 'should consider 30x status as incomplete' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(308))
expect(@uploader.complete?).to eq(false)
expect(@uploader.expired?).to eq(false)
end
it 'should consider 40x status as fatal' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(404))
expect(@uploader.expired?).to eq(true)
end
it 'should detect changes to location' do
request = @uploader.to_http_request
@uploader.process_http_response(mock_result(308, 'location' => 'https://www.googleapis.com/upload/drive/v1/files/abcdef'))
expect(@uploader.uri.to_s).to eq('https://www.googleapis.com/upload/drive/v1/files/abcdef')
end
it 'should resume from the saved range reported by the server' do
@uploader.chunk_size = 200
@uploader.to_http_request # Send bytes 0-199, only 0-99 saved
@uploader.process_http_response(mock_result(308, 'range' => '0-99'))
method, url, headers, body = @uploader.to_http_request # Send bytes 100-299
expect(headers['Content-Range']).to eq("bytes 100-299/#{@media.length}")
expect(headers['Content-length']).to eq("200")
end
it 'should resync the offset after 5xx errors' do
@uploader.chunk_size = 200
@uploader.to_http_request
@uploader.process_http_response(mock_result(500)) # Invalidates range
method, url, headers, body = @uploader.to_http_request # Resync
expect(headers['Content-Range']).to eq("bytes */#{@media.length}")
expect(headers['Content-length']).to eq("0")
@uploader.process_http_response(mock_result(308, 'range' => '0-99'))
method, url, headers, body = @uploader.to_http_request # Send next chunk at correct range
expect(headers['Content-Range']).to eq("bytes 100-299/#{@media.length}")
expect(headers['Content-length']).to eq("200")
end
def mock_result(status, headers = {})
reference = Google::APIClient::Reference.new(:api_method => @drive.files.insert)
double('result', :status => status, :headers => headers, :reference => reference)
end
end
-29
View File
@@ -1,29 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Request do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
it 'should normalize parameter names to strings' do
request = Google::APIClient::Request.new(:uri => 'https://www.google.com', :parameters => {
:a => '1', 'b' => '2'
})
expect(request.parameters['a']).to eq('1')
expect(request.parameters['b']).to eq('2')
end
end
-207
View File
@@ -1,207 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
RSpec.describe Google::APIClient::Result do
CLIENT = Google::APIClient.new(:application_name => 'API Client Tests') unless defined?(CLIENT)
describe 'with the plus API' do
before do
CLIENT.authorization = nil
@plus = CLIENT.discovered_api('plus', 'v1')
@reference = Google::APIClient::Reference.new({
:api_method => @plus.activities.list,
:parameters => {
'userId' => 'me',
'collection' => 'public',
'maxResults' => 20
}
})
@request = @reference.to_http_request
# Response double
@response = double("response")
allow(@response).to receive(:status).and_return(200)
allow(@response).to receive(:headers).and_return({
'etag' => '12345',
'x-google-apiary-auth-scopes' =>
'https://www.googleapis.com/auth/plus.me',
'content-type' => 'application/json; charset=UTF-8',
'date' => 'Mon, 23 Apr 2012 00:00:00 GMT',
'cache-control' => 'private, max-age=0, must-revalidate, no-transform',
'server' => 'GSE',
'connection' => 'close'
})
end
describe 'with a next page token' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"nextPageToken": "NEXT+PAGE+TOKEN",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"nextLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should indicate a successful response' do
expect(@result.error?).to be_falsey
end
it 'should return the correct next page token' do
expect(@result.next_page_token).to eq('NEXT+PAGE+TOKEN')
end
it 'should escape the next page token when calling next_page' do
reference = @result.next_page
expect(Hash[reference.parameters]).to include('pageToken')
expect(Hash[reference.parameters]['pageToken']).to eq('NEXT+PAGE+TOKEN')
url = reference.to_env(CLIENT.connection)[:url]
expect(url.to_s).to include('pageToken=NEXT%2BPAGE%2BTOKEN')
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.nextPageToken).to eq('NEXT+PAGE+TOKEN')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.nextLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?' +
'maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'without a next page token' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should not return a next page token' do
expect(@result.next_page_token).to eq(nil)
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'with JSON error response' do
before do
allow(@response).to receive(:body).and_return(
<<-END_OF_STRING
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
END_OF_STRING
)
allow(@response).to receive(:status).and_return(400)
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should return error status correctly' do
expect(@result.error?).to be_truthy
end
it 'should return the correct error message' do
expect(@result.error_message).to eq('Parse Error')
end
end
describe 'with 204 No Content response' do
before do
allow(@response).to receive(:body).and_return('')
allow(@response).to receive(:status).and_return(204)
allow(@response).to receive(:headers).and_return({})
@result = Google::APIClient::Result.new(@reference, @response)
end
it 'should indicate no data is available' do
expect(@result.data?).to be_falsey
end
it 'should return nil for data' do
expect(@result.data).to eq(nil)
end
it 'should return nil for media_type' do
expect(@result.media_type).to eq(nil)
end
end
end
end
@@ -1,169 +0,0 @@
# Copyright 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::KeyUtils do
it 'should read PKCS12 files from the filesystem' do
if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8')
pending "Reading from PKCS12 not supported on jruby 1.8.x"
end
path = File.expand_path('files/privatekey.p12', fixtures_path)
key = Google::APIClient::KeyUtils.load_from_pkcs12(path, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PKCS12 files from loaded files' do
if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8')
pending "Reading from PKCS12 not supported on jruby 1.8.x"
end
path = File.expand_path('files/privatekey.p12', fixtures_path)
content = File.read(path)
key = Google::APIClient::KeyUtils.load_from_pkcs12(content, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PEM files from the filesystem' do
path = File.expand_path('files/secret.pem', fixtures_path)
key = Google::APIClient::KeyUtils.load_from_pem(path, 'notasecret')
expect(key).not_to eq(nil)
end
it 'should read PEM files from loaded files' do
path = File.expand_path('files/secret.pem', fixtures_path)
content = File.read(path)
key = Google::APIClient::KeyUtils.load_from_pem(content, 'notasecret')
expect(key).not_to eq(nil)
end
end
RSpec.describe Google::APIClient::JWTAsserter do
include ConnectionHelpers
before do
@key = OpenSSL::PKey::RSA.new 2048
end
it 'should generate valid JWTs' do
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
jwt = asserter.to_authorization.to_jwt
expect(jwt).not_to eq(nil)
claim = JWT.decode(jwt, @key.public_key, true)
claim = claim[0] if claim[0]
expect(claim["iss"]).to eq('client1')
expect(claim["scope"]).to eq('scope1 scope2')
end
it 'should allow impersonation' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize('user1@email.com', { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.person).to eq('user1@email.com')
conn.verify
end
it 'should send valid access token request' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize(nil, { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.access_token).to eq("1/abcdef1234567890")
conn.verify
end
it 'should be refreshable' do
conn = stub_connection do |stub|
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
stub.post('/o/oauth2/token') do |env|
params = Addressable::URI.form_unencode(env[:body])
JWT.decode(params.assoc("assertion").last, @key.public_key)
expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer'])
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/0987654321fedcba",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key)
auth = asserter.authorize(nil, { :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth.access_token).to eq("1/abcdef1234567890")
auth.fetch_access_token!(:connection => conn)
expect(auth.access_token).to eq("1/0987654321fedcba")
conn.verify
end
end
RSpec.describe Google::APIClient::ComputeServiceAccount do
include ConnectionHelpers
it 'should query metadata server' do
conn = stub_connection do |stub|
stub.get('/computeMetadata/v1beta1/instance/service-accounts/default/token') do |env|
expect(env.url.host).to eq('metadata')
[200, {'content-type' => 'application/json'}, '{
"access_token" : "1/abcdef1234567890",
"token_type" : "Bearer",
"expires_in" : 3600
}']
end
end
service_account = Google::APIClient::ComputeServiceAccount.new
auth = service_account.fetch_access_token!({ :connection => conn })
expect(auth).not_to eq(nil?)
expect(auth["access_token"]).to eq("1/abcdef1234567890")
conn.verify
end
end
-618
View File
@@ -1,618 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client'
require 'google/api_client/service'
fixtures_path = File.expand_path('../../../fixtures', __FILE__)
RSpec.describe Google::APIClient::Service do
include ConnectionHelpers
APPLICATION_NAME = 'API Client Tests'
it 'should error out when called without an API name or version' do
expect(lambda do
Google::APIClient::Service.new
end).to raise_error(ArgumentError)
end
it 'should error out when called without an API version' do
expect(lambda do
Google::APIClient::Service.new('foo')
end).to raise_error(ArgumentError)
end
it 'should error out when the options hash is not a hash' do
expect(lambda do
Google::APIClient::Service.new('foo', 'v1', 42)
end).to raise_error(ArgumentError)
end
describe 'with the AdSense Management API' do
it 'should make a valid call for a method with no parameters' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.adclients.list.execute()
conn.verify
end
it 'should make a valid call for a method with parameters' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/adclients/1/adunits') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.adunits.list(:adClientId => '1').execute()
end
it 'should make a valid call for a deep method' do
conn = stub_connection do |stub|
stub.get('/adsense/v1.3/accounts/1/adclients') do |env|
[200, {}, '{}']
end
end
adsense = Google::APIClient::Service.new(
'adsense',
'v1.3',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = adsense.accounts.adclients.list(:accountId => '1').execute()
end
describe 'with no connection' do
before do
@adsense = Google::APIClient::Service.new('adsense', 'v1.3',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a resource when using a valid resource name' do
expect(@adsense.accounts).to be_a(Google::APIClient::Service::Resource)
end
it 'should throw an error when using an invalid resource name' do
expect(lambda do
@adsense.invalid_resource
end).to raise_error
end
it 'should return a request when using a valid method name' do
req = @adsense.adclients.list
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('adsense.adclients.list')
expect(req.parameters).to be_nil
end
it 'should throw an error when using an invalid method name' do
expect(lambda do
@adsense.adclients.invalid_method
end).to raise_error
end
it 'should return a valid request with parameters' do
req = @adsense.adunits.list(:adClientId => '1')
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('adsense.adunits.list')
expect(req.parameters).not_to be_nil
expect(req.parameters[:adClientId]).to eq('1')
end
end
end
describe 'with the Prediction API' do
it 'should make a valid call with an object body' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.5/trainedmodels?project=1') do |env|
expect(env.body).to eq('{"id":"1"}')
[200, {}, '{}']
end
end
prediction = Google::APIClient::Service.new(
'prediction',
'v1.5',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = prediction.trainedmodels.insert(:project => '1').body({'id' => '1'}).execute()
conn.verify
end
it 'should make a valid call with a text body' do
conn = stub_connection do |stub|
stub.post('/prediction/v1.5/trainedmodels?project=1') do |env|
expect(env.body).to eq('{"id":"1"}')
[200, {}, '{}']
end
end
prediction = Google::APIClient::Service.new(
'prediction',
'v1.5',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = prediction.trainedmodels.insert(:project => '1').body('{"id":"1"}').execute()
conn.verify
end
describe 'with no connection' do
before do
@prediction = Google::APIClient::Service.new('prediction', 'v1.5',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a valid request with a body' do
req = @prediction.trainedmodels.insert(:project => '1').body({'id' => '1'})
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('prediction.trainedmodels.insert')
expect(req.body).to eq({'id' => '1'})
expect(req.parameters).not_to be_nil
expect(req.parameters[:project]).to eq('1')
end
it 'should return a valid request with a body when using resource name' do
req = @prediction.trainedmodels.insert(:project => '1').training({'id' => '1'})
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('prediction.trainedmodels.insert')
expect(req.training).to eq({'id' => '1'})
expect(req.parameters).not_to be_nil
expect(req.parameters[:project]).to eq('1')
end
end
end
describe 'with the Drive API' do
before do
@metadata = {
'title' => 'My movie',
'description' => 'The best home movie ever made'
}
@file = File.expand_path('files/sample.txt', fixtures_path)
@media = Google::APIClient::UploadIO.new(@file, 'text/plain')
end
it 'should make a valid call with an object body and media upload' do
conn = stub_connection do |stub|
stub.post('/upload/drive/v1/files?uploadType=multipart') do |env|
expect(env.body).to be_a Faraday::CompositeReadIO
[200, {}, '{}']
end
end
drive = Google::APIClient::Service.new(
'drive',
'v1',
{
:application_name => APPLICATION_NAME,
:authenticated => false,
:connection => conn,
:cache_store => nil
}
)
req = drive.files.insert(:uploadType => 'multipart').body(@metadata).media(@media).execute()
conn.verify
end
describe 'with no connection' do
before do
@drive = Google::APIClient::Service.new('drive', 'v1',
{:application_name => APPLICATION_NAME, :cache_store => nil})
end
it 'should return a valid request with a body and media upload' do
req = @drive.files.insert(:uploadType => 'multipart').body(@metadata).media(@media)
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('drive.files.insert')
expect(req.body).to eq(@metadata)
expect(req.media).to eq(@media)
expect(req.parameters).not_to be_nil
expect(req.parameters[:uploadType]).to eq('multipart')
end
it 'should return a valid request with a body and media upload when using resource name' do
req = @drive.files.insert(:uploadType => 'multipart').file(@metadata).media(@media)
expect(req).to be_a(Google::APIClient::Service::Request)
expect(req.method.id).to eq('drive.files.insert')
expect(req.file).to eq(@metadata)
expect(req.media).to eq(@media)
expect(req.parameters).not_to be_nil
expect(req.parameters[:uploadType]).to eq('multipart')
end
end
end
describe 'with the Discovery API' do
it 'should make a valid end-to-end request' do
discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authenticated => false,
:cache_store => nil})
result = discovery.apis.get_rest(:api => 'discovery', :version => 'v1').execute
expect(result).not_to be_nil
expect(result.data.name).to eq('discovery')
expect(result.data.version).to eq('v1')
end
end
end
RSpec.describe Google::APIClient::Service::Result do
describe 'with the plus API' do
before do
@plus = Google::APIClient::Service.new('plus', 'v1',
{:application_name => APPLICATION_NAME, :cache_store => nil})
@reference = Google::APIClient::Reference.new({
:api_method => @plus.activities.list.method,
:parameters => {
'userId' => 'me',
'collection' => 'public',
'maxResults' => 20
}
})
@request = @plus.activities.list(:userId => 'me', :collection => 'public',
:maxResults => 20)
# Response double
@response = double("response")
allow(@response).to receive(:status).and_return(200)
allow(@response).to receive(:headers).and_return({
'etag' => '12345',
'x-google-apiary-auth-scopes' =>
'https://www.googleapis.com/auth/plus.me',
'content-type' => 'application/json; charset=UTF-8',
'date' => 'Mon, 23 Apr 2012 00:00:00 GMT',
'cache-control' => 'private, max-age=0, must-revalidate, no-transform',
'server' => 'GSE',
'connection' => 'close'
})
end
describe 'with a next page token' do
before do
@body = <<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"nextPageToken": "NEXT+PAGE+TOKEN",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"nextLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should indicate a successful response' do
expect(@result.error?).to be_falsey
end
it 'should return the correct next page token' do
expect(@result.next_page_token).to eq('NEXT+PAGE+TOKEN')
end
it 'generate a correct request when calling next_page' do
next_page_request = @result.next_page
expect(next_page_request.parameters).to include('pageToken')
expect(next_page_request.parameters['pageToken']).to eq('NEXT+PAGE+TOKEN')
@request.parameters.each_pair do |param, value|
expect(next_page_request.parameters[param]).to eq(value)
end
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.nextPageToken).to eq('NEXT+PAGE+TOKEN')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.nextLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?' +
'maxResults=20&pageToken=NEXT%2BPAGE%2BTOKEN'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'without a next page token' do
before do
@body = <<-END_OF_STRING
{
"kind": "plus#activityFeed",
"etag": "FOO",
"selfLink": "https://www.googleapis.com/plus/v1/people/foo/activities/public?",
"title": "Plus Public Activity Feed for ",
"updated": "2012-04-23T00:00:00.000Z",
"id": "123456790",
"items": []
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should not return a next page token' do
expect(@result.next_page_token).to eq(nil)
end
it 'should return content type correctly' do
expect(@result.media_type).to eq('application/json')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
it 'should return the result data correctly' do
expect(@result.data?).to be_truthy
expect(@result.data.class.to_s).to eq(
'Google::APIClient::Schema::Plus::V1::ActivityFeed'
)
expect(@result.data.kind).to eq('plus#activityFeed')
expect(@result.data.etag).to eq('FOO')
expect(@result.data.selfLink).to eq(
'https://www.googleapis.com/plus/v1/people/foo/activities/public?'
)
expect(@result.data.title).to eq('Plus Public Activity Feed for ')
expect(@result.data.id).to eq("123456790")
expect(@result.data.items).to be_empty
end
end
describe 'with JSON error response' do
before do
@body = <<-END_OF_STRING
{
"error": {
"errors": [
{
"domain": "global",
"reason": "parseError",
"message": "Parse Error"
}
],
"code": 400,
"message": "Parse Error"
}
}
END_OF_STRING
allow(@response).to receive(:body).and_return(@body)
allow(@response).to receive(:status).and_return(400)
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should return error status correctly' do
expect(@result.error?).to be_truthy
end
it 'should return the correct error message' do
expect(@result.error_message).to eq('Parse Error')
end
it 'should return the body correctly' do
expect(@result.body).to eq(@body)
end
end
describe 'with 204 No Content response' do
before do
allow(@response).to receive(:body).and_return('')
allow(@response).to receive(:status).and_return(204)
allow(@response).to receive(:headers).and_return({})
base_result = Google::APIClient::Result.new(@reference, @response)
@result = Google::APIClient::Service::Result.new(@request, base_result)
end
it 'should indicate no data is available' do
expect(@result.data?).to be_falsey
end
it 'should return nil for data' do
expect(@result.data).to eq(nil)
end
it 'should return nil for media_type' do
expect(@result.media_type).to eq(nil)
end
end
end
end
RSpec.describe Google::APIClient::Service::BatchRequest do
include ConnectionHelpers
context 'with a service connection' do
before do
@conn = stub_connection do |stub|
stub.post('/batch') do |env|
[500, {'Content-Type' => 'application/json'}, '{}']
end
end
@discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authorization => nil,
:cache_store => nil, :connection => @conn})
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'discovery', :version => 'v1')
]
end
it 'should use the service connection' do
batch = @discovery.batch(@calls) do
end
batch.execute
@conn.verify
end
end
describe 'with the discovery API' do
before do
@discovery = Google::APIClient::Service.new('discovery', 'v1',
{:application_name => APPLICATION_NAME, :authorization => nil,
:cache_store => nil})
end
describe 'with two valid requests' do
before do
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'discovery', :version => 'v1')
]
end
it 'should execute both when using a global callback' do
block_called = 0
batch = @discovery.batch(@calls) do |result|
block_called += 1
expect(result.status).to eq(200)
end
batch.execute
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
call1_returned, call2_returned = false, false
batch = @discovery.batch
batch.add(@calls[0]) do |result|
call1_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(0)
end
batch.add(@calls[1]) do |result|
call2_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(1)
end
batch.execute
expect(call1_returned).to eq(true)
expect(call2_returned).to eq(true)
end
end
describe 'with a valid request and an invalid one' do
before do
@calls = [
@discovery.apis.get_rest(:api => 'plus', :version => 'v1'),
@discovery.apis.get_rest(:api => 'invalid', :version => 'invalid')
]
end
it 'should execute both when using a global callback' do
block_called = 0
batch = @discovery.batch(@calls) do |result|
block_called += 1
if result.call_index == 0
expect(result.status).to eq(200)
else
expect(result.status).to be >= 400
expect(result.status).to be < 500
end
end
batch.execute
expect(block_called).to eq(2)
end
it 'should execute both when using individual callbacks' do
call1_returned, call2_returned = false, false
batch = @discovery.batch
batch.add(@calls[0]) do |result|
call1_returned = true
expect(result.status).to eq(200)
expect(result.call_index).to eq(0)
end
batch.add(@calls[1]) do |result|
call2_returned = true
expect(result.status).to be >= 400
expect(result.status).to be < 500
expect(result.call_index).to eq(1)
end
batch.execute
expect(call1_returned).to eq(true)
expect(call2_returned).to eq(true)
end
end
end
end
@@ -1,133 +0,0 @@
# encoding:utf-8
# Copyright 2013 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'spec_helper'
require 'google/api_client/service/simple_file_store'
RSpec.describe Google::APIClient::Service::SimpleFileStore do
FILE_NAME = 'test.cache'
describe 'with no cache file' do
before(:each) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
@cache = Google::APIClient::Service::SimpleFileStore.new(FILE_NAME)
end
it 'should return nil when asked if a key exists' do
expect(@cache.exist?('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should return nil when asked to read a key' do
expect(@cache.read('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should return nil when asked to fetch a key' do
expect(@cache.fetch('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
it 'should create a cache file when asked to fetch a key with a default' do
expect(@cache.fetch('new_key') do
'value'
end).to eq('value')
expect(File.exists?(FILE_NAME)).to be_truthy
end
it 'should create a cache file when asked to write a key' do
@cache.write('new_key', 'value')
expect(File.exists?(FILE_NAME)).to be_truthy
end
it 'should return nil when asked to delete a key' do
expect(@cache.delete('invalid')).to be_nil
expect(File.exists?(FILE_NAME)).to be_falsey
end
end
describe 'with an existing cache' do
before(:each) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
@cache = Google::APIClient::Service::SimpleFileStore.new(FILE_NAME)
@cache.write('existing_key', 'existing_value')
end
it 'should return true when asked if an existing key exists' do
expect(@cache.exist?('existing_key')).to be_truthy
end
it 'should return false when asked if a nonexistent key exists' do
expect(@cache.exist?('invalid')).to be_falsey
end
it 'should return the value for an existing key when asked to read it' do
expect(@cache.read('existing_key')).to eq('existing_value')
end
it 'should return nil for a nonexistent key when asked to read it' do
expect(@cache.read('invalid')).to be_nil
end
it 'should return the value for an existing key when asked to read it' do
expect(@cache.read('existing_key')).to eq('existing_value')
end
it 'should return nil for a nonexistent key when asked to fetch it' do
expect(@cache.fetch('invalid')).to be_nil
end
it 'should return and save the default value for a nonexistent key when asked to fetch it with a default' do
expect(@cache.fetch('new_key') do
'value'
end).to eq('value')
expect(@cache.read('new_key')).to eq('value')
end
it 'should remove an existing value and return true when asked to delete it' do
expect(@cache.delete('existing_key')).to be_truthy
expect(@cache.read('existing_key')).to be_nil
end
it 'should return false when asked to delete a nonexistent key' do
expect(@cache.delete('invalid')).to be_falsey
end
it 'should convert keys to strings when storing them' do
@cache.write(:symbol_key, 'value')
expect(@cache.read('symbol_key')).to eq('value')
end
it 'should convert keys to strings when reading them' do
expect(@cache.read(:existing_key)).to eq('existing_value')
end
it 'should convert keys to strings when fetching them' do
expect(@cache.fetch(:existing_key)).to eq('existing_value')
end
it 'should convert keys to strings when deleting them' do
expect(@cache.delete(:existing_key)).to be_truthy
expect(@cache.read('existing_key')).to be_nil
end
end
after(:all) do
File.delete(FILE_NAME) if File.exists?(FILE_NAME)
end
end