fog-aws-0.7.6/ 0000755 0000041 0000041 00000000000 12576636531 013135 5 ustar www-data www-data fog-aws-0.7.6/Rakefile 0000644 0000041 0000041 00000000240 12576636531 014576 0 ustar www-data www-data require "bundler/gem_tasks"
task :default => :test
mock = ENV['FOG_MOCK'] || 'true'
task :test do
sh("export FOG_MOCK=#{mock} && bundle exec shindont")
end
fog-aws-0.7.6/Gemfile 0000644 0000041 0000041 00000000306 12576636531 014427 0 ustar www-data www-data source 'https://rubygems.org'
# Specify your gem's dependencies in fog-aws.gemspec
gemspec
group :test, :default do
gem 'pry-nav'
end
gem "codeclimate-test-reporter", group: :test, require: nil
fog-aws-0.7.6/tests/ 0000755 0000041 0000041 00000000000 12576636531 014277 5 ustar www-data www-data fog-aws-0.7.6/tests/helper.rb 0000644 0000041 0000041 00000001427 12576636531 016107 0 ustar www-data www-data begin
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start
rescue LoadError => e
$stderr.puts "not recording test coverage: #{e.inspect}"
end
require File.expand_path('../../lib/fog/aws', __FILE__)
Bundler.require(:test)
Excon.defaults.merge!(:debug_request => true, :debug_response => true)
require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper'))
# This overrides the default 600 seconds timeout during live test runs
unless Fog.mocking?
Fog.timeout = ENV['FOG_TEST_TIMEOUT'] || 2_000
Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds"
end
def lorem_file
File.open(File.dirname(__FILE__) + '/lorem.txt', 'r')
end
def array_differences(array_a, array_b)
(array_a - array_b) | (array_b - array_a)
end
fog-aws-0.7.6/tests/lorem.txt 0000644 0000041 0000041 00000000676 12576636531 016167 0 ustar www-data www-data Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. fog-aws-0.7.6/tests/signaturev4_tests.rb 0000644 0000041 0000041 00000015135 12576636531 020326 0 ustar www-data www-data # encoding: utf-8
Shindo.tests('AWS | signaturev4', ['aws']) do
@now = Fog::Time.utc(2011,9,9,23,36,0)
# These testcases are from http://docs.amazonwebservices.com/general/latest/gr/signature-v4-test-suite.html
@signer = Fog::AWS::SignatureV4.new('AKIDEXAMPLE', 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', 'us-east-1','host')
tests('get-vanilla') do
returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'
end
end
tests('get-headers-mixed-case-headers') do
returns(@signer.sign({:headers => {'HOST' => 'host.foo.com', 'date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'
end
end
tests('get-vanilla-query-order-key with symbol keys') do
returns(@signer.sign({:query => {:'a' => 'foo', :'b' => 'foo'}, :headers => {:'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b'
end
end
tests('get-vanilla-query-order-key') do
returns(@signer.sign({:query => {'a' => 'foo', 'b' => 'foo'}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=0dc122f3b28b831ab48ba65cb47300de53fbe91b577fe113edac383730254a3b'
end
end
tests('get-unreserved') do
returns(@signer.sign({:headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/-._~0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=830cc36d03f0f84e6ee4953fbe701c1c8b71a0372c63af9255aa364dd183281e'
end
end
tests('post-x-www-form-urlencoded-parameter') do
returns(@signer.sign({:headers => {'Content-type' => 'application/x-www-form-urlencoded; charset=utf8', 'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :post, :path => '/',
:body => 'foo=bar'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=b105eb10c6d318d2294de9d49dd8b031b55e3c3fe139f2e637da70511e9e7b71'
end
end
tests('get with relative path') do
returns(@signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/foo/bar/../..'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'
end
end
tests('get with pointless .') do
returns(@signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/./foo'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=910e4d6c9abafaf87898e1eb4c929135782ea25bb0279703146455745391e63a'
end
end
tests('get with repeated / ') do
returns(@signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '//'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470'
end
end
tests('get with repeated // inside path') do
returns(@signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/foo//bar//baz'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b250c85c72c5d7c33f67759c7a1ad79ea381cf62105290cecd530af2771575d4'
end
end
tests('get with repeated trailing / ') do
returns(@signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '//foo//'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=date;host, Signature=b00392262853cfe3201e47ccf945601079e9b8a7f51ee4c3d9ee4f187aa9bf19'
end
end
tests('get signature as components') do
returns(@signer.signature_parameters({:query => {'a' => 'foo', 'b' => 'foo'}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now)) do
{
'X-Amz-Algorithm' => 'AWS4-HMAC-SHA256',
'X-Amz-Credential' => 'AKIDEXAMPLE/20110909/us-east-1/host/aws4_request',
'X-Amz-SignedHeaders' => 'date;host',
'X-Amz-Signature' => 'a6c6304682c74bcaebeeab2fdfb8041bbb39c6976300791a283057bccf333fb2'
}
end
end
tests("inject body sha") do
returns(@signer.signature_parameters({:query => {'a' => 'foo', 'b' => 'foo'}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '/'}, @now, 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD')) do
{
'X-Amz-Algorithm' => 'AWS4-HMAC-SHA256',
'X-Amz-Credential' => 'AKIDEXAMPLE/20110909/us-east-1/host/aws4_request',
'X-Amz-SignedHeaders' => 'date;host',
'X-Amz-Signature' => '22c32bb0d0b859b94839de4e9360bca1806e73d853f5f97ae0d849f0bdf42fb0'
}
end
end
tests("s3 signer does not normalize path") do
signer=Fog::AWS::SignatureV4.new('AKIDEXAMPLE', 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY', 'us-east-1','s3')
returns(signer.sign({:query => {}, :headers => {'Host' => 'host.foo.com', 'Date' => 'Mon, 09 Sep 2011 23:36:00 GMT'}, :method => :get, :path => '//foo/../bar/./'}, @now)) do
'AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/s3/aws4_request, SignedHeaders=date;host, Signature=72407ad06b8e5750360f42e8aad9f33a0be363bcfeecdcae0aea58c99709fb4a'
end
end
Fog::Time.now = ::Time.now
end
fog-aws-0.7.6/tests/requests/ 0000755 0000041 0000041 00000000000 12576636531 016152 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/sts/ 0000755 0000041 0000041 00000000000 12576636531 016763 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/sts/get_federation_token_tests.rb 0000644 0000041 0000041 00000001065 12576636531 024713 0 ustar www-data www-data Shindo.tests('AWS::STS | session tokens', ['aws']) do
@policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
@federation_format = {
'SessionToken' => String,
'SecretAccessKey' => String,
'Expiration' => String,
'AccessKeyId' => String,
'Arn' => String,
'FederatedUserId' => String,
'PackedPolicySize' => String,
'RequestId' => String
}
tests("#get_federation_token('test@fog.io', #{@policy.inspect})").formats(@federation_format) do
Fog::AWS[:sts].get_federation_token("test@fog.io", @policy).body
end
end
fog-aws-0.7.6/tests/requests/sts/assume_role_with_web_identity_tests.rb 0000644 0000041 0000041 00000001544 12576636531 026655 0 ustar www-data www-data Shindo.tests('AWS::STS | assume role with web identity', ['aws']) do
@sts = Fog::AWS[:sts]
@iam = Fog::AWS[:iam]
@role = @iam.create_role('sts', Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY).body['Role']
@token = Fog::AWS::Mock.key_id
@response_format = {
'AssumedRoleUser' => {
'Arn' => String,
'AssumedRoleId' => String,
},
'Audience' => String,
'Credentials' => {
'AccessKeyId' => String,
'Expiration' => Time,
'SecretAccessKey' => String,
'SessionToken' => String,
},
'Provider' => String,
'SubjectFromWebIdentityToken' => String,
}
tests("#assume_role_with_web_identity('#{@role['Arn']}', '#{@token}', 'fog')").formats(@response_format) do
@sts.assume_role_with_web_identity(@role['Arn'], @token, 'fog', :iam => @iam).body
end
end
fog-aws-0.7.6/tests/requests/sts/assume_role_tests.rb 0000644 0000041 0000041 00000001134 12576636531 023047 0 ustar www-data www-data Shindo.tests('AWS::STS | assume role', ['aws']) do
@policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
@response_format = {
'SessionToken' => String,
'SecretAccessKey' => String,
'Expiration' => String,
'AccessKeyId' => String,
'Arn' => String,
'RequestId' => String
}
tests("#assume_role('rolename', 'assumed_role_session', 'external_id', #{@policy.inspect}, 900)").formats(@response_format) do
pending if Fog.mocking?
Fog::AWS[:sts].assume_role("rolename","assumed_role_session","external_id", @policy, 900).body
end
end
fog-aws-0.7.6/tests/requests/sts/assume_role_with_saml_tests.rb 0000644 0000041 0000041 00000001217 12576636531 025120 0 ustar www-data www-data Shindo.tests('AWS::STS | assume role with SAML', ['aws']) do
@policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
@response_format = {
'SessionToken' => String,
'SecretAccessKey' => String,
'Expiration' => String,
'AccessKeyId' => String,
'Arn' => String,
'RequestId' => String
}
tests("#assume_role_with_saml('role_arn', 'principal_arn', 'saml_assertion', #{@policy.inspect}, 900)").formats(@response_format) do
pending if Fog.mocking?
Fog::AWS[:sts].assume_role_with_saml("role_arn","principal_arn","saml_assertion", @policy, 900).body
end
end
fog-aws-0.7.6/tests/requests/sts/session_token_tests.rb 0000644 0000041 0000041 00000000535 12576636531 023420 0 ustar www-data www-data Shindo.tests('AWS::STS | session tokens', ['aws']) do
@session_format = {
'SessionToken' => String,
'SecretAccessKey' => String,
'Expiration' => String,
'AccessKeyId' => String,
'RequestId' => String
}
tests("#get_session_token").formats(@session_format) do
pending if Fog.mocking?
Fog::AWS[:sts].get_session_token.body
end
end
fog-aws-0.7.6/tests/requests/sqs/ 0000755 0000041 0000041 00000000000 12576636531 016760 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/sqs/helper.rb 0000644 0000041 0000041 00000000212 12576636531 020557 0 ustar www-data www-data class AWS
module SQS
module Formats
BASIC = {
'ResponseMetadata' => {'RequestId' => String}
}
end
end
end
fog-aws-0.7.6/tests/requests/sqs/message_tests.rb 0000644 0000041 0000041 00000003176 12576636531 022162 0 ustar www-data www-data Shindo.tests('AWS::SQS | message requests', ['aws']) do
tests('success') do
@queue_url = Fog::AWS[:sqs].create_queue('fog_message_tests').body['QueueUrl']
send_message_format = AWS::SQS::Formats::BASIC.merge({
'MessageId' => String,
'MD5OfMessageBody' => String
})
tests("#send_message('#{@queue_url}', 'message')").formats(send_message_format) do
Fog::AWS[:sqs].send_message(@queue_url, 'message').body
end
receive_message_format = AWS::SQS::Formats::BASIC.merge({
'Message' => [{
'Attributes' => {
'ApproximateFirstReceiveTimestamp' => Time,
'ApproximateReceiveCount' => Integer,
'SenderId' => String,
'SentTimestamp' => Time
},
'Body' => String,
'MD5OfBody' => String,
'MessageId' => String,
'ReceiptHandle' => String
}]
})
tests("#receive_message").formats(receive_message_format) do
data = Fog::AWS[:sqs].receive_message(@queue_url).body
@receipt_handle = data['Message'].first['ReceiptHandle']
data
end
tests("#change_message_visibility('#{@queue_url}, '#{@receipt_handle}', 60)").formats(AWS::SQS::Formats::BASIC) do
Fog::AWS[:sqs].change_message_visibility(@queue_url, @receipt_handle, 60).body
end
tests("#delete_message('#{@queue_url}', '#{@receipt_handle}')").formats(AWS::SQS::Formats::BASIC) do
Fog::AWS[:sqs].delete_message(@queue_url, @receipt_handle).body
end
unless Fog.mocking?
Fog::AWS[:sqs].delete_queue(@queue_url)
end
end
end
fog-aws-0.7.6/tests/requests/sqs/queue_tests.rb 0000644 0000041 0000041 00000003223 12576636531 021653 0 ustar www-data www-data Shindo.tests('AWS::SQS | queue requests', ['aws']) do
tests('success') do
create_queue_format = AWS::SQS::Formats::BASIC.merge({
'QueueUrl' => String
})
tests("#create_queue('fog_queue_tests')").formats(create_queue_format) do
data = Fog::AWS[:sqs].create_queue('fog_queue_tests').body
@queue_url = data['QueueUrl']
data
end
list_queues_format = AWS::SQS::Formats::BASIC.merge({
'QueueUrls' => [String]
})
tests("#list_queues").formats(list_queues_format) do
Fog::AWS[:sqs].list_queues.body
end
tests("#set_queue_attributes('#{@queue_url}', 'VisibilityTimeout', 60)").formats(AWS::SQS::Formats::BASIC) do
Fog::AWS[:sqs].set_queue_attributes(@queue_url, 'VisibilityTimeout', 60).body
end
get_queue_attributes_format = AWS::SQS::Formats::BASIC.merge({
'Attributes' => {
'ApproximateNumberOfMessages' => Integer,
'ApproximateNumberOfMessagesNotVisible' => Integer,
'CreatedTimestamp' => Time,
'MaximumMessageSize' => Integer,
'LastModifiedTimestamp' => Time,
'MessageRetentionPeriod' => Integer,
'QueueArn' => String,
'VisibilityTimeout' => Integer
}
})
tests("#get_queue_attributes('#{@queue_url}', 'All')").formats(get_queue_attributes_format) do
Fog::AWS[:sqs].get_queue_attributes(@queue_url, 'All').body
end
tests("#delete_queue('#{@queue_url}')").formats(AWS::SQS::Formats::BASIC) do
Fog::AWS[:sqs].delete_queue(@queue_url).body
end
end
end
fog-aws-0.7.6/tests/requests/storage/ 0000755 0000041 0000041 00000000000 12576636531 017616 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/storage/multipart_upload_tests.rb 0000644 0000041 0000041 00000010303 12576636531 024747 0 ustar www-data www-data Shindo.tests('Fog::Storage[:aws] | multipart upload requests', ["aws"]) do
@directory = Fog::Storage[:aws].directories.create(:key => uniq_id('fogmultipartuploadtests'))
tests('success') do
@initiate_multipart_upload_format = {
'Bucket' => String,
'Key' => String,
'UploadId' => String
}
tests("#initiate_multipart_upload('#{@directory.identity}')", 'fog_multipart_upload').formats(@initiate_multipart_upload_format) do
data = Fog::Storage[:aws].initiate_multipart_upload(@directory.identity, 'fog_multipart_upload').body
@upload_id = data['UploadId']
data
end
@list_multipart_uploads_format = {
'Bucket' => String,
'IsTruncated' => Fog::Boolean,
'MaxUploads' => Integer,
'KeyMarker' => NilClass,
'NextKeyMarker' => String,
'NextUploadIdMarker' => Fog::Nullable::String,
'Upload' => [{
'Initiated' => Time,
'Initiator' => {
'DisplayName' => String,
'ID' => String
},
'Key' => String,
'Owner' => {
'DisplayName' => String,
'ID' => String
},
'StorageClass' => String,
'UploadId' => String
}],
'UploadIdMarker' => NilClass,
}
tests("#list_multipart_uploads('#{@directory.identity})").formats(@list_multipart_uploads_format) do
pending if Fog.mocking?
Fog::Storage[:aws].list_multipart_uploads(@directory.identity).body
end
@parts = []
tests("#upload_part('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', 1, ('x' * 6 * 1024 * 1024))").succeeds do
data = Fog::Storage[:aws].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 1, ('x' * 6 * 1024 * 1024))
@parts << data.headers['ETag']
end
@list_parts_format = {
'Bucket' => String,
'Initiator' => {
'DisplayName' => String,
'ID' => String
},
'IsTruncated' => Fog::Boolean,
'Key' => String,
'MaxParts' => Integer,
'NextPartNumberMarker' => String,
'Part' => [{
'ETag' => String,
'LastModified' => Time,
'PartNumber' => Integer,
'Size' => Integer
}],
'PartNumberMarker' => String,
'StorageClass' => String,
'UploadId' => String
}
tests("#list_parts('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}')").formats(@list_parts_format) do
pending if Fog.mocking?
Fog::Storage[:aws].list_parts(@directory.identity, 'fog_multipart_upload', @upload_id).body
end
@parts << Fog::Storage[:aws].upload_part(@directory.identity, 'fog_multipart_upload', @upload_id, 2, ('x' * 4 * 1024 * 1024)).headers['ETag']
@complete_multipart_upload_format = {
'Bucket' => String,
'ETag' => String,
'Key' => String,
'Location' => String
}
tests("#complete_multipart_upload('#{@directory.identity}', 'fog_multipart_upload', '#{@upload_id}', #{@parts.inspect})").formats(@complete_multipart_upload_format) do
Fog::Storage[:aws].complete_multipart_upload(@directory.identity, 'fog_multipart_upload', @upload_id, @parts).body
end
tests("#get_object('#{@directory.identity}', 'fog_multipart_upload').body").succeeds do
Fog::Storage[:aws].get_object(@directory.identity, 'fog_multipart_upload').body == ('x' * 10 * 1024 * 1024)
end
@directory.files.new(:key => 'fog_multipart_upload').destroy
@upload_id = Fog::Storage[:aws].initiate_multipart_upload(@directory.identity, 'fog_multipart_abort').body['UploadId']
tests("#abort_multipart_upload('#{@directory.identity}', 'fog_multipart_abort', '#{@upload_id}')").succeeds do
Fog::Storage[:aws].abort_multipart_upload(@directory.identity, 'fog_multipart_abort', @upload_id)
end
end
tests('failure') do
tests("initiate_multipart_upload")
tests("list_multipart_uploads")
tests("upload_part")
tests("list_parts")
tests("complete_multipart_upload")
tests("abort_multipart_upload")
end
@directory.destroy
end
fog-aws-0.7.6/tests/requests/storage/object_tests.rb 0000644 0000041 0000041 00000020424 12576636531 022635 0 ustar www-data www-data # encoding: utf-8
Shindo.tests('AWS::Storage | object requests', ['aws']) do
@directory = Fog::Storage[:aws].directories.create(:key => 'fogobjecttests-' + Time.now.to_i.to_s(32))
@aws_owner = Fog::Storage[:aws].get_bucket_acl(@directory.key).body['Owner']
tests('success') do
@multiple_delete_format = {
'DeleteResult' => [{
'Deleted' => {
'Key' => String
}
}]
}
tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file)").succeeds do
Fog::Storage[:aws].put_object(@directory.identity, 'fog_object', lorem_file)
end
if RUBY_VERSION =~ /^1\.8\./
tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file, {'x-amz-meta-json' => 'ä'}").succeeds do
Fog::Storage[:aws].put_object(@directory.identity, 'fog_object', lorem_file, {'x-amz-meta-json' => 'ä'})
end
end
tests("#copy_object('#{@directory.identity}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").succeeds do
Fog::Storage[:aws].copy_object(@directory.identity, 'fog_object', @directory.identity, 'fog_other_object')
end
@directory.files.get('fog_other_object').destroy
tests("#get_object('#{@directory.identity}', 'fog_object')").returns(lorem_file.read) do
Fog::Storage[:aws].get_object(@directory.identity, 'fog_object').body
end
tests("#get_object('#{@directory.identity}', 'fog_object', &block)").returns(lorem_file.read) do
data = ''
Fog::Storage[:aws].get_object(@directory.identity, 'fog_object') do |chunk, remaining_bytes, total_bytes|
data << chunk
end
data
end
tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-20'})").returns(lorem_file.read[0..20]) do
Fog::Storage[:aws].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-20'}).body
end
tests("#get_object('#{@directory.identity}', 'fog_object', {'Range' => 'bytes=0-0'})").returns(lorem_file.read[0..0]) do
Fog::Storage[:aws].get_object(@directory.identity, 'fog_object', {'Range' => 'bytes=0-0'}).body
end
tests("#head_object('#{@directory.identity}', 'fog_object')").succeeds do
Fog::Storage[:aws].head_object(@directory.identity, 'fog_object')
end
tests("#post_object_restore('#{@directory.identity}', 'fog_object')").succeeds do
pending unless Fog.mocking?
Fog::Storage[:aws].post_object_restore(@directory.identity, 'fog_object')
end
tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'private')").succeeds do
Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', 'private')
end
acl = {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => @aws_owner,
'Permission' => "FULL_CONTROL"
}
]}
tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with id)").returns(acl) do
Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', acl)
Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body
end
tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with email)").returns({
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' },
'Permission' => "FULL_CONTROL"
}
]}) do
pending if Fog.mocking?
Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' },
'Permission' => "FULL_CONTROL"
}
]})
Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body
end
acl = {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' },
'Permission' => "FULL_CONTROL"
}
]}
tests("#put_object_acl('#{@directory.identity}', 'fog_object', hash with uri)").returns(acl) do
Fog::Storage[:aws].put_object_acl(@directory.identity, 'fog_object', acl)
Fog::Storage[:aws].get_object_acl(@directory.identity, 'fog_object').body
end
tests("#delete_object('#{@directory.identity}', 'fog_object')").succeeds do
Fog::Storage[:aws].delete_object(@directory.identity, 'fog_object')
end
tests("#get_object_http_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do
object_url = Fog::Storage[:aws].get_object_http_url(@directory.identity, 'fog_object', (Time.now + 60))
(object_url =~ /http:\/\/#{Regexp.quote(@directory.identity)}\.s3\.amazonaws\.com\/fog_object/) != nil
end
tests("#head_object_url('#{@directory.identity}', 'fog_object', expiration timestamp)").returns(true) do
object_url = Fog::Storage[:aws].head_object_url(@directory.identity, 'fog_object', (Time.now + 60))
puts object_url
(object_url =~ /https:\/\/#{Regexp.quote(@directory.identity)}\.s3\.amazonaws\.com\/fog_object/) != nil
end
tests("delete_multiple_objects('#{@directory.identity}', ['fog_object', 'fog_other_object'])").formats(@multiple_delete_format) do
Fog::Storage[:aws].delete_multiple_objects(@directory.identity, ['fog_object', 'fog_other_object']).body
end
end
fognonbucket = uniq_id('fognonbucket')
tests('failure') do
tests("#put_object('#{fognonbucket}', 'fog_non_object', lorem_file)").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].put_object(fognonbucket, 'fog_non_object', lorem_file)
end
unless RUBY_VERSION =~ /^1\.8\./
tests("#put_object('#{@directory.identity}', 'fog_object', lorem_file, {'x-amz-meta-json' => 'ä'}").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].put_object(@directory.identity, 'fog_object', lorem_file, {'x-amz-meta-json' => 'ä'})
end
end
tests("#copy_object('#{fognonbucket}', 'fog_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].copy_object(fognonbucket, 'fog_object', @directory.identity, 'fog_other_object')
end
tests("#copy_object('#{@directory.identity}', 'fog_non_object', '#{@directory.identity}', 'fog_other_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].copy_object(@directory.identity, 'fog_non_object', @directory.identity, 'fog_other_object')
end
tests("#copy_object('#{@directory.identity}', 'fog_object', 'fognonbucket', 'fog_other_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].copy_object(@directory.identity, 'fog_object', fognonbucket, 'fog_other_object')
end
tests("#get_object('#{fognonbucket}', 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_object(fognonbucket, 'fog_non_object')
end
tests("#get_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_object(@directory.identity, 'fog_non_object')
end
tests("#head_object(fognonbucket, 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].head_object(fognonbucket, 'fog_non_object')
end
tests("#head_object('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].head_object(@directory.identity, 'fog_non_object')
end
tests("#delete_object('#{fognonbucket}', 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].delete_object(fognonbucket, 'fog_non_object')
end
tests("#delete_multiple_objects('#{fognonbucket}', ['fog_non_object'])").raises(Excon::Errors::NotFound) do
pending if Fog.mocking?
Fog::Storage[:aws].delete_multiple_objects(fognonbucket, ['fog_non_object'])
end
tests("#put_object_acl('#{@directory.identity}', 'fog_object', 'invalid')").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].put_object_acl('#{@directory.identity}', 'fog_object', 'invalid')
end
tests("#post_object_restore('#{@directory.identity}', 'fog_non_object')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].post_object_restore(@directory.identity, 'fog_non_object')
end
end
@directory.destroy
end
fog-aws-0.7.6/tests/requests/storage/acl_utils_tests.rb 0000644 0000041 0000041 00000022462 12576636531 023352 0 ustar www-data www-data require 'fog/aws/requests/storage/acl_utils'
Shindo.tests('Fog::Storage::AWS | ACL utils', ["aws"]) do
tests(".hash_to_acl") do
tests(".hash_to_acl({}) at xpath //AccessControlPolicy").returns("", "has an empty AccessControlPolicy") do
xml = Fog::Storage::AWS.hash_to_acl({})
Nokogiri::XML(xml).xpath("//AccessControlPolicy").first.content.chomp
end
tests(".hash_to_acl({}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do
xml = Fog::Storage::AWS.hash_to_acl({})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first
end
tests(".hash_to_acl('Owner' => {}) at xpath //AccessControlPolicy/Owner").returns(nil, "does not have an Owner element") do
xml = Fog::Storage::AWS.hash_to_acl('Owner' => {})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner").first
end
tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/ID").returns("abcdef0123456789", "returns the Owner ID") do
xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first.content
end
tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/ID").returns(nil, "does not have an Owner ID element") do
xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'DisplayName' => 'bob'})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/ID").first
end
tests(".hash_to_acl('Owner' => {'DisplayName' => 'bob'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns("bob", "returns the Owner DisplayName") do
xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'DisplayName' => 'bob'})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first.content
end
tests(".hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'}) at xpath //AccessControlPolicy/Owner/DisplayName").returns(nil, "does not have an Owner DisplayName element") do
xml = Fog::Storage::AWS.hash_to_acl('Owner' => {'ID' => 'abcdef0123456789'})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/Owner/DisplayName").first
end
tests(".hash_to_acl({}) at xpath //AccessControlPolicy/AccessControlList").returns(nil, "has no AccessControlList") do
xml = Fog::Storage::AWS.hash_to_acl({})
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlPolicy").first
end
acl = {
'AccessControlList' => [
{
'Grantee' => {
'ID' => 'abcdef0123456789',
'DisplayName' => 'bob'
},
'Permission' => 'READ'
}
]
}
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("CanonicalUser", "has an xsi:type of CanonicalUser") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the Grantee ID") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").returns("bob", "returns the Grantee DisplayName") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/DisplayName").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("READ", "returns the Grantee Permission") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content
end
acl = {
'AccessControlList' => [
{
'Grantee' => {
'EmailAddress' => 'user@example.com'
},
'Permission' => 'FULL_CONTROL'
}
]
}
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("AmazonCustomerByEmail", "has an xsi:type of AmazonCustomerByEmail") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the Grantee EmailAddress") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("FULL_CONTROL", "returns the Grantee Permission") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content
end
acl = {
'AccessControlList' => [
{
'Grantee' => {
'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers'
},
'Permission' => 'WRITE'
}
]
}
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee").returns("Group", "has an xsi:type of Group") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee").first.attributes["type"].value
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the Grantee URI") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Permission").returns("WRITE", "returns the Grantee Permission") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Permission").first.content
end
acl = {
'AccessControlList' => [
{
'Grantee' => {
'ID' => 'abcdef0123456789',
'DisplayName' => 'bob'
},
'Permission' => 'READ'
},
{
'Grantee' => {
'EmailAddress' => 'user@example.com'
},
'Permission' => 'FULL_CONTROL'
},
{
'Grantee' => {
'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers'
},
'Permission' => 'WRITE'
}
]
}
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant").returns(3, "has three elements") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant").size
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/ID").returns("abcdef0123456789", "returns the first Grant's Grantee ID") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/ID").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").returns("user@example.com", "returns the second Grant's Grantee EmailAddress") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/EmailAddress").first.content
end
tests(".hash_to_acl(#{acl.inspect}) at xpath //AccessControlPolicy/AccessControlList/Grant/Grantee/URI").returns("http://acs.amazonaws.com/groups/global/AllUsers", "returns the third Grant's Grantee URI") do
xml = Fog::Storage::AWS.hash_to_acl(acl)
Nokogiri::XML(xml).xpath("//AccessControlPolicy/AccessControlList/Grant/Grantee/URI").first.content
end
end
tests(".acl_to_hash") do
acl_xml = <<-XML
2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0
me
2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0
me
FULL_CONTROL
XML
tests(".acl_to_hash(#{acl_xml.inspect})").returns({
"Owner" => {
"DisplayName" => "me",
"ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"
},
"AccessControlList" => [{
"Grantee" => {
"DisplayName" => "me",
"ID" => "2744ccd10c7533bd736ad890f9dd5cab2adb27b07d500b9493f29cdc420cb2e0"
},
"Permission" => "FULL_CONTROL"
}]
}, 'returns hash of ACL XML') do
Fog::Storage::AWS.acl_to_hash(acl_xml)
end
end
end
fog-aws-0.7.6/tests/requests/storage/delete_multiple_objects_tests.rb 0000644 0000041 0000041 00000001040 12576636531 026246 0 ustar www-data www-data Shindo.tests('AWS::Storage | delete_multiple_objects', ['aws']) do
@directory = Fog::Storage[:aws].directories.create(:key => 'fogobjecttests-' + Time.now.to_i.to_s(32))
tests("doesn't alter options") do
version_id = {'fog_object' => ['12345']}
options = {:quiet => true, 'versionId' => version_id}
Fog::Storage[:aws].delete_multiple_objects(@directory.identity, ['fog_object'], options)
test(":quiet is unchanged") { options[:quiet] }
test("'versionId' is unchanged") { options['versionId'] == version_id }
end
end
fog-aws-0.7.6/tests/requests/storage/versioning_tests.rb 0000644 0000041 0000041 00000024253 12576636531 023556 0 ustar www-data www-data def clear_bucket
Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name).body['Versions'].each do |version|
object = version[version.keys.first]
Fog::Storage[:aws].delete_object(@aws_bucket_name, object['Key'], 'versionId' => object['VersionId'])
end
end
def create_versioned_bucket
@aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16)
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled')
end
def delete_bucket
Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name).body['Versions'].each do |version|
object = version[version.keys.first]
Fog::Storage[:aws].delete_object(@aws_bucket_name, object['Key'], 'versionId' => object['VersionId'])
end
Fog::Storage[:aws].delete_bucket(@aws_bucket_name)
end
Shindo.tests('Fog::Storage[:aws] | versioning', ["aws"]) do
tests('success') do
tests("#put_bucket_versioning") do
@aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16)
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
tests("#put_bucket_versioning('#{@aws_bucket_name}', 'Enabled')").succeeds do
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled')
end
tests("#put_bucket_versioning('#{@aws_bucket_name}', 'Suspended')").succeeds do
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Suspended')
end
delete_bucket
end
tests("#get_bucket_versioning('#{@aws_bucket_name}')") do
@aws_bucket_name = 'fogbuckettests-' + Fog::Mock.random_hex(16)
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
tests("#get_bucket_versioning('#{@aws_bucket_name}') without versioning").returns({}) do
Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration']
end
tests("#get_bucket_versioning('#{@aws_bucket_name}') with versioning enabled").returns('Enabled') do
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Enabled')
Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration']['Status']
end
tests("#get_bucket_versioning('#{@aws_bucket_name}') with versioning suspended").returns('Suspended') do
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'Suspended')
Fog::Storage[:aws].get_bucket_versioning(@aws_bucket_name).body['VersioningConfiguration']['Status']
end
delete_bucket
end
tests("#get_bucket_object_versions('#{@aws_bucket_name}')") do
create_versioned_bucket
before do
@versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name)
end
v1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file')
v2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => v1.key)
v3 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abc', :key => v1.key)
v4 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abcd', :key => v1.key)
tests("versions").returns([v4.version, v3.version, v2.version, v1.version]) do
@versions.body['Versions'].map {|v| v['Version']['VersionId']}
end
tests("version sizes").returns([4, 3, 2, 1]) do
@versions.body['Versions'].map {|v| v['Version']['Size']}
end
tests("latest version").returns(v4.version) do
latest = @versions.body['Versions'].find {|v| v['Version']['IsLatest']}
latest['Version']['VersionId']
end
end
tests("get_object('#{@aws_bucket_name}', 'file')") do
clear_bucket
v1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file')
v2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => v1.key)
tests("get_object('#{@aws_bucket_name}', '#{v2.key}') returns the latest version").returns(v2.version) do
res = Fog::Storage[:aws].get_object(@aws_bucket_name, v2.key)
res.headers['x-amz-version-id']
end
tests("get_object('#{@aws_bucket_name}', '#{v1.key}', 'versionId' => '#{v1.version}') returns the specified version").returns(v1.version) do
res = Fog::Storage[:aws].get_object(@aws_bucket_name, v1.key, 'versionId' => v1.version)
res.headers['x-amz-version-id']
end
v2.destroy
tests("get_object('#{@aws_bucket_name}', '#{v2.key}') raises exception if delete marker is latest version").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_object(@aws_bucket_name, v2.key)
end
end
tests("delete_object('#{@aws_bucket_name}', 'file')") do
clear_bucket
file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file')
tests("deleting an object just stores a delete marker").returns(true) do
file.destroy
versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name)
versions.body['Versions'].first.key?('DeleteMarker')
end
tests("there are two versions: the original and the delete marker").returns(2) do
versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name)
versions.body['Versions'].size
end
tests("deleting the delete marker makes the object available again").returns(file.version) do
versions = Fog::Storage[:aws].get_bucket_object_versions(@aws_bucket_name)
delete_marker = versions.body['Versions'].find { |v| v.key?('DeleteMarker') }
Fog::Storage[:aws].delete_object(@aws_bucket_name, file.key, 'versionId' => delete_marker['DeleteMarker']['VersionId'])
res = Fog::Storage[:aws].get_object(@aws_bucket_name, file.key)
res.headers['x-amz-version-id']
end
end
tests("deleting_multiple_objects('#{@aws_bucket_name}", 'file') do
clear_bucket
bucket = Fog::Storage[:aws].directories.get(@aws_bucket_name)
file_count = 5
file_names = []
files = {}
file_count.times do |id|
file_names << "file_#{id}"
files[file_names.last] = bucket.files.create(:body => 'a',
:key => file_names.last)
end
tests("deleting an object just stores a delete marker").returns(true) do
Fog::Storage[:aws].delete_multiple_objects(@aws_bucket_name,
file_names)
versions = Fog::Storage[:aws].get_bucket_object_versions(
@aws_bucket_name)
all_versions = {}
versions.body['Versions'].each do |version|
object = version[version.keys.first]
next if file_names.index(object['Key']).nil?
if !all_versions.key?(object['Key'])
all_versions[object['Key']] = version.key?('DeleteMarker')
else
all_versions[object['Key']] |= version.key?('DeleteMarker')
end
end
all_true = true
all_versions.values.each do |marker|
all_true = false if !marker
end
all_true
end
tests("there are two versions: the original and the delete marker").
returns(file_count*2) do
versions = Fog::Storage[:aws].get_bucket_object_versions(
@aws_bucket_name)
versions.body['Versions'].size
end
tests("deleting the delete marker makes the object available again").
returns(true) do
versions = Fog::Storage[:aws].get_bucket_object_versions(
@aws_bucket_name)
delete_markers = []
file_versions = {}
versions.body['Versions'].each do |version|
object = version[version.keys.first]
next if object['VersionId'] == files[object['Key']].version
file_versions[object['Key']] = object['VersionId']
end
Fog::Storage[:aws].delete_multiple_objects(@aws_bucket_name,
file_names,
'versionId' => file_versions)
all_true = true
file_names.each do |file|
res = Fog::Storage[:aws].get_object(@aws_bucket_name, file)
all_true = false if res.headers['x-amz-version-id'] !=
files[file].version
end
all_true
end
end
tests("get_bucket('#{@aws_bucket_name}'") do
clear_bucket
file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'file')
tests("includes a non-DeleteMarker object").returns(1) do
Fog::Storage[:aws].get_bucket(@aws_bucket_name).body['Contents'].size
end
file.destroy
tests("does not include a DeleteMarker object").returns(0) do
Fog::Storage[:aws].get_bucket(@aws_bucket_name).body['Contents'].size
end
end
delete_bucket
end
tests('failure') do
create_versioned_bucket
tests("#put_bucket_versioning('#{@aws_bucket_name}', 'bad_value')").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].put_bucket_versioning(@aws_bucket_name, 'bad_value')
end
tests("#put_bucket_versioning('fognonbucket', 'Enabled')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].put_bucket_versioning('fognonbucket', 'Enabled')
end
tests("#get_bucket_versioning('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_bucket_versioning('fognonbucket')
end
tests("#get_bucket_object_versions('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_bucket_object_versions('fognonbucket')
end
file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'y', :key => 'x')
tests("#get_object('#{@aws_bucket_name}', '#{file.key}', 'versionId' => 'bad_version'").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].get_object(@aws_bucket_name, file.key, 'versionId' => '-1')
end
tests("#delete_object('#{@aws_bucket_name}', '#{file.key}', 'versionId' => 'bad_version'").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].delete_object(@aws_bucket_name, file.key, 'versionId' => '-1')
end
end
# don't keep the bucket around
delete_bucket
end
fog-aws-0.7.6/tests/requests/storage/cors_utils_tests.rb 0000644 0000041 0000041 00000011642 12576636531 023557 0 ustar www-data www-data require 'fog/aws/requests/storage/cors_utils'
Shindo.tests('Fog::Storage::AWS | CORS utils', ["aws"]) do
tests(".hash_to_cors") do
tests(".hash_to_cors({}) at xpath //CORSConfiguration").returns("", "has an empty CORSConfiguration") do
xml = Fog::Storage::AWS.hash_to_cors({})
Nokogiri::XML(xml).xpath("//CORSConfiguration").first.content.chomp
end
tests(".hash_to_cors({}) at xpath //CORSConfiguration/CORSRule").returns(nil, "has no CORSRules") do
xml = Fog::Storage::AWS.hash_to_cors({})
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule").first
end
cors = {
'CORSConfiguration' => [
{
'AllowedOrigin' => ['origin_123', 'origin_456'],
'AllowedMethod' => ['GET', 'POST'],
'AllowedHeader' => ['Accept', 'Content-Type'],
'ID' => 'blah-888',
'MaxAgeSeconds' => 2500,
'ExposeHeader' => ['x-some-header', 'x-other-header']
}
]
}
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_123", "returns the CORSRule AllowedOrigin") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedOrigin").returns("origin_456", "returns the CORSRule AllowedOrigin") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedOrigin")[1].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("GET", "returns the CORSRule AllowedMethod") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedMethod").returns("POST", "returns the CORSRule AllowedMethod") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedMethod")[1].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Accept", "returns the CORSRule AllowedHeader") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/AllowedHeader").returns("Content-Type", "returns the CORSRule AllowedHeader") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/AllowedHeader")[1].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ID").returns("blah-888", "returns the CORSRule ID") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ID")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/MaxAgeSeconds").returns("2500", "returns the CORSRule MaxAgeSeconds") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/MaxAgeSeconds")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-some-header", "returns the CORSRule ExposeHeader") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[0].content
end
tests(".hash_to_cors(#{cors.inspect}) at xpath //CORSConfiguration/CORSRule/ExposeHeader").returns("x-other-header", "returns the CORSRule ExposeHeader") do
xml = Fog::Storage::AWS.hash_to_cors(cors)
Nokogiri::XML(xml).xpath("//CORSConfiguration/CORSRule/ExposeHeader")[1].content
end
end
tests(".cors_to_hash") do
cors_xml = <<-XML
http://www.example.com
http://www.example2.com
Content-Length
X-Foobar
PUT
GET
3000
x-amz-server-side-encryption
x-amz-balls
XML
tests(".cors_to_hash(#{cors_xml.inspect})").returns({
"CORSConfiguration" => [{
"AllowedOrigin" => ["http://www.example.com", "http://www.example2.com"],
"AllowedHeader" => ["Content-Length", "X-Foobar"],
"AllowedMethod" => ["PUT", "GET"],
"MaxAgeSeconds" => 3000,
"ExposeHeader" => ["x-amz-server-side-encryption", "x-amz-balls"]
}]
}, 'returns hash of CORS XML') do
Fog::Storage::AWS.cors_to_hash(cors_xml)
end
end
end
fog-aws-0.7.6/tests/requests/storage/bucket_tests.rb 0000644 0000041 0000041 00000036553 12576636531 022656 0 ustar www-data www-data Shindo.tests('Fog::Storage[:aws] | bucket requests', ["aws"]) do
@aws_bucket_name = 'fogbuckettests-' + Time.now.to_i.to_s(32)
tests('success') do
@bucket_format = {
'CommonPrefixes' => [],
'IsTruncated' => Fog::Boolean,
'Marker' => NilClass,
'MaxKeys' => Integer,
'Name' => String,
'Prefix' => NilClass,
'Contents' => [{
'ETag' => String,
'Key' => String,
'LastModified' => Time,
'Owner' => {
'DisplayName' => String,
'ID' => String
},
'Size' => Integer,
'StorageClass' => String
}]
}
@bucket_lifecycle_format = {
'Rules' => [{
'ID' => String,
'Prefix' => Fog::Nullable::String,
'Enabled' => Fog::Boolean,
'Expiration' => Fog::Nullable::Hash,
'Transition' => Fog::Nullable::Hash
}]
}
@service_format = {
'Buckets' => [{
'CreationDate' => Time,
'Name' => String,
}],
'Owner' => {
'DisplayName' => String,
'ID' => String
}
}
tests("#put_bucket('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
@aws_owner = Fog::Storage[:aws].get_bucket_acl(Fog::Storage[:aws].directories.first.key).body['Owner']
end
tests('put existing bucket - default region') do
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
tests("#put_bucket('#{@aws_bucket_name}') existing").succeeds do
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
end
end
tests('put existing bucket - default region - preserves files') do
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
test_key = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'test', :key => 'test/key')
Fog::Storage[:aws].put_bucket(@aws_bucket_name)
tests(".body['Contents'].first['Key']").returns('test/key') do
Fog::Storage[:aws].get_bucket(@aws_bucket_name).body['Contents'].first['Key']
end
test_key.destroy
end
tests("#get_service").formats(@service_format) do
Fog::Storage[:aws].get_service.body
end
file = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'y', :key => 'x')
tests("#get_bucket('#{@aws_bucket_name}')").formats(@bucket_format) do
Fog::Storage[:aws].get_bucket(@aws_bucket_name).body
end
tests("#head_bucket('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].head_bucket(@aws_bucket_name)
end
file.destroy
file1 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'a', :key => 'a/a1/file1')
file2 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'ab', :key => 'a/file2')
file3 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abc', :key => 'b/file3')
file4 = Fog::Storage[:aws].directories.get(@aws_bucket_name).files.create(:body => 'abcd', :key => 'file4')
tests("#get_bucket('#{@aws_bucket_name}')") do
before do
@bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name)
end
tests(".body['Contents'].map{|n| n['Key']}").returns(["a/a1/file1", "a/file2", "b/file3", "file4"]) do
@bucket.body['Contents'].map{|n| n['Key']}
end
tests(".body['Contents'].map{|n| n['Size']}").returns([1, 2, 3, 4]) do
@bucket.body['Contents'].map{|n| n['Size']}
end
tests(".body['CommonPrefixes']").returns([]) do
@bucket.body['CommonPrefixes']
end
end
tests("#get_bucket('#{@aws_bucket_name}', 'delimiter' => '/')") do
before do
@bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name, 'delimiter' => '/')
end
tests(".body['Contents'].map{|n| n['Key']}").returns(['file4']) do
@bucket.body['Contents'].map{|n| n['Key']}
end
tests(".body['CommonPrefixes']").returns(['a/', 'b/']) do
@bucket.body['CommonPrefixes']
end
end
tests("#get_bucket('#{@aws_bucket_name}', 'delimiter' => '/', 'prefix' => 'a/')") do
before do
@bucket = Fog::Storage[:aws].get_bucket(@aws_bucket_name, 'delimiter' => '/', 'prefix' => 'a/')
end
tests(".body['Contents'].map{|n| n['Key']}").returns(['a/file2']) do
@bucket.body['Contents'].map{|n| n['Key']}
end
tests(".body['CommonPrefixes']").returns(['a/a1/']) do
@bucket.body['CommonPrefixes']
end
end
file1.destroy; file2.destroy; file3.destroy; file4.destroy
tests("#get_bucket_location('#{@aws_bucket_name}')").formats('LocationConstraint' => NilClass) do
Fog::Storage[:aws].get_bucket_location(@aws_bucket_name).body
end
tests("#get_request_payment('#{@aws_bucket_name}')").formats('Payer' => String) do
Fog::Storage[:aws].get_request_payment(@aws_bucket_name).body
end
tests("#put_request_payment('#{@aws_bucket_name}', 'Requester')").succeeds do
Fog::Storage[:aws].put_request_payment(@aws_bucket_name, 'Requester')
end
# This should show a warning, but work (second parameter is options hash for now)
tests("#put_bucket_website('#{@aws_bucket_name}', 'index.html')").succeeds do
Fog::Storage[:aws].put_bucket_website(@aws_bucket_name, 'index.html')
end
tests("#put_bucket_website('#{@aws_bucket_name}', :IndexDocument => 'index.html')").succeeds do
Fog::Storage[:aws].put_bucket_website(@aws_bucket_name, :IndexDocument => 'index.html')
end
tests("#put_bucket_website('#{@aws_bucket_name}', :RedirectAllRequestsTo => 'redirect.example..com')").succeeds do
Fog::Storage[:aws].put_bucket_website(@aws_bucket_name, :RedirectAllRequestsTo => 'redirect.example.com')
end
tests("#put_bucket_acl('#{@aws_bucket_name}', 'private')").succeeds do
Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, 'private')
end
acl = {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => @aws_owner,
'Permission' => "FULL_CONTROL"
}
]
}
tests("#put_bucket_acl('#{@aws_bucket_name}', hash with id)").returns(acl) do
Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, acl)
Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body
end
tests("#put_bucket_acl('#{@aws_bucket_name}', hash with email)").returns({
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'ID' => 'f62f0218873cfa5d56ae9429ae75a592fec4fd22a5f24a20b1038a7db9a8f150', 'DisplayName' => 'mtd' },
'Permission' => "FULL_CONTROL"
}
]
}) do
pending if Fog.mocking?
Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'EmailAddress' => 'mtd@amazon.com' },
'Permission' => "FULL_CONTROL"
}
]
})
Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body
end
acl = {
'Owner' => @aws_owner,
'AccessControlList' => [
{
'Grantee' => { 'URI' => 'http://acs.amazonaws.com/groups/global/AllUsers' },
'Permission' => "FULL_CONTROL"
}
]
}
tests("#put_bucket_acl('#{@aws_bucket_name}', hash with uri)").returns(acl) do
Fog::Storage[:aws].put_bucket_acl(@aws_bucket_name, acl)
Fog::Storage[:aws].get_bucket_acl(@aws_bucket_name).body
end
tests("#delete_bucket_website('#{@aws_bucket_name}')").succeeds do
pending if Fog.mocking?
Fog::Storage[:aws].delete_bucket_website(@aws_bucket_name)
end
tests('bucket lifecycle') do
pending if Fog.mocking?
lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Days' => 42}]}
tests('non-existant bucket') do
tests('#put_bucket_lifecycle').returns([404, 'NoSuchBucket']) do
begin
Fog::Storage[:aws].put_bucket_lifecycle('fognonbucket', lifecycle)
rescue Excon::Errors::NotFound => e
[e.response.status, e.response.body.match(%r{(.*)
})[1]]
end
end
tests('#get_bucket_lifecycle').returns([404, 'NoSuchBucket']) do
begin
Fog::Storage[:aws].get_bucket_lifecycle('fognonbucket')
rescue Excon::Errors::NotFound => e
[e.response.status, e.response.body.match(%r{(.*)
})[1]]
end
end
tests('#delete_bucket_lifecycle').returns([404, 'NoSuchBucket']) do
begin
Fog::Storage[:aws].delete_bucket_lifecycle('fognonbucket')
rescue Excon::Errors::NotFound => e
[e.response.status, e.response.body.match(%r{(.*)
})[1]]
end
end
end
tests('no lifecycle') do
tests('#get_bucket_lifecycle').returns([404, 'NoSuchLifecycleConfiguration']) do
begin
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name)
rescue Excon::Errors::NotFound => e
[e.response.status, e.response.body.match(%r{(.*)
})[1]]
end
end
tests('#delete_bucket_lifecycle').succeeds do
Fog::Storage[:aws].delete_bucket_lifecycle(@aws_bucket_name)
end
end
tests('create').succeeds do
Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle)
end
tests('read').formats(@bucket_lifecycle_format) do
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body
end
lifecycle = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Days' => i} } }
lifecycle_return = { 'Rules' => 5.upto(6).map { |i| {'ID' => "rule\##{i}", 'Prefix' => i.to_s, 'Enabled' => true, 'Expiration' => {'Days' => i}} } }
tests('update').returns(lifecycle_return) do
Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle)
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body
end
lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Expiration' => {'Days' => 42}, 'Transition' => {'Days' => 6, 'StorageClass'=>'GLACIER'}}]}
tests('transition').returns(lifecycle) do
Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle)
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body
end
lifecycle = {'Rules' => [{'ID' => 'test rule', 'Prefix' => '/prefix', 'Enabled' => true, 'Expiration' => {'Date' => '2012-12-31T00:00:00.000Z'}}]}
tests('date').returns(lifecycle) do
Fog::Storage[:aws].put_bucket_lifecycle(@aws_bucket_name, lifecycle)
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name).body
end
tests('delete').succeeds do
Fog::Storage[:aws].delete_bucket_lifecycle(@aws_bucket_name)
end
tests('read').returns([404, 'NoSuchLifecycleConfiguration']) do
begin
Fog::Storage[:aws].get_bucket_lifecycle(@aws_bucket_name)
rescue Excon::Errors::NotFound => e
[e.response.status, e.response.body.match(%r{(.*)
})[1]]
end
end
end
tests("put_bucket_cors('#{@aws_bucket_name}', cors)").succeeds do
cors = {'CORSConfiguration' =>
[
{
'AllowedOrigin' => 'http://localhost:3000',
'AllowedMethod' => ['POST', 'GET'],
'AllowedHeader' => '*',
'MaxAgeSeconds' => 3000
}
]
}
Fog::Storage[:aws].put_bucket_cors(@aws_bucket_name, cors)
end
tests("bucket tagging") do
tests("#put_bucket_tagging('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].put_bucket_tagging(@aws_bucket_name, {'Key1' => 'Value1', 'Key2' => 'Value2'})
end
tests("#get_bucket_tagging('#{@aws_bucket_name}')").
returns('BucketTagging' => {'Key1' => 'Value1', 'Key2' => 'Value2'}) do
Fog::Storage[:aws].get_bucket_tagging(@aws_bucket_name).body
end
tests("#delete_bucket_tagging('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].delete_bucket_tagging(@aws_bucket_name)
end
end
tests("bucket notification") do
@topic_arn = Fog::AWS[:sns].create_topic('fog_notifications_tests').body['TopicArn']
tests("#put_bucket_notification('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].put_bucket_notification(@aws_bucket_name, { 'Topics' => [{
'Topic' => @topic_arn, 'Event' => 's3:ObjectCreated:CompleteMultipartUpload'
}]})
end
tests("#get_bucket_notification('#{@aws_bucket_name}')").
returns({'Topics' => [{ 'Topic' => @topic_arn, 'Event' => 's3:ObjectCreated:CompleteMultipartUpload' }]}) do
Fog::Storage[:aws].get_bucket_notification(@aws_bucket_name).body
end
Fog::AWS[:sns].delete_topic(@topic_arn)
end
tests("#delete_bucket('#{@aws_bucket_name}')").succeeds do
Fog::Storage[:aws].delete_bucket(@aws_bucket_name)
end
end
tests('failure') do
tests("#delete_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].delete_bucket('fognonbucket')
end
@bucket = Fog::Storage[:aws].directories.create(:key => 'fognonempty')
@file = @bucket.files.create(:key => 'foo', :body => 'bar')
tests("#delete_bucket('fognonempty')").raises(Excon::Errors::Conflict) do
Fog::Storage[:aws].delete_bucket('fognonempty')
end
@file.destroy
@bucket.destroy
tests("#get_bucket('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_bucket('fognonbucket')
end
tests("#get_bucket_location('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_bucket_location('fognonbucket')
end
tests("#get_bucket_notification('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_bucket_notification('fognonbucket')
end
tests("#get_request_payment('fognonbucket')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].get_request_payment('fognonbucket')
end
tests("#put_request_payment('fognonbucket', 'Requester')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].put_request_payment('fognonbucket', 'Requester')
end
tests("#put_bucket_acl('fognonbucket', 'invalid')").raises(Excon::Errors::BadRequest) do
Fog::Storage[:aws].put_bucket_acl('fognonbucket', 'invalid')
end
tests("#put_bucket_website('fognonbucket', 'index.html')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].put_bucket_website('fognonbucket', 'index.html')
end
tests('put existing bucket - non-default region') do
storage_eu_endpoint = Fog::Storage[:aws]
storage_eu_endpoint.region = "eu-west-1"
storage_eu_endpoint.put_bucket(@aws_bucket_name)
tests("#put_bucket('#{@aws_bucket_name}') existing").raises(Excon::Errors::Conflict) do
storage_eu_endpoint.put_bucket(@aws_bucket_name)
end
end
tests("#put_bucket_website('fognonbucket', :RedirectAllRequestsTo => 'redirect.example.com')").raises(Excon::Errors::NotFound) do
Fog::Storage[:aws].put_bucket_website('fognonbucket', :RedirectAllRequestsTo => 'redirect.example.com')
end
end
# don't keep the bucket around
Fog::Storage[:aws].delete_bucket(@aws_bucket_name) rescue nil
end
fog-aws-0.7.6/tests/requests/emr/ 0000755 0000041 0000041 00000000000 12576636531 016735 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/emr/helper.rb 0000644 0000041 0000041 00000011547 12576636531 020551 0 ustar www-data www-data class AWS
module EMR
module Formats
BASIC = {
'RequestId' => String
}
RUN_JOB_FLOW = BASIC.merge({
'JobFlowId' => String
})
ADD_INSTANCE_GROUPS = {
'JobFlowId' => String,
'InstanceGroupIds' => Array
}
SIMPLE_DESCRIBE_JOB_FLOW = {
'JobFlows' => [{
'Name' => String,
'BootstrapActions' => {
'ScriptBootstrapActionConfig' => {
'Args' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String,
'LastStateChangeReason' => String
},
'Steps' => [{
'ActionOnFailure' => String,
'Name' => String,
'StepConfig' => {
'HadoopJarStepConfig' => {
'MainClass' => String,
'Jar' => String,
'Args' => Array,
'Properties' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String
}
}],
'JobFlowId' => String,
'Instances' => {
'InstanceCount' => String,
'NormalizedInstanceHours' => String,
'KeepJobFlowAliveWhenNoSteps' => String,
'Placement' => {
'AvailabilityZone' => String
},
'MasterInstanceType' => String,
'SlaveInstanceType' => String,
'InstanceGroups' => Array,
'TerminationProtected' => String,
'HadoopVersion' => String
}
}]
}
JOB_FLOW_WITHOUT_CHANGE = {
'JobFlows' => [{
'Name' => String,
'BootstrapActions' => {
'ScriptBootstrapActionConfig' => {
'Args' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String,
'LastStateChangeReason' => NilClass
},
'Steps' => [{
'ActionOnFailure' => String,
'Name' => String,
'StepConfig' => {
'HadoopJarStepConfig' => {
'MainClass' => String,
'Jar' => String,
'Args' => Array,
'Properties' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String
}
}],
'JobFlowId' => String,
'Instances' => {
'InstanceCount' => String,
'NormalizedInstanceHours' => String,
'KeepJobFlowAliveWhenNoSteps' => String,
'Placement' => {
'AvailabilityZone' => String
},
'MasterInstanceType' => String,
'SlaveInstanceType' => String,
'InstanceGroups' => Array,
'TerminationProtected' => String,
'HadoopVersion' => String
}
}]
}
DESCRIBE_JOB_FLOW_WITH_INSTANCE_GROUPS = {
'JobFlows' => [{
'Name' => String,
'BootstrapActions' => {
'ScriptBootstrapActionConfig' => {
'Args' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String,
'LastStateChangeReason' => NilClass
},
'Steps' => [{
'ActionOnFailure' => String,
'Name' => String,
'StepConfig' => {
'HadoopJarStepConfig' => {
'MainClass' => String,
'Jar' => String,
'Args' => Array,
'Properties' => Array
}
},
'ExecutionStatusDetail' => {
'CreationDateTime' => String,
'State' => String
}
}],
'JobFlowId' => String,
'Instances' => {
'InstanceCount' => String,
'NormalizedInstanceHours' => String,
'KeepJobFlowAliveWhenNoSteps' => String,
'Placement' => {
'AvailabilityZone' => String
},
'InstanceGroups' => [{
'Name' => String,
'InstanceRole' => String,
'CreationDateTime' => String,
'LastStateChangeReason' => nil,
'InstanceGroupId' => String,
'Market' => String,
'InstanceType' => String,
'State' => String,
'InstanceRunningCount' => String,
'InstanceRequestCount' => String
}],
'MasterInstanceType' => String,
'SlaveInstanceType' => String,
'TerminationProtected' => String,
'HadoopVersion' => String
}
}]
}
end
end
end
fog-aws-0.7.6/tests/requests/emr/job_flow_tests.rb 0000644 0000041 0000041 00000004375 12576636531 022316 0 ustar www-data www-data Shindo.tests('AWS::EMR | job flows', ['aws', 'emr']) do
pending if Fog.mocking?
@job_flow_name = "fog_job_flow_#{Time.now.to_f.to_s.gsub('.','')}"
@job_flow_options = {
'Instances' => {
'MasterInstanceType' => 'm1.small',
'SlaveInstanceType' => 'm1.small',
'InstanceCount' => 2,
'Placement' => {
'AvailabilityZone' => 'us-east-1a'
},
'KeepJobFlowAliveWhenNoSteps' => false,
'TerminationProtected' => false,
'HadoopVersion' => '0.20'
}
}
@step_name = "fog_job_flow_step_#{Time.now.to_f.to_s.gsub('.','')}"
@job_flow_steps = {
'Steps' => [{
'Name' => @step_name,
'ActionOnFailure' => 'CONTINUE',
'HadoopJarStep' => {
'Jar' => 'FakeJar',
'MainClass' => 'FakeMainClass',
'Args' => ['arg1', 'arg2']
}
}]
}
@job_flow_id = nil
tests('success') do
tests("#run_job_flow").formats(AWS::EMR::Formats::RUN_JOB_FLOW) do
pending if Fog.mocking?
result = Fog::AWS[:emr].run_job_flow(@job_flow_name, @job_flow_options).body
@job_flow_id = result['JobFlowId']
result
end
tests("#add_job_flow_steps").formats(AWS::EMR::Formats::BASIC) do
pending if Fog.mocking?
result = Fog::AWS[:emr].add_job_flow_steps(@job_flow_id, @job_flow_steps).body
result
end
tests("#set_termination_protection").formats(AWS::EMR::Formats::BASIC) do
result = Fog::AWS[:emr].set_termination_protection(true, 'JobFlowIds' => [@job_flow_id]).body
test("protected?") do
res = Fog::AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body
jf = res['JobFlows'].first
jf['Instances']['TerminationProtected'] == 'true'
end
result
end
tests("#terminate_job_flow").formats(AWS::EMR::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:emr].set_termination_protection(false, 'JobFlowIds' => [@job_flow_id])
result = Fog::AWS[:emr].terminate_job_flows('JobFlowIds' => [@job_flow_id]).body
result
end
tests("#describe_job_flows").formats(AWS::EMR::Formats::SIMPLE_DESCRIBE_JOB_FLOW) do
pending if Fog.mocking?
result = Fog::AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body
result
end
end
end
fog-aws-0.7.6/tests/requests/emr/instance_group_tests.rb 0000644 0000041 0000041 00000006364 12576636531 023535 0 ustar www-data www-data Shindo.tests('AWS::EMR | instance groups', ['aws', 'emr']) do
pending if Fog.mocking?
@job_flow_name = "fog_job_flow_#{Time.now.to_f.to_s.gsub('.','')}"
@job_flow_options = {
'Instances' => {
'MasterInstanceType' => 'm1.small',
'SlaveInstanceType' => 'm1.small',
'InstanceCount' => 2,
'Placement' => {
'AvailabilityZone' => 'us-east-1a'
},
'KeepJobFlowAliveWhenNoSteps' => false,
'TerminationProtected' => false,
'HadoopVersion' => '0.20'
}
}
@job_flow_steps = {
'Steps' => [{
'Name' => 'Dummy streaming job',
'ActionOnFailure' => 'CONTINUE',
'HadoopJarStep' => {
'Jar' => '/home/hadoop/contrib/streaming/hadoop-streaming.jar',
'MainClass' => nil,
'Args' => %w(-input s3n://elasticmapreduce/samples/wordcount/input -output hdfs:///examples/output/2011-11-03T090856 -mapper s3n://elasticmapreduce/samples/wordcount/wordSplitter.py -reducer aggregate)
}
}]
}
@instance_group_name = "fog_instance_group_#{Time.now.to_f.to_s.gsub('.','')}"
@instance_groups = {
'InstanceGroups' => [{
'Name' => @instance_group_name,
'InstanceRole' => 'TASK',
'InstanceType' => 'm1.small',
'InstanceCount' => 2
}]
}
result = Fog::AWS[:emr].run_job_flow(@job_flow_name, @job_flow_options).body
@job_flow_id = result['JobFlowId']
tests('success') do
tests("#add_instance_groups").formats(AWS::EMR::Formats::ADD_INSTANCE_GROUPS) do
pending if Fog.mocking?
result = Fog::AWS[:emr].add_instance_groups(@job_flow_id, @instance_groups).body
@instance_group_id = result['InstanceGroupIds'].first
result
end
tests("#describe_job_flows_with_instance_groups").formats(AWS::EMR::Formats::DESCRIBE_JOB_FLOW_WITH_INSTANCE_GROUPS) do
pending if Fog.mocking?
result = Fog::AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body
result
end
tests("#modify_instance_groups").formats(AWS::EMR::Formats::BASIC) do
pending if Fog.mocking?
# Add a step so the state doesn't go directly from STARTING to SHUTTING_DOWN
Fog::AWS[:emr].add_job_flow_steps(@job_flow_id, @job_flow_steps)
# Wait until job has started before modifying the instance group
begin
sleep 10
result = Fog::AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body
job_flow = result['JobFlows'].first
state = job_flow['ExecutionStatusDetail']['State']
print "."
end while(state == 'STARTING')
# Check results
result = Fog::AWS[:emr].modify_instance_groups('InstanceGroups' => [{'InstanceGroupId' => @instance_group_id, 'InstanceCount' => 4}]).body
# Check the it actually modified the instance count
tests("modify worked?") do
ig_res = Fog::AWS[:emr].describe_job_flows('JobFlowIds' => [@job_flow_id]).body
matched = false
jf = ig_res['JobFlows'].first
jf['Instances']['InstanceGroups'].each do | ig |
if ig['InstanceGroupId'] == @instance_group_id
matched = true if ig['InstanceRequestCount'].to_i == 4
end
end
matched
end
result
end
end
Fog::AWS[:emr].terminate_job_flows('JobFlowIds' => [@job_flow_id])
end
fog-aws-0.7.6/tests/requests/auto_scaling/ 0000755 0000041 0000041 00000000000 12576636531 020622 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/auto_scaling/helper.rb 0000644 0000041 0000041 00000014752 12576636531 022437 0 ustar www-data www-data class AWS
module AutoScaling
module Formats
BASIC = {
'ResponseMetadata' => {'RequestId' => String}
}
PAGINATED = {
'NextToken' => Fog::Nullable::String
}
ACTIVITY = {
'ActivityId' => String,
'AutoScalingGroupName' => String,
'Cause' => Fog::Nullable::String,
'Description' => String,
'EndTime' => Time,
'Progress' => Integer,
'StartTime' => Time,
'StatusCode' => String,
'StatusMessage' => Fog::Nullable::String
}
ALARM = {
'AlarmARN' => String,
'AlarmName' => String
}
BLOCK_DEVICE_MAPPING = {
'DeviceName' => String,
'Ebs' => {'SnapshotId' => String, 'VolumeSize' => Integer},
'VirtualName' => String
}
ENABLED_METRIC = {
'Granularity' => Array,
'Metric' => Array
}
INSTANCE = {
'AvailabilityZone' => String,
'HealthStatus' => String,
'InstanceId' => String,
'LaunchConfigurationName' => String,
'LifecycleState' => String
}
NOTIFICATION_CONFIGURATION = {
'AutoScalingGroupName' => String,
'NotificationType' => String,
'TopicARN' => String
}
SCHEDULED_UPDATE_GROUP_ACTION = {
'AutoScalingGroupName' => String,
'DesiredCapacity' => Integer,
'EndTime' => Time,
'MaxSize' => Integer,
'MinSize' => Integer,
'Recurrence' => String,
'ScheduledActionARN' => String,
'ScheduledActionName' => String,
'StartTime' => Time,
}
PROCESS_TYPE = {
'ProcessName' => String
}
SUSPENDED_PROCESS = PROCESS_TYPE.merge({
'SuspensionReason' => String
})
TAG_DESCRIPTION = {
'Key' => String,
'PropagateAtLaunch' => Fog::Boolean,
'ResourceId' => String,
'ResourceType' => String,
'Value' => Fog::Nullable::String
}
AUTO_SCALING_GROUP = {
'AutoScalingGroupARN' => String,
'AutoScalingGroupName' => String,
'AvailabilityZones' => Array,
'CreatedTime' => Time,
'DefaultCooldown' => Integer,
'DesiredCapacity' => Integer,
'EnabledMetrics' => [ENABLED_METRIC],
'HealthCheckGracePeriod' => Integer,
'HealthCheckType' => String,
'Instances' => [INSTANCE],
'LaunchConfigurationName' => String,
'LoadBalancerNames' => Array,
'MaxSize' => Integer,
'MinSize' => Integer,
'PlacementGroup' => Fog::Nullable::String,
'Status' => Fog::Nullable::String,
'SuspendedProcesses' => [SUSPENDED_PROCESS],
'Tags' => [TAG_DESCRIPTION],
'TerminationPolicies' => [String],
'VPCZoneIdentifier' => Fog::Nullable::String
}
AUTO_SCALING_INSTANCE_DETAILS = INSTANCE.merge({
'AutoScalingGroupName' => String
})
LAUNCH_CONFIGURATION = {
'BlockDeviceMappings' => [BLOCK_DEVICE_MAPPING],
'CreatedTime' => Time,
'ImageId' => String,
'InstanceMonitoring' => {'Enabled' => Fog::Boolean},
'InstanceType' => String,
'KernelId' => Fog::Nullable::String,
'KeyName' => Fog::Nullable::String,
'LaunchConfigurationARN' => String,
'LaunchConfigurationName' => String,
'RamdiskId' => Fog::Nullable::String,
'SpotPrice' => Fog::Nullable::String,
'SecurityGroups' => Array,
'UserData' => Fog::Nullable::String
}
SCALING_POLICY = {
'AdjustmentType' => String,
'Alarms' => [ALARM],
'AutoScalingGroupName' => String,
'Cooldown' => Integer,
'MinAdjustmentStep' => Integer,
'PolicyARN' => String,
'PolicyName' => String,
'ScalingAdjustment' => Integer
}
DESCRIBE_ADJUSTMENT_TYPES = BASIC.merge({
'DescribeAdjustmentTypesResult' => {
'AdjustmentTypes' => [{'AdjustmentType' => String}]
}
})
DESCRIBE_AUTO_SCALING_GROUPS = BASIC.merge({
'DescribeAutoScalingGroupsResult' => PAGINATED.merge({
'AutoScalingGroups' => [AUTO_SCALING_GROUP],
})
})
DESCRIBE_AUTO_SCALING_INSTANCES = BASIC.merge({
'DescribeAutoScalingInstancesResult' => PAGINATED.merge({
'AutoScalingInstances' => [AUTO_SCALING_INSTANCE_DETAILS],
})
})
DESCRIBE_AUTO_SCALING_NOTIFICATION_TYPES = BASIC.merge({
'DescribeAutoScalingNotificationTypesResult' => {
'AutoScalingNotificationTypes' => [String]
}
})
DESCRIBE_LAUNCH_CONFIGURATIONS = BASIC.merge({
'DescribeLaunchConfigurationsResult' => PAGINATED.merge({
'LaunchConfigurations' => [LAUNCH_CONFIGURATION],
})
})
DESCRIBE_METRIC_COLLECTION_TYPES = BASIC.merge({
'DescribeMetricCollectionTypesResult' => {
'Granularities' => [{'Granularity' => String}],
'Metrics' => [{'Metric' => String}]
}
})
DESCRIBE_NOTIFICATION_CONFIGURATIONS = BASIC.merge({
'DescribeNotificationConfigurationsResult' => PAGINATED.merge({
'NotificationConfigurations' => [NOTIFICATION_CONFIGURATION]
})
})
DESCRIBE_POLICIES = BASIC.merge({
'DescribePoliciesResult' => PAGINATED.merge({
'ScalingPolicies' => [SCALING_POLICY]
})
})
DESCRIBE_SCALING_ACTIVITIES = BASIC.merge({
'DescribeScalingActivitiesResult' => PAGINATED.merge({
'Activities' => [ACTIVITY],
})
})
DESCRIBE_SCALING_PROCESS_TYPES = BASIC.merge({
'DescribeScalingProcessTypesResult' => {
'Processes' => [PROCESS_TYPE]
}
})
DESCRIBE_SCHEDULED_ACTIONS = BASIC.merge({
'DescribeScheduledActionsResult' => PAGINATED.merge({
'ScheduledUpdateGroupActions' => [SCHEDULED_UPDATE_GROUP_ACTION]
})
})
DESCRIBE_TAGS = BASIC.merge({
'DescribeTagsResult' => PAGINATED.merge({
'Tags' => [TAG_DESCRIPTION]
})
})
DESCRIBE_TERMINATION_POLICY_TYPES = BASIC.merge({
'DescribeTerminationPolicyTypesResult' => {
'TerminationPolicyTypes' => [String]
}
})
PUT_SCALING_POLICY = BASIC.merge({
'PutScalingPolicyResult' => {
'PolicyARN' => String
}
})
TERMINATE_INSTANCE_IN_AUTO_SCALING_GROUP = BASIC.merge({
'TerminateInstanceInAutoScalingGroupResult' => {
'Activity' => [ACTIVITY]
}
})
end
end
end
fog-aws-0.7.6/tests/requests/auto_scaling/auto_scaling_tests.rb 0000644 0000041 0000041 00000010404 12576636531 025040 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | auto_scaling_tests', ['aws', 'auto_scaling']) do
@asg_name = 'fog-test-asg'
@lc_name = 'fog-test-lc'
tests('success') do
tests("#create_launch_configuration").formats(AWS::AutoScaling::Formats::BASIC) do
image_id = 'ami-8c1fece5'
instance_type = 't1.micro'
#listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'http'}]
Fog::AWS[:auto_scaling].create_launch_configuration(image_id, instance_type, @lc_name).body
end
tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do
Fog::AWS[:auto_scaling].describe_launch_configurations().body
end
tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do
Fog::AWS[:auto_scaling].describe_launch_configurations('LaunchConfigurationNames' => @lc_name).body
end
tests("#describe_launch_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_LAUNCH_CONFIGURATIONS) do
Fog::AWS[:auto_scaling].describe_launch_configurations('LaunchConfigurationNames' => [@lc_name]).body
end
tests("#create_auto_scaling_group").formats(AWS::AutoScaling::Formats::BASIC) do
zones = ['us-east-1d']
max_size = 0
min_size = 0
Fog::AWS[:auto_scaling].create_auto_scaling_group(@asg_name, zones, @lc_name, max_size, min_size).body
end
tests("#attach_load_balancers").formats(AWS::AutoScaling::Formats::BASIC) do
Fog::AWS[:auto_scaling].attach_load_balancers(@asg_name, 'LoadBalancerNames' => 'elb-test-fog').body
end
tests("#detach_load_balancers").formats(AWS::AutoScaling::Formats::BASIC) do
Fog::AWS[:auto_scaling].detach_load_balancers(@asg_name, 'LoadBalancerNames' => 'elb-test-fog').body
end
tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do
Fog::AWS[:auto_scaling].describe_auto_scaling_groups().body
end
tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do
Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => @asg_name).body
end
tests("#describe_auto_scaling_groups").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do
Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => [@asg_name]).body
end
tests("#describe_auto_scaling_instances").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_INSTANCES) do
Fog::AWS[:auto_scaling].describe_auto_scaling_instances().body
end
tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].describe_scaling_activities().body
end
tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].describe_scaling_activities('ActivityIds' => '1').body
end
tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].describe_scaling_activities('ActivityIds' => ['1', '2']).body
end
tests("#describe_scaling_activities").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_ACTIVITIES) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].describe_scaling_activities('AutoScalingGroupName' => @asg_name).body
end
tests("#set_desired_capacity").formats(AWS::AutoScaling::Formats::BASIC) do
desired_capacity = 0
Fog::AWS[:auto_scaling].set_desired_capacity(@asg_name, desired_capacity).body
end
tests("#delete_auto_scaling_group").formats(AWS::AutoScaling::Formats::BASIC) do
Fog::AWS[:auto_scaling].delete_auto_scaling_group(@asg_name, 'ForceDelete' => true).body
end
tests("#delete_auto_scaling_group that does not exists").raises(Fog::AWS::AutoScaling::ValidationError) do
Fog::AWS[:auto_scaling].delete_auto_scaling_group("group that does not exist")
end
tests("#delete_launch_configuration").formats(AWS::AutoScaling::Formats::BASIC) do
Fog::AWS[:auto_scaling].delete_launch_configuration(@lc_name).body
end
end
end
fog-aws-0.7.6/tests/requests/auto_scaling/describe_types_tests.rb 0000644 0000041 0000041 00000006337 12576636531 025406 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | describe types requests', ['aws', 'auto_scaling']) do
tests('success') do
tests("#describe_adjustment_types").formats(AWS::AutoScaling::Formats::DESCRIBE_ADJUSTMENT_TYPES) do
body = Fog::AWS[:auto_scaling].describe_adjustment_types.body
[ 'ChangeInCapacity',
'ExactCapacity',
'PercentChangeInCapacity'
].each do |v|
returns(true, "AdjustmentTypes contains #{v}") do
body['DescribeAdjustmentTypesResult']['AdjustmentTypes'].any? {|t| t['AdjustmentType'] == v}
end
end
body
end
tests("#describe_auto_scaling_notification_types").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_NOTIFICATION_TYPES) do
body = Fog::AWS[:auto_scaling].describe_auto_scaling_notification_types.body
[ 'autoscaling:EC2_INSTANCE_LAUNCH',
'autoscaling:EC2_INSTANCE_LAUNCH_ERROR',
'autoscaling:EC2_INSTANCE_TERMINATE',
'autoscaling:EC2_INSTANCE_TERMINATE_ERROR',
'autoscaling:TEST_NOTIFICATION'
].each do |v|
returns(true, "AutoScalingNotificationTypes contains #{v}") do
body['DescribeAutoScalingNotificationTypesResult']['AutoScalingNotificationTypes'].include?(v)
end
end
body
end
tests("#describe_metric_collection_types").formats(AWS::AutoScaling::Formats::DESCRIBE_METRIC_COLLECTION_TYPES) do
body = Fog::AWS[:auto_scaling].describe_metric_collection_types.body
[ 'GroupDesiredCapacity',
'GroupInServiceInstances',
'GroupMaxSize',
'GroupMinSize',
'GroupPendingInstances',
'GroupTerminatingInstances',
'GroupTotalInstances'
].each do |v|
returns(true, "Metrics contains #{v}") do
body['DescribeMetricCollectionTypesResult']['Metrics'].any? {|t| t['Metric'] == v}
end
end
[ '1Minute'
].each do |v|
returns(true, "Granularities contains #{v}") do
body['DescribeMetricCollectionTypesResult']['Granularities'].any? {|t| t['Granularity'] == v}
end
end
body
end
tests("#describe_scaling_process_types").formats(AWS::AutoScaling::Formats::DESCRIBE_SCALING_PROCESS_TYPES) do
body = Fog::AWS[:auto_scaling].describe_scaling_process_types.body
[ 'AZRebalance',
'AddToLoadBalancer',
'AlarmNotification',
'HealthCheck',
'Launch',
'ReplaceUnhealthy',
'ScheduledActions',
'Terminate'
].each do |v|
returns(true, "Processes contains #{v}") do
body['DescribeScalingProcessTypesResult']['Processes'].any? {|t| t['ProcessName'] == v}
end
end
body
end
tests("#describe_termination_policy_types").formats(AWS::AutoScaling::Formats::DESCRIBE_TERMINATION_POLICY_TYPES) do
body = Fog::AWS[:auto_scaling].describe_termination_policy_types.body
[ 'ClosestToNextInstanceHour',
'Default',
'NewestInstance',
'OldestInstance',
'OldestLaunchConfiguration'
].each do |v|
returns(true, "TerminationPolicyTypes contains #{v}") do
body['DescribeTerminationPolicyTypesResult']['TerminationPolicyTypes'].include?(v)
end
end
body
end
end
end
fog-aws-0.7.6/tests/requests/auto_scaling/notification_configuration_tests.rb 0000644 0000041 0000041 00000012612 12576636531 030010 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | notification configuration requests', ['aws', 'auto_scaling']) do
image_id = { # Ubuntu 12.04 LTS 64-bit EBS
'ap-northeast-1' => 'ami-60c77761',
'ap-southeast-1' => 'ami-a4ca8df6',
'ap-southeast-2' => 'ami-fb8611c1',
'eu-west-1' => 'ami-e1e8d395',
'sa-east-1' => 'ami-8cd80691',
'us-east-1' => 'ami-a29943cb',
'us-west-1' => 'ami-87712ac2',
'us-west-2' => 'ami-20800c10'
}
now = Time.now.utc.to_i
lc_name = "fog-test-#{now}"
asg_name = "fog-test-#{now}"
topic_name = "fog-test-#{now}"
begin
topic = Fog::AWS[:sns].create_topic(topic_name).body
topic_arn = topic['TopicArn']
rescue Fog::Errors::MockNotImplemented
topic_arn = Fog::AWS::Mock.arn('sns', Fog::AWS[:auto_scaling].data[:owner_id], "fog-test-#{now}", Fog::AWS[:auto_scaling].region)
end
lc = Fog::AWS[:auto_scaling].create_launch_configuration(image_id[Fog::AWS[:auto_scaling].region], 't1.micro', lc_name)
asg = Fog::AWS[:auto_scaling].create_auto_scaling_group(asg_name, "#{Fog::AWS[:auto_scaling].region}a", lc_name, 0, 0)
tests('raises') do
tests("#put_notification_configuration(non-existent-group)").raises(Fog::AWS::AutoScaling::ValidationError) do
Fog::AWS[:auto_scaling].put_notification_configuration('fog-test-nonexistent-group', 'autoscaling:TEST_NOTIFICATION', topic_arn)
end
tests("#put_notification_configuration(null-types)").raises(Fog::AWS::AutoScaling::ValidationError) do
Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, [], topic_arn)
end
end
tests('success') do
tests("#put_notification_configuration(string)").formats(AWS::AutoScaling::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, 'autoscaling:TEST_NOTIFICATION', topic_arn).body
end
tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do
pending if Fog.mocking?
body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupNames' => asg_name).body
notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations']
returns(true, 'exactly 1 configurations') do
notification_configurations.size == 1
end
returns(true) do
config = notification_configurations.first
config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == 'autoscaling:TEST_NOTIFICATION'
end
body
end
tests("#put_notification_configuration(array)").formats(AWS::AutoScaling::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].put_notification_configuration(asg_name, ['autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'], topic_arn).body
end
tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do
pending if Fog.mocking?
body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupName' => asg_name).body
notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations']
returns(true, 'exactly 2 configurations') do
notification_configurations.size == 2
end
[ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'].each do |type|
returns(true) do
notification_configurations.any? do |config|
config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == type
end
end
end
body
end
tests("#describe_notification_configurations(all)").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do
pending if Fog.mocking?
body = Fog::AWS[:auto_scaling].describe_notification_configurations().body
notification_configurations = body['DescribeNotificationConfigurationsResult']['NotificationConfigurations']
returns(true, 'at least 2 configurations') do
notification_configurations.size >= 2
end
[ 'autoscaling:EC2_INSTANCE_LAUNCH', 'autoscaling:EC2_INSTANCE_TERMINATE'].each do |type|
returns(true) do
notification_configurations.any? do |config|
config['AutoScalingGroupName'] == asg_name && config['TopicARN'] == topic_arn && config['NotificationType'] == type
end
end
end
body
end
tests("#delete_notification_configuration").formats(AWS::AutoScaling::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:auto_scaling].delete_notification_configuration(asg_name, topic_arn).body
end
tests("#describe_notification_configurations").formats(AWS::AutoScaling::Formats::DESCRIBE_NOTIFICATION_CONFIGURATIONS) do
pending if Fog.mocking?
body = Fog::AWS[:auto_scaling].describe_notification_configurations('AutoScalingGroupNames' => asg_name).body
returns(true) do
body['DescribeNotificationConfigurationsResult']['NotificationConfigurations'].empty?
end
body
end
end
Fog::AWS[:auto_scaling].delete_auto_scaling_group(asg_name)
Fog::AWS[:auto_scaling].delete_launch_configuration(lc_name)
if topic
begin
Fog::AWS[:sns].delete_topic(topic_arn)
rescue Fog::Errors::MockNotImplemented
end
end
end
fog-aws-0.7.6/tests/requests/auto_scaling/model_tests.rb 0000644 0000041 0000041 00000017133 12576636531 023476 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | model_tests', ['aws', 'auto_scaling']) do
tests('success') do
lc = nil
lc_id = 'fog-model-lc'
tests('configurations') do
tests('getting a missing configuration') do
returns(nil) { Fog::AWS[:auto_scaling].configurations.get('fog-no-such-lc') }
end
tests('create configuration') do
lc = Fog::AWS[:auto_scaling].configurations.create(:id => lc_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro')
#tests("dns names is set").returns(true) { lc.dns_name.is_a?(String) }
tests("created_at is set").returns(true) { Time === lc.created_at }
#tests("policies is empty").returns([]) { lc.policies }
end
tests('all configurations') do
lc_ids = Fog::AWS[:auto_scaling].configurations.all.map{|e| e.id}
tests("contains lc").returns(true) { lc_ids.include? lc_id }
end
tests('get configuration') do
lc2 = Fog::AWS[:auto_scaling].configurations.get(lc_id)
tests('ids match').returns(lc_id) { lc2.id }
end
tests('creating a duplicate configuration') do
raises(Fog::AWS::AutoScaling::IdentifierTaken) do
Fog::AWS[:auto_scaling].configurations.create(:id => lc_id, :image_id => 'ami-8c1fece5', :instance_type => 't1.micro')
end
end
end
tests('groups') do
tests('getting a missing group') do
returns(nil) { Fog::AWS[:auto_scaling].groups.get('fog-no-such-asg') }
end
asg = nil
asg_id = 'fog-model-asg'
tests('create') do
asg = Fog::AWS[:auto_scaling].groups.create(:id => asg_id, :availability_zones => ['us-east-1d'], :launch_configuration_name => lc_id)
#tests("dns names is set").returns(true) { asg.dns_name.is_a?(String) }
tests("created_at is set").returns(true) { Time === asg.created_at }
#tests("policies is empty").returns([]) { asg.policies }
end
tests('all') do
asg_ids = Fog::AWS[:auto_scaling].groups.all.map{|e| e.id}
tests("contains asg").returns(true) { asg_ids.include? asg_id }
end
tests('get') do
asg2 = Fog::AWS[:auto_scaling].groups.get(asg_id)
tests('ids match').returns(asg_id) { asg2.id }
end
tests('suspend processes') do
asg.suspend_processes()
tests('processes suspended').returns([]) { asg.suspended_processes }
end
tests('resume processes') do
asg.resume_processes()
tests('no processes suspended').returns([]) { asg.suspended_processes }
end
tests('creating a duplicate group') do
raises(Fog::AWS::AutoScaling::IdentifierTaken) do
Fog::AWS[:auto_scaling].groups.create(:id => asg_id, :availability_zones => ['us-east-1d'], :launch_configuration_name => lc_id)
end
end
tests('destroy group') do
asg.destroy
asg = nil
end
#tests('registering an invalid instance') do
# raises(Fog::AWS::AutoScaling::InvalidInstance) { asg.register_instances('i-00000000') }
#end
#tests('deregistering an invalid instance') do
# raises(Fog::AWS::AutoScaling::InvalidInstance) { asg.deregister_instances('i-00000000') }
#end
end
tests('configurations') do
tests('destroy configuration') do
lc.destroy
lc = nil
end
end
#server = Fog::AWS[:compute].servers.create
#tests('register instance') do
# begin
# elb.register_instances(server.id)
# rescue Fog::AWS::ELB::InvalidInstance
# # It may take a moment for a newly created instances to be visible to ELB requests
# raise if @retried_registered_instance
# @retried_registered_instance = true
# sleep 1
# retry
# end
#
# returns([server.id]) { elb.instances }
#end
#tests('instance_health') do
# returns('OutOfService') do
# elb.instance_health.detect{|hash| hash['InstanceId'] == server.id}['State']
# end
#
# returns([server.id]) { elb.instances_out_of_service }
#end
#tests('deregister instance') do
# elb.deregister_instances(server.id)
# returns([]) { elb.instances }
#end
#server.destroy
#tests('disable_availability_zones') do
# elb.disable_availability_zones(%w{us-east-1c us-east-1d})
# returns(%w{us-east-1a us-east-1b}) { elb.availability_zones.sort }
#end
#tests('enable_availability_zones') do
# elb.enable_availability_zones(%w{us-east-1c us-east-1d})
# returns(%w{us-east-1a us-east-1b us-east-1c us-east-1d}) { elb.availability_zones.sort }
#end
#tests('default health check') do
# default_health_check = {
# "HealthyThreshold"=>10,
# "Timeout"=>5,
# "UnhealthyThreshold"=>2,
# "Interval"=>30,
# "Target"=>"TCP:80"
# }
# returns(default_health_check) { elb.health_check }
#end
#tests('configure_health_check') do
# new_health_check = {
# "HealthyThreshold"=>5,
# "Timeout"=>10,
# "UnhealthyThreshold"=>3,
# "Interval"=>15,
# "Target"=>"HTTP:80/index.html"
# }
# elb.configure_health_check(new_health_check)
# returns(new_health_check) { elb.health_check }
#end
#tests('listeners') do
# default_listener_description = [{"Listener"=>{"InstancePort"=>80, "Protocol"=>"HTTP", "LoadBalancerPort"=>80}, "PolicyNames"=>[]}]
# tests('default') do
# returns(1) { elb.listeners.size }
#
# listener = elb.listeners.first
# returns([80,80,'HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.policy_names] }
#
# end
#
# tests('#get') do
# returns(80) { elb.listeners.get(80).lb_port }
# end
#
# tests('create') do
# new_listener = { 'InstancePort' => 443, 'LoadBalancerPort' => 443, 'Protocol' => 'TCP'}
# elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP')
# returns(2) { elb.listeners.size }
# returns(443) { elb.listeners.get(443).lb_port }
# end
#
# tests('destroy') do
# elb.listeners.get(443).destroy
# returns(nil) { elb.listeners.get(443) }
# end
#end
#tests('policies') do
# app_policy_id = 'my-app-policy'
#
# tests 'are empty' do
# returns([]) { elb.policies.to_a }
# end
#
# tests('#all') do
# returns([]) { elb.policies.all.to_a }
# end
#
# tests('create app policy') do
# elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app)
# returns(app_policy_id) { elb.policies.first.id }
# end
#
# tests('get policy') do
# returns(app_policy_id) { elb.policies.get(app_policy_id).id }
# end
#
# tests('destroy app policy') do
# elb.policies.first.destroy
# returns([]) { elb.policies.to_a }
# end
#
# lb_policy_id = 'my-lb-policy'
# tests('create lb policy') do
# elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb)
# returns(lb_policy_id) { elb.policies.first.id }
# end
#
# tests('setting a listener policy') do
# elb.set_listener_policy(80, lb_policy_id)
# returns([lb_policy_id]) { elb.listeners.get(80).policy_names }
# end
#
# tests('unsetting a listener policy') do
# elb.unset_listener_policy(80)
# returns([]) { elb.listeners.get(80).policy_names }
# end
#
# tests('a malformed policy') do
# raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') }
# end
#end
end
end
fog-aws-0.7.6/tests/requests/auto_scaling/tag_tests.rb 0000644 0000041 0000041 00000004441 12576636531 023147 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | tag requests', ['aws', 'auto_scaling']) do
image_id = { # Ubuntu 12.04 LTS 64-bit EBS
'ap-northeast-1' => 'ami-60c77761',
'ap-southeast-1' => 'ami-a4ca8df6',
'ap-southeast-2' => 'ami-fb8611c1',
'eu-west-1' => 'ami-e1e8d395',
'sa-east-1' => 'ami-8cd80691',
'us-east-1' => 'ami-a29943cb',
'us-west-1' => 'ami-87712ac2',
'us-west-2' => 'ami-20800c10'
}
now = Time.now.utc.to_i
lc_name = "fog-test-#{now}"
asg_name = "fog-test-#{now}"
asg_tag = {
'Key' => 'Name',
'PropagateAtLaunch' => true,
'ResourceId' => asg_name,
'ResourceType' => 'auto-scaling-group',
'Value' => asg_name
}
lc = Fog::AWS[:auto_scaling].create_launch_configuration(image_id[Fog::AWS[:auto_scaling].region], 't1.micro', lc_name)
asg = Fog::AWS[:auto_scaling].create_auto_scaling_group(asg_name, "#{Fog::AWS[:auto_scaling].region}a", lc_name, 0, 0, 'Tags' => [asg_tag])
tests('raises') do
tests("#create_or_update_tags(empty)").raises(Fog::AWS::AutoScaling::ValidationError) do
Fog::AWS[:auto_scaling].create_or_update_tags([])
end
tests("#delete_tags(empty)").raises(Fog::AWS::AutoScaling::ValidationError) do
Fog::AWS[:auto_scaling].delete_tags([])
end
end
tests('success') do
tests("#describe_auto_scaling_groups(#{asg_name}").formats(AWS::AutoScaling::Formats::DESCRIBE_AUTO_SCALING_GROUPS) do
body = Fog::AWS[:auto_scaling].describe_auto_scaling_groups('AutoScalingGroupNames' => asg_name).body
auto_scaling_group = body['DescribeAutoScalingGroupsResult']['AutoScalingGroups'].first
returns(true) { auto_scaling_group.key?('Tags') }
returns(true) { auto_scaling_group['Tags'].size == 1 }
returns(true) { auto_scaling_group['Tags'].first == asg_tag }
body
end
tests("#describe_tags").formats(AWS::AutoScaling::Formats::DESCRIBE_TAGS) do
pending if Fog.mocking?
body = Fog::AWS[:auto_scaling].describe_tags.body
tags = body['DescribeTagsResult']['Tags']
returns(true) { tags.any? {|tag| tag == asg_tag} }
body
end
# TODO: more tests!
end
Fog::AWS[:auto_scaling].delete_auto_scaling_group(asg_name)
Fog::AWS[:auto_scaling].delete_launch_configuration(lc_name)
end
fog-aws-0.7.6/tests/requests/redshift/ 0000755 0000041 0000041 00000000000 12576636531 017762 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/redshift/cluster_parameter_group_tests.rb 0000644 0000041 0000041 00000005524 12576636531 026474 0 ustar www-data www-data Shindo.tests('Fog::Redshift[:aws] | cluster parameter group requests', ['aws']) do
pending if Fog.mocking?
suffix = rand(65536).to_s(16)
parameter_group = "test-cluster-parameter-group-#{suffix}"
@cluster_parameter_format = {
'Parameter' => {
"ParameterValue" => String,
"DataType" => String,
"Source" => String,
"IsModifiable" => Fog::Boolean,
"Description" => String,
"ParameterName" => String
}
}
@cluster_parameters_format = {
"Parameters"=> [@cluster_parameter_format]
}
@cluster_parameter_group_format = {
'ClusterParameterGroup' => {
"ParameterGroupFamily" => String,
"Description" => String,
"ParameterGroupName" => String
}
}
@cluster_parameter_groups_format = {
"ParameterGroups"=> [@cluster_parameter_group_format]
}
@modify_cluster_parameter_group_format = {
"ParameterGroupStatus" => String,
"ParameterGroupName" => String
}
tests('success') do
tests("create_cluster_parameter_group").formats(@cluster_parameter_group_format) do
body = Fog::AWS[:redshift].create_cluster_parameter_group(:parameter_group_name=> parameter_group,
:parameter_group_family=>"redshift-1.0",
:description=>'testing').body
body
end
tests("describe_cluster_parameter_groups").formats(@cluster_parameter_groups_format) do
body = Fog::AWS[:redshift].describe_cluster_parameter_groups.body
body
end
tests("describe_cluster_parameters").formats(@cluster_parameters_format) do
body = Fog::AWS[:redshift].describe_cluster_parameters(:parameter_group_name=>parameter_group).body
body
end
tests("modify_cluster_parameter_groups").formats(@modify_cluster_parameter_group_format) do
body = Fog::AWS[:redshift].modify_cluster_parameter_group(:parameter_group_name=>parameter_group,
:parameters=>{
:parameter_name=>'extra_float_digits',
:parameter_value=>2}).body
body
end
tests("delete_cluster_parameter_group") do
present = !Fog::AWS[:redshift].describe_cluster_parameter_groups(:parameter_group_name=>parameter_group).body['ParameterGroups'].empty?
tests("verify presence before deletion").returns(true) { present }
Fog::AWS[:redshift].delete_cluster_parameter_group(:parameter_group_name=>parameter_group)
not_present = Fog::AWS[:redshift].describe_cluster_parameter_groups(:parameter_group_name=>parameter_group).body['ParameterGroups'].empty?
tests("verify deletion").returns(true) { not_present }
end
end
end
fog-aws-0.7.6/tests/requests/redshift/cluster_tests.rb 0000644 0000041 0000041 00000006251 12576636531 023216 0 ustar www-data www-data Shindo.tests('Fog::Redshift[:aws] | cluster requests', ['aws']) do
pending if Fog.mocking?
identifier = "test-cluster-#{rand(65536).to_s(16)}"
@cluster_format = {
'Cluster' => {
"ClusterParameterGroups" => [{
"ClusterParameterGroup" => {
"ParameterApplyStatus" => String,
"ParameterGroupName" => String
}
}],
"ClusterSecurityGroups" => [{
'ClusterSecurityGroup' => {
"Status" => String,
"ClusterSecurityGroupName" => String
}
}],
"VpcSecurityGroups" => Fog::Nullable::Array,
"EndPoint" => Fog::Nullable::Hash,
"PendingModifiedValues" => Fog::Nullable::Hash,
"RestoreStatus" => Fog::Nullable::Hash,
"ClusterVersion" => String,
"ClusterStatus" => String,
"Encrypted" => Fog::Boolean,
"NumberOfNodes" => Integer,
"PubliclyAccessible" => Fog::Boolean,
"AutomatedSnapshotRetentionPeriod" => Integer,
"DBName" => String,
"PreferredMaintenanceWindow" => String,
"NodeType" => String,
"ClusterIdentifier" => String,
"AllowVersionUpgrade" => Fog::Boolean,
"MasterUsername" => String
}
}
@describe_clusters_format = {
"ClusterSet" => [{
'Cluster' => @cluster_format['Cluster'].merge({"ClusterCreateTime"=>Time, "AvailabilityZone"=>String, "EndPoint"=>{"Port"=>Integer, "Address"=>String}})
}]
}
tests('success') do
tests('create_cluster').formats(@cluster_format) do
body = Fog::AWS[:redshift].create_cluster(:cluster_identifier => identifier,
:master_user_password => 'Password1234',
:master_username => 'testuser',
:node_type => 'dw.hs1.xlarge',
:cluster_type => 'single-node').body
Fog.wait_for do
"available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body['ClusterSet'].first['Cluster']['ClusterStatus']
end
body
end
tests('describe_clusters').formats(@describe_clusters_format["ClusterSet"]) do
sleep 30 unless Fog.mocking?
body = Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body["ClusterSet"]
body
end
tests('reboot_cluster') do
sleep 30 unless Fog.mocking?
body = Fog::AWS[:redshift].reboot_cluster(:cluster_identifier=>identifier).body
tests("verify reboot").returns("rebooting") { body['Cluster']['ClusterStatus']}
body
end
tests('delete_cluster') do
Fog.wait_for do
"available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>identifier).body['ClusterSet'].first['Cluster']['ClusterStatus']
end
sleep 30 unless Fog.mocking?
body = Fog::AWS[:redshift].delete_cluster(:cluster_identifier=>identifier, :skip_final_cluster_snapshot=>true).body
tests("verify delete").returns("deleting") { body['Cluster']['ClusterStatus']}
body
end
end
end
fog-aws-0.7.6/tests/requests/redshift/cluster_security_group_tests.rb 0000644 0000041 0000041 00000003200 12576636531 026350 0 ustar www-data www-data Shindo.tests('Fog::Redshift[:aws] | cluster security group requests', ['aws']) do
pending if Fog.mocking?
suffix = rand(65536).to_s(16)
identifier = "test-cluster-security-group-#{suffix}"
@cluster_security_group_format = {
"ClusterSecurityGroup" => {
"EC2SecurityGroups" => Fog::Nullable::Array,
"IPRanges" => Fog::Nullable::Array,
"Description" => String,
"ClusterSecurityGroupName" => String
}
}
@describe_cluster_security_groups_format = {
"ClusterSecurityGroups" => [@cluster_security_group_format]
}
tests('success') do
tests("create_cluster_security_group").formats(@cluster_security_group_format) do
body = Fog::AWS[:redshift].create_cluster_security_group(:cluster_security_group_name => identifier, :description => 'testing').body
body
end
tests("describe_cluster_security_groups").formats(@describe_cluster_security_groups_format) do
body = Fog::AWS[:redshift].describe_cluster_security_groups.body
body
end
tests("delete_cluster_security_group") do
present = !Fog::AWS[:redshift].describe_cluster_security_groups(:cluster_security_group_name => identifier).body['ClusterSecurityGroups'].empty?
tests("verify presence before deletion").returns(true) { present }
Fog::AWS[:redshift].delete_cluster_security_group(:cluster_security_group_name => identifier)
not_present = Fog::AWS[:redshift].describe_cluster_security_groups(:cluster_security_group_name => identifier).body['ClusterSecurityGroups'].empty?
tests("verify deletion").returns(true) { not_present }
end
end
end
fog-aws-0.7.6/tests/requests/redshift/cluster_snapshot_tests.rb 0000644 0000041 0000041 00000006474 12576636531 025144 0 ustar www-data www-data Shindo.tests('Fog::Redshift[:aws] | cluster snapshot requests', ['aws']) do
pending if Fog.mocking?
suffix = rand(65536).to_s(16)
identifier = "test-snapshot-#{suffix}"
cluster = "test-cluster-#{suffix}"
start_time = Fog::Time.now.to_iso8601_basic
@cluster_snapshot_format = {
'Snapshot' => {
"AccountsWithRestoreAccess" => Fog::Nullable::Array,
"Port" => Integer,
"SnapshotIdentifier" => String,
"OwnerAccount" => String,
"Status" => String,
"SnapshotType" => String,
"ClusterVersion" => String,
"EstimatedSecondsToCompletion" => Integer,
"SnapshotCreateTime" => Time,
"Encrypted" => Fog::Boolean,
"NumberOfNodes" => Integer,
"DBName" => String,
"CurrentBackupRateInMegaBytesPerSecond" => Float,
"ClusterCreateTime" => Time,
"AvailabilityZone" => String,
"ActualIncrementalBackupSizeInMegaBytes" => Float,
"TotalBackupSizeInMegaBytes" => Float,
"ElapsedTimeInSeconds" => Integer,
"BackupProgressInMegaBytes" => Float,
"NodeType" => String,
"ClusterIdentifier" => String,
"MasterUsername" => String
}
}
@describe_cluster_snapshots_format = {
"Snapshots" => [@cluster_snapshot_format]
}
tests('success') do
tests("create_cluster_snapshot").formats(@cluster_snapshot_format) do
Fog::AWS[:redshift].create_cluster(:cluster_identifier => cluster,
:master_user_password => 'Pass1234',
:master_username => 'testuser',
:node_type => 'dw.hs1.xlarge',
:cluster_type => 'single-node')
Fog.wait_for do
"available" == Fog::AWS[:redshift].describe_clusters(:cluster_identifier=>cluster).body['ClusterSet'].first['Cluster']['ClusterStatus']
end
body = Fog::AWS[:redshift].create_cluster_snapshot(:snapshot_identifier => identifier,
:cluster_identifier => cluster).body
body
end
tests('describe_cluster_snaphots').formats(@describe_cluster_snapshots_format) do
sleep 30 unless Fog.mocking?
body = Fog::AWS[:redshift].describe_cluster_snapshots(:start_time=>start_time).body
body
end
tests('delete_cluster_snapshot').formats(@cluster_snapshot_format) do
Fog.wait_for do
"available" == Fog::AWS[:redshift].describe_cluster_snapshots(:snapshot_identifier=>identifier).body['Snapshots'].first['Snapshot']['Status']
end
sleep 30 unless Fog.mocking?
body = Fog::AWS[:redshift].delete_cluster_snapshot(:snapshot_identifier=>identifier).body
body
end
Fog::AWS[:redshift].delete_cluster(:cluster_identifier => cluster,
:skip_final_cluster_snapshot => true)
end
end
fog-aws-0.7.6/tests/requests/beanstalk/ 0000755 0000041 0000041 00000000000 12576636531 020116 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/beanstalk/application_tests.rb 0000644 0000041 0000041 00000010147 12576636531 024173 0 ustar www-data www-data Shindo.tests('AWS::ElasticBeanstalk | application_tests', ['aws', 'beanstalk']) do
def unique_name(prefix)
#get time (with 1/100th of sec accuracy)
#want unique domain name and if provider is fast, this can be called more than once per second
time = Time.now.to_i.to_s
prefix + time
end
unless Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
end
@test_description = "A unique description."
@test_app_name = unique_name("fog-test-app-")
tests('success') do
pending if Fog.mocking?
@describe_applications_format = {
'DescribeApplicationsResult' => {
'Applications' => [
'ApplicationName' => String,
'ConfigurationTemplates' => [String],
'Description' => Fog::Nullable::String,
'DateCreated' => Time,
'DateUpdated' => Time,
'Versions' => [String]
]},
'ResponseMetadata' => {'RequestId'=> String},
}
tests("#describe_applications format").formats(@describe_applications_format) do
result = @beanstalk.describe_applications.body
end
test("#create_application") {
response = @beanstalk.create_application({
'ApplicationName' => @test_app_name,
'Description' => @test_description
})
result = false
if response.status == 200
app_info = response.body['CreateApplicationResult']['Application']
if app_info
if app_info['ApplicationName'] == @test_app_name &&
app_info['Description'] == @test_description &&
app_info['ConfigurationTemplates'].empty? &&
app_info['Versions'].empty?
result = true
end
end
end
result
}
test("#describe_applications all") {
response = @beanstalk.describe_applications
result = false
if response.status == 200
apps = response.body['DescribeApplicationsResult']['Applications']
apps.each { |app_info|
if app_info
if app_info['ApplicationName'] == @test_app_name &&
app_info['Description'] == @test_description &&
app_info['ConfigurationTemplates'].empty? &&
app_info['Versions'].empty?
result = true
end
end
}
end
result
}
test("#create_application filter") {
# Test for a specific app
response = @beanstalk.describe_applications([@test_app_name])
result = false
if response.status == 200
apps = response.body['DescribeApplicationsResult']['Applications']
if apps && apps.length == 1
app_info = apps.first
if app_info['ApplicationName'] == @test_app_name &&
app_info['Description'] == @test_description &&
app_info['ConfigurationTemplates'].empty? &&
app_info['Versions'].empty?
result = true
end
end
end
result
}
test("#update_application description") {
@test_description = "A completely new description."
response = @beanstalk.update_application({
'ApplicationName' => @test_app_name,
'Description' => @test_description
})
result = false
if response.status == 200
app_info = response.body['UpdateApplicationResult']['Application']
if app_info
if app_info['ApplicationName'] == @test_app_name &&
app_info['Description'] == @test_description &&
app_info['ConfigurationTemplates'].empty? &&
app_info['Versions'].empty?
result = true
end
end
end
result
}
test("#delete_application") {
response = @beanstalk.delete_application(@test_app_name)
result = false
if response.status == 200
result = true
end
result
}
end
end
fog-aws-0.7.6/tests/requests/beanstalk/solution_stack_tests.rb 0000644 0000041 0000041 00000001217 12576636531 024727 0 ustar www-data www-data Shindo.tests('AWS::ElasticBeanstalk | solution_stack_tests', ['aws', 'beanstalk']) do
tests('success') do
pending if Fog.mocking?
@solution_stack_result_format = {
'ListAvailableSolutionStacksResult' => {
'SolutionStackDetails' => [
'SolutionStackName' => String,
'PermittedFileTypes' => [String]
],
'SolutionStacks' => [String]
},
'ResponseMetadata' => {'RequestId'=> String},
}
tests("#list_available_solution_stacks").formats(@solution_stack_result_format) do
Fog::AWS[:beanstalk].list_available_solution_stacks.body
end
end
end
fog-aws-0.7.6/tests/requests/cloud_watch/ 0000755 0000041 0000041 00000000000 12576636531 020446 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/cloud_watch/put_metric_data_tests.rb 0000644 0000041 0000041 00000002575 12576636531 025372 0 ustar www-data www-data Shindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do
tests('success') do
namespace = 'Custom/Test'
@puts_format = {'ResponseMetadata' => {'RequestId' => String}}
tests('#puts_value').formats(@puts_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'Value' => 1}]).body
end
tests('#puts_statistics_set').succeeds do
pending if Fog.mocking?
Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'StatisticValues' => {'Minimum' => 0, 'Maximum' => 9, 'Sum' => 45, 'SampleCount' => 10, 'Average' => 4.5}}]).body
end
tests('#puts with dimensions').succeeds do
pending if Fog.mocking?
dimensions = [{}]
Fog::AWS[:cloud_watch].put_metric_data(namespace, [{'MetricName' => 'RequestTest', 'Unit' => 'None', 'Value' => 1, 'Dimensions' => dimensions}]).body
end
tests('#puts more than one').succeeds do
pending if Fog.mocking?
datapoints = (0...3).map do |i|
dp = {'MetricName' => "#{i}RequestTest", 'Unit' => 'None', 'Value' => i}
if i%2==0
dp['Dimensions'] = [{'Name' => 'Ruler', 'Value' => "measurement_#{i}"}]
end
dp
end
Fog::AWS[:cloud_watch].put_metric_data(namespace, datapoints).body
end
end
end
fog-aws-0.7.6/tests/requests/cloud_watch/list_metrics_test.rb 0000644 0000041 0000041 00000003740 12576636531 024537 0 ustar www-data www-data Shindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do
tests('success') do
@metrics_list_format = {
'ListMetricsResult' => {
'Metrics' =>
[{
'Dimensions' =>
[{
'Name' => String,
'Value' => String
}],
"MetricName" => String,
"Namespace" => String
}],
'NextToken' => Fog::Nullable::String,
},
'ResponseMetadata' => {"RequestId"=> String},
}
@instanceId = 'i-2f3eab59'
@dimension_filtered_metrics_list_format = {
'ListMetricsResult' => {
'Metrics' =>
[{
'Dimensions' =>
[{
'Name' => 'InstanceId',
'Value' => @instanceId
}],
"MetricName" => String,
"Namespace" => String
}],
'NextToken' => Fog::Nullable::String,
},
'ResponseMetadata' => {"RequestId"=> String},
}
tests("#list_metrics").formats(@metrics_list_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_watch].list_metrics.body
end
tests("#dimension_filtered_list_metrics").formats(@dimension_filtered_metrics_list_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_watch].list_metrics('Dimensions' => [{'Name' => 'InstanceId', 'Value' => @instanceId}]).body
end
tests("#metric_name_filtered_list_metrics").returns(true) do
pending if Fog.mocking?
metricName = "CPUUtilization"
Fog::AWS[:cloud_watch].list_metrics('MetricName' => metricName).body['ListMetricsResult']['Metrics'].all? do |metric|
metric['MetricName'] == metricName
end
end
tests("#namespace_filtered_list_metrics").returns(true) do
pending if Fog.mocking?
namespace = "AWS/EC2"
Fog::AWS[:cloud_watch].list_metrics('Namespace' => namespace).body['ListMetricsResult']['Metrics'].all? do |metric|
metric['Namespace'] == namespace
end
end
end
end
fog-aws-0.7.6/tests/requests/cloud_watch/get_metric_statistics_tests.rb 0000644 0000041 0000041 00000001777 12576636531 026625 0 ustar www-data www-data Shindo.tests('AWS::CloudWatch | metric requests', ['aws', 'cloudwatch']) do
tests('success') do
@metrics_statistic_format = {
'GetMetricStatisticsResult' => {
'Label' => String,
'Datapoints' => [{
"Timestamp" => Time,
'Unit' => String,
'Minimum' => Float,
'Maximum' => Float,
'Average' => Float,
'Sum' => Float,
'SampleCount' => Float
}],
},
'ResponseMetadata' => {
'RequestId' => String
}
}
tests("#get_metric_statistics").formats(@metrics_statistic_format) do
pending if Fog.mocking?
instanceId = 'i-420c352f'
Fog::AWS[:cloud_watch].get_metric_statistics({'Statistics' => ['Minimum','Maximum','Sum','SampleCount','Average'], 'StartTime' => (Time.now-600).iso8601, 'EndTime' => Time.now.iso8601, 'Period' => 60, 'MetricName' => 'DiskReadBytes', 'Namespace' => 'AWS/EC2', 'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instanceId}]}).body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/ 0000755 0000041 0000041 00000000000 12576636531 016724 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/ecs/task_tests.rb 0000644 0000041 0000041 00000013170 12576636531 021437 0 ustar www-data www-data require 'fog/json'
Shindo.tests('AWS::ECS | task requests', ['aws', 'ecs']) do
Fog::AWS[:ecs].reset_data
tests('success') do
tests("#list_tasks").formats(AWS::ECS::Formats::LIST_TASKS) do
result = Fog::AWS[:ecs].list_tasks.body
list_instances_arns = result['ListTasksResult']['taskArns']
returns(true) { list_instances_arns.empty? }
result
end
tests("#run_task").formats(AWS::ECS::Formats::RUN_TASK) do
task_def_params = Fog::JSON.decode(IO.read(AWS::ECS::Samples::TASK_DEFINITION_1))
result1 = Fog::AWS[:ecs].register_task_definition(task_def_params).body
task_def = result1['RegisterTaskDefinitionResult']['taskDefinition']
task_def_arn = task_def['taskDefinitionArn']
result2 = Fog::AWS[:ecs].run_task('taskDefinition' => task_def_arn).body
task = result2['RunTaskResult']['tasks'].first
returns(true) { task.has_key?('containerInstanceArn') }
returns(true) { task['containers'].size.eql?(2) }
returns(true) { task['desiredStatus'].eql?('RUNNING') }
returns(true) { task['taskDefinitionArn'].eql?(task_def_arn) }
result2
end
tests("#describe_tasks").formats(AWS::ECS::Formats::DESCRIBE_TASKS) do
result1 = Fog::AWS[:ecs].list_tasks.body
task_arn = result1['ListTasksResult']['taskArns'].first
result2 = Fog::AWS[:ecs].describe_tasks('tasks' => task_arn).body
task = result2['DescribeTasksResult']['tasks'].first
returns(true) { task['taskArn'].eql?(task_arn) }
returns(true) { task['containers'].size.eql?(2) }
returns(true) { task['desiredStatus'].eql?('RUNNING') }
result2
end
tests("#list_tasks").formats(AWS::ECS::Formats::LIST_TASKS) do
result = Fog::AWS[:ecs].list_tasks.body
list_instances_arns = result['ListTasksResult']['taskArns']
returns(false) { list_instances_arns.empty? }
result
end
tests("#stop_task").formats(AWS::ECS::Formats::STOP_TASK) do
result1 = Fog::AWS[:ecs].list_tasks.body
task_arn = result1['ListTasksResult']['taskArns'].first
result2 = Fog::AWS[:ecs].stop_task('task' => task_arn).body
task = result2['StopTaskResult']['task']
returns(true) { task['taskArn'].eql?(task_arn) }
returns(true) { task['containers'].size.eql?(2) }
returns(true) { task['desiredStatus'].eql?('STOPPED') }
result2
end
tests("#start_task").formats(AWS::ECS::Formats::START_TASK) do
owner_id = Fog::AWS::Mock.owner_id
container_instance_path = "container-instance/#{Fog::UUID.uuid}"
region = "us-east-1"
container_instance_arn = Fog::AWS::Mock.arn('ecs', owner_id, container_instance_path, region)
task_def_params = Fog::JSON.decode(IO.read(AWS::ECS::Samples::TASK_DEFINITION_1))
result1 = Fog::AWS[:ecs].register_task_definition(task_def_params).body
task_def = result1['RegisterTaskDefinitionResult']['taskDefinition']
task_def_arn = task_def['taskDefinitionArn']
result2 = Fog::AWS[:ecs].start_task(
'taskDefinition' => task_def_arn,
'containerInstances' => container_instance_arn
).body
task = result2['StartTaskResult']['tasks'].first
returns(true) { task['containerInstanceArn'].eql?(container_instance_arn) }
returns(true) { task['containers'].size.eql?(2) }
returns(true) { task['desiredStatus'].eql?('RUNNING') }
returns(true) { task['taskDefinitionArn'].eql?(task_def_arn) }
result2
end
tests("#list_tasks").formats(AWS::ECS::Formats::LIST_TASKS) do
result = Fog::AWS[:ecs].list_tasks.body
list_instances_arns = result['ListTasksResult']['taskArns']
returns(false) { list_instances_arns.empty? }
result
end
end
tests('failures') do
tests("#describe_tasks nonexistent") do
task_arn = "arn:aws:ecs:us-west-2:938269302734:task/6893440f-2165-47aa-8cfa-b2f413a26f00"
result = Fog::AWS[:ecs].describe_tasks('tasks' => task_arn).body
end
tests('describe_tasks without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].describe_tasks.body
end
tests('#run_task without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].run_task.body
end
tests('#run_task nonexistent').raises(Fog::AWS::ECS::Error) do
task_def_arn = "arn:aws:ecs:us-west-2:539573770077:task-definition/foo-xanadu-app-static:33"
response = Fog::AWS[:ecs].run_task('taskDefinition' => task_def_arn).body
end
tests('#start_task without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].start_task.body
end
tests('#start_task with missing params').raises(Fog::AWS::ECS::Error) do
task_def_arn = "arn:aws:ecs:us-west-2:539573770077:task-definition/foo-xanadu-app-static:33"
response = Fog::AWS[:ecs].start_task('taskDefinition' => task_def_arn).body
end
tests('#start_task nonexistent').raises(Fog::AWS::ECS::Error) do
task_def_arn = "arn:aws:ecs:us-west-2:539573770077:task-definition/foo-xanadu-app-static:33"
container_instance_arn = "arn:aws:ecs:us-west-2:938269302734:container-instance/6893440f-2165-47aa-8cfa-b2f413a26f00"
response = Fog::AWS[:ecs].start_task(
'taskDefinition' => task_def_arn,
'containerInstances' => container_instance_arn
).body
end
tests('#stop_task without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].stop_task.body
end
tests('#stop_task nonexistent params').raises(Fog::AWS::ECS::Error) do
task_arn = "arn:aws:ecs:us-west-2:938269302734:task/6893440f-2165-47aa-8cfa-b2f413a26f00"
response = Fog::AWS[:ecs].stop_task('task' => task_arn).body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/helper.rb 0000644 0000041 0000041 00000023145 12576636531 020535 0 ustar www-data www-data class AWS
module ECS
module Formats
BASIC = {
'ResponseMetadata' => { 'RequestId' => String }
}
CREATE_CLUSTER = BASIC.merge({
'CreateClusterResult' => {
'cluster' => {
'clusterName' => String,
'clusterArn' => String,
'status' => String,
'registeredContainerInstancesCount' => Integer,
'runningTasksCount' => Integer,
'pendingTasksCount' => Integer
}
}
})
LIST_CLUSTERS = BASIC.merge({
'ListClustersResult' => {
'clusterArns' => [String],
'nextToken' => Fog::Nullable::String
}
})
DELETE_CLUSTER = BASIC.merge({
'DeleteClusterResult' => {
'cluster' => {
'clusterName' => String,
'clusterArn' => String,
'status' => String,
'registeredContainerInstancesCount' => Integer,
'runningTasksCount' => Integer,
'pendingTasksCount' => Integer
}
}
})
DESCRIBE_CLUSTERS = BASIC.merge({
'DescribeClustersResult' => {
'failures' => [Fog::Nullable::Hash],
'clusters' => [Fog::Nullable::Hash]
}
})
REGISTER_TASK_DEFINITION = BASIC.merge({
'RegisterTaskDefinitionResult' => {
'taskDefinition' => {
'revision' => Integer,
'taskDefinitionArn' => String,
'family' => String,
'containerDefinitions' => [Hash],
'volumes' => Fog::Nullable::Array
}
}
})
LIST_TASK_DEFINITIONS = BASIC.merge({
'ListTaskDefinitionsResult' => {
'taskDefinitionArns' => [String]
}
})
DESCRIBE_TASK_DEFINITION = BASIC.merge({
'DescribeTaskDefinitionResult' => {
'taskDefinition' => {
'revision' => Integer,
'taskDefinitionArn' => String,
'family' => String,
'containerDefinitions' => [Hash],
'volumes' => Fog::Nullable::Array
}
}
})
DEREGISTER_TASK_DEFINITION = BASIC.merge({
'DeregisterTaskDefinitionResult' => {
'taskDefinition' => {
'revision' => Integer,
'taskDefinitionArn' => String,
'family' => String,
'containerDefinitions' => [Hash],
'volumes' => Fog::Nullable::Array
}
}
})
LIST_TASK_DEFINITION_FAMILIES = BASIC.merge({
'ListTaskDefinitionFamiliesResult' => {
'families' => [String]
}
})
CREATE_SERVICE = BASIC.merge({
'CreateServiceResult' => {
'service' => {
'events' => [Fog::Nullable::Hash],
'serviceName' => String,
'serviceArn' => String,
'taskDefinition' => String,
'clusterArn' => String,
'status' => String,
'roleArn' => Fog::Nullable::String,
'loadBalancers' => [Fog::Nullable::Hash],
'deployments' => [Fog::Nullable::Hash],
'desiredCount' => Integer,
'pendingCount' => Integer,
'runningCount' => Integer
}
}
})
DELETE_SERVICE = BASIC.merge({
'DeleteServiceResult' => {
'service' => {
'events' => [Fog::Nullable::Hash],
'serviceName' => String,
'serviceArn' => String,
'taskDefinition' => String,
'clusterArn' => String,
'status' => String,
'roleArn' => Fog::Nullable::String,
'loadBalancers' => [Fog::Nullable::Hash],
'deployments' => [Fog::Nullable::Hash],
'desiredCount' => Integer,
'pendingCount' => Integer,
'runningCount' => Integer
}
}
})
DESCRIBE_SERVICES = BASIC.merge({
'DescribeServicesResult' => {
'failures' => [Fog::Nullable::Hash],
'services' => [{
'events' => [Fog::Nullable::Hash],
'serviceName' => String,
'serviceArn' => String,
'taskDefinition' => String,
'clusterArn' => String,
'status' => String,
'roleArn' => Fog::Nullable::String,
'loadBalancers' => [Fog::Nullable::Hash],
'deployments' => [Fog::Nullable::Hash],
'desiredCount' => Integer,
'pendingCount' => Integer,
'runningCount' => Integer
}]
}
})
LIST_SERVICES = BASIC.merge({
'ListServicesResult' => {
'serviceArns' => [Fog::Nullable::String],
'nextToken' => Fog::Nullable::String
}
})
UPDATE_SERVICE = BASIC.merge({
'UpdateServiceResult' => {
'service' => {
'events' => [Fog::Nullable::Hash],
'serviceName' => String,
'serviceArn' => String,
'taskDefinition' => String,
'clusterArn' => String,
'status' => String,
'roleArn' => Fog::Nullable::String,
'loadBalancers' => [Fog::Nullable::Hash],
'deployments' => [Fog::Nullable::Hash],
'desiredCount' => Integer,
'pendingCount' => Integer,
'runningCount' => Integer
}
}
})
LIST_CONTAINER_INSTANCES = BASIC.merge({
'ListContainerInstancesResult' => {
'containerInstanceArns' => [Fog::Nullable::String]
}
})
DESCRIBE_CONTAINER_INSTANCES = BASIC.merge({
'DescribeContainerInstancesResult' => {
'containerInstances' => [{
'remainingResources' => [Hash],
'agentConnected' => Fog::Boolean,
'runningTasksCount' => Integer,
'status' => String,
'registeredResources' => [Hash],
'containerInstanceArn' => String,
'pendingTasksCount' => Integer,
'ec2InstanceId' => String
}],
'failures' => [Fog::Nullable::Hash],
}
})
DEREGISTER_CONTAINER_INSTANCE = BASIC.merge({
'DeregisterContainerInstanceResult' => {
'containerInstance' => {
'remainingResources' => [Hash],
'agentConnected' => Fog::Boolean,
'runningTasksCount' => Integer,
'status' => String,
'registeredResources' => [Hash],
'containerInstanceArn' => String,
'pendingTasksCount' => Integer,
'ec2InstanceId' => String
}
}
})
LIST_TASKS = BASIC.merge({
'ListTasksResult' => {
'taskArns' => [Fog::Nullable::String]
}
})
DESCRIBE_TASKS = BASIC.merge({
'DescribeTasksResult' => {
'failures' => [Fog::Nullable::Hash],
'tasks' => [
{
'clusterArn' => String,
'containers' => Array,
'overrides' => Fog::Nullable::Hash,
'startedBy' => Fog::Nullable::String,
'desiredStatus' => String,
'taskArn' => String,
'containerInstanceArn' => String,
'lastStatus' => String,
'taskDefinitionArn' => String
}
]
}
})
RUN_TASK = BASIC.merge({
'RunTaskResult' => {
'failures' => [Fog::Nullable::Hash],
'tasks' => [
{
'clusterArn' => String,
'containers' => [Hash],
'overrides' => Fog::Nullable::Hash,
'desiredStatus' => String,
'taskArn' => String,
'containerInstanceArn' => String,
'lastStatus' => String,
'taskDefinitionArn' => String
}
]
}
})
STOP_TASK = BASIC.merge({
'StopTaskResult' => {
'task' => {
'clusterArn' => String,
'containers' => [Hash],
'overrides' => Fog::Nullable::Hash,
'desiredStatus' => String,
'taskArn' => String,
'startedBy' => Fog::Nullable::String,
'containerInstanceArn' => String,
'lastStatus' => String,
'taskDefinitionArn' => String
}
}
})
START_TASK = BASIC.merge({
'StartTaskResult' => {
'failures' => [Fog::Nullable::Hash],
'tasks' => [
{
'clusterArn' => String,
'containers' => [Hash],
'overrides' => Fog::Nullable::Hash,
'desiredStatus' => String,
'taskArn' => String,
'containerInstanceArn' => String,
'lastStatus' => String,
'taskDefinitionArn' => String
}
]
}
})
end
module Samples
TASK_DEFINITION_1 = File.dirname(__FILE__) + '/sample_task_definition1.json'
end
end
end
fog-aws-0.7.6/tests/requests/ecs/service_tests.rb 0000644 0000041 0000041 00000011553 12576636531 022140 0 ustar www-data www-data Shindo.tests('AWS::ECS | service requests', ['aws', 'ecs']) do
Fog::AWS[:ecs].reset_data
cluster = 'arn:aws:ecs:us-east-1:994922842243:cluster/default'
desired_count = 1
role = 'arn:aws:iam::806753142346:role/ecsServiceRole'
service_name = 'sample-webapp'
task_definition = 'console-sample-app-static:18'
load_balancers = [{
'containerName' => 'simple-app',
'containerPort' => 80,
'loadBalancerName' => 'ecsunittests-EcsElastic-OI09IAP3PVIP'
}]
tests('success') do
tests("#list_services").formats(AWS::ECS::Formats::LIST_SERVICES) do
result = Fog::AWS[:ecs].list_services('cluster' => cluster).body
list_services_arns = result['ListServicesResult']['serviceArns']
returns(true) { list_services_arns.empty? }
result
end
tests("#create_service").formats(AWS::ECS::Formats::CREATE_SERVICE) do
params = {
'cluster' => cluster,
'desiredCount' => desired_count,
'loadBalancers' => load_balancers,
'role' => role,
'serviceName' => service_name,
'taskDefinition' => task_definition
}
result = Fog::AWS[:ecs].create_service(params).body
service = result['CreateServiceResult']['service']
returns('sample-webapp') { service['serviceName'] }
returns(false) { service['serviceArn'].match(/^arn:aws:ecs:.+:.+:service\/.+$/).nil? }
result
end
tests("#list_services again").formats(AWS::ECS::Formats::LIST_SERVICES) do
result = Fog::AWS[:ecs].list_services('cluster' => cluster).body
list_services_arns = result['ListServicesResult']['serviceArns']
returns(false) { list_services_arns.empty? }
returns(true) { !list_services_arns.first.match(/#{service_name}/).nil? }
result
end
tests("#describe_services").formats(AWS::ECS::Formats::DESCRIBE_SERVICES) do
result1 = Fog::AWS[:ecs].list_services('cluster' => cluster).body
service_arn = result1['ListServicesResult']['serviceArns'].first
result2 = Fog::AWS[:ecs].describe_services(
'services' => service_arn,
'cluster' => cluster
).body
returns(true) { result2['DescribeServicesResult']['services'].size.eql?(1) }
service = result2['DescribeServicesResult']['services'].first
returns(true) { service['serviceName'].eql?(service_name) }
returns(true) { service['status'].eql?('ACTIVE') }
returns(false) { service['deployments'].empty? }
returns(true) { service['desiredCount'].eql?(desired_count) }
result2
end
tests("#update_service").formats(AWS::ECS::Formats::UPDATE_SERVICE) do
new_task_def = 'arn:aws:ecs:us-east-1:994922842243:task-definitions/foobar-app:32'
result1 = Fog::AWS[:ecs].list_services('cluster' => cluster).body
service_arn = result1['ListServicesResult']['serviceArns'].first
result2 = Fog::AWS[:ecs].update_service(
'service' => service_arn,
'cluster' => cluster,
'taskDefinition' => new_task_def
).body
service = result2['UpdateServiceResult']['service']
returns(true) { service['serviceName'].eql?(service_name) }
returns(true) { service['taskDefinition'].eql?(new_task_def) }
result2
end
tests("#delete_service").formats(AWS::ECS::Formats::DELETE_SERVICE) do
result1 = Fog::AWS[:ecs].list_services('cluster' => cluster).body
service_arn = result1['ListServicesResult']['serviceArns'].first
result2 = Fog::AWS[:ecs].delete_service(
'service' => service_arn,
'cluster' => cluster
).body
service = result2['DeleteServiceResult']['service']
returns(true) { service['serviceName'].eql?(service_name) }
result2
end
tests("#list_services yet again").formats(AWS::ECS::Formats::LIST_SERVICES) do
result = Fog::AWS[:ecs].list_services('cluster' => cluster).body
list_services_arns = result['ListServicesResult']['serviceArns']
returns(true) { list_services_arns.empty? }
result
end
end
tests('failures') do
tests('#describe_services without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].describe_services.body
end
tests('#create_service without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].create_service.body
end
tests('#update_service without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].update_service.body
end
tests('#update_service nonexistent').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].update_service('service' => 'whatever2329').body
end
tests('#delete_service without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].delete_service.body
end
tests('#delete_service nonexistent').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].delete_service('service' => 'foobar787383').body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/task_definitions_tests.rb 0000644 0000041 0000041 00000010232 12576636531 024026 0 ustar www-data www-data require 'fog/json'
Shindo.tests('AWS::ECS | task definitions requests', ['aws', 'ecs']) do
Fog::AWS[:ecs].reset_data
tests('success') do
tests("#list_task_definitions").formats(AWS::ECS::Formats::LIST_TASK_DEFINITIONS) do
result = Fog::AWS[:ecs].list_task_definitions.body
list_task_def_arns = result['ListTaskDefinitionsResult']['taskDefinitionArns']
returns(true) { list_task_def_arns.empty? }
result
end
tests("#register_task_definition").formats(AWS::ECS::Formats::REGISTER_TASK_DEFINITION) do
task_def_params = Fog::JSON.decode(IO.read(AWS::ECS::Samples::TASK_DEFINITION_1))
result = Fog::AWS[:ecs].register_task_definition(task_def_params).body
task_def = result['RegisterTaskDefinitionResult']['taskDefinition']
returns('console-sample-app-static') { task_def['family'] }
returns(true) { task_def['revision'] > 0 }
returns(false) { task_def['taskDefinitionArn'].match(/^arn:aws:ecs:.+:.+:task-definition\/.+:\d+$/).nil? }
result
end
tests("#list_task_definition_families").formats(AWS::ECS::Formats::LIST_TASK_DEFINITION_FAMILIES) do
result = Fog::AWS[:ecs].list_task_definition_families.body
families = result['ListTaskDefinitionFamiliesResult']['families']
returns(false) { families.empty? }
returns(true) { families.include?('console-sample-app-static') }
result
end
tests("#list_task_definitions again").formats(AWS::ECS::Formats::LIST_TASK_DEFINITIONS) do
result = Fog::AWS[:ecs].list_task_definitions.body
list_task_def_arns = result['ListTaskDefinitionsResult']['taskDefinitionArns']
returns(true) { list_task_def_arns.size.eql?(1) }
result
end
tests("#describe_task_definition").formats(AWS::ECS::Formats::DESCRIBE_TASK_DEFINITION) do
result1 = Fog::AWS[:ecs].list_task_definitions.body
task_def_arn = result1['ListTaskDefinitionsResult']['taskDefinitionArns'].first
result2 = Fog::AWS[:ecs].describe_task_definition('taskDefinition' => task_def_arn).body
task_def = result2['DescribeTaskDefinitionResult']['taskDefinition']
returns(true) { task_def['taskDefinitionArn'].eql?(task_def_arn) }
returns(true) { task_def['containerDefinitions'].size > 0 }
result2
end
tests("#deregister_task_definition").formats(AWS::ECS::Formats::DEREGISTER_TASK_DEFINITION) do
result1 = Fog::AWS[:ecs].list_task_definitions.body
task_def_arn = result1['ListTaskDefinitionsResult']['taskDefinitionArns'].first
result2 = Fog::AWS[:ecs].deregister_task_definition('taskDefinition' => task_def_arn).body
task_def = result2['DeregisterTaskDefinitionResult']['taskDefinition']
returns(true) { task_def['taskDefinitionArn'].eql?(task_def_arn) }
result2
end
tests("#list_task_definitions yet again").formats(AWS::ECS::Formats::LIST_TASK_DEFINITIONS) do
result = Fog::AWS[:ecs].list_task_definitions.body
list_task_def_arns = result['ListTaskDefinitionsResult']['taskDefinitionArns']
returns(true) { list_task_def_arns.empty? }
result
end
tests("#list_task_definition_families again").formats(AWS::ECS::Formats::LIST_TASK_DEFINITION_FAMILIES) do
result = Fog::AWS[:ecs].list_task_definition_families.body
families = result['ListTaskDefinitionFamiliesResult']['families']
returns(true) { families.empty? }
returns(false) { families.include?('console-sample-app-static') }
result
end
end
tests('failures') do
tests('#describe_task_definition without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].describe_task_definition.body
end
tests('#describe_task_definition nonexistent').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].describe_task_definition('taskDefinition' => 'foobar').body
end
tests('#deregister_task_definition without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].deregister_task_definition.body
end
tests('#deregister_task_definition nonexistent').raises(Fog::AWS::ECS::NotFound) do
response = Fog::AWS[:ecs].deregister_task_definition('taskDefinition' => 'foobar:7873287283').body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/cluster_tests.rb 0000644 0000041 0000041 00000010505 12576636531 022155 0 ustar www-data www-data Shindo.tests('AWS::ECS | cluster requests', ['aws', 'ecs']) do
Fog::AWS[:ecs].reset_data
tests('success') do
tests("#create_cluster").formats(AWS::ECS::Formats::CREATE_CLUSTER) do
result = Fog::AWS[:ecs].create_cluster('clusterName' => 'cluster1').body
cluster = result['CreateClusterResult']['cluster']
returns('cluster1') { cluster['clusterName'] }
returns('ACTIVE') { cluster['status'] }
result
end
tests("#create_cluster another").formats(AWS::ECS::Formats::CREATE_CLUSTER) do
result = Fog::AWS[:ecs].create_cluster('clusterName' => 'foobar').body
cluster = result['CreateClusterResult']['cluster']
returns('foobar') { cluster['clusterName'] }
returns('ACTIVE') { cluster['status'] }
result
end
tests("#create_cluster without params").formats(AWS::ECS::Formats::CREATE_CLUSTER) do
result = Fog::AWS[:ecs].create_cluster.body
cluster = result['CreateClusterResult']['cluster']
returns('default') { cluster['clusterName'] }
result
end
tests("#list_clusters").formats(AWS::ECS::Formats::LIST_CLUSTERS) do
result = Fog::AWS[:ecs].list_clusters.body
clusters = result['ListClustersResult']['clusterArns']
returns(true) { clusters.size.eql?(3) }
result
end
tests("#describe_clusters with name").formats(AWS::ECS::Formats::DESCRIBE_CLUSTERS) do
result = Fog::AWS[:ecs].describe_clusters('clusters' => 'cluster1').body
clusters = result['DescribeClustersResult']['clusters']
failures = result['DescribeClustersResult']['failures']
returns(true) { clusters.size.eql?(1) }
returns('cluster1') { clusters.first['clusterName'] }
returns(true) { failures.empty? }
result
end
tests("#describe_clusters without params").formats(AWS::ECS::Formats::DESCRIBE_CLUSTERS) do
result = Fog::AWS[:ecs].describe_clusters.body
clusters = result['DescribeClustersResult']['clusters']
failures = result['DescribeClustersResult']['failures']
returns(true) { clusters.size.eql?(1) }
returns('default') { clusters.first['clusterName'] }
result
end
tests("#describe_clusters several with name").formats(AWS::ECS::Formats::DESCRIBE_CLUSTERS) do
result = Fog::AWS[:ecs].describe_clusters('clusters' => %w(cluster1 foobar)).body
clusters = result['DescribeClustersResult']['clusters']
cluster_names = clusters.map { |c| c['clusterName'] }.sort
returns(true) { clusters.size.eql?(2) }
returns('cluster1') { cluster_names.first }
returns('foobar') { cluster_names[1] }
result
end
tests("#describe_clusters with errors").formats(AWS::ECS::Formats::DESCRIBE_CLUSTERS) do
result = Fog::AWS[:ecs].describe_clusters('clusters' => %w(foobar not_here wtf)).body
clusters = result['DescribeClustersResult']['clusters']
failures = result['DescribeClustersResult']['failures']
returns(true) { failures.size.eql?(2) }
returns('MISSING') { failures.first['reason'] }
returns(true) { clusters.size.eql?(1) }
result
end
tests("#delete_cluster").formats(AWS::ECS::Formats::DELETE_CLUSTER) do
cluster_name = 'foobar'
result = Fog::AWS[:ecs].delete_cluster('cluster' => cluster_name).body
cluster = result['DeleteClusterResult']['cluster']
returns(true) { cluster['clusterName'].eql?(cluster_name) }
returns('INACTIVE') { cluster['status'] }
result
end
tests("#list_clusters after one delete").formats(AWS::ECS::Formats::LIST_CLUSTERS) do
result = Fog::AWS[:ecs].list_clusters.body
clusters = result['ListClustersResult']['clusterArns']
returns(true) { clusters.size.eql?(2) }
result
end
tests("#delete_cluster by arn").formats(AWS::ECS::Formats::DELETE_CLUSTER) do
result1 = Fog::AWS[:ecs].describe_clusters.body
cluster1 = result1['DescribeClustersResult']['clusters'].first
result2 = Fog::AWS[:ecs].delete_cluster('cluster' => cluster1['clusterArn']).body
cluster2 = result2['DeleteClusterResult']['cluster']
returns('default') { cluster2['clusterName'] }
returns('INACTIVE') { cluster2['status'] }
result2
end
end
tests('failures') do
tests('#delete_cluster without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].delete_cluster.body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/container_instance_tests.rb 0000644 0000041 0000041 00000010625 12576636531 024345 0 ustar www-data www-data Shindo.tests('AWS::ECS | container instance requests', ['aws', 'ecs']) do
Fog::AWS[:ecs].reset_data
container_instance_arn = 'arn:aws:ecs:us-west-2:738152598183:container-instance/eff1068d-5fcb-4804-89f0-7d18ffc6879c'
ec2_instance_id = 'i-58f4b4ae'
Fog::AWS[:ecs].data[:container_instances] << {
'remainingResources' => [
{
'longValue' => 0,
'name' => 'CPU',
'integerValue' => 1004,
'doubleValue' => 0.0,
'type' => 'INTEGER'
},
{
'longValue' => 0,
'name' => 'MEMORY',
'integerValue' => 496,
'doubleValue' => 0.0,
'type' => 'INTEGER'
},
{
'stringSetValue' => [2376, 22, 80, 51678, 2375],
'longValue' => 0,
'name' => 'PORTS',
'integerValue' => 0,
'doubleValue' => 0.0,
'type' => 'STRINGSET'
}
],
'agentConnected' => true,
'runningTasksCount' => 1,
'status' => 'ACTIVE',
'registeredResources' => [
{
'longValue' => 0,
'name' => 'CPU',
'integerValue' => 1024,
'doubleValue' => 0.0,
'type' => 'INTEGER'
},
{
'longValue' => 0,
'name' => 'MEMORY',
'integerValue' => 996,
'doubleValue' => 0.0,
'type' => 'INTEGER'
},
{
'stringSetValue' => [2376, 22, 80, 51678, 2375],
'longValue' => 0,
'name' => 'PORTS',
'integerValue' => 0,
'doubleValue' => 0.0,
'type' => 'STRINGSET'
}
],
'containerInstanceArn' => container_instance_arn,
'pendingTasksCount' => 0,
'ec2InstanceId' => ec2_instance_id
}
tests('success') do
tests("#list_container_instances").formats(AWS::ECS::Formats::LIST_CONTAINER_INSTANCES) do
result = Fog::AWS[:ecs].list_container_instances.body
list_instances_arns = result['ListContainerInstancesResult']['containerInstanceArns']
returns(false) { list_instances_arns.empty? }
returns(true) { list_instances_arns.first.eql?(container_instance_arn) }
result
end
tests("#describe_container_instances").formats(AWS::ECS::Formats::DESCRIBE_CONTAINER_INSTANCES) do
result = Fog::AWS[:ecs].describe_container_instances('containerInstances' => container_instance_arn).body
instance = result['DescribeContainerInstancesResult']['containerInstances'].first
returns(true) { instance['containerInstanceArn'].eql?(container_instance_arn) }
returns(true) { instance['ec2InstanceId'].eql?(ec2_instance_id) }
returns(true) { instance['status'].eql?('ACTIVE') }
result
end
tests("#deregister_container_instance").formats(AWS::ECS::Formats::DEREGISTER_CONTAINER_INSTANCE) do
result = Fog::AWS[:ecs].deregister_container_instance('containerInstance' => container_instance_arn).body
instance = result['DeregisterContainerInstanceResult']['containerInstance']
returns(true) { instance['containerInstanceArn'].eql?(container_instance_arn) }
returns(true) { instance['ec2InstanceId'].eql?(ec2_instance_id) }
returns(true) { instance['pendingTasksCount'].eql?(0) }
result
end
tests("#list_container_instances again").formats(AWS::ECS::Formats::LIST_CONTAINER_INSTANCES) do
result = Fog::AWS[:ecs].list_container_instances.body
list_instances_arns = result['ListContainerInstancesResult']['containerInstanceArns']
returns(true) { list_instances_arns.empty? }
result
end
end
tests('failures') do
tests('#describe_container_instances without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].describe_container_instances.body
end
tests('#deregister_container_instance without params').raises(Fog::AWS::ECS::Error) do
response = Fog::AWS[:ecs].deregister_container_instance.body
end
tests('#deregister_container_instance nonexistent').raises(Fog::AWS::ECS::Error) do
instance_uuid = 'ffffffff-ffff-0000-ffff-deadbeefff'
response = Fog::AWS[:ecs].deregister_container_instance('containerInstance' => instance_uuid).body
end
end
end
fog-aws-0.7.6/tests/requests/ecs/sample_task_definition1.json 0000644 0000041 0000041 00000002717 12576636531 024422 0 ustar www-data www-data {
"family": "console-sample-app-static",
"containerDefinitions": [
{
"name": "simple-app",
"image": "httpd:2.4",
"cpu": 10,
"memory": 300,
"environment": [],
"portMappings": [
{
"hostPort": 80,
"containerPort": 80
}
],
"volumesFrom": [],
"links": [],
"mountPoints": [
{
"sourceVolume": "my-vol",
"containerPath": "/usr/local/apache2/htdocs"
}
],
"essential": true
},
{
"name": "busybox",
"image": "busybox",
"cpu": 10,
"memory": 200,
"entryPoint": [
"sh",
"-c"
],
"environment": [],
"command": [
"/bin/sh -c \"while true; do echo '
Amazon ECS Sample App Amazon ECS Sample App
Congratulations!
Your application is now running on a container in Amazon ECS.
' > top; /bin/date > date ; echo '
' > bottom; cat top date bottom > /usr/local/apache2/htdocs/index.html ; sleep 1; done\""
],
"portMappings": [],
"volumesFrom": [
{
"sourceContainer": "simple-app"
}
],
"links": [],
"mountPoints": [],
"essential": false
}
],
"volumes": [
{
"name": "my-vol",
"host": {}
}
]
}
fog-aws-0.7.6/tests/requests/glacier/ 0000755 0000041 0000041 00000000000 12576636531 017560 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/glacier/multipart_upload_tests.rb 0000644 0000041 0000041 00000003026 12576636531 024715 0 ustar www-data www-data Shindo.tests('AWS::Glacier | glacier archive tests', ['aws']) do
pending if Fog.mocking?
Fog::AWS[:glacier].create_vault('Fog-Test-Vault-upload')
tests('initiate and abort') do
id = Fog::AWS[:glacier].initiate_multipart_upload('Fog-Test-Vault-upload', 1024*1024).headers['x-amz-multipart-upload-id']
returns(true){ Fog::AWS[:glacier].list_multipart_uploads('Fog-Test-Vault-upload').body['UploadsList'].map {|item| item['MultipartUploadId']}.include?(id)}
Fog::AWS[:glacier].abort_multipart_upload('Fog-Test-Vault-upload', id)
returns(false){ Fog::AWS[:glacier].list_multipart_uploads('Fog-Test-Vault-upload').body['UploadsList'].map {|item| item['MultipartUploadId']}.include?(id)}
end
tests('do multipart upload') do
hash = Fog::AWS::Glacier::TreeHash.new
id = Fog::AWS[:glacier].initiate_multipart_upload('Fog-Test-Vault-upload', 1024*1024).headers['x-amz-multipart-upload-id']
part = 't'*1024*1024
hash_for_part = hash.add_part(part)
Fog::AWS[:glacier].upload_part('Fog-Test-Vault-upload', id, part, 0, hash_for_part)
part_2 = 'u'*1024*1024
hash_for_part_2 = hash.add_part(part_2)
Fog::AWS[:glacier].upload_part('Fog-Test-Vault-upload', id, part_2, 1024*1024, hash_for_part_2)
archive = Fog::AWS[:glacier].complete_multipart_upload('Fog-Test-Vault-upload', id, 2*1024*1024, hash.hexdigest).headers['x-amz-archive-id']
Fog::AWS[:glacier].delete_archive('Fog-Test-Vault-upload', archive)
#amazon won't let us delete the vault because it has been written to in the past day
end
end
fog-aws-0.7.6/tests/requests/glacier/tree_hash_tests.rb 0000644 0000041 0000041 00000004443 12576636531 023276 0 ustar www-data www-data Shindo.tests('AWS::Glacier | glacier tree hash calcuation', ['aws']) do
tests('tree_hash(single part < 1MB)') do
returns(Digest::SHA256.hexdigest('')) { Fog::AWS::Glacier::TreeHash.digest('')}
end
tests('tree_hash(multibyte characters)') do
body = ("\xC2\xA1" * 1024*1024)
body.force_encoding('UTF-8') if body.respond_to? :encoding
expected = Digest::SHA256.hexdigest(
Digest::SHA256.digest("\xC2\xA1" * 1024*512) + Digest::SHA256.digest("\xC2\xA1" * 1024*512)
)
returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)}
end
tests('tree_hash(power of 2 number of parts)') do
body = ('x' * 1024*1024) + ('y'*1024*1024) + ('z'*1024*1024) + ('t'*1024*1024)
expected = Digest::SHA256.hexdigest(
Digest::SHA256.digest(
Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024)
) +
Digest::SHA256.digest(
Digest::SHA256.digest('z' * 1024*1024) + Digest::SHA256.digest('t' * 1024*1024)
)
)
returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)}
end
tests('tree_hash(non power of 2 number of parts)') do
body = ('x' * 1024*1024) + ('y'*1024*1024) + ('z'*1024*1024)
expected = Digest::SHA256.hexdigest(
Digest::SHA256.digest(
Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024)
) +
Digest::SHA256.digest('z' * 1024*1024)
)
returns(expected) { Fog::AWS::Glacier::TreeHash.digest(body)}
end
tests('multipart') do
tree_hash = Fog::AWS::Glacier::TreeHash.new
part = ('x' * 1024*1024) + ('y'*1024*1024)
returns(Fog::AWS::Glacier::TreeHash.digest(part)) { tree_hash.add_part part }
tree_hash.add_part('z'* 1024*1024 + 't'*1024*1024)
expected = Digest::SHA256.hexdigest(
Digest::SHA256.digest(
Digest::SHA256.digest('x' * 1024*1024) + Digest::SHA256.digest('y' * 1024*1024)
) +
Digest::SHA256.digest(
Digest::SHA256.digest('z' * 1024*1024) + Digest::SHA256.digest('t' * 1024*1024)
)
)
returns(expected) { tree_hash.hexdigest}
end
end
fog-aws-0.7.6/tests/requests/glacier/vault_tests.rb 0000644 0000041 0000041 00000002574 12576636531 022472 0 ustar www-data www-data Shindo.tests('AWS::Glacier | glacier vault requests', ['aws']) do
pending if Fog.mocking?
topic_arn = Fog::AWS[:sns].create_topic( 'fog_test_glacier_topic').body['TopicArn']
Fog::AWS[:glacier].create_vault('Fog-Test-Vault')
tests('list_vaults') do
returns(true){Fog::AWS[:glacier].list_vaults.body['VaultList'].map {|data| data['VaultName']}.include?('Fog-Test-Vault')}
end
tests('describe_vault') do
returns('Fog-Test-Vault'){Fog::AWS[:glacier].describe_vault('Fog-Test-Vault').body['VaultName']}
end
tests('set_vault_notification_configuration') do
Fog::AWS[:glacier].set_vault_notification_configuration 'Fog-Test-Vault', topic_arn, ['ArchiveRetrievalCompleted']
end
tests('get_vault_notification_configuration') do
returns('SNSTopic' => topic_arn, 'Events' => ['ArchiveRetrievalCompleted']){ Fog::AWS[:glacier].get_vault_notification_configuration( 'Fog-Test-Vault').body}
end
tests('delete_vault_notification_configuration') do
Fog::AWS[:glacier].delete_vault_notification_configuration( 'Fog-Test-Vault')
raises(Excon::Errors::NotFound){Fog::AWS[:glacier].get_vault_notification_configuration( 'Fog-Test-Vault')}
end
tests('delete_vault') do
Fog::AWS[:glacier].delete_vault( 'Fog-Test-Vault')
raises(Excon::Errors::NotFound){Fog::AWS[:glacier].describe_vault( 'Fog-Test-Vault')}
end
Fog::AWS[:sns].delete_topic topic_arn
end
fog-aws-0.7.6/tests/requests/glacier/archive_tests.rb 0000644 0000041 0000041 00000000714 12576636531 022752 0 ustar www-data www-data Shindo.tests('AWS::Glacier | glacier archive tests', ['aws']) do
pending if Fog.mocking?
Fog::AWS[:glacier].create_vault('Fog-Test-Vault-upload')
tests('single part upload') do
id = Fog::AWS[:glacier].create_archive('Fog-Test-Vault-upload', 'data body').headers['x-amz-archive-id']
Fog::AWS[:glacier].delete_archive('Fog-Test-Vault-upload', id)
end
#amazon won't let us delete the vault because it has been written to in the past day
end
fog-aws-0.7.6/tests/requests/ses/ 0000755 0000041 0000041 00000000000 12576636531 016744 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/ses/helper.rb 0000644 0000041 0000041 00000000212 12576636531 020543 0 ustar www-data www-data class AWS
module SES
module Formats
BASIC = {
'ResponseMetadata' => {'RequestId' => String}
}
end
end
end
fog-aws-0.7.6/tests/requests/ses/verified_email_address_tests.rb 0000644 0000041 0000041 00000001516 12576636531 025167 0 ustar www-data www-data Shindo.tests('AWS::SES | verified email address requests', ['aws', 'ses']) do
tests('success') do
tests("#verify_email_address('test@example.com')").formats(AWS::SES::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:ses].verify_email_address('test@example.com').body
end
tests("#list_verified_email_addresses").formats(AWS::SES::Formats::BASIC.merge('VerifiedEmailAddresses' => [String])) do
pending if Fog.mocking?
Fog::AWS[:ses].list_verified_email_addresses.body
end
# email won't be there to delete, but succeeds regardless
tests("#delete_verified_email_address('test@example.com')").formats(AWS::SES::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:ses].delete_verified_email_address('notaanemail@example.com').body
end
end
tests('failure') do
end
end
fog-aws-0.7.6/tests/requests/ses/verified_domain_identity_tests.rb 0000644 0000041 0000041 00000000521 12576636531 025546 0 ustar www-data www-data Shindo.tests('AWS::SES | verified domain identity requests', ['aws', 'ses']) do
tests('success') do
tests("#verify_domain_identity('example.com')").formats(AWS::SES::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:ses].verify_domain_identity('example.com').body
end
end
tests('failure') do
end
end
fog-aws-0.7.6/tests/requests/dns/ 0000755 0000041 0000041 00000000000 12576636531 016736 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/dns/helper.rb 0000644 0000041 0000041 00000001035 12576636531 020541 0 ustar www-data www-data class AWS
module DNS
module Formats
RESOURCE_RECORD_SET = {
"ResourceRecords" => Array,
"Name" => String,
"Type" => String,
"AliasTarget"=> Fog::Nullable::Hash,
"TTL" => Fog::Nullable::String
}
LIST_RESOURCE_RECORD_SETS = {
"ResourceRecordSets" => [RESOURCE_RECORD_SET],
"IsTruncated" => Fog::Boolean,
"MaxItems" => Integer,
"NextRecordName" => Fog::Nullable::String,
"NextRecordType" => Fog::Nullable::String
}
end
end
end
fog-aws-0.7.6/tests/requests/dns/dns_tests.rb 0000644 0000041 0000041 00000017522 12576636531 021300 0 ustar www-data www-data Shindo.tests('Fog::DNS[:aws] | DNS requests', ['aws', 'dns']) do
@org_zone_count = 0
@zone_id = ''
@change_id = ''
@new_records = []
@domain_name = generate_unique_domain
@elb_connection = Fog::AWS::ELB.new
@r53_connection = Fog::DNS[:aws]
tests('success') do
test('get current zone count') do
@org_zone_count= 0
response = @r53_connection.list_hosted_zones
if response.status == 200
@hosted_zones = response.body['HostedZones']
@org_zone_count = @hosted_zones.count
end
response.status == 200
end
test('create simple zone') {
result = false
response = @r53_connection.create_hosted_zone(@domain_name)
if response.status == 201
zone = response.body['HostedZone']
change_info = response.body['ChangeInfo']
ns_servers = response.body['NameServers']
if (zone and change_info and ns_servers)
@zone_id = zone['Id']
caller_ref = zone['CallerReference']
@change_id = change_info['Id']
status = change_info['Status']
ns_srv_count = ns_servers.count
if (@zone_id.length > 0) and (caller_ref.length > 0) and (@change_id.length > 0) and
(status.length > 0) and (ns_srv_count > 0)
result = true
end
end
end
result
}
test("get status of change #{@change_id}") {
result = false
response = @r53_connection.get_change(@change_id)
if response.status == 200
status = response.body['Status']
if (status == 'PENDING') or (status == 'INSYNC')
result = true
end
end
result
}
test("get info on hosted zone #{@zone_id}") {
result = false
response = @r53_connection.get_hosted_zone(@zone_id)
if response.status == 200
zone = response.body['HostedZone']
zone_id = zone['Id']
name = zone['Name']
caller_ref = zone['CallerReference']
ns_servers = response.body['NameServers']
# AWS returns domain with a dot at end - so when compare, remove dot
if (zone_id == @zone_id) and (name.chop == @domain_name) and (caller_ref.length > 0) and
(ns_servers.count > 0)
result = true
end
end
result
}
test('list zones') do
result = false
response = @r53_connection.list_hosted_zones
if response.status == 200
zones= response.body['HostedZones']
if (zones.count > 0)
zone = zones[0]
zone_id = zone['Id']
zone_name= zone['Name']
caller_ref = zone['CallerReference']
end
max_items = response.body['MaxItems']
if (zone_id.length > 0) and (zone_name.length > 0) and (caller_ref.length > 0) and
(max_items > 0)
result = true
end
end
result
end
test("add a A resource record") {
# create an A resource record
host = 'www.' + @domain_name
ip_addrs = ['1.2.3.4']
resource_record = { :name => host, :type => 'A', :ttl => 3600, :resource_records => ip_addrs }
resource_record_set = resource_record.merge(:action => 'CREATE')
change_batch = []
change_batch << resource_record_set
options = { :comment => 'add A record to domain'}
response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options)
Fog.wait_for { @r53_connection.get_change(response.body["Id"]).body["Status"] != "PENDING" }
@new_records << resource_record
@r53_connection.get_change(response.body["Id"]).body["Status"] == "INSYNC"
}
test("add a CNAME resource record") {
# create a CNAME resource record
host = 'mail.' + @domain_name
value = ['www.' + @domain_name]
resource_record = { :name => host, :type => 'CNAME', :ttl => 3600, :resource_records => value }
resource_record_set = resource_record.merge(:action => 'CREATE')
change_batch = []
change_batch << resource_record_set
options = { :comment => 'add CNAME record to domain'}
response = @r53_connection.change_resource_record_sets( @zone_id, change_batch, options)
Fog.wait_for { @r53_connection.get_change(response.body["Id"]).body["Status"] != "PENDING" }
@new_records << resource_record
@r53_connection.get_change(response.body["Id"]).body["Status"] == "INSYNC"
}
test("add a MX resource record") {
# create a MX resource record
host = @domain_name
value = ['7 mail.' + @domain_name]
resource_record = { :name => host, :type => 'MX', :ttl => 3600, :resource_records => value }
resource_record_set = resource_record.merge( :action => 'CREATE')
change_batch = []
change_batch << resource_record_set
options = { :comment => 'add MX record to domain'}
response = @r53_connection.change_resource_record_sets( @zone_id, change_batch, options)
Fog.wait_for { @r53_connection.get_change(response.body["Id"]).body["Status"] != "PENDING" }
@new_records << resource_record
@r53_connection.get_change(response.body["Id"]).body["Status"] == "INSYNC"
}
test("add an ALIAS resource record") {
# create a load balancer
@elb_connection.create_load_balancer(["us-east-1a"], "fog", [{"Protocol" => "HTTP", "LoadBalancerPort" => "80", "InstancePort" => "80"}])
elb_response = @elb_connection.describe_load_balancers("LoadBalancerNames" => "fog")
elb = elb_response.body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first
hosted_zone_id = elb["CanonicalHostedZoneNameID"]
dns_name = elb["DNSName"]
# create an ALIAS record
host = @domain_name
alias_target = {
:hosted_zone_id => hosted_zone_id,
:dns_name => dns_name,
:evaluate_target_health => false
}
resource_record = { :name => host, :type => 'A', :alias_target => alias_target }
resource_record_set = resource_record.merge(:action => 'CREATE')
change_batch = []
change_batch << resource_record_set
options = { :comment => 'add ALIAS record to domain'}
puts "Hosted Zone ID (ELB): #{hosted_zone_id}"
puts "DNS Name (ELB): #{dns_name}"
puts "Zone ID for Route 53: #{@zone_id}"
response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options)
Fog.wait_for { @r53_connection.get_change(response.body["Id"]).body["Status"] != "PENDING" }
@new_records << resource_record
@r53_connection.get_change(response.body["Id"]).body["Status"] == "INSYNC"
}
tests("list resource records").formats(AWS::DNS::Formats::LIST_RESOURCE_RECORD_SETS) {
# get resource records for zone
@r53_connection.list_resource_record_sets(@zone_id).body
}
test("delete #{@new_records.count} resource records") {
change_batch = @new_records.map { |record| record.merge(:action => 'DELETE') }
options = { :comment => 'remove records from domain'}
response = @r53_connection.change_resource_record_sets(@zone_id, change_batch, options)
Fog.wait_for { @r53_connection.get_change(response.body["Id"]).body["Status"] != "PENDING" }
@r53_connection.get_change(response.body["Id"]).body["Status"] == "INSYNC"
}
test("delete hosted zone #{@zone_id}") {
# cleanup the ELB as well
@elb_connection.delete_load_balancer("fog")
@r53_connection.delete_hosted_zone(@zone_id).status == 200
}
end
tests('failure') do
tests('create hosted zone using invalid domain name').raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
@r53_connection.create_hosted_zone('invalid-domain')
end
tests('get hosted zone using invalid ID').raises(Excon::Errors::NotFound) do
pending if Fog.mocking?
zone_id = 'dummy-id'
@r53_connection.get_hosted_zone(zone_id)
end
end
end
fog-aws-0.7.6/tests/requests/dns/change_resource_record_sets_tests.rb 0000644 0000041 0000041 00000002145 12576636531 026237 0 ustar www-data www-data Shindo.tests('Fog::DNS[:aws] | change_resource_record_sets', ['aws', 'dns']) do
tests('success') do
test('#elb_hosted_zone_mapping from DNS name') do
zone_id = Fog::DNS::AWS.hosted_zone_for_alias_target('arbitrary-sub-domain.eu-west-1.elb.amazonaws.com')
zone_id == Fog::DNS::AWS.elb_hosted_zone_mapping['eu-west-1']
end
end
tests("#change_resource_record_sets_data formats geolocation properly") do
change_batch = [{
:action=>"CREATE",
:name=>"ark.m.example.net.",
:resource_records=>["1.1.1.1"],
:ttl=>"300",
:type=>"A",
:set_identifier=>"ark",
:geo_location=>{"CountryCode"=>"US", "SubdivisionCode"=>"AR"},
}]
version = '2013-04-01'
result = Fog::DNS::AWS.change_resource_record_sets_data('zone_id123', change_batch, version)
doc = Nokogiri::XML(result)
returns("https://route53.amazonaws.com/doc/#{version}/") { doc.namespaces['xmlns'] }
returns(%w[US AR]) {
[
doc.css("GeoLocation CountryCode").text,
doc.css("GeoLocation SubdivisionCode").text
]
}
result
end
end
fog-aws-0.7.6/tests/requests/dns/health_check_tests.rb 0000644 0000041 0000041 00000013571 12576636531 023116 0 ustar www-data www-data Shindo.tests('Fog::DNS[:aws] | DNS requests', ['aws', 'dns']) do
pending if Fog.mocking?
@r53_connection = Fog::DNS[:aws]
tests('success') do
tests('create a health check') do
after do
@r53_connection.delete_health_check(@response.body['HealthCheck']['Id'])
end
test('create an IP TCP based health check') do
@response = @r53_connection.create_health_check('8.8.8.8', '53', 'TCP')
@response.status == 201 &&
@response.body['HealthCheck']['HealthCheckConfig']['IPAddress'] == '8.8.8.8' &&
@response.body['HealthCheck']['HealthCheckConfig']['Port'] == '53'
end
test('create a FQDN HTTP based health check') do
@options = {
:fqdn => "www.amazon.com",
:resource_path => "/gp/cart/view.html/ref=nav_cart"
}
@response = @r53_connection.create_health_check(nil, '80', 'HTTP', @options)
@response.status == 201 &&
@response.body['HealthCheck']['HealthCheckConfig']['IPAddress'].nil? &&
@response.body['HealthCheck']['HealthCheckConfig']['Port'] == '80' &&
@response.body['HealthCheck']['HealthCheckConfig']['FullyQualifiedDomainName'] == 'www.amazon.com'
end
end
tests('get a health check') do
@options = {
:fqdn => "www.amazon.com",
:resource_path => "/gp/cart/view.html/ref=nav_cart",
:search_string => "Amazon",
:request_interval => 10,
:failure_threshold => "7"
}
create_response = @r53_connection.create_health_check('8.8.8.8', '443', 'HTTPS_STR_MATCH', @options)
@health_check_id = create_response.body['HealthCheck']['Id']
@response = @r53_connection.get_health_check(@health_check_id)
sleep 2
@r53_connection.delete_health_check(@health_check_id)
test('id') do
@response.body['HealthCheck']['Id'] == @health_check_id
end
{
'IPAddress' => '8.8.8.8',
'Port' => '443',
'Type' => 'HTTPS_STR_MATCH',
'FullyQualifiedDomainName' => @options[:fqdn],
'ResourcePath' => @options[:resource_path],
'RequestInterval' => @options[:request_interval],
'FailureThreshold' => @options[:failure_threshold]
}.each do |key, value|
test("and check property #{key}") do
@response.body['HealthCheck']['HealthCheckConfig'][key] == value
end
end
end
tests('delete a health check') do
before do
response = @r53_connection.create_health_check('8.8.8.8', '53', 'TCP')
@health_check_id = response.body['HealthCheck']['Id']
end
test('setup as IP TCP') do
response = @r53_connection.delete_health_check(@health_check_id)
response.status == 200
end
end
tests('listing health checks') do
test('succeeds') do
response = @r53_connection.list_health_checks
response.status == 200
end
before do
response_1 = @r53_connection.create_health_check('8.8.8.8', '53', 'TCP')
@health_check_1_id = response_1.body['HealthCheck']['Id']
options = {
:fqdn => "www.amazon.com",
:resource_path => "/gp/cart/view.html/ref=nav_cart"
}
response_2 = @r53_connection.create_health_check(nil, '80', 'HTTP', options)
@health_check_2_id = response_2.body['HealthCheck']['Id']
@health_check_ids = [@health_check_1_id, @health_check_2_id]
end
after do
@health_check_ids.each { |id| @r53_connection.delete_health_check id }
end
test('contains 2 new health checks') do
sleep 2
response = @r53_connection.list_health_checks
health_checks_by_id = response.body['HealthChecks'].map do |health_check|
health_check['Id']
end.to_a
@health_check_ids.all? { |id| health_checks_by_id.include?(id) }
end
test('contains properties') do
sleep 2
response = @r53_connection.list_health_checks
list_response_2 = response.body['HealthChecks'].find { |health_check| health_check['Id'] == @health_check_2_id }
list_response_2['HealthCheckConfig']['Type'] == 'HTTP' &&
list_response_2['HealthCheckConfig']['FullyQualifiedDomainName'] == 'www.amazon.com' &&
list_response_2['HealthCheckConfig']['IPAddress'].nil?
end
end
tests('assign a health check to a DNS record') do
after do
@r53_connection.change_resource_record_sets(@zone_id, [@resource_record.merge(:action => 'DELETE')])
@r53_connection.delete_hosted_zone(@zone_id)
@r53_connection.delete_health_check @health_check_id
end
health_check_response = @r53_connection.create_health_check('8.8.8.8', '53', 'TCP')
raise "Health check was not created" unless health_check_response.status == 201
@health_check_id = health_check_response.body['HealthCheck']['Id']
@domain_name = generate_unique_domain
zone_response = @r53_connection.create_hosted_zone(@domain_name)
raise "Zone was not created for #{@domain_name}" unless zone_response.status == 201
@zone_id = zone_response.body['HostedZone']['Id']
@resource_record = {
:name => "www.#{@domain_name}.",
:type => 'A',
:ttl => 3600,
:resource_records => ['8.8.4.4'],
:health_check_id => @health_check_id,
:set_identifier => SecureRandom.hex(8),
:weight => 50
}
resource_record_set = [@resource_record.merge(:action => 'CREATE')]
record_response = @r53_connection.change_resource_record_sets @zone_id, resource_record_set
raise "A record was not created" unless record_response.status == 200
test('succeeds') do
new_record = @r53_connection.list_resource_record_sets(@zone_id).body['ResourceRecordSets'].find do |record|
record['Name'] == @resource_record[:name]
end
new_record['HealthCheckId'] == @health_check_id
end
end
end
end
fog-aws-0.7.6/tests/requests/elb/ 0000755 0000041 0000041 00000000000 12576636531 016714 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/elb/helper.rb 0000644 0000041 0000041 00000005663 12576636531 020532 0 ustar www-data www-data class AWS
module ELB
module Formats
BASIC = {
'ResponseMetadata' => {'RequestId' => String}
}
LOAD_BALANCER = {
"AvailabilityZones" => Array,
"BackendServerDescriptions" => Array,
"CanonicalHostedZoneName" => String,
"CanonicalHostedZoneNameID" => String,
"CreatedTime" => Time,
"DNSName" => String,
"HealthCheck" => {"HealthyThreshold" => Integer, "Timeout" => Integer, "UnhealthyThreshold" => Integer, "Interval" => Integer, "Target" => String},
"Instances" => Array,
"ListenerDescriptions" => [{
'PolicyNames' => Array,
'Listener' => {
'InstancePort' => Integer,
'InstanceProtocol' => String,
'LoadBalancerPort' => Integer,
'Protocol' => String,
'SSLCertificateId' => Fog::Nullable::String
}
}],
"LoadBalancerName" => String,
"Policies" => {"LBCookieStickinessPolicies" => Array, "AppCookieStickinessPolicies" => Array, "OtherPolicies" => Array},
"Scheme" => String,
"SecurityGroups" => [Fog::Nullable::String],
"SourceSecurityGroup" => {"GroupName" => String, "OwnerAlias" => String},
"Subnets" => [Fog::Nullable::String]
}
CREATE_LOAD_BALANCER = BASIC.merge({
'CreateLoadBalancerResult' => { 'DNSName' => String }
})
DESCRIBE_LOAD_BALANCERS = BASIC.merge({
'DescribeLoadBalancersResult' => {'LoadBalancerDescriptions' => [LOAD_BALANCER], 'NextMarker' => Fog::Nullable::String}
})
POLICY_ATTRIBUTE_DESCRIPTION = {
"AttributeName" => String,
"AttributeValue" => String
}
POLICY = {
"PolicyAttributeDescriptions" => [POLICY_ATTRIBUTE_DESCRIPTION],
"PolicyName" => String,
"PolicyTypeName" => String
}
DESCRIBE_LOAD_BALANCER_POLICIES = BASIC.merge({
'DescribeLoadBalancerPoliciesResult' => { 'PolicyDescriptions' => [POLICY] }
})
POLICY_ATTRIBUTE_TYPE_DESCRIPTION = {
"AttributeName" => String,
"AttributeType" => String,
"Cardinality" => String,
"DefaultValue" => String,
"Description" => String
}
POLICY_TYPE = {
"Description" => String,
"PolicyAttributeTypeDescriptions" => [POLICY_ATTRIBUTE_TYPE_DESCRIPTION],
"PolicyTypeName" => String
}
DESCRIBE_LOAD_BALANCER_POLICY_TYPES = BASIC.merge({
'DescribeLoadBalancerPolicyTypesResult' => {'PolicyTypeDescriptions' => [POLICY_TYPE] }
})
CONFIGURE_HEALTH_CHECK = BASIC.merge({
'ConfigureHealthCheckResult' => {'HealthCheck' => {
'Target' => String,
'Interval' => Integer,
'Timeout' => Integer,
'UnhealthyThreshold' => Integer,
'HealthyThreshold' => Integer
}}
})
DELETE_LOAD_BALANCER = BASIC.merge({
'DeleteLoadBalancerResult' => NilClass
})
end
end
end
fog-aws-0.7.6/tests/requests/elb/listener_tests.rb 0000644 0000041 0000041 00000006731 12576636531 022317 0 ustar www-data www-data Shindo.tests('AWS::ELB | listener_tests', ['aws', 'elb']) do
@load_balancer_id = 'fog-test-listener'
@key_name = 'fog-test'
tests('success') do
Fog::AWS[:elb].create_load_balancer(['us-east-1a'], @load_balancer_id, [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'HTTP'}])
@certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate']
tests("#create_load_balancer_listeners").formats(AWS::ELB::Formats::BASIC) do
listeners = [
{'Protocol' => 'TCP', 'InstanceProtocol' => 'TCP', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']},
{'Protocol' => 'HTTP', 'InstanceProtocol' => 'HTTP', 'LoadBalancerPort' => 80, 'InstancePort' => 80}
]
response = Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body
response
end
tests("#delete_load_balancer_listeners").formats(AWS::ELB::Formats::BASIC) do
ports = [80, 443]
Fog::AWS[:elb].delete_load_balancer_listeners(@load_balancer_id, ports).body
end
tests("#create_load_balancer_listeners with non-existant SSL certificate") do
listeners = [
{'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => 'non-existant'},
]
raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners) }
end
tests("#create_load_balancer_listeners with invalid SSL certificate").raises(Fog::AWS::IAM::NotFound) do
sleep 8 unless Fog.mocking?
listeners = [
{'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => "#{@certificate['Arn']}fake"},
]
Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body
end
# This is sort of fucked up, but it may or may not fail, thanks AWS
tests("#create_load_balancer_listeners with SSL certificate").formats(AWS::ELB::Formats::BASIC) do
sleep 8 unless Fog.mocking?
listeners = [
{'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']},
]
Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body
end
tests("#set_load_balancer_listener_ssl_certificate").formats(AWS::ELB::Formats::BASIC) do
Fog::AWS[:elb].set_load_balancer_listener_ssl_certificate(@load_balancer_id, 443, @certificate['Arn']).body
end
tests("#create_load_balancer_listeners with invalid Protocol and InstanceProtocol configuration").raises(Fog::AWS::ELB::ValidationError) do
listeners = [
{'Protocol' => 'HTTP', 'InstanceProtocol' => 'TCP', 'LoadBalancerPort' => 80, 'InstancePort' => 80},
]
Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body
end
tests("#create_load_balancer_listeners with valid Protocol and InstanceProtocol configuration").formats(AWS::ELB::Formats::BASIC) do
listeners = [
{'Protocol' => 'HTTP', 'InstanceProtocol' => 'HTTPS', 'LoadBalancerPort' => 80, 'InstancePort' => 80},
]
Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners).body
end
Fog::AWS[:iam].delete_server_certificate(@key_name)
Fog::AWS[:elb].delete_load_balancer(@load_balancer_id)
end
end
fog-aws-0.7.6/tests/requests/elb/policy_tests.rb 0000644 0000041 0000041 00000014512 12576636531 021765 0 ustar www-data www-data Shindo.tests('AWS::ELB | policy_tests', ['aws', 'elb']) do
@load_balancer_id = 'fog-test-policies'
tests('success') do
listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'Protocol' => 'HTTP'}]
Fog::AWS[:elb].create_load_balancer(['us-east-1a'], @load_balancer_id, listeners)
tests("#describe_load_balancer_policy_types").formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCER_POLICY_TYPES) do
@policy_types = Fog::AWS[:elb].describe_load_balancer_policy_types.body
end
tests("#create_app_cookie_stickiness_policy").formats(AWS::ELB::Formats::BASIC) do
cookie, policy = 'fog-app-cookie', 'fog-app-policy'
Fog::AWS[:elb].create_app_cookie_stickiness_policy(@load_balancer_id, policy, cookie).body
end
tests("#create_lb_cookie_stickiness_policy with expiry").formats(AWS::ELB::Formats::BASIC) do
policy = 'fog-lb-expiry'
expiry = 300
Fog::AWS[:elb].create_lb_cookie_stickiness_policy(@load_balancer_id, policy, expiry).body
end
tests("#create_lb_cookie_stickiness_policy without expiry").formats(AWS::ELB::Formats::BASIC) do
policy = 'fog-lb-no-expiry'
Fog::AWS[:elb].create_lb_cookie_stickiness_policy(@load_balancer_id, policy).body
end
tests("#create_load_balancer_policy").formats(AWS::ELB::Formats::BASIC) do
policy = 'fog-policy'
Fog::AWS[:elb].create_load_balancer_policy(@load_balancer_id, policy, 'PublicKeyPolicyType', {'PublicKey' => AWS::IAM::SERVER_CERT_PUBLIC_KEY}).body
end
tests("#describe_load_balancer_policies") do
body = Fog::AWS[:elb].describe_load_balancer_policies(@load_balancer_id).body
formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCER_POLICIES) { body }
# Check the result of each policy by name
returns({
"PolicyAttributeDescriptions"=>[{
"AttributeName"=>"CookieName",
"AttributeValue"=>"fog-app-cookie"
}],
"PolicyName"=>"fog-app-policy",
"PolicyTypeName"=>"AppCookieStickinessPolicyType"
}) do
body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].find{|e| e['PolicyName'] == 'fog-app-policy' }
end
returns({
"PolicyAttributeDescriptions"=>[{
"AttributeName"=>"CookieExpirationPeriod",
"AttributeValue"=>"300"
}],
"PolicyName"=>"fog-lb-expiry",
"PolicyTypeName"=>"LBCookieStickinessPolicyType"
}) do
body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].find{|e| e['PolicyName'] == 'fog-lb-expiry' }
end
returns({
"PolicyAttributeDescriptions"=>[{
"AttributeName"=>"CookieExpirationPeriod",
"AttributeValue"=>"0"
}],
"PolicyName"=>"fog-lb-no-expiry",
"PolicyTypeName"=>"LBCookieStickinessPolicyType"
}) do
body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].find{|e| e['PolicyName'] == 'fog-lb-no-expiry' }
end
returns({
"PolicyAttributeDescriptions"=>[{
"AttributeName"=>"PublicKey",
"AttributeValue"=> AWS::IAM::SERVER_CERT_PUBLIC_KEY
}],
"PolicyName"=>"fog-policy",
"PolicyTypeName"=>"PublicKeyPolicyType"
}) do
body["DescribeLoadBalancerPoliciesResult"]["PolicyDescriptions"].find{|e| e['PolicyName'] == 'fog-policy' }
end
end
tests("#describe_load_balancer includes all policies") do
lb = Fog::AWS[:elb].describe_load_balancers("LoadBalancerNames" => [@load_balancer_id]).body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first
returns([
{"PolicyName"=>"fog-app-policy", "CookieName"=>"fog-app-cookie"}
]) { lb["Policies"]["AppCookieStickinessPolicies"] }
returns([
{"PolicyName"=>"fog-lb-expiry", "CookieExpirationPeriod"=> 300}
]) { lb["Policies"]["LBCookieStickinessPolicies"].select{|e| e["PolicyName"] == "fog-lb-expiry"} }
returns([
{"PolicyName" => "fog-lb-no-expiry"}
]) { lb["Policies"]["LBCookieStickinessPolicies"].select{|e| e["PolicyName"] == "fog-lb-no-expiry"} }
returns([
"fog-policy"
]) { lb["Policies"]["OtherPolicies"] }
end
tests("#delete_load_balancer_policy").formats(AWS::ELB::Formats::BASIC) do
policy = 'fog-lb-no-expiry'
Fog::AWS[:elb].delete_load_balancer_policy(@load_balancer_id, policy).body
end
tests("#set_load_balancer_policies_of_listener adds policy").formats(AWS::ELB::Formats::BASIC) do
port, policies = 80, ['fog-lb-expiry']
Fog::AWS[:elb].set_load_balancer_policies_of_listener(@load_balancer_id, port, policies).body
end
tests("#set_load_balancer_policies_of_listener removes policy").formats(AWS::ELB::Formats::BASIC) do
port = 80
Fog::AWS[:elb].set_load_balancer_policies_of_listener(@load_balancer_id, port, []).body
end
proxy_policy = "EnableProxyProtocol"
Fog::AWS[:elb].create_load_balancer_policy(@load_balancer_id, proxy_policy, 'ProxyProtocolPolicyType', { "ProxyProtocol" => true })
tests("#set_load_balancer_policies_for_backend_server replaces policies on port").formats(AWS::ELB::Formats::BASIC) do
Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(@load_balancer_id, 80, [proxy_policy]).body
end
tests("#describe_load_balancers has other policies") do
Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(@load_balancer_id, 80, [proxy_policy]).body
description = Fog::AWS[:elb].describe_load_balancers("LoadBalancerNames" => [@load_balancer_id]).body["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first
returns(true) { description["Policies"]["OtherPolicies"].include?(proxy_policy) }
end
Fog::AWS[:elb].delete_load_balancer(@load_balancer_id)
end
end
fog-aws-0.7.6/tests/requests/elb/load_balancer_tests.rb 0000644 0000041 0000041 00000007403 12576636531 023235 0 ustar www-data www-data Shindo.tests('AWS::ELB | load_balancer_tests', ['aws', 'elb']) do
@load_balancer_id = 'fog-test-elb'
@key_name = 'fog-test'
tests('success') do
if (Fog::AWS[:iam].get_server_certificate(@key_name) rescue nil)
Fog::AWS[:iam].delete_server_certificate(@key_name)
end
@certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate']
tests("#create_load_balancer").formats(AWS::ELB::Formats::CREATE_LOAD_BALANCER) do
zones = ['us-east-1a']
listeners = [{'LoadBalancerPort' => 80, 'InstancePort' => 80, 'InstanceProtocol' => 'HTTP', 'Protocol' => 'HTTP'}]
Fog::AWS[:elb].create_load_balancer(zones, @load_balancer_id, listeners).body
end
tests("#describe_load_balancers").formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCERS) do
Fog::AWS[:elb].describe_load_balancers.body
end
tests('#describe_load_balancers with bad lb') do
raises(Fog::AWS::ELB::NotFound) { Fog::AWS[:elb].describe_load_balancers('LoadBalancerNames' => 'none-such-lb') }
end
tests("#describe_load_balancers with SSL listener") do
sleep 5 unless Fog.mocking?
listeners = [
{'Protocol' => 'HTTPS', 'LoadBalancerPort' => 443, 'InstancePort' => 443, 'SSLCertificateId' => @certificate['Arn']},
]
Fog::AWS[:elb].create_load_balancer_listeners(@load_balancer_id, listeners)
response = Fog::AWS[:elb].describe_load_balancers('LoadBalancerNames' => @load_balancer_id).body
tests("SSLCertificateId is set").returns(@certificate['Arn']) do
listeners = response["DescribeLoadBalancersResult"]["LoadBalancerDescriptions"].first["ListenerDescriptions"]
listeners.find {|l| l["Listener"]["Protocol"] == 'HTTPS' }["Listener"]["SSLCertificateId"]
end
end
tests("modify_load_balancer_attributes") do
attributes = {
'ConnectionDraining' => {'Enabled' => true, 'Timeout' => 600},
'CrossZoneLoadBalancing' => {'Enabled' => true},
'ConnectionSettings' => {'IdleTimeout' => 180}
}
Fog::AWS[:elb].modify_load_balancer_attributes(@load_balancer_id, attributes).body
response = Fog::AWS[:elb].describe_load_balancer_attributes(@load_balancer_id).
body['DescribeLoadBalancerAttributesResult']['LoadBalancerAttributes']
tests("ConnectionDraining is enabled") do
response['ConnectionDraining']['Enabled'] == true
end
tests("ConnectionDraining has a 600 second Timeout").returns(600) do
response['ConnectionDraining']['Timeout']
end
tests("ConnectionSettings has a 180 second IdleTimeout").returns(180) do
response['ConnectionSettings']['IdleTimeout']
end
tests("CrossZoneLoadBalancing is enabled") do
response['CrossZoneLoadBalancing']['Enabled'] == true
end
end
tests("#configure_health_check").formats(AWS::ELB::Formats::CONFIGURE_HEALTH_CHECK) do
health_check = {
'Target' => 'HTTP:80/index.html',
'Interval' => 10,
'Timeout' => 5,
'UnhealthyThreshold' => 2,
'HealthyThreshold' => 3
}
Fog::AWS[:elb].configure_health_check(@load_balancer_id, health_check).body
end
tests("#delete_load_balancer").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do
Fog::AWS[:elb].delete_load_balancer(@load_balancer_id).body
end
tests("#delete_load_balancer when non existant").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do
Fog::AWS[:elb].delete_load_balancer('non-existant').body
end
tests("#delete_load_balancer when already deleted").formats(AWS::ELB::Formats::DELETE_LOAD_BALANCER) do
Fog::AWS[:elb].delete_load_balancer(@load_balancer_id).body
end
Fog::AWS[:iam].delete_server_certificate(@key_name)
end
end
fog-aws-0.7.6/tests/requests/data_pipeline/ 0000755 0000041 0000041 00000000000 12576636531 020750 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/data_pipeline/helper.rb 0000644 0000041 0000041 00000003064 12576636531 022557 0 ustar www-data www-data class AWS
module DataPipeline
module Formats
BASIC = {
'pipelineId' => String,
}
FIELDS = [
{
"key" => String,
"refValue" => Fog::Nullable::String,
"stringValue" => Fog::Nullable::String,
}
]
LIST_PIPELINES = {
"hasMoreResults" => Fog::Nullable::Boolean,
"marker" => Fog::Nullable::String,
"pipelineIdList" => [
{
"id" => String,
"name" => String,
}
]
}
QUERY_OBJECTS = {
"hasMoreResults" => Fog::Nullable::Boolean,
"marker" => Fog::Nullable::String,
"ids" => Fog::Nullable::Array,
}
DESCRIBE_OBJECTS = {
"hasMoreResults" => Fog::Nullable::Boolean,
"marker" => Fog::Nullable::String,
"pipelineObjects" => [
{
'id' => String,
'name' => String,
'fields' => FIELDS,
}
]
}
DESCRIBE_PIPELINES = {
"pipelineDescriptionList" => [
{
"description" => Fog::Nullable::String,
"name" => String,
"pipelineId" => String,
"fields" => FIELDS,
}
]
}
PUT_PIPELINE_DEFINITION = {
"errored" => Fog::Boolean,
"validationErrors" => Fog::Nullable::Array,
}
GET_PIPELINE_DEFINITION = {
"pipelineObjects" => [
{
"id" => String,
"name" => String,
"fields" => FIELDS,
}
]
}
end
end
end
fog-aws-0.7.6/tests/requests/data_pipeline/pipeline_tests.rb 0000644 0000041 0000041 00000005143 12576636531 024327 0 ustar www-data www-data Shindo.tests('AWS::DataPipeline | pipeline_tests', ['aws', 'data_pipeline']) do
pending if Fog.mocking?
@pipeline_id = nil
tests('success') do
tests("#create_pipeline").formats(AWS::DataPipeline::Formats::BASIC) do
unique_id = 'fog-test-pipeline-unique-id'
name = 'fog-test-pipeline-name'
description = 'Fog test pipeline'
result = Fog::AWS[:data_pipeline].create_pipeline(unique_id, name, description, {})
@pipeline_id = result['pipelineId']
result
end
tests("#list_pipelines").formats(AWS::DataPipeline::Formats::LIST_PIPELINES) do
Fog::AWS[:data_pipeline].list_pipelines()
end
tests("#describe_pipelines").formats(AWS::DataPipeline::Formats::DESCRIBE_PIPELINES) do
ids = [@pipeline_id]
Fog::AWS[:data_pipeline].describe_pipelines(ids)
end
tests("#put_pipeline_definition").formats(AWS::DataPipeline::Formats::PUT_PIPELINE_DEFINITION) do
objects = [
{
"id" => "Nightly",
"type" => "Schedule",
"startDateTime" => Time.now.strftime("%Y-%m-%dT%H:%M:%S"),
"period" => "24 hours",
},
{
"id" => "Default",
"role" => "role-dumps",
"resourceRole" => "role-dumps-inst",
"schedule" => { "ref" => "Nightly" },
},
]
Fog::AWS[:data_pipeline].put_pipeline_definition(@pipeline_id, objects)
end
tests("#activate_pipeline") do
Fog::AWS[:data_pipeline].activate_pipeline(@pipeline_id)
end
tests("#get_pipeline_definition").formats(AWS::DataPipeline::Formats::GET_PIPELINE_DEFINITION) do
Fog::AWS[:data_pipeline].get_pipeline_definition(@pipeline_id)
end
tests("#query_objects") do
tests("for COMPONENTs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do
Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'COMPONENT')
end
tests("for INSTANCEs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do
Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'INSTANCE')
end
tests("for ATTEMPTs").formats(AWS::DataPipeline::Formats::QUERY_OBJECTS) do
Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'ATTEMPT')
end
end
tests('#describe_objects').formats(AWS::DataPipeline::Formats::DESCRIBE_OBJECTS) do
attempts = Fog::AWS[:data_pipeline].query_objects(@pipeline_id, 'ATTEMPT')
object_ids = attempts['ids'][0..5]
Fog::AWS[:data_pipeline].describe_objects(@pipeline_id, object_ids)
end
tests("#delete_pipeline").returns(true) do
Fog::AWS[:data_pipeline].delete_pipeline(@pipeline_id)
end
end
end
fog-aws-0.7.6/tests/requests/kms/ 0000755 0000041 0000041 00000000000 12576636531 016744 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/kms/helper.rb 0000644 0000041 0000041 00000001222 12576636531 020545 0 ustar www-data www-data class AWS
module KMS
module Formats
BASIC = {
'ResponseMetadata' => { 'RequestId' => String }
}
DESCRIBE_KEY = {
"KeyMetadata" => {
"KeyUsage" => String,
"AWSAccountId" => String,
"KeyId" => String,
"Description" => Fog::Nullable::String,
"CreationDate" => Time,
"Arn" => String,
"Enabled" => Fog::Boolean
}
}
LIST_KEYS = {
"Keys" => [{ "KeyId" => String, "KeyArn" => String }],
"Truncated" => Fog::Boolean,
"Marker" => Fog::Nullable::String
}
end
end
end
fog-aws-0.7.6/tests/requests/kms/key_tests.rb 0000644 0000041 0000041 00000001163 12576636531 021304 0 ustar www-data www-data Shindo.tests('AWS::KMS | key requests', ['aws', 'kms']) do
key_id = nil
tests('success') do
tests("#create_key").data_matches_schema(AWS::KMS::Formats::DESCRIBE_KEY) do
result = Fog::AWS[:kms].create_key.body
key_id = result["KeyMetadata"]["KeyId"]
result
end
end
tests("#describe_key").data_matches_schema(AWS::KMS::Formats::DESCRIBE_KEY) do
result = Fog::AWS[:kms].describe_key(key_id).body
returns(key_id) { result['KeyMetadata']['KeyId'] }
result
end
tests("#list_keys").data_matches_schema(AWS::KMS::Formats::LIST_KEYS) do
Fog::AWS[:kms].list_keys.body
end
end
fog-aws-0.7.6/tests/requests/cdn/ 0000755 0000041 0000041 00000000000 12576636531 016716 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/cdn/cdn_tests.rb 0000644 0000041 0000041 00000014700 12576636531 021233 0 ustar www-data www-data Shindo.tests('Fog::CDN[:aws] | CDN requests', ['aws', 'cdn']) do
@cf_connection = Fog::CDN[:aws]
tests('distributions success') do
test('get current ditribution list count') do
@count= 0
response = @cf_connection.get_distribution_list
if response.status == 200
@distributions = response.body['DistributionSummary']
@count = @distributions.count
end
response.status == 200
end
test('create distribution') {
result = false
response = @cf_connection.post_distribution('S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => true)
if response.status == 201
@dist_id = response.body['Id']
@etag = response.headers['ETag']
@caller_reference = response.body['DistributionConfig']['CallerReference']
if (@dist_id.length > 0)
result = true
end
end
result
}
test("get info on distribution #{@dist_id}") {
result = false
response = @cf_connection.get_distribution(@dist_id)
if response.status == 200
@etag = response.headers['ETag']
status = response.body['Status']
if ((status == 'Deployed') or (status == 'InProgress')) and not @etag.nil?
result = true
end
end
result
}
test('list distributions') do
result = false
response = @cf_connection.get_distribution_list
if response.status == 200
distributions = response.body['DistributionSummary']
if (distributions.count > 0)
dist = distributions[0]
dist_id = dist['Id']
end
max_items = response.body['MaxItems']
if (dist_id.length > 0) and (max_items > 0)
result = true
end
end
result
end
test("invalidate paths") {
response = @cf_connection.post_invalidation(@dist_id, ["/test.html", "/path/to/file.html"])
if response.status == 201
@invalidation_id = response.body['Id']
end
response.status == 201
}
test("list invalidations") {
result = false
response = @cf_connection.get_invalidation_list(@dist_id)
if response.status == 200
if response.body['InvalidationSummary'].find { |f| f['Id'] == @invalidation_id }
result = true
end
end
result
}
test("get invalidation information") {
result = false
response = @cf_connection.get_invalidation(@dist_id, @invalidation_id)
if response.status == 200
paths = response.body['InvalidationBatch']['Path'].sort
status = response.body['Status']
if status.length > 0 and paths == [ '/test.html', '/path/to/file.html' ].sort
result = true
end
end
result
}
test("disable distribution #{@dist_id} - can take 15 minutes to complete...") {
result = false
response = @cf_connection.put_distribution_config(@dist_id, @etag, 'S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => false, 'CallerReference' => @caller_reference)
if response.status == 200
@etag = response.headers['ETag']
unless @etag.nil?
result = true
end
end
result
}
test("remove distribution #{@dist_id}") {
result = true
# unfortunately you can delete only after a distribution becomes Deployed
Fog.wait_for {
response = @cf_connection.get_distribution(@dist_id)
@etag = response.headers['ETag']
response.status == 200 and response.body['Status'] == 'Deployed'
}
response = @cf_connection.delete_distribution(@dist_id, @etag)
if response.status != 204
result = false
end
result
}
end
tests('streaming distributions success') do
test('get current streaming ditribution list count') do
@count= 0
response = @cf_connection.get_streaming_distribution_list
if response.status == 200
@distributions = response.body['StreamingDistributionSummary']
@count = @distributions.count
end
response.status == 200
end
test('create distribution') {
result = false
response = @cf_connection.post_streaming_distribution('S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => true)
if response.status == 201
@dist_id = response.body['Id']
@etag = response.headers['ETag']
@caller_reference = response.body['StreamingDistributionConfig']['CallerReference']
if (@dist_id.length > 0)
result = true
end
end
result
}
test("get info on distribution #{@dist_id}") {
result = false
response = @cf_connection.get_streaming_distribution(@dist_id)
if response.status == 200
@etag = response.headers['ETag']
status = response.body['Status']
if ((status == 'Deployed') or (status == 'InProgress')) and not @etag.nil?
result = true
end
end
result
}
test('list streaming distributions') do
result = false
response = @cf_connection.get_streaming_distribution_list
if response.status == 200
distributions = response.body['StreamingDistributionSummary']
if (distributions.count > 0)
dist = distributions[0]
dist_id = dist['Id']
end
max_items = response.body['MaxItems']
if (dist_id.length > 0) and (max_items > 0)
result = true
end
end
result
end
test("disable distribution #{@dist_id} - can take 15 minutes to complete...") {
result = false
response = @cf_connection.put_streaming_distribution_config(@dist_id, @etag, 'S3Origin' => { 'DNSName' => 'test_cdn.s3.amazonaws.com'}, 'Enabled' => false, 'CallerReference' => @caller_reference)
if response.status == 200
@etag = response.headers['ETag']
unless @etag.nil?
result = true
end
end
result
}
test("remove distribution #{@dist_id}") {
result = true
# unfortunately you can delete only after a distribution becomes Deployed
Fog.wait_for {
response = @cf_connection.get_streaming_distribution(@dist_id)
@etag = response.headers['ETag']
response.status == 200 and response.body['Status'] == 'Deployed'
}
response = @cf_connection.delete_streaming_distribution(@dist_id, @etag)
if response.status != 204
result = false
end
result
}
end
end
fog-aws-0.7.6/tests/requests/dynamodb/ 0000755 0000041 0000041 00000000000 12576636531 017747 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/dynamodb/table_tests.rb 0000644 0000041 0000041 00000006550 12576636531 022613 0 ustar www-data www-data Shindo.tests('Fog::AWS[:dynamodb] | table requests', ['aws']) do
@table_format = {
'CreationDateTime' => Float,
'KeySchema' => {
'HashKeyElement' => {
'AttributeName' => String,
'AttributeType' => String
}
},
'ProvisionedThroughput' => {
'ReadCapacityUnits' => Integer,
'WriteCapacityUnits' => Integer
},
'TableName' => String,
'TableStatus' => String
}
@table_name = "fog_table_#{Time.now.to_f.to_s.gsub('.','')}"
tests('success') do
tests("#create_table(#{@table_name}, {'HashKeyElement' => {'AttributeName' => 'id', 'AttributeType' => 'S'}, {'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5})").formats('TableDescription' => @table_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].create_table(@table_name, {'HashKeyElement' => {'AttributeName' => 'id', 'AttributeType' => 'S'}}, {'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5}).body
end
tests("#describe_table(#{@table_name})").formats('Table' => @table_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].describe_table(@table_name).body
end
tests("#list_tables").formats({'LastEvaluatedTableName' => Fog::Nullable::String, 'TableNames' => [String]}) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].list_tables.body
end
unless Fog.mocking?
Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' }
end
@update_table_format = {
'TableDescription' => @table_format.merge({
'ItemCount' => Integer,
'ProvisionedThroughput' => {
'LastIncreaseDateTime' => Float,
'ReadCapacityUnits' => Integer,
'WriteCapacityUnits' => Integer
},
'TableSizeBytes' => Integer
})
}
tests("#update_table(#{@table_name}, {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10})").formats(@update_table_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_table(@table_name, {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10}).body
end
unless Fog.mocking?
Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' }
end
@delete_table_format = {
'TableDescription' => {
'ProvisionedThroughput' => {
'ReadCapacityUnits' => Integer,
'WriteCapacityUnits' => Integer
},
'TableName' => String,
'TableStatus' => String
}
}
tests("#delete_table(#{@table_name}").formats(@delete_table_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_table(@table_name).body
end
end
tests('failure') do
tests("#delete_table('notatable')").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_table('notatable')
end
tests("#describe_table('notatable')").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].describe_table('notatable')
end
tests("#update_table('notatable', {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10})").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_table('notatable', {'ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10}).body
end
end
end
fog-aws-0.7.6/tests/requests/dynamodb/item_tests.rb 0000644 0000041 0000041 00000011730 12576636531 022456 0 ustar www-data www-data Shindo.tests('Fog::AWS[:dynamodb] | item requests', ['aws']) do
@table_name = "fog_table_#{Time.now.to_f.to_s.gsub('.','')}"
unless Fog.mocking?
Fog::AWS[:dynamodb].create_table(
@table_name,
{'HashKeyElement' => {'AttributeName' => 'key', 'AttributeType' => 'S'}},
{'ReadCapacityUnits' => 5, 'WriteCapacityUnits' => 5}
)
Fog.wait_for { Fog::AWS[:dynamodb].describe_table(@table_name).body['Table']['TableStatus'] == 'ACTIVE' }
end
tests('success') do
tests("#put_item('#{@table_name}', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].put_item(@table_name, {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}}).body
end
tests("#update_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}}).body
end
@batch_get_item_format = {
'Responses' => {
@table_name => {
'ConsumedCapacityUnits' => Float,
'Items' => [{
'key' => { 'S' => String },
'value' => { 'S' => String }
}]
}
},
'UnprocessedKeys' => {}
}
tests("#batch_get_item({'#{@table_name}' => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}})").formats(@batch_get_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].batch_get_item(
{@table_name => {'Keys' => [{'HashKeyElement' => {'S' => 'key'}}]}}
).body
end
@batch_put_item_format = {
'Responses'=> {
@table_name => {
'ConsumedCapacityUnits' => Float}
},
'UnprocessedItems'=> {}
}
tests("#batch_put_item({ '#{@table_name}' => [{ 'PutRequest' => { 'Item' =>
{ 'HashKeyElement' => { 'S' => 'key' }, 'RangeKeyElement' => { 'S' => 'key' }}}}]})"
).formats(@batch_put_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].batch_put_item(
{@table_name => [{'PutRequest'=> {'Item'=>
{'HashKeyElement' => { 'S' => 'key' },
'RangeKeyElement' => { 'S' => 'key' }
}}}]}
).body
end
@get_item_format = {
'ConsumedCapacityUnits' => Float,
'Item' => {
'key' => { 'S' => String },
'value' => { 'S' => String }
}
}
tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats(@get_item_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
tests("#get_item('#{@table_name}', {'HashKeyElement' => {'S' => 'notakey'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].get_item(@table_name, {'HashKeyElement' => {'S' => 'notakey'}}).body
end
@query_format = {
'ConsumedCapacityUnits' => Float,
'Count' => Integer,
'Items' => [{
'key' => { 'S' => String },
'value' => { 'S' => String }
}],
'LastEvaluatedKey' => NilClass
}
tests("#query('#{@table_name}', {'S' => 'key'}").formats(@query_format) do
pending if Fog.mocking?
pending # requires a table with range key
Fog::AWS[:dynamodb].query(@table_name, {'S' => 'key'}).body
end
@scan_format = @query_format.merge('ScannedCount' => Integer)
tests("scan('#{@table_name}')").formats(@scan_format) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].scan(@table_name).body
end
tests("#delete_item('#{@table_name}', {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
tests("#delete_item('#{@table_name}, {'HashKeyElement' => {'S' => 'key'}})").formats('ConsumedCapacityUnits' => Float) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].delete_item(@table_name, {'HashKeyElement' => {'S' => 'key'}}).body
end
end
tests('failure') do
tests("#put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].put_item('notatable', {'key' => {'S' => 'key'}}, {'value' => {'S' => 'value'}})
end
tests("#update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})").raises(Excon::Errors::BadRequest) do
pending if Fog.mocking?
Fog::AWS[:dynamodb].update_item('notatable', {'HashKeyElement' => {'S' => 'key'}}, {'value' => {'Value' => {'S' => 'value'}}})
end
end
unless Fog.mocking?
Fog::AWS[:dynamodb].delete_table(@table_name)
end
end
fog-aws-0.7.6/tests/requests/rds/ 0000755 0000041 0000041 00000000000 12576636531 016742 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/rds/security_group_tests.rb 0000644 0000041 0000041 00000011263 12576636531 023577 0 ustar www-data www-data Shindo.tests('AWS::RDS | security group requests', ['aws', 'rds']) do
suffix = rand(65536).to_s(16)
@sec_group_name = "fog-sec-group-#{suffix}"
if Fog.mocking?
@owner_id = '123456780'
else
@owner_id = Fog::AWS[:rds].security_groups.get('default').owner_id
end
tests('success') do
tests("#create_db_security_group").formats(AWS::RDS::Formats::CREATE_DB_SECURITY_GROUP) do
body = Fog::AWS[:rds].create_db_security_group(@sec_group_name, 'Some description').body
returns( @sec_group_name) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['DBSecurityGroupName']}
returns( 'Some description') { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['DBSecurityGroupDescription']}
returns( []) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['EC2SecurityGroups']}
returns( []) { body['CreateDBSecurityGroupResult']['DBSecurityGroup']['IPRanges']}
body
end
tests("#describe_db_security_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_SECURITY_GROUP) do
Fog::AWS[:rds].describe_db_security_groups.body
end
tests("#authorize_db_security_group_ingress CIDR").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do
@cidr = '0.0.0.0/0'
body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'CIDRIP'=>@cidr}).body
returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].find{|h| h['CIDRIP'] == @cidr}['Status']}
body
end
sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name)
sec_group.wait_for {ready?}
tests("#authorize_db_security_group_ingress another CIDR").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do
@cidr = "10.0.0.0/24"
body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'CIDRIP'=>@cidr}).body
returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].find{|h| h['CIDRIP'] == @cidr}['Status']}
body
end
sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name)
sec_group.wait_for {ready?}
tests("#count CIDRIP").formats(AWS::RDS::Formats::DESCRIBE_DB_SECURITY_GROUP) do
body = Fog::AWS[:rds].describe_db_security_groups(@sec_group_name).body
returns(2) { body['DescribeDBSecurityGroupsResult']['DBSecurityGroups'][0]['IPRanges'].size }
body
end
tests("#revoke_db_security_group_ingress CIDR").formats(AWS::RDS::Formats::REVOKE_DB_SECURITY_GROUP) do
@cidr = '0.0.0.0/0'
body = Fog::AWS[:rds].revoke_db_security_group_ingress(@sec_group_name,{'CIDRIP'=> @cidr}).body
returns("revoking") { body['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup']['IPRanges'].find{|h| h['CIDRIP'] == @cidr}['Status']}
body
end
tests("#authorize_db_security_group_ingress EC2").formats(AWS::RDS::Formats::AUTHORIZE_DB_SECURITY_GROUP) do
@ec2_sec_group = 'default'
body = Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id}).body
returns("authorizing") { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].find{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['Status']}
returns(@owner_id) { body['AuthorizeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].find{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['EC2SecurityGroupOwnerId']}
body
end
tests("duplicate #authorize_db_security_group_ingress EC2").raises(Fog::AWS::RDS::AuthorizationAlreadyExists) do
@ec2_sec_group = 'default'
Fog::AWS[:rds].authorize_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id})
end
sec_group = Fog::AWS[:rds].security_groups.get(@sec_group_name)
sec_group.wait_for {ready?}
tests("#revoke_db_security_group_ingress EC2").formats(AWS::RDS::Formats::REVOKE_DB_SECURITY_GROUP) do
@ec2_sec_group = 'default'
body = Fog::AWS[:rds].revoke_db_security_group_ingress(@sec_group_name,{'EC2SecurityGroupName' => @ec2_sec_group, 'EC2SecurityGroupOwnerId' => @owner_id}).body
returns("revoking") { body['RevokeDBSecurityGroupIngressResult']['DBSecurityGroup']['EC2SecurityGroups'].find{|h| h['EC2SecurityGroupName'] == @ec2_sec_group}['Status']}
body
end
#TODO, authorize ec2 security groups
tests("#delete_db_security_group").formats(AWS::RDS::Formats::BASIC) do
body = Fog::AWS[:rds].delete_db_security_group(@sec_group_name).body
raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_security_groups(@sec_group_name)}
body
end
end
end
fog-aws-0.7.6/tests/requests/rds/subnet_groups_tests.rb 0000644 0000041 0000041 00000003567 12576636531 023423 0 ustar www-data www-data Shindo.tests('AWS::RDS | subnet group requests', ['aws', 'rds']) do
# random_differentiator
# Useful when rapidly re-running tests, so we don't have to wait
# serveral minutes for deleted VPCs/subnets to disappear
suffix = rand(65536).to_s(16)
@subnet_group_name = "fog-test-#{suffix}"
vpc_range = rand(245) + 10
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => "10.#{vpc_range}.0.0/16")
# Create 4 subnets in this VPC, each one in a different AZ
subnet_az = 'us-east-1a'
subnet_range = 8
@subnets = (1..4).map do
subnet = Fog::Compute[:aws].create_subnet(@vpc.id, "10.#{vpc_range}.#{subnet_range}.0/24",
'AvailabilityZone' => subnet_az).body['subnet']
subnet_az = subnet_az.succ
subnet_range *= 2
subnet
end
tests('success') do
subnet_ids = @subnets.map { |sn| sn['subnetId'] }.to_a
tests("#create_db_subnet_group").formats(AWS::RDS::Formats::CREATE_DB_SUBNET_GROUP) do
result = Fog::AWS[:rds].create_db_subnet_group(@subnet_group_name, subnet_ids, 'A subnet group').body
returns(@subnet_group_name) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['DBSubnetGroupName'] }
returns('A subnet group') { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['DBSubnetGroupDescription'] }
returns(@vpc.id) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['VpcId'] }
returns(subnet_ids.sort) { result['CreateDBSubnetGroupResult']['DBSubnetGroup']['Subnets'].sort }
result
end
tests("#describe_db_subnet_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_SUBNET_GROUPS) do
Fog::AWS[:rds].describe_db_subnet_groups.body
end
tests("#delete_db_subnet_group").formats(AWS::RDS::Formats::BASIC) do
Fog::AWS[:rds].delete_db_subnet_group(@subnet_group_name).body
end
end
@subnets.each do |sn|
Fog::Compute[:aws].delete_subnet(sn['subnetId'])
end
@vpc.destroy
end
fog-aws-0.7.6/tests/requests/rds/helper.rb 0000644 0000041 0000041 00000022572 12576636531 020556 0 ustar www-data www-data class AWS
module RDS
module Formats
BASIC = {
'ResponseMetadata' => { 'RequestId' => String }
}
DB_AVAILABILITY_ZONE_OPTION = {
'Name' => String,
'ProvisionedIopsCapable' => Fog::Boolean
}
DB_PARAMETER_GROUP = {
'DBParameterGroupFamily' => String,
'DBParameterGroupName' => String,
'Description' => String
}
CREATE_DB_PARAMETER_GROUP = {
'ResponseMetadata' => { 'RequestId' => String },
'CreateDBParameterGroupResult' => {
'DBParameterGroup' => DB_PARAMETER_GROUP
}
}
DB_SECURITY_GROUP = {
'DBSecurityGroupDescription' => String,
'DBSecurityGroupName' => String,
'EC2SecurityGroups' => [Fog::Nullable::Hash],
'IPRanges' => [Fog::Nullable::Hash],
'OwnerId' => Fog::Nullable::String
}
CREATE_DB_SECURITY_GROUP = BASIC.merge({
'CreateDBSecurityGroupResult' => {
'DBSecurityGroup' => DB_SECURITY_GROUP
}
})
AUTHORIZE_DB_SECURITY_GROUP = BASIC.merge({
'AuthorizeDBSecurityGroupIngressResult' => {
'DBSecurityGroup' => DB_SECURITY_GROUP
}
})
REVOKE_DB_SECURITY_GROUP = BASIC.merge({
'RevokeDBSecurityGroupIngressResult' => {
'DBSecurityGroup' => DB_SECURITY_GROUP
}
})
DESCRIBE_DB_SECURITY_GROUP = BASIC.merge({
'DescribeDBSecurityGroupsResult' => {
'DBSecurityGroups' => [DB_SECURITY_GROUP]
}
})
DB_SUBNET_GROUP = {
'DBSubnetGroupName' => String,
'DBSubnetGroupDescription' => String,
'SubnetGroupStatus' => String,
'VpcId' => String,
'Subnets' => [String]
}
CREATE_DB_SUBNET_GROUP = BASIC.merge({
'CreateDBSubnetGroupResult' => {
'DBSubnetGroup' => DB_SUBNET_GROUP
}
})
DESCRIBE_DB_SUBNET_GROUPS = BASIC.merge({
'DescribeDBSubnetGroupsResult' => {
'DBSubnetGroups' => [DB_SUBNET_GROUP]
}
})
DESCRIBE_DB_PARAMETER_GROUP = {
'ResponseMetadata' => { 'RequestId' => String },
'DescribeDBParameterGroupsResult' => {
'DBParameterGroups' => [DB_PARAMETER_GROUP]
}
}
ORDERABLE_DB_INSTANCE_OPTION = {
'MultiAZCapable' => Fog::Boolean,
'Engine' => String,
'LicenseModel' => String,
'ReadReplicaCapable' => Fog::Boolean,
'EngineVersion' => String,
'AvailabilityZones' => [DB_AVAILABILITY_ZONE_OPTION],
'DBInstanceClass' => String,
'Vpc' => Fog::Boolean
}
DESCRIBE_ORDERABLE_DB_INSTANCE_OPTION = BASIC.merge({
'DescribeOrderableDBInstanceOptionsResult' => {
'OrderableDBInstanceOptions' => [ORDERABLE_DB_INSTANCE_OPTION]
}
})
MODIFY_PARAMETER_GROUP = BASIC.merge({
'ModifyDBParameterGroupResult' => {
'DBParameterGroupName' => String
}
})
DB_PARAMETER = {
'ParameterValue' => Fog::Nullable::String,
'DataType' => String,
'AllowedValues' => Fog::Nullable::String,
'Source' => String,
'IsModifiable' => Fog::Boolean,
'Description' => String,
'ParameterName' => String,
'ApplyType' => String
}
DESCRIBE_DB_PARAMETERS = BASIC.merge({
'DescribeDBParametersResult' => {
'Marker' => Fog::Nullable::String,
'Parameters' => [DB_PARAMETER]
}
})
DB_LOG_FILE = {
'LastWritten' => Time,
'Size' => Integer,
'LogFileName' => String
}
DESCRIBE_DB_LOG_FILES = BASIC.merge({
'DescribeDBLogFilesResult' => {
'Marker' => Fog::Nullable::String,
'DBLogFiles' => [DB_LOG_FILE]
}
})
SNAPSHOT = {
'AllocatedStorage' => Integer,
'AvailabilityZone' => String,
'DBInstanceIdentifier' => String,
'DBSnapshotIdentifier' => String,
'EngineVersion' => String,
'Engine' => String,
'InstanceCreateTime' => Time,
'Iops' => Fog::Nullable::Integer,
'MasterUsername' => String,
'Port' => Integer,
'SnapshotCreateTime' => Fog::Nullable::Time,
'Status' => String,
'SnapshotType' => String
}
INSTANCE = {
'AllocatedStorage' => Integer,
'AutoMinorVersionUpgrade' => Fog::Boolean,
'AvailabilityZone' => Fog::Nullable::String,
'BackupRetentionPeriod' => Integer,
'CACertificateIdentifier' => String,
'CharacterSetName' => Fog::Nullable::String,
'DbiResourceId' => Fog::Nullable::String,
'DBInstanceClass' => String,
'DBInstanceIdentifier' => String,
'DBInstanceStatus' => String,
'DBName' => Fog::Nullable::String,
'DBParameterGroups' => [{
'ParameterApplyStatus' => String,
'DBParameterGroupName' => String
}],
'DBSecurityGroups' => [{
'Status' => String,
'DBSecurityGroupName' => String
}],
'DBSubnetGroupName' => Fog::Nullable::String,
'PubliclyAccessible' => Fog::Boolean,
'Endpoint' => {
'Address' => Fog::Nullable::String,
'Port' => Fog::Nullable::Integer
},
'Engine' => String,
'EngineVersion' => String,
'InstanceCreateTime' => Fog::Nullable::Time,
'Iops' => Fog::Nullable::Integer,
'KmsKeyId' => Fog::Nullable::String,
'LatestRestorableTime' => Fog::Nullable::Time,
'LicenseModel' => String,
'MasterUsername' => String,
'MultiAZ' => Fog::Boolean,
'PendingModifiedValues' => {
'BackupRetentionPeriod' => Fog::Nullable::Integer,
'DBInstanceClass' => Fog::Nullable::String,
'EngineVersion' => Fog::Nullable::String,
'MasterUserPassword' => Fog::Nullable::String,
'MultiAZ' => Fog::Nullable::Boolean,
'AllocatedStorage' => Fog::Nullable::Integer,
'Port' => Fog::Nullable::Integer
},
'PreferredBackupWindow' => String,
'PreferredMaintenanceWindow' => String,
'ReadReplicaDBInstanceIdentifiers' => [Fog::Nullable::String],
'StorageType' => String,
'StorageEncrypted' => Fog::Boolean,
'TdeCredentialArn' => Fog::Nullable::String
}
REPLICA_INSTANCE = INSTANCE.merge({
'PreferredBackupWindow' => Fog::Nullable::String,
'ReadReplicaSourceDBInstanceIdentifier' => String
})
CREATE_DB_INSTANCE = BASIC.merge({
'CreateDBInstanceResult' => {
'DBInstance' => INSTANCE
}
})
DESCRIBE_DB_INSTANCES = BASIC.merge({
'DescribeDBInstancesResult' => {
'Marker' => Fog::Nullable::String,
'DBInstances' => [INSTANCE]
}
})
MODIFY_DB_INSTANCE = BASIC.merge({
'ModifyDBInstanceResult' => {
'DBInstance' => INSTANCE
}
})
DELETE_DB_INSTANCE = BASIC.merge({
'DeleteDBInstanceResult' => {
'DBInstance' => INSTANCE
}
})
REBOOT_DB_INSTANCE = BASIC.merge({
'RebootDBInstanceResult' => {
'DBInstance' => INSTANCE
}
})
CREATE_READ_REPLICA = BASIC.merge({
'CreateDBInstanceReadReplicaResult' => {
'DBInstance' => REPLICA_INSTANCE
}
})
PROMOTE_READ_REPLICA = BASIC.merge({
'PromoteReadReplicaResult' => {
'DBInstance' => INSTANCE
}
})
CREATE_DB_SNAPSHOT = BASIC.merge({
'CreateDBSnapshotResult' => {
'DBSnapshot' => SNAPSHOT
}
})
DESCRIBE_DB_SNAPSHOTS = BASIC.merge({
'DescribeDBSnapshotsResult' => {
'Marker' => Fog::Nullable::String,
'DBSnapshots' => [SNAPSHOT]
}
})
DELETE_DB_SNAPSHOT = BASIC.merge({
'DeleteDBSnapshotResult' => {
'DBSnapshot' => SNAPSHOT
}
})
LIST_TAGS_FOR_RESOURCE = {
'ListTagsForResourceResult' => {
'TagList' => Fog::Nullable::Hash
}
}
EVENT_SUBSCRIPTION = {
'CustSubscriptionId' => String,
'EventCategories' => Array,
'SourceType' => Fog::Nullable::String,
'Enabled' => String,
'Status' => String,
'CreationTime' => Time,
'SnsTopicArn' => String
}
CREATE_EVENT_SUBSCRIPTION = {
'CreateEventSubscriptionResult' => {
'EventSubscription' => EVENT_SUBSCRIPTION
}
}
DESCRIBE_EVENT_SUBSCRIPTIONS = {
'DescribeEventSubscriptionsResult' => {
'EventSubscriptionsList' => [EVENT_SUBSCRIPTION]
}
}
DB_ENGINE_VERSION = {
'Engine' => String,
'DBParameterGroupFamily' => String,
'DBEngineDescription' => String,
'EngineVersion' => String,
'DBEngineVersionDescription' => String
}
DB_ENGINE_VERSIONS_LIST = BASIC.merge(
'DescribeDBEngineVersionsResult' => {
'DBEngineVersions' => [DB_ENGINE_VERSION]
}
)
end
end
end
fog-aws-0.7.6/tests/requests/rds/event_subscription_tests.rb 0000644 0000041 0000041 00000002621 12576636531 024437 0 ustar www-data www-data Shindo.tests('AWS::RDS | event subscription requests', ['aws', 'rds']) do
pending unless Fog.mocking?
@name = 'fog'
@arn = 'arn:aws:sns:us-east-1:12345678910:fog'
tests('success') do
tests('#create_event_subscription').formats(AWS::RDS::Formats::CREATE_EVENT_SUBSCRIPTION) do
body = Fog::AWS[:rds].create_event_subscription('SubscriptionName' => @name, 'SnsTopicArn' => @arn).body
returns(@name) { body['CreateEventSubscriptionResult']['EventSubscription']['CustSubscriptionId'] }
returns('creating') { body['CreateEventSubscriptionResult']['EventSubscription']['Status'] }
body
end
tests("#describe_event_subscriptions").formats(AWS::RDS::Formats::DESCRIBE_EVENT_SUBSCRIPTIONS) do
returns('active') { Fog::AWS[:rds].describe_event_subscriptions.body['DescribeEventSubscriptionsResult']['EventSubscriptionsList'].first['Status'] }
Fog::AWS[:rds].describe_event_subscriptions.body
end
tests("#delete_event_subscription").formats(AWS::RDS::Formats::BASIC) do
body = Fog::AWS[:rds].delete_event_subscription(@name).body
returns('deleting') { Fog::AWS[:rds].describe_event_subscriptions('SubscriptionName' => @name).body['DescribeEventSubscriptionsResult']['EventSubscriptionsList'].first['Status'] }
raises(Fog::AWS::RDS::NotFound) { Fog::AWS[:rds].describe_event_subscriptions('SubscriptionName' => @name) }
body
end
end
end
fog-aws-0.7.6/tests/requests/rds/db_engine_versions.rb 0000644 0000041 0000041 00000000411 12576636531 023125 0 ustar www-data www-data Shindo.tests('AWS::RDS | describe db engine versions', ['aws', 'rds']) do
tests('success') do
tests("#describe_db_engine_versions").formats(AWS::RDS::Formats::DB_ENGINE_VERSIONS_LIST) do
Fog::AWS[:rds].describe_db_engine_versions.body
end
end
end
fog-aws-0.7.6/tests/requests/rds/tagging_tests.rb 0000644 0000041 0000041 00000005154 12576636531 022136 0 ustar www-data www-data Shindo.tests('AWS::RDS | tagging requests', ['aws', 'rds']) do
@rds = Fog::AWS[:rds]
@db_instance_id = "fog-test-#{rand(65536).to_s(16)}"
Fog::Formatador.display_line "Creating RDS instance #{@db_instance_id}"
@rds.create_db_instance(@db_instance_id, 'AllocatedStorage' => 5,
'DBInstanceClass' => 'db.t1.micro', 'Engine' => 'mysql',
'MasterUsername' => 'foguser', 'MasterUserPassword' => 'fogpassword')
Fog::Formatador.display_line "Waiting for instance #{@db_instance_id} to be ready"
@db = @rds.servers.get(@db_instance_id)
@db.wait_for { ready? }
tests('success') do
single_tag = {'key1' => 'value1'}
two_tags = {'key2' => 'value2', 'key3' => 'value3'}
tests("#add_tags_to_resource with a single tag").
formats(AWS::RDS::Formats::BASIC) do
result = @rds.add_tags_to_resource(@db_instance_id, single_tag).body
returns(single_tag) do
@rds.list_tags_for_resource(@db_instance_id).
body['ListTagsForResourceResult']['TagList']
end
result
end
tests("#add_tags_to_resource with a multiple tags").
formats(AWS::RDS::Formats::BASIC) do
result = @rds.add_tags_to_resource(@db_instance_id, two_tags).body
returns(single_tag.merge(two_tags)) do
@rds.list_tags_for_resource(@db_instance_id).
body['ListTagsForResourceResult']['TagList']
end
result
end
tests("#remove_tags_from_resource").formats(AWS::RDS::Formats::BASIC) do
result = @rds.remove_tags_from_resource(
@db_instance_id, single_tag.keys).body
returns(two_tags) do
@rds.list_tags_for_resource(@db_instance_id).
body['ListTagsForResourceResult']['TagList']
end
result
end
tests("#list_tags_for_resource").
formats(AWS::RDS::Formats::LIST_TAGS_FOR_RESOURCE) do
result = @rds.list_tags_for_resource(@db_instance_id).body
returns(two_tags) do
result['ListTagsForResourceResult']['TagList']
end
result
end
end
tests('failure') do
tests "tagging a nonexisting instance" do
raises(Fog::AWS::RDS::NotFound) do
@rds.add_tags_to_resource('doesnexist', {'key1' => 'value1'})
end
end
tests "listing tags for a nonexisting instance" do
raises(Fog::AWS::RDS::NotFound) do
@rds.list_tags_for_resource('doesnexist')
end
end
tests "removing tags for a nonexisting instance" do
raises(Fog::AWS::RDS::NotFound) do
@rds.remove_tags_from_resource('doesnexist', ['key1'])
end
end
end
Fog::Formatador.display_line "Destroying DB instance #{@db_instance_id}"
@db.destroy
end
fog-aws-0.7.6/tests/requests/rds/describe_events.rb 0000644 0000041 0000041 00000000540 12576636531 022432 0 ustar www-data www-data Shindo.tests('AWS::RDS | describe DB events requests',['aws', 'rds']) do
tests('success') do
pending if Fog.mocking?
tests(
'#describe_events'
).formats(AWS::RDS::Formats::EVENT_LIST) do
Fog::AWS[:rds].describe_events().body['Events']
end
end
tests('failure') do
#TODO: What constitutes a failure here?
end
end
fog-aws-0.7.6/tests/requests/rds/parameter_request_tests.rb 0000644 0000041 0000041 00000002403 12576636531 024240 0 ustar www-data www-data Shindo.tests('AWS::RDS | parameter requests', ['aws', 'rds']) do
tests('success') do
pending if Fog.mocking?
Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description')
tests('#modify_db_parameter_group').formats(AWS::RDS::Formats::MODIFY_PARAMETER_GROUP) do
body = Fog::AWS[:rds].modify_db_parameter_group('fog-group',[
{'ParameterName' => 'query_cache_size',
'ParameterValue' => '12345',
'ApplyMethod' => 'immediate'}
]).body
body
end
tests('#describe_db_parameters').formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETERS) do
Fog::AWS[:rds].describe_db_parameters('fog-group', :max_records => 20).body
end
tests("#describe_db_parameters :source => 'user'")do
body = Fog::AWS[:rds].describe_db_parameters('fog-group', :source => 'user').body
returns(1){ body['DescribeDBParametersResult']['Parameters'].length}
param = body['DescribeDBParametersResult']['Parameters'].first
returns('query_cache_size'){param['ParameterName']}
returns('12345'){param['ParameterValue']}
returns(true){param['IsModifiable']}
returns('query_cache_size'){param['ParameterName']}
end
Fog::AWS[:rds].delete_db_parameter_group('fog-group')
end
end
fog-aws-0.7.6/tests/requests/rds/parameter_group_tests.rb 0000644 0000041 0000041 00000004677 12576636531 023723 0 ustar www-data www-data Shindo.tests('AWS::RDS | parameter group requests', ['aws', 'rds']) do
tests('success') do
tests("#create_db_parameter_groups").formats(AWS::RDS::Formats::CREATE_DB_PARAMETER_GROUP) do
body = Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description').body
returns( 'mysql5.1') { body['CreateDBParameterGroupResult']['DBParameterGroup']['DBParameterGroupFamily']}
returns( 'fog-group') { body['CreateDBParameterGroupResult']['DBParameterGroup']['DBParameterGroupName']}
returns( 'Some description') { body['CreateDBParameterGroupResult']['DBParameterGroup']['Description']}
body
end
Fog::AWS[:rds].create_db_parameter_group('other-fog-group', 'MySQL5.1', 'Some description')
tests("#describe_db_parameter_groups").formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETER_GROUP) do
body = Fog::AWS[:rds].describe_db_parameter_groups().body
returns(4) {body['DescribeDBParameterGroupsResult']['DBParameterGroups'].length}
body
end
tests("#describe_db_parameter_groups('fog-group)").formats(AWS::RDS::Formats::DESCRIBE_DB_PARAMETER_GROUP) do
body = Fog::AWS[:rds].describe_db_parameter_groups('fog-group').body
returns(1) {body['DescribeDBParameterGroupsResult']['DBParameterGroups'].length}
group = body['DescribeDBParameterGroupsResult']['DBParameterGroups'].first
returns( 'mysql5.1') { group['DBParameterGroupFamily']}
returns( 'fog-group') { group['DBParameterGroupName']}
returns( 'Some description') { group['Description']}
body
end
tests("delete_db_parameter_group").formats(AWS::RDS::Formats::BASIC) do
body = Fog::AWS[:rds].delete_db_parameter_group('fog-group').body
raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_parameter_groups('fog-group')}
body
end
Fog::AWS[:rds].delete_db_parameter_group('other-fog-group')
end
tests("failures") do
raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_parameter_groups('doesntexist')}
raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].delete_db_parameter_group('doesntexist')}
tests "creating second group with same id" do
Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description')
raises(Fog::AWS::RDS::IdentifierTaken) {Fog::AWS[:rds].create_db_parameter_group('fog-group', 'MySQL5.1', 'Some description')}
end
Fog::AWS[:rds].delete_db_parameter_group('fog-group')
end
end
fog-aws-0.7.6/tests/requests/rds/log_file_tests.rb 0000644 0000041 0000041 00000001113 12576636531 022265 0 ustar www-data www-data Shindo.tests('AWS::RDS | log file requests', %w[aws rds]) do
tests('success') do
pending if Fog.mocking?
suffix = rand(65536).to_s(16)
@db_instance_id = "fog-test-#{suffix}"
tests('#describe_db_log_files').formats(AWS::RDS::Formats::DESCRIBE_DB_LOG_FILES) do
result = Fog::AWS[:rds].describe_db_log_files(@db_instance_id).body['DescribeDBLogFilesResult']
returns(true) { result['DBLogFiles'].size > 0 }
result
end
end
tests('failures') do
raises(Fog::AWS::RDS::NotFound) {Fog::AWS[:rds].describe_db_log_files('doesntexist')}
end
end
fog-aws-0.7.6/tests/requests/rds/instance_option_tests.rb 0000644 0000041 0000041 00000001371 12576636531 023707 0 ustar www-data www-data Shindo.tests('AWS::RDS | db instance option requests', ['aws', 'rds']) do
tests('success') do
tests("#describe_orderable_db_instance_options('mysql)").formats(AWS::RDS::Formats::DESCRIBE_ORDERABLE_DB_INSTANCE_OPTION) do
body = Fog::AWS[:rds].describe_orderable_db_instance_options('mysql').body
returns(2) {body['DescribeOrderableDBInstanceOptionsResult']['OrderableDBInstanceOptions'].length}
group = body['DescribeOrderableDBInstanceOptionsResult']['OrderableDBInstanceOptions'].first
returns( true ) { group['MultiAZCapable'] }
returns( 'mysql' ) { group['Engine'] }
returns( true ) { group['ReadReplicaCapable'] }
returns( true ) { group['AvailabilityZones'].length >= 1 }
body
end
end
end
fog-aws-0.7.6/tests/requests/rds/instance_tests.rb 0000644 0000041 0000041 00000013130 12576636531 022313 0 ustar www-data www-data Shindo.tests('AWS::RDS | instance requests', ['aws', 'rds']) do
# random_differentiator
# Useful when rapidly re-running tests, so we don't have to wait
# serveral minutes for deleted servers to disappear
suffix = rand(65536).to_s(16)
@db_instance_id = "fog-test-#{suffix}"
@db_replica_id = "fog-replica-#{suffix}"
@db_snapshot_id = "fog-snapshot-#{suffix}"
@db_final_snapshot_id = "fog-final-snapshot-#{suffix}"
tests('success') do
tests("#create_db_instance").formats(AWS::RDS::Formats::CREATE_DB_INSTANCE) do
default_params = rds_default_server_params
# creation of replicas requires a > 0 BackupRetentionPeriod value
# InvalidDBInstanceState => Automated backups are not enabled for this database instance. To enable automated backups, use ModifyDBInstance to set the backup retention period to a non-zero value. (Fog::AWS::RDS::Error)
backup_retention_period = 1
result = Fog::AWS[:rds].create_db_instance(@db_instance_id,
'AllocatedStorage' => default_params.fetch(:allocated_storage),
'DBInstanceClass' => default_params.fetch(:flavor_id),
'Engine' => default_params.fetch(:engine),
'EngineVersion' => default_params.fetch(:version),
'MasterUsername' => default_params.fetch(:master_username),
'BackupRetentionPeriod' => backup_retention_period,
'MasterUserPassword' => default_params.fetch(:password)).body
instance = result['CreateDBInstanceResult']['DBInstance']
returns('creating') { instance['DBInstanceStatus'] }
result
end
tests("#describe_db_instances").formats(AWS::RDS::Formats::DESCRIBE_DB_INSTANCES) do
Fog::AWS[:rds].describe_db_instances.body
end
server = Fog::AWS[:rds].servers.get(@db_instance_id)
server.wait_for { ready? }
new_storage = 6
tests("#modify_db_instance with immediate apply").formats(AWS::RDS::Formats::MODIFY_DB_INSTANCE) do
body = Fog::AWS[:rds].modify_db_instance(@db_instance_id, true, 'AllocatedStorage' => new_storage).body
tests 'pending storage' do
instance = body['ModifyDBInstanceResult']['DBInstance']
returns(new_storage) { instance['PendingModifiedValues']['AllocatedStorage'] }
end
body
end
server.wait_for { state == 'modifying' }
server.wait_for { state == 'available' }
tests 'new storage' do
returns(new_storage) { server.allocated_storage }
end
tests("reboot db instance") do
tests("#reboot").formats(AWS::RDS::Formats::REBOOT_DB_INSTANCE) do
Fog::AWS[:rds].reboot_db_instance(@db_instance_id).body
end
end
server.wait_for { state == 'rebooting' }
server.wait_for { state == 'available' }
tests("#create_db_snapshot").formats(AWS::RDS::Formats::CREATE_DB_SNAPSHOT) do
body = Fog::AWS[:rds].create_db_snapshot(@db_instance_id, @db_snapshot_id).body
returns('creating') { body['CreateDBSnapshotResult']['DBSnapshot']['Status'] }
body
end
tests("#describe_db_snapshots").formats(AWS::RDS::Formats::DESCRIBE_DB_SNAPSHOTS) do
Fog::AWS[:rds].describe_db_snapshots.body
end
server.wait_for { state == 'available' }
tests("#create read replica").formats(AWS::RDS::Formats::CREATE_READ_REPLICA) do
Fog::AWS[:rds].create_db_instance_read_replica(@db_replica_id, @db_instance_id).body
end
replica = Fog::AWS[:rds].servers.get(@db_replica_id)
replica.wait_for { ready? }
tests("replica source") do
returns(@db_instance_id) { replica.read_replica_source }
end
server.reload
tests("replica identifiers") do
returns([@db_replica_id]) { server.read_replica_identifiers }
end
tests("#promote read replica").formats(AWS::RDS::Formats::PROMOTE_READ_REPLICA) do
Fog::AWS[:rds].promote_read_replica(@db_replica_id).body
end
tests("#delete_db_instance").formats(AWS::RDS::Formats::DELETE_DB_INSTANCE) do
#server.wait_for { state == 'available' }
Fog::AWS[:rds].delete_db_instance(@db_replica_id, nil, true)
body = Fog::AWS[:rds].delete_db_instance(@db_instance_id, @db_final_snapshot_id).body
tests "final snapshot" do
returns('creating') { Fog::AWS[:rds].describe_db_snapshots(:snapshot_id => @db_final_snapshot_id).body['DescribeDBSnapshotsResult']['DBSnapshots'].first['Status'] }
end
body
end
tests("#delete_db_snapshot").formats(AWS::RDS::Formats::DELETE_DB_SNAPSHOT) do
Fog::AWS[:rds].snapshots.get(@db_snapshot_id).wait_for { ready? }
Fog::AWS[:rds].delete_db_snapshot(@db_snapshot_id).body
end
tests("snapshot.destroy") do
snapshot = Fog::AWS[:rds].snapshots.get(@db_final_snapshot_id)
snapshot.wait_for { ready? }
snapshot.destroy
returns(nil) { Fog::AWS[:rds].snapshots.get(@db_final_snapshot_id) }
end
end
tests('failure') do
tests "deleting nonexisting instance" do
raises(Fog::AWS::RDS::NotFound) { Fog::AWS[:rds].delete_db_instance('doesnexist', 'irrelevant') }
end
tests "deleting non existing snapshot" do
raises(Fog::AWS::RDS::NotFound) { Fog::AWS[:rds].delete_db_snapshot('doesntexist') }
end
tests "modifying non existing instance" do
raises(Fog::AWS::RDS::NotFound) { Fog::AWS[:rds].modify_db_instance 'doesntexit', true, 'AllocatedStorage' => 10 }
end
end
end
fog-aws-0.7.6/tests/requests/lambda/ 0000755 0000041 0000041 00000000000 12576636531 017372 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/lambda/function_sample_1.js 0000644 0000041 0000041 00000000475 12576636531 023344 0 ustar www-data www-data console.log('Loading function');
exports.handler = function(event, context) {
console.log('value1 =', event.key1);
console.log('value2 =', event.key2);
console.log('value3 =', event.key3);
context.succeed(event.key1); // Echo back the first key value
// context.fail('Something went wrong');
};
fog-aws-0.7.6/tests/requests/lambda/helper.rb 0000644 0000041 0000041 00000005046 12576636531 021203 0 ustar www-data www-data class AWS
class Lambda
module Formats
require 'zip/zip'
GET_FUNCTION_CONFIGURATION = {
'CodeSize' => Integer,
'Description' => Fog::Nullable::String,
'FunctionArn' => String,
'FunctionName' => String,
'Handler' => String,
'LastModified' => Time,
'MemorySize' => Integer,
'Role' => String,
'Runtime' => String,
'Timeout' => Integer
}
LIST_FUNCTIONS = {
'Functions' => [GET_FUNCTION_CONFIGURATION],
'NextMarker' => Fog::Nullable::String
}
GET_FUNCTION = {
'Code' => {
'Location' => String,
'RepositoryType' => String
},
'Configuration' => GET_FUNCTION_CONFIGURATION
}
UPDATE_FUNCTION_CONFIGURATION = GET_FUNCTION_CONFIGURATION
UPDATE_FUNCTION_CODE = GET_FUNCTION_CONFIGURATION
CREATE_FUNCTION = GET_FUNCTION_CONFIGURATION
ADD_PERMISSION = {
'Statement' => {
'Condition' => Fog::Nullable::Hash,
'Action' => Array,
'Resource' => String,
'Effect' => String,
'Principal' => Hash,
'Sid' => String
}
}
GET_POLICY = {
'Policy' => {
'Version' => String,
'Id' => String,
'Statement' => [ADD_PERMISSION['Statement']]
}
}
GET_EVENT_SOURCE_MAPPING = {
'BatchSize' => Integer,
'EventSourceArn' => String,
'FunctionArn' => String,
'LastModified' => Float,
'LastProcessingResult' => String,
'State' => String,
'StateTransitionReason' => String,
'UUID' => String
}
LIST_EVENT_SOURCE_MAPPINGS = {
'EventSourceMappings' => [GET_EVENT_SOURCE_MAPPING],
'NextMarker' => Fog::Nullable::String
}
CREATE_EVENT_SOURCE_MAPPING = GET_EVENT_SOURCE_MAPPING
UPDATE_EVENT_SOURCE_MAPPING = GET_EVENT_SOURCE_MAPPING
DELETE_EVENT_SOURCE_MAPPING = GET_EVENT_SOURCE_MAPPING
def self.zip(data, filename='index.js')
data_io = Zip::ZipOutputStream.write_buffer do |zio|
zio.put_next_entry(filename)
zio.write(data)
end
data_io.rewind
data_io.sysread
end
end
module Samples
FUNCTION_1 = File.dirname(__FILE__) + '/function_sample_1.js'
FUNCTION_2 = File.dirname(__FILE__) + '/function_sample_2.js'
end
end
end
fog-aws-0.7.6/tests/requests/lambda/function_sample_2.js 0000644 0000041 0000041 00000000476 12576636531 023346 0 ustar www-data www-data console.log('Loading function');
exports.handler = function(event, context) {
console.log('value1 =', event.key1);
console.log('value2 =', event.key2);
console.log('value3 =', event.key3);
context.succeed(event.key2); // Echo back the second key value
// context.fail('Something went wrong');
};
fog-aws-0.7.6/tests/requests/lambda/function_tests.rb 0000644 0000041 0000041 00000044124 12576636531 022773 0 ustar www-data www-data Shindo.tests('AWS::Lambda | function requests', ['aws', 'lambda']) do
_lambda = Fog::AWS[:lambda]
account_id = _lambda.account_id
region = _lambda.region
function1 = IO.read(AWS::Lambda::Samples::FUNCTION_1)
function2 = IO.read(AWS::Lambda::Samples::FUNCTION_2)
zipped_function1 = Base64::encode64(AWS::Lambda::Formats.zip(function1))
zipped_function2 = Base64::encode64(AWS::Lambda::Formats.zip(function2))
function1_arn = nil
function1_name = 'function1'
function2_name = 'function2'
function1_handler = 'index.handler'
function_role = 'arn:aws:iam::647975416665:role/lambda_basic_execution'
sns_principal = 'sns.amazonaws.com'
sns_topic_sid = Fog::Mock.random_letters_and_numbers(32)
sns_allowed_action = 'lambda:invoke'
sns_topic_arn = Fog::AWS::Mock.arn('sns', account_id, 'mock_topic', region)
kinesis_stream_arn = Fog::AWS::Mock.arn('kinesis', account_id, 'mock_stream', region)
event_source_mapping1_id = nil
tests('success') do
tests('#list_functions').formats(AWS::Lambda::Formats::LIST_FUNCTIONS) do
result = _lambda.list_functions.body
functions = result['Functions']
returns(true) { functions.empty? }
result
end
tests('#create_function').formats(AWS::Lambda::Formats::CREATE_FUNCTION) do
description = 'a copy of my first function'
result = _lambda.create_function(
'FunctionName' => function1_name,
'Handler' => function1_handler,
'Role' => function_role,
'Description' => description,
'Code' => { 'ZipFile' => zipped_function1 }
).body
returns(true) { result.has_key?('FunctionArn') }
returns(true) { result['CodeSize'] > 0 }
returns(true) { result['MemorySize'] >= 128 }
returns(true) { result['FunctionName'].eql?(function1_name) }
returns(true) { result['Handler'].eql?(function1_handler) }
function1_arn = result['FunctionArn']
result
end
tests('#invoke') do
payload = { 'value1' => 2, 'value2' => 42 }
result = _lambda.invoke(
'FunctionName' => function1_name,
'Payload' => payload
).body
returns(false) { result.length.zero? }
returns(false) { result.match(/function:#{function1_name} was invoked/).nil? }
result
end
tests('#get_function').formats(AWS::Lambda::Formats::GET_FUNCTION) do
result = _lambda.get_function('FunctionName' => function1_name).body
func_config = result['Configuration']
returns(false) { result['Code']['Location'].match(/^https:\/\/awslambda-/).nil? }
returns(true) { func_config.has_key?('FunctionArn') }
returns(true) { func_config['CodeSize'] > 0 }
returns(true) { func_config['MemorySize'] >= 128 }
returns(true) { func_config['FunctionName'].eql?(function1_name) }
returns(true) { func_config['Handler'].eql?(function1_handler) }
returns(true) { func_config['FunctionArn'].eql?(function1_arn) }
result
end
tests('#get_function_configuration').formats(AWS::Lambda::Formats::GET_FUNCTION_CONFIGURATION) do
result = _lambda.get_function_configuration(
'FunctionName' => function1_name).body
returns(true) { result.has_key?('FunctionArn') }
returns(true) { result['CodeSize'] > 0 }
returns(true) { result['MemorySize'] >= 128 }
returns(true) { result['FunctionName'].eql?(function1_name) }
returns(true) { result['Handler'].eql?(function1_handler) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
result
end
tests('#update_function_configuration').formats(AWS::Lambda::Formats::UPDATE_FUNCTION_CONFIGURATION) do
new_memory_size = 256
new_description = "this function does nothing, just let's call it foobar"
new_timeout = 10
result = _lambda.update_function_configuration(
'FunctionName' => function1_name,
'MemorySize' => new_memory_size,
'Description' => new_description,
'Timeout' => new_timeout
).body
returns(true) { result['CodeSize'] > 0 }
returns(true) { result['MemorySize'].eql?(new_memory_size) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
returns(true) { result['Description'].eql?(new_description) }
returns(true) { result['Timeout'].eql?(new_timeout) }
result
end
tests('#update_function_code').formats(AWS::Lambda::Formats::UPDATE_FUNCTION_CODE) do
result = _lambda.update_function_code(
'FunctionName' => function1_name,
'ZipFile' => zipped_function2
).body
returns(true) { result.has_key?('FunctionArn') }
returns(true) { result['CodeSize'] > 0 }
returns(true) { result['MemorySize'] >= 128 }
returns(true) { result['FunctionName'].eql?(function1_name) }
returns(true) { result['Handler'].eql?(function1_handler) }
result
end
tests('#add_permission').formats(AWS::Lambda::Formats::ADD_PERMISSION) do
params = {
'FunctionName' => function1_name,
'Principal' => sns_principal,
'StatementId' => sns_topic_sid,
'Action' => sns_allowed_action,
'SourceArn' => sns_topic_arn
}
result = _lambda.add_permission(params).body
statement = result['Statement']
returns(true) { statement['Action'].include?(sns_allowed_action) }
returns(true) { statement['Principal']['Service'].eql?(sns_principal) }
returns(true) { statement['Sid'].eql?(sns_topic_sid) }
returns(true) { statement['Resource'].eql?(function1_arn) }
returns(true) { statement['Effect'].eql?('Allow') }
returns(false) { statement['Condition'].empty? }
result
end
tests('#get_policy').formats(AWS::Lambda::Formats::GET_POLICY) do
result = _lambda.get_policy('FunctionName' => function1_name).body
policy = result['Policy']
returns(false) { policy['Statement'].empty? }
statement = policy['Statement'].first
returns(true) { statement['Action'].include?(sns_allowed_action) }
returns(true) { statement['Principal']['Service'].eql?(sns_principal) }
returns(true) { statement['Sid'].eql?(sns_topic_sid) }
returns(true) { statement['Resource'].eql?(function1_arn) }
returns(true) { statement['Effect'].eql?('Allow') }
returns(false) { statement['Condition'].empty? }
result
end
tests('#remove_permission') do
params = {
'FunctionName' => function1_name,
'StatementId' => sns_topic_sid
}
result = _lambda.remove_permission(params).body
returns(true) { result.empty? }
raises(Fog::AWS::Lambda::Error) do
_lambda.get_policy('FunctionName' => function1_name)
end
result
end
tests('#create_event_source_mapping').formats(AWS::Lambda::Formats::CREATE_EVENT_SOURCE_MAPPING) do
params = {
'FunctionName' => function1_name,
'EventSourceArn' => kinesis_stream_arn,
'Enabled' => true,
'StartingPosition' => 'TRIM_HORIZON'
}
result = _lambda.create_event_source_mapping(params).body
returns(true) { result['BatchSize'] > 0 }
returns(true) { result['EventSourceArn'].eql?(kinesis_stream_arn) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
returns(true) { result['LastProcessingResult'].eql?('No records processed') }
returns(true) { result['State'].eql?('Creating') }
returns(true) { result['StateTransitionReason'].eql?('User action') }
event_source_mapping1_id = result['UUID']
result
end
tests('#list_event_source_mappings').formats(AWS::Lambda::Formats::LIST_EVENT_SOURCE_MAPPINGS) do
params = { 'FunctionName' => function1_name }
result = _lambda.list_event_source_mappings(params).body
event_source_mappings = result['EventSourceMappings']
returns(false) { event_source_mappings.empty? }
mapping = event_source_mappings.first
returns(true) { mapping['UUID'].eql?(event_source_mapping1_id) }
result
end
tests('#get_event_source_mapping').formats(AWS::Lambda::Formats::GET_EVENT_SOURCE_MAPPING) do
params = { 'UUID' => event_source_mapping1_id }
result = _lambda.get_event_source_mapping(params).body
returns(true) { result['BatchSize'] > 0 }
returns(true) { result['EventSourceArn'].eql?(kinesis_stream_arn) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
returns(true) { result['LastProcessingResult'].eql?('OK') }
returns(true) { result['State'].eql?('Enabled') }
returns(true) { result['StateTransitionReason'].eql?('User action') }
returns(true) { result['UUID'].eql?(event_source_mapping1_id) }
result
end
tests('#update_event_source_mapping').formats(AWS::Lambda::Formats::UPDATE_EVENT_SOURCE_MAPPING) do
new_batch_size = 500
enabled_mapping = false
params = {
'UUID' => event_source_mapping1_id,
'BatchSize' => new_batch_size,
'Enabled' => enabled_mapping
}
result = _lambda.update_event_source_mapping(params).body
returns(true) { result['BatchSize'].eql?(new_batch_size) }
returns(true) { result['EventSourceArn'].eql?(kinesis_stream_arn) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
returns(true) { result['LastProcessingResult'].eql?('OK') }
returns(true) { result['State'].eql?('Disabling') }
returns(true) { result['StateTransitionReason'].eql?('User action') }
returns(true) { result['UUID'].eql?(event_source_mapping1_id) }
result
end
tests('#delete_event_source_mapping').formats(AWS::Lambda::Formats::DELETE_EVENT_SOURCE_MAPPING) do
params = { 'UUID' => event_source_mapping1_id }
result = _lambda.delete_event_source_mapping(params).body
returns(true) { result['BatchSize'] > 0 }
returns(true) { result['EventSourceArn'].eql?(kinesis_stream_arn) }
returns(true) { result['FunctionArn'].eql?(function1_arn) }
returns(false) { result['LastProcessingResult'].empty? }
returns(true) { result['State'].eql?('Deleting') }
returns(true) { result['StateTransitionReason'].eql?('User action') }
returns(true) { result['UUID'].eql?(event_source_mapping1_id) }
result
end
tests('#list_event_source_mappings again').formats(AWS::Lambda::Formats::LIST_EVENT_SOURCE_MAPPINGS) do
params = { 'FunctionName' => function1_name }
result = _lambda.list_event_source_mappings(params).body
event_source_mappings = result['EventSourceMappings']
returns(true) { event_source_mappings.empty? }
result
end
tests('#delete_function') do
result = _lambda.delete_function('FunctionName' => function1_name).body
returns(true) { result.empty? }
raises(Fog::AWS::Lambda::Error) do
_lambda.get_function('FunctionName' => function1_name)
end
result
end
tests('#list_functions again').formats(AWS::Lambda::Formats::LIST_FUNCTIONS) do
result = _lambda.list_functions.body
functions = result['Functions']
returns(true) { functions.empty? }
result
end
tests('#create_function for failures tests').formats(AWS::Lambda::Formats::CREATE_FUNCTION) do
description = 'failure tests function'
result = _lambda.create_function(
'FunctionName' => function2_name,
'Handler' => function1_handler,
'Role' => function_role,
'Description' => description,
'Code' => { 'ZipFile' => zipped_function1 }
).body
returns(true) { result.has_key?('FunctionArn') }
returns(true) { result['CodeSize'] > 0 }
returns(true) { result['MemorySize'] >= 128 }
returns(true) { result['FunctionName'].eql?(function2_name) }
returns(true) { result['Handler'].eql?(function1_handler) }
result
end
end
tests('failures') do
tests("#invoke without function name").raises(Fog::AWS::Lambda::Error) do
response = _lambda.invoke.body
end
tests("#invoke nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = Fog::AWS[:lambda].invoke('FunctionName' => 'nonexistent').body
end
tests("#get_function without function name").raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_function.body
end
tests("#get_function on nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_function('FunctionName' => 'nonexistent').body
end
tests("#get_function_configuration without function name").raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_function_configuration.body
end
tests("#get_function_configuration on nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_function_configuration('FunctionName' => 'nonexistent').body
end
tests("update_function_configuration without function name").raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_function_configuration.body
end
tests("#update_function_configuration on nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_function_configuration('FunctionName' => 'nonexistent').body
end
tests("update_function_code without function name").raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_function_code.body
end
tests("#update_function_code on nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_function_code(
'FunctionName' => 'nonexistent',
'ZipFile' => zipped_function2
).body
end
tests("#update_function_code on valid function without source").raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_function_code('FunctionName' => 'foobar').body
end
tests("#delete_function without params").raises(Fog::AWS::Lambda::Error) do
response = _lambda.delete_function.body
end
tests("#delete_function on nonexistent function").raises(Fog::AWS::Lambda::Error) do
response = _lambda.delete_function('FunctionName' => 'nonexistent').body
end
tests('#get_policy without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_policy.body
end
tests('#get_policy on nonexistent function').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_policy('FunctionName' => 'nonexistent').body
end
tests('#get_policy on function without permissions').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_policy('FunctionName' => function2_name).body
end
tests('#add_permission without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.add_permission.body
end
tests('#add_permission on nonexistent function').raises(Fog::AWS::Lambda::Error) do
response = _lambda.add_permission('FunctionName' => 'nonexistent').body
end
tests('#add_permission with missing params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.add_permission('FunctionName' => function2_name).body
end
tests('#remove_permission without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.remove_permission.body
end
tests('#remove_permission on nonexistent function').raises(Fog::AWS::Lambda::Error) do
response = _lambda.remove_permission('FunctionName' => 'nonexistent').body
end
tests('#remove_permission on function with missing sid param').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_policy('FunctionName' => function2_name).body
end
tests('#remove_permission on function with missing sid param').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_policy(
'FunctionName' => function2_name,
'StatementId' => 'nonexistent_statement_id'
).body
end
tests('#create_event_source_mapping without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.create_event_source_mapping.body
end
tests('#create_event_source_mapping on nonexistent function').raises(Fog::AWS::Lambda::Error) do
response = _lambda.create_event_source_mapping('FunctionName' => 'nonexistent').body
end
tests('#create_event_source_mapping with missing params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.create_event_source_mapping('FunctionName' => function2_name).body
end
tests('#get_event_source_mapping without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.get_event_source_mapping.body
end
tests('#get_event_source_mapping nonexistent').raises(Fog::AWS::Lambda::Error) do
mapping_id = "deadbeef-caca-cafe-cafa-ffffdeadbeef"
response = _lambda.get_event_source_mapping('UUID' => mapping_id).body
end
tests('#update_event_source_mapping without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.update_event_source_mapping.body
end
tests('#update_event_source_mapping nonexistent').raises(Fog::AWS::Lambda::Error) do
mapping_id = "deadbeef-caca-cafe-cafa-ffffdeadbeef"
response = _lambda.update_event_source_mapping('UUID' => mapping_id).body
end
tests('#delete_event_source_mapping without params').raises(Fog::AWS::Lambda::Error) do
response = _lambda.delete_event_source_mapping.body
end
tests('#delete_event_source_mapping nonexistent').raises(Fog::AWS::Lambda::Error) do
mapping_id = "deadbeef-caca-cafe-cafa-ffffdeadbeef"
response = _lambda.create_event_source_mapping('UUID' => mapping_id).body
end
end
end
fog-aws-0.7.6/tests/requests/compute/ 0000755 0000041 0000041 00000000000 12576636531 017626 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/compute/spot_price_history_tests.rb 0000644 0000041 0000041 00000001127 12576636531 025326 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | spot price history requests', ['aws']) do
@spot_price_history_format = {
'spotPriceHistorySet' => [{
'availabilityZone' => String,
'instanceType' => String,
'spotPrice' => Float,
'productDescription' => String,
'timestamp' => Time
}],
'requestId' => String,
'nextToken' => Fog::Nullable::String
}
tests('success') do
tests("#describe_spot_price_history").formats(@spot_price_history_format) do
Fog::Compute[:aws].describe_spot_price_history.body
end
end
end
fog-aws-0.7.6/tests/requests/compute/availability_zone_tests.rb 0000644 0000041 0000041 00000001276 12576636531 025110 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | availability zone requests', ['aws']) do
@availability_zones_format = {
'availabilityZoneInfo' => [{
'messageSet' => [],
'regionName' => String,
'zoneName' => String,
'zoneState' => String
}],
'requestId' => String
}
tests('success') do
tests('#describe_availability_zones').formats(@availability_zones_format) do
Fog::Compute[:aws].describe_availability_zones.body
end
tests("#describe_availability_zones('zone-name' => 'us-east-1a')").formats(@availability_zones_format) do
Fog::Compute[:aws].describe_availability_zones('zone-name' => 'us-east-1a').body
end
end
end
fog-aws-0.7.6/tests/requests/compute/security_group_tests.rb 0000644 0000041 0000041 00000047554 12576636531 024477 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | security group requests', ['aws']) do
# See https://github.com/fog/fog/issues/2932hj0
pending
@create_security_group_format = {
'requestId' => String,
'groupId' => String,
'return' => Fog::Boolean
}
@security_groups_format = {
'requestId' => String,
'securityGroupInfo' => [{
'groupDescription' => String,
'groupId' => Fog::Nullable::String,
'groupName' => String,
'ipPermissions' => [{
'fromPort' => Fog::Nullable::Integer,
'groups' => [{ 'groupName' => Fog::Nullable::String, 'userId' => String, 'groupId' => String }],
'ipProtocol' => String,
'ipRanges' => [Fog::Nullable::Hash],
'toPort' => Fog::Nullable::Integer,
}],
'ipPermissionsEgress' => [],
'ownerId' => String,
'vpcId' => Fog::Nullable::String
}]
}
@owner_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'default').body['securityGroupInfo'].first['ownerId']
@group_id_default = Fog::Compute[:aws].describe_security_groups('group-name' => 'default').body['securityGroupInfo'].first['groupId']
tests('success') do
tests("#create_security_group('fog_security_group', 'tests group')").formats(@create_security_group_format) do
Fog::Compute[:aws].create_security_group('fog_security_group', 'tests group').body
end
tests("#create_security_group('fog_security_group_two', 'tests group')").formats(@create_security_group_format) do
Fog::Compute[:aws].create_security_group('fog_security_group_two', 'tests group').body
end
@group_id_two = Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group_two').body['securityGroupInfo'].first['groupId']
group_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['groupId']
to_be_revoked = []
expected_permissions = []
permission = { 'SourceSecurityGroupName' => 'default' }
tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body
end
to_be_revoked.push([permission, expected_permissions.dup])
expected_permissions = [
{"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}],
"fromPort"=>1,
"ipRanges"=>[],
"ipProtocol"=>"tcp",
"toPort"=>65535},
{"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}],
"fromPort"=>1,
"ipRanges"=>[],
"ipProtocol"=>"udp",
"toPort"=>65535},
{"groups"=>[{"groupName"=>"default", "userId"=>@owner_id, "groupId"=>@group_id_default}],
"fromPort"=>-1,
"ipRanges"=>[],
"ipProtocol"=>"icmp",
"toPort"=>-1}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
tests("#describe_security_groups('group-id' => '#{group_id}')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-id' => group_id).body['securityGroupInfo'].first['ipPermissions'])
end
permission = { 'SourceSecurityGroupName' => 'fog_security_group_two', 'SourceSecurityGroupOwnerId' => @owner_id }
tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body
end
to_be_revoked.push([permission, expected_permissions.dup])
expected_permissions = [
{"groups"=>
[{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default},
{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}],
"ipRanges"=>[],
"ipProtocol"=>"tcp",
"fromPort"=>1,
"toPort"=>65535},
{"groups"=>
[{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default},
{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}],
"ipRanges"=>[],
"ipProtocol"=>"udp",
"fromPort"=>1,
"toPort"=>65535},
{"groups"=>
[{"userId"=>@owner_id, "groupName"=>"default", "groupId"=>@group_id_default},
{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}],
"ipRanges"=>[],
"ipProtocol"=>"icmp",
"fromPort"=>-1,
"toPort"=>-1}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
permission = { 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22' }
tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body
end
to_be_revoked.push([permission, expected_permissions.dup])
# previous did nothing
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
permission = { 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22', 'CidrIp' => '10.0.0.0/8' }
tests("#authorize_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permission).body
end
to_be_revoked.push([permission, expected_permissions.dup])
expected_permissions += [
{"groups"=>[],
"ipRanges"=>[{"cidrIp"=>"10.0.0.0/8"}],
"ipProtocol"=>"tcp",
"fromPort"=>22,
"toPort"=>22}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
# authorize with nested IpProtocol without IpRanges or Groups does nothing
permissions = {
'IpPermissions' => [
{ 'IpProtocol' => 'tcp', 'FromPort' => '22', 'ToPort' => '22' }
]
}
tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body
end
to_be_revoked.push([permissions, expected_permissions.dup])
# previous did nothing
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
# authorize with nested IpProtocol with IpRanges
permissions = {
'IpPermissions' => [
{
'IpProtocol' => 'tcp', 'FromPort' => '80', 'ToPort' => '80',
'IpRanges' => [{ 'CidrIp' => '192.168.0.0/24' }]
}
]
}
tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body
end
to_be_revoked.push([permissions, expected_permissions.dup])
expected_permissions += [
{"groups"=>[],
"ipRanges"=>[{"cidrIp"=>"192.168.0.0/24"}],
"ipProtocol"=>"tcp",
"fromPort"=>80,
"toPort"=>80}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
# authorize with nested IpProtocol with Groups
permissions = {
'IpPermissions' => [
{
'IpProtocol' => 'tcp', 'FromPort' => '8000', 'ToPort' => '8000',
'Groups' => [{ 'GroupName' => 'fog_security_group_two' }]
}
]
}
tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body
end
to_be_revoked.push([permissions, expected_permissions.dup])
expected_permissions += [
{"groups"=>[{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}],
"ipRanges"=>[],
"ipProtocol"=>"tcp",
"fromPort"=>8000,
"toPort"=>8000}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
# authorize with nested IpProtocol with IpRanges and Groups
# try integers on this one instead of strings
permissions = {
'IpPermissions' => [
{
'IpProtocol' => 'tcp', 'FromPort' => 9000, 'ToPort' => 9000,
'IpRanges' => [{ 'CidrIp' => '172.16.0.0/24' }],
'Groups' => [{ 'GroupName' => 'fog_security_group_two' }]
}
]
}
tests("#authorize_security_group_ingress('fog_security_group', #{permissions.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', permissions).body
end
to_be_revoked.push([permissions, expected_permissions.dup])
expected_permissions += [
{"groups"=>
[{"userId"=>@owner_id, "groupName"=>"fog_security_group_two", "groupId"=>@group_id_two}],
"ipRanges"=>[{"cidrIp"=>"172.16.0.0/24"}],
"ipProtocol"=>"tcp",
"fromPort"=>9000,
"toPort"=>9000}
]
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
tests("#describe_security_groups").formats(@security_groups_format) do
Fog::Compute[:aws].describe_security_groups.body
end
tests("#describe_security_groups('group-name' => 'fog_security_group')").formats(@security_groups_format) do
Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body
end
to_be_revoked.reverse.each do |permission, expected_permissions_after|
tests("#revoke_security_group_ingress('fog_security_group', #{permission.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].revoke_security_group_ingress('fog_security_group', permission).body
end
tests("#describe_security_groups('group-name' => 'fog_security_group')").returns([]) do
array_differences(expected_permissions_after, Fog::Compute[:aws].describe_security_groups('group-name' => 'fog_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
end
tests("#delete_security_group('fog_security_group')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_security_group('fog_security_group').body
end
tests("#delete_security_group('fog_security_group_two')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_security_group('fog_security_group_two').body
end
vpc_id = Fog::Compute[:aws].create_vpc('10.255.254.64/28').body['vpcSet'].first['vpcId']
# Create security group in VPC
tests("#create_security_group('vpc_security_group', 'tests group')").formats(@create_security_group_format) do
Fog::Compute[:aws].create_security_group('vpc_security_group', 'tests group', vpc_id).body
end
group_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'vpc_security_group').body['securityGroupInfo'].first['groupId']
permissions = {
'IpPermissions' => [
{
'IpProtocol' => '42',
'IpRanges' => [{ 'CidrIp' => '10.0.0.0/8' }],
}
]
}
expected_permissions = [
{"groups"=>[],
"ipRanges"=>[{"cidrIp"=>"10.0.0.0/8"}],
"ipProtocol"=>"42"}
]
options = permissions.clone
options['GroupId'] = group_id
tests("#authorize_security_group_ingress(#{options.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress(options).body
end
tests("#describe_security_groups('group-name' => 'vpc_security_group')").returns([]) do
array_differences(expected_permissions, Fog::Compute[:aws].describe_security_groups('group-name' => 'vpc_security_group').body['securityGroupInfo'].first['ipPermissions'])
end
tests("#revoke_security_group_ingress(#{options.inspect})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].revoke_security_group_ingress(options).body
end
vpc_group=Fog::Compute[:aws].security_groups.get_by_id(group_id)
vpc_group.destroy
Fog::Compute[:aws].delete_vpc(vpc_id)
end
## Rate limiting seems to want us to take a break otherwise it will throw errors
tests('failure') do
@security_group = Fog::Compute[:aws].security_groups.create(:description => 'tests group', :name => 'fog_security_group')
@other_security_group = Fog::Compute[:aws].security_groups.create(:description => 'tests group', :name => 'fog_other_security_group')
tests("duplicate #create_security_group(#{@security_group.name}, #{@security_group.description})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_security_group(@security_group.name, @security_group.description)
end
tests("#authorize_security_group_ingress('not_a_group_name', {'FromPort' => 80, 'IpProtocol' => 'tcp', 'toPort' => 80})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].authorize_security_group_ingress(
'not_a_group_name',
{
'FromPort' => 80,
'IpProtocol' => 'tcp',
'ToPort' => 80,
}
)
end
tests("#authorize_security_group_ingress('not_a_group_name', {'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => '#{@owner_id}'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].authorize_security_group_ingress(
'not_a_group_name',
{
'SourceSecurityGroupName' => 'not_a_group_name',
'SourceSecurityGroupOwnerId' => @owner_id
}
)
end
tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]}).body
end
tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'IpProtocol' => 'tcp', 'FromPort' => 80, 'ToPort' => 80, 'IpRanges' => [{'CidrIp' => '10.0.0.0/8'}]}]})
end
tests("#authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'Groups' => [{'GroupName' => '#{@other_security_group.name}'}], 'FromPort' => 80, 'ToPort' => 80, 'IpProtocol' => 'tcp'}]})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', {'IpPermissions' => [{'Groups' => [{'GroupName' => @other_security_group.name}], 'FromPort' => 80, 'ToPort' => 80, 'IpProtocol' => 'tcp'}]}).body
end
tests("#delete_security_group('#{@other_security_group.name}')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].delete_security_group(@other_security_group.name)
end
broken_params = [
{},
{ "IpProtocol" => "what" },
{ "IpProtocol" => "tcp" },
{ "IpProtocol" => "what", "FromPort" => 1, "ToPort" => 1 },
]
broken_params += broken_params.map do |broken_params_item|
{ "IpPermissions" => [broken_params_item] }
end
broken_params += [
{ "IpPermissions" => [] },
{ "IpPermissions" => nil }
]
broken_params.each do |broken_params_item|
tests("#authorize_security_group_ingress('fog_security_group', #{broken_params_item.inspect})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].authorize_security_group_ingress('fog_security_group', broken_params_item)
end
tests("#revoke_security_group_ingress('fog_security_group', #{broken_params_item.inspect})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].revoke_security_group_ingress('fog_security_group', broken_params_item)
end
end
tests("#revoke_security_group_ingress('not_a_group_name', {'FromPort' => 80, 'IpProtocol' => 'tcp', 'toPort' => 80})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].revoke_security_group_ingress(
'not_a_group_name',
{
'FromPort' => 80,
'IpProtocol' => 'tcp',
'ToPort' => 80,
}
)
end
tests("#revoke_security_group_ingress('not_a_group_name', {'SourceSecurityGroupName' => 'not_a_group_name', 'SourceSecurityGroupOwnerId' => '#{@owner_id}'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].revoke_security_group_ingress(
'not_a_group_name',
{
'SourceSecurityGroupName' => 'not_a_group_name',
'SourceSecurityGroupOwnerId' => @owner_id
}
)
end
tests("#delete_security_group('not_a_group_name')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_security_group('not_a_group_name')
end
@rds_security_group = Fog::AWS[:rds].security_groups.create(:id => "rdsgroup", :description => 'fog rds test')
tests("#delete_security_group('when authorized to an rds firewall')").raises(Fog::Compute::AWS::Error) do
@rds_security_group.authorize_ec2_security_group(@security_group.name)
Fog::Compute[:aws].delete_security_group(@security_group.name)
end
@rds_security_group.destroy
@security_group.destroy
@other_security_group.destroy
tests("#delete_security_group('default')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].delete_security_group('default')
end
broken_params = [
['fog_security_group', { 'GroupName' => 'fog_security_group' }],
[nil, nil],
[nil, { 'GroupId' => nil }],
[nil, { 'GroupName' => nil, 'GroupId' => nil }]
]
broken_params.each do |list_elem|
tests("#authorize_security_group_ingress(#{list_elem[0].inspect}, #{list_elem[1].inspect})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].authorize_security_group_ingress(list_elem[0], list_elem[1])
end
tests("#revoke_security_group_ingress(#{list_elem[0].inspect}, #{list_elem[1].inspect})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].revoke_security_group_ingress(list_elem[0], list_elem[1])
end
end
end
end
fog-aws-0.7.6/tests/requests/compute/helper.rb 0000644 0000041 0000041 00000000235 12576636531 021432 0 ustar www-data www-data class AWS
module Compute
module Formats
BASIC = {
'requestId' => String,
'return' => ::Fog::Boolean
}
end
end
end
fog-aws-0.7.6/tests/requests/compute/region_tests.rb 0000644 0000041 0000041 00000003322 12576636531 022660 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | region requests', ['aws']) do
@regions_format = {
'regionInfo' => [{
'regionEndpoint' => String,
'regionName' => String
}],
'requestId' => String
}
tests('success') do
tests("#describe_regions").formats(@regions_format) do
Fog::Compute[:aws].describe_regions.body
end
tests("#describe_regions('region-name' => 'us-east-1')").formats(@regions_format) do
Fog::Compute[:aws].describe_regions('region-name' => 'us-east-1').body
end
tests("#incorrect_region") do
raises(ArgumentError, "Unknown region: world-antarctica-1") do
Fog::Compute::AWS.new({:aws_access_key_id => 'dummykey',
:aws_secret_access_key => 'dummysecret',
:aws_session_token => 'dummytoken',
:region => 'world-antarctica-1'})
end
end
tests("#unknown_endpoint").formats(@regions_format) do
Fog::Compute::AWS.new({:aws_access_key_id => 'dummykey',
:aws_secret_access_key => 'dummysecret',
:aws_session_token => 'dummytoken',
:region => 'world-antarctica-1',
:endpoint => 'http://aws-clone.example'}).describe_regions.body
end
tests("#invalid_endpoint") do
raises(Fog::Compute::AWS::InvalidURIError) do
Fog::Compute::AWS.new({:aws_access_key_id => 'dummykey',
:aws_secret_access_key => 'dummysecret',
:aws_session_token => 'dummytoken',
:region => 'world-antarctica-1',
:endpoint => 'aws-clone.example'})
end
end
end
end
fog-aws-0.7.6/tests/requests/compute/image_tests.rb 0000644 0000041 0000041 00000015344 12576636531 022466 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | image requests', ['aws']) do
@describe_images_format = {
'imagesSet' => [{
'architecture' => String,
'blockDeviceMapping' => [Fog::Nullable::Hash],
'description' => Fog::Nullable::String,
'hypervisor' => String,
'imageId' => String,
'imageLocation' => String,
'imageOwnerAlias' => Fog::Nullable::String,
'imageOwnerId' => String,
'imageState' => String,
'imageType' => String,
'isPublic' => Fog::Boolean,
'kernelId' => String,
'name' => String,
'platform' => Fog::Nullable::String,
'productCodes' => [],
'ramdiskId' => Fog::Nullable::String,
'rootDeviceName' => String,
'rootDeviceType' => String,
'stateReason' => {},
'tagSet' => {},
'virtualizationType' => String
}],
'requestId' => String,
}
@register_image_format = {
'imageId' => String,
'requestId' => String
}
@modify_image_attribute_format = {
'return' => Fog::Boolean,
'requestId' => String
}
@create_image_format = {
'requestId' => String,
'imageId' => String
}
@image_copy_result = {
'requestId' => String,
'imageId' => String
}
tests('success') do
# the result for this is HUGE and relatively uninteresting...
# tests("#describe_images").formats(@images_format) do
# Fog::Compute[:aws].describe_images.body
# end
@image_id = 'ami-1aad5273'
if Fog.mocking?
@other_account = Fog::Compute::AWS.new(:aws_access_key_id => 'other', :aws_secret_access_key => 'account')
@server = Fog::Compute[:aws].servers.create
@server.wait_for{state == 'running'}
@created_image
tests("#create_image").formats(@create_image_format) do
result = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image', false).body
@created_image = Fog::Compute[:aws].images.get(result['imageId'])
result
end
tests("#create_image - no reboot").formats(@create_image_format) do
result = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image', true).body
@created_image = Fog::Compute[:aws].images.get(result['imageId'])
result
end
tests("#create_image - automatic ebs image registration").returns(true) do
create_image_response = Fog::Compute[:aws].create_image(@server.id, 'Fog-Test-Image', 'Fog Test Image')
Fog::Compute[:aws].images.get(create_image_response.body['imageId']) != nil
end
@server.destroy
tests("#copy_image (#{@image_id}, 'eu-west-1')").formats(@image_copy_result) do
data = Fog::Compute.new(:provider => :aws, :region => "us-west-1", :version => "2013-02-01").copy_image(@image_id, "eu-east-1").body
@eu_image_id = data['imageId']
data
end
tests("#register_image").formats(@register_image_format) do
@image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1').body
end
tests("#register_image - with ebs block device mapping").formats(@register_image_format) do
@ebs_image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1', [ { 'DeviceName' => '/dev/sdh', "SnapshotId" => "snap-123456789", "VolumeSize" => "10G", "DeleteOnTermination" => true}]).body
end
tests("#register_image - with ephemeral block device mapping").formats(@register_image_format) do
@ephemeral_image = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1', [ { 'VirtualName' => 'ephemeral0', "DeviceName" => "/dev/sdb"} ]).body
end
@image_id = @image['imageId']
sleep 1
tests("#describe_images('Owner' => 'self')").formats(@describe_images_format) do
Fog::Compute[:aws].describe_images('Owner' => 'self').body
end
tests("#describe_images('state' => 'available')").formats(@describe_images_format) do
Fog::Compute[:aws].describe_images('state' => 'available').body
end
tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([]) do
@other_account.describe_images('image-id' => @image_id).body['imagesSet']
end
tests("#modify_image_attribute('#{@image_id}', 'Add.UserId' => ['#{@other_account.data[:owner_id]}'])").formats(@modify_image_attribute_format) do
Fog::Compute[:aws].modify_image_attribute(@image_id, { 'Add.UserId' => [@other_account.data[:owner_id]] }).body
end
tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([@image_id]) do
@other_account.describe_images('image-id' => @image_id).body['imagesSet'].map {|i| i['imageId'] }
end
tests("#modify_image_attribute('#{@image_id}', 'Remove.UserId' => ['#{@other_account.data[:owner_id]}'])").formats(@modify_image_attribute_format) do
Fog::Compute[:aws].modify_image_attribute(@image_id, { 'Remove.UserId' => [@other_account.data[:owner_id]] }).body
end
tests("other_account#describe_images('image-id' => '#{@image_id}')").returns([]) do
@other_account.describe_images('image-id' => @image_id).body['imagesSet']
end
end
tests("#describe_images('image-id' => '#{@image_id}')").formats(@describe_images_format) do
@other_image = Fog::Compute[:aws].describe_images('image-id' => @image_id).body
end
unless Fog.mocking?
tests("#describe_images('Owner' => '#{@other_image['imageOwnerAlias']}', 'image-id' => '#{@image_id}')").formats(@describe_images_format) do
Fog::Compute[:aws].describe_images('Owner' => @other_image['imageOwnerAlias'], 'image-id' => @image_id).body
end
end
#NOTE: waiting for the image to complete can sometimes take up to 1 hour
# for quicker tests: uncomment the rest of this block
#Fog.wait_for { Fog::Compute.new(:provider => :aws, :region => "us-west-1").snapshots.get(@eu_image_id) }
#tests("#delete_snapshots(#{@eu_image_id})").formats(AWS::Compute::Formats::BASIC) do
# Fog::Compute.new(:provider => :aws, :region => "us-west-1").delete_snapshot(@eu_image_id).body
#end
end
tests('failure') do
tests("#modify_image_attribute(nil, { 'Add.Group' => ['all'] })").raises(ArgumentError) do
Fog::Compute[:aws].modify_image_attribute(nil, { 'Add.Group' => ['all'] }).body
end
tests("#modify_image_attribute('ami-00000000', { 'Add.UserId' => ['123456789012'] })").raises(Fog::Compute::AWS::NotFound) do
pending unless Fog.mocking?
Fog::Compute[:aws].modify_image_attribute('ami-00000000', { 'Add.UserId' => ['123456789012'] }).body
end
end
end
fog-aws-0.7.6/tests/requests/compute/subnet_tests.rb 0000644 0000041 0000041 00000005334 12576636531 022702 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | subnet requests', ['aws']) do
@subnet_format = {
'subnetId' => String,
'state' => String,
'vpcId' => String,
'cidrBlock' => String,
'availableIpAddressCount' => String,
'availabilityZone' => String,
'tagSet' => Hash,
}
@single_subnet_format = {
'subnet' => @subnet_format,
'requestId' => String,
}
@subnets_format = {
'subnetSet' => [@subnet_format],
'requestId' => String
}
@modify_subnet_format = {
'requestId' => String,
'return' => Fog::Boolean
}
@vpc_network = '10.0.10.0/24'
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => @vpc_network)
@vpc_id = @vpc.id
tests('success') do
@subnet_id = nil
@subnet_network = '10.0.10.16/28'
tests("#create_subnet('#{@vpc_id}', '#{@subnet_network}')").formats(@single_subnet_format) do
data = Fog::Compute[:aws].create_subnet(@vpc_id, @subnet_network).body
@subnet_id = data['subnet']['subnetId']
data
end
tests("modify_subnet('#{@subnet_id}'").formats(@modify_subnet_format) do
Fog::Compute[:aws].modify_subnet_attribute(@subnet_id, 'MapPublicIpOnLaunch' => true).body
end
@vpc2=Fog::Compute[:aws].vpcs.create('cidr_block' => @vpc_network)
@vpc2_id = @vpc2.id
# Create a second subnet in a second VPC with the same netblock
tests("#create_subnet('#{@vpc2_id}', '#{@subnet_network}')").formats(@single_subnet_format) do
data = Fog::Compute[:aws].create_subnet(@vpc2_id, @subnet_network).body
@subnet2_id = data['subnet']['subnetId']
data
end
Fog::Compute[:aws].delete_subnet(@subnet2_id)
tests('#describe_subnets').formats(@subnets_format) do
Fog::Compute[:aws].describe_subnets.body
end
tests("#delete_subnet('#{@subnet_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_subnet(@subnet_id).body
end
end
tests('failure') do
tests("#create_subnet('vpc-00000000', '10.0.10.0/16')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_subnet('vpc-00000000', '10.0.10.0/16')
end
tests("#create_subnet('#{@vpc_id}', '10.0.9.16/28')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_subnet(@vpc_id, '10.0.9.16/28')
end
# Attempt to create two subnets with conflicting CIDRs in the same VPC
tests("#create_subnet('#{@vpc_id}', '10.0.10.0/24'); " \
"#create_subnet('#{@vpc_id}', '10.0.10.64/26'); ").raises(::Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_subnet(@vpc_id, '10.0.10.0/24')
Fog::Compute[:aws].create_subnet(@vpc_id, '10.0.10.64/26')
end
end
@vpc.destroy
end
fog-aws-0.7.6/tests/requests/compute/snapshot_tests.rb 0000644 0000041 0000041 00000005031 12576636531 023233 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | snapshot requests', ['aws']) do
@snapshot_format = {
'description' => Fog::Nullable::String,
'encrypted' => Fog::Boolean,
'ownerId' => String,
'progress' => String,
'snapshotId' => String,
'startTime' => Time,
'status' => String,
'volumeId' => String,
'volumeSize' => Integer
}
@snapshots_format = {
'requestId' => String,
'snapshotSet' => [@snapshot_format.merge('tagSet' => {})]
}
@snapshot_copy_result = {
'requestId' => String,
'snapshotId' => String
}
@volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1)
tests('success') do
@snapshot_id = nil
tests("#create_snapshot(#{@volume.identity})").formats(@snapshot_format.merge('progress' => NilClass, 'requestId' => String)) do
data = Fog::Compute[:aws].create_snapshot(@volume.identity).body
@snapshot_id = data['snapshotId']
data
end
Fog.wait_for { Fog::Compute[:aws].snapshots.get(@snapshot_id) }
Fog::Compute[:aws].snapshots.get(@snapshot_id).wait_for { ready? }
tests("#describe_snapshots").formats(@snapshots_format) do
Fog::Compute[:aws].describe_snapshots.body
end
tests("#describe_snapshots('snapshot-id' => '#{@snapshot_id}')").formats(@snapshots_format) do
Fog::Compute[:aws].describe_snapshots('snapshot-id' => @snapshot_id).body
end
tests("#copy_snapshot (#{@snapshot_id}, 'us-east-1')").formats(@snapshot_copy_result) do
data = Fog::Compute.new(:provider => :aws, :region => "us-west-1").copy_snapshot(@snapshot_id, "us-east-1").body
@west_snapshot_id = data['snapshotId']
data
end
tests("#delete_snapshots(#{@snapshot_id})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_snapshot(@snapshot_id).body
end
#NOTE: waiting for the copy to complete can sometimes take up to 5 minutes (but sometimes it's nearly instant)
#for faster tests: comment out the rest of this block
Fog.wait_for { Fog::Compute.new(:provider => :aws, :region => "us-west-1").snapshots.get(@west_snapshot_id) }
tests("#delete_snapshots(#{@west_snapshot_id})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute.new(:provider => :aws, :region => "us-west-1").delete_snapshot(@west_snapshot_id).body
end
end
tests('failure') do
tests("#delete_snapshot('snap-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_snapshot('snap-00000000')
end
end
@volume.destroy
end
fog-aws-0.7.6/tests/requests/compute/spot_datafeed_subscription_tests.rb 0000644 0000041 0000041 00000003331 12576636531 027003 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | spot datafeed subscription requests', ['aws']) do
@spot_datafeed_subscription_format = {
'spotDatafeedSubscription' => {
'bucket' => String,
'ownerId' => String,
'prefix' => String,
'state' => String
},
'requestId' => String
}
@directory = Fog::Storage[:aws].directories.create(:key => 'fogspotdatafeedsubscriptiontests')
tests('success') do
pending if Fog.mocking?
tests("#create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/')").formats(@spot_datafeed_subscription_format) do
Fog::Compute[:aws].create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/').body
end
tests("duplicate #create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/')").succeeds do
Fog::Compute[:aws].create_spot_datafeed_subscription('fogspotdatafeedsubscriptiontests', 'fogspotdatafeedsubscription/')
end
tests("#describe_spot_datafeed_subscription").formats(@spot_datafeed_subscription_format) do
Fog::Compute[:aws].describe_spot_datafeed_subscription.body
end
tests("#delete_spot_datafeed_subscription").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_spot_datafeed_subscription.body
end
tests("duplicate #delete_spot_datafeed_subscription").succeeds do
Fog::Compute[:aws].delete_spot_datafeed_subscription
end
end
tests('failure') do
pending if Fog.mocking?
tests("#describe_spot_datafeed_subscription").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].describe_spot_datafeed_subscription
end
end
@directory.destroy
end
fog-aws-0.7.6/tests/requests/compute/internet_gateway_tests.rb 0000644 0000041 0000041 00000003446 12576636531 024755 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | internet_gateway requests', ['aws']) do
@internet_gateways_format = {
'internetGatewaySet' => [{
'internetGatewayId' => String,
'attachmentSet' => Hash,
'tagSet' => Fog::Nullable::Hash,
}],
'requestId' => String
}
tests('success') do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@vpc_id = @vpc.id
@subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24')
@subnet_id = @subnet.subnet_id
@igw_id = nil
tests('#create_internet_gateway').formats(@internet_gateways_format) do
data = Fog::Compute[:aws].create_internet_gateway().body
@igw_id = data['internetGatewaySet'].first['internetGatewayId']
data
end
tests('#describe_internet_gateways').formats(@internet_gateways_format) do
Fog::Compute[:aws].describe_internet_gateways.body
end
tests('#describe_internet_gateways with tags').formats(@internet_gateways_format) do
Fog::Compute[:aws].create_tags @igw_id, {"environment" => "production"}
Fog::Compute[:aws].describe_internet_gateways.body
end
tests("#attach_internet_gateway('#{@igw_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].attach_internet_gateway(@igw_id, @vpc_id).body
end
tests("#detach_internet_gateway('#{@igw_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].detach_internet_gateway(@igw_id, @vpc_id).body
end
tests("#delete_internet_gateway('#{@igw_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_internet_gateway(@igw_id).body
end
@subnet.destroy
@vpc.destroy
end
end
fog-aws-0.7.6/tests/requests/compute/network_interface_tests.rb 0000644 0000041 0000041 00000025310 12576636531 025107 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | network interface requests', ['aws']) do
@network_interface_format = {
'networkInterfaceId' => String,
'subnetId' => String,
'vpcId' => String,
'availabilityZone' => String,
'description' => Fog::Nullable::String,
'ownerId' => String,
'requesterId' => Fog::Nullable::String,
'requesterManaged' => String,
'status' => String,
'macAddress' => String,
'privateIpAddress' => String,
'privateDnsName' => Fog::Nullable::String,
'sourceDestCheck' => Fog::Boolean,
'groupSet' => Fog::Nullable::Hash,
'attachment' => Hash,
'association' => Hash,
'tagSet' => Hash
}
@network_interface_create_format = {
'networkInterface' => @network_interface_format,
'requestId' => String
}
@network_interfaces_format = {
'requestId' => String,
'networkInterfaceSet' => [ @network_interface_format ]
}
@attach_network_interface_format = {
'requestId' => String,
'attachmentId' => String
}
tests('success') do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
# Create environment
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
@security_group = Fog::Compute[:aws].security_groups.create('name' => 'sg_name', 'description' => 'sg_desc', 'vpc_id' => @vpc.id)
@owner_id = Fog::Compute[:aws].describe_security_groups('group-name' => 'default').body['securityGroupInfo'].first['ownerId']
@subnet_id = @subnet.subnet_id
@security_group_id = @security_group.group_id
@security_groups = [
@security_group.name, {
'groupDescription' => @security_group.description,
'groupName' => @security_group.name,
'groupId' => @security_group_id,
'ipPermissionsEgress' => [],
'ipPermissions' => [],
'ownerId' => @owner_id,
'vpcId' => @vpc.id
}
]
DESCRIPTION = "Small and green"
tests("#create_network_interface(#{@subnet_id})").formats(@network_interface_create_format) do
data = Fog::Compute[:aws].create_network_interface(@subnet_id, {"PrivateIpAddress" => "10.0.10.23"}).body
@nic_id = data['networkInterface']['networkInterfaceId']
data
end
# Describe network interfaces
tests('#describe_network_interfaces').formats(@network_interfaces_format) do
Fog::Compute[:aws].describe_network_interfaces.body
end
# Describe network interface attribute
tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(nil) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body['description']
end
# test describe of all supported attributes
[ 'description', 'groupSet', 'sourceDestCheck', 'attachment'].each do |attrib|
tests("#describe_network_interface_attribute(#{@nic_id}, #{attrib})").returns(@nic_id) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, attrib).body['networkInterfaceId']
end
end
# Modify network interface description attribute
tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '#{DESCRIPTION}')").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', DESCRIPTION).body["return"]
end
# Describe network interface attribute again
tests("#describe_network_interface_attribute(#{@nic_id}, 'description')").returns(DESCRIPTION) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'description').body["description"]
end
# Restore network interface description attribute
tests("#modify_network_interface_attribute(#{@nic_id}, 'description', '')").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'description', '').body["return"]
end
# Check modifying the group set
tests("#modify_network_interface_attribute(#{@nic_id}, 'groupSet', [#{@security_group_id}])").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'groupSet', [@security_group_id]).body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'groupSet')").returns({ @security_group_id => "sg_name" }) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'groupSet').body["groupSet"]
end
# Check modifying the source dest check (and reset)
tests("#modify_network_interface_attribute(#{@nic_id}, 'sourceDestCheck', false)").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'sourceDestCheck', false).body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(false) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"]
end
tests("#reset_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do
Fog::Compute[:aws].reset_network_interface_attribute(@nic_id, 'sourceDestCheck').body["return"]
end
tests("#describe_network_interface_attribute(#{@nic_id}, 'sourceDestCheck')").returns(true) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic_id, 'sourceDestCheck').body["sourceDestCheck"]
end
@server = Fog::Compute[:aws].servers.create({:flavor_id => 'm1.small', :subnet_id => @subnet_id })
@server.wait_for { ready? }
@instance_id=@server.id
# attach
@device_index = 1
tests('#attach_network_interface').formats(@attach_network_interface_format) do
data = Fog::Compute[:aws].attach_network_interface(@nic_id, @instance_id, @device_index).body
@attachment_id = data['attachmentId']
data
end
# Check modifying the attachment
attach_attr = {
'attachmentId' => @attachment_id,
'deleteOnTermination' => true
}
tests("#modify_network_interface_attribute(#{@nic_id}, 'attachment', #{attach_attr.inspect})").returns(true) do
Fog::Compute[:aws].modify_network_interface_attribute(@nic_id, 'attachment', attach_attr).body["return"]
end
# detach
tests('#detach_network_interface').returns(true) do
Fog::Compute[:aws].detach_network_interface(@attachment_id,true).body["return"]
end
if !Fog.mocking?
Fog::Compute[:aws].network_interfaces.get(@nic_id).wait_for { status == 'available'}
end
# Create network interface with arguments
options = {
"PrivateIpAddress" => "10.0.10.24",
"Description" => DESCRIPTION,
"GroupSet" => [@security_group_id]
}
tests("#create_network_interface(#{@subnet_id}), #{options.inspect}").returns("10.0.10.24") do
data = Fog::Compute[:aws].create_network_interface(@subnet_id, options).body
@nic2_id = data['networkInterface']['networkInterfaceId']
data['networkInterface']['privateIpAddress']
end
# Check assigned values
tests("#describe_network_interface_attribute(#{@nic2_id}, 'description')").returns(DESCRIPTION) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'description').body["description"]
end
tests("#describe_network_interface_attribute(#{@nic2_id}, 'groupSet')").returns({ @security_group_id => @security_groups }) do
Fog::Compute[:aws].describe_network_interface_attribute(@nic2_id, 'groupSet').body["groupSet"]
end
# Delete network interfaces
tests("#delete_network_interface('#{@nic2_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_interface(@nic2_id).body
end
tests("#delete_network_interface('#{@nic_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_interface(@nic_id).body
end
@server.destroy
if !Fog.mocking?
@server.wait_for { state == 'terminated' }
# despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing
sleep 5
end
# Bring up another server to test vpc public IP association
@server = Fog::Compute[:aws].servers.create(:flavor_id => 'm1.small', :subnet_id => @subnet_id, :associate_public_ip => true)
@server.wait_for { ready? }
@instance_id = @server.id
test("#associate_public_ip") do
server = Fog::Compute[:aws].servers.get(@instance_id)
server.public_ip_address.nil? == false
end
# Clean up resources
@server.destroy
if !Fog.mocking?
@server.wait_for { state == 'terminated' }
# despite the fact that the state goes to 'terminated' we need a little delay for aws to do its thing
sleep 5
end
@security_group.destroy
@subnet.destroy
@vpc.destroy
end
tests('failure') do
# Attempt to attach a nonexistent interface
tests("#attach_network_interface('eni-00000000', 'i-00000000', '1')").raises(::Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].attach_network_interface('eni-00000000', 'i-00000000', '1')
end
# Create environment
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
@subnet_id = @subnet.subnet_id
data = Fog::Compute[:aws].create_network_interface(@subnet_id).body
@nic_id = data['networkInterface']['networkInterfaceId']
# Attempt to re-use an existing IP for another ENI
tests("#create_network_interface('#{@subnet_id}', " \
"{'PrivateIpAddress' => " \
"'#{data['networkInterface']['privateIpAddress']}'}").raises(::Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_network_interface(@subnet_id, {'PrivateIpAddress' => data['networkInterface']['privateIpAddress']})
end
# Attempt to attach a valid ENI to a nonexistent instance.
tests("#attach_network_interface('#{@nic_id}', 'i-00000000', '0')").raises(::Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].attach_network_interface(@nic_id, 'i-00000000', '0')
end
@server = Fog::Compute[:aws].servers.create({:flavor_id => 'm1.small', :subnet_id => @subnet_id })
@server.wait_for { ready? }
@instance_id=@server.id
@device_index = 1
data = Fog::Compute[:aws].attach_network_interface(@nic_id, @instance_id, @device_index).body
# Attempt to attach two ENIs to the same instance with the same device
# index.
tests("#attach_network_interface('#{@nic_id}', '#{@instance_id}', '#{@device_index}')").raises(::Fog::Compute::AWS::Error) do
Fog::Compute[:aws].attach_network_interface(@nic_id, @instance_id, @device_index)
end
Fog::Compute::AWS::Mock.reset if Fog.mocking?
end
end
fog-aws-0.7.6/tests/requests/compute/route_tests.rb 0000644 0000041 0000041 00000040764 12576636531 022546 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | route table requests', ['aws']) do
@route_table_format = {
'routeTable' => [{
'routeSet' => [{
'destinationCidrBlock' => String,
'gatewayId' => String,
'state' => String,
}],
'tagSet' => Hash,
'associationSet' => Array,
'routeTableId' => String,
'vpcId' => String,
}],
'requestId' => String
}
@route_tables_format = {
'routeTableSet' => [{
'associationSet' => [{
'routeTableAssociationId' => Fog::Nullable::String,
'routeTableId' => String,
'subnetId' => Fog::Nullable::String,
'main' => Fog::Boolean
}],
'tagSet' => Hash,
'routeSet' => [{
'destinationCidrBlock' => String,
'gatewayId' => Fog::Nullable::String,
'instanceId' => Fog::Nullable::String,
'instanceOwnerId' => Fog::Nullable::String,
'networkInterfaceId' => Fog::Nullable::String,
'vpcPeeringConnectionId' => Fog::Nullable::String,
'state' => String,
'origin' => String
}],
'routeTableId' => String,
'vpcId' => String,
}],
'requestId' => String
}
Fog::Compute::AWS::Mock.reset if Fog.mocking?
vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
if !Fog.mocking?
vpc.wait_for { state.eql? "available" }
end
@subnet_id = Fog::Compute[:aws].create_subnet(vpc.id, '10.0.10.0/24').body['subnet']['subnetId']
@network_interface = Fog::Compute[:aws].create_network_interface(@subnet_id, {"PrivateIpAddress" => "10.0.10.23"}).body
@internet_gateway_id = Fog::Compute[:aws].create_internet_gateway.body['internetGatewaySet'].first['internetGatewayId']
@alt_internet_gateway_id = Fog::Compute[:aws].create_internet_gateway.body['internetGatewaySet'].first['internetGatewayId']
@network_interface_id = @network_interface['networkInterface']['networkInterfaceId']
key_name = uniq_id('fog-test-key')
key = Fog::Compute[:aws].key_pairs.create(:name => key_name)
@cidr_block = '10.0.10.0/24'
@destination_cidr_block = '10.0.10.0/23'
@ami = 'ami-79c0ae10' # ubuntu 12.04 daily build 20120728
tests('success') do
# Test create_route_table
#
tests("#create_route_table('#{vpc.id}')").formats(@route_table_format) do
data = Fog::Compute[:aws].create_route_table(vpc.id).body
@route_table_id = data['routeTable'].first['routeTableId']
data
end
# Test associate_route_table
#
tests("#associate_route_table('#{@route_table_id}', '#{@subnet_id}')").formats({'requestId'=>String, 'associationId'=>String}) do
data = Fog::Compute[:aws].associate_route_table(@route_table_id, @subnet_id).body
@association_id = data['associationId']
data
end
# Tests create_route
# - using internet gateway
# - using instance id
# - using network interface
#
Fog::Compute[:aws].attach_internet_gateway(@internet_gateway_id, vpc.id).body
tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', '#{@internet_gateway_id}', 'nil')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id, nil).body
end
instance = Fog::Compute[:aws].servers.create(:image_id => @ami, :flavor_id => 't1.micro', :key_name => key_name, :subnet_id => @subnet_id)
instance.wait_for { state.eql? "running" }
tests("#create_route('#{@route_table_id}', '10.0.10.0/22', 'nil', '#{instance.id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/22', nil, instance.id).body
end
tests("#create_route('#{@route_table_id}', '10.0.10.0/21', 'nil', 'nil', '#{@network_interface_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/21', nil, nil, @network_interface_id).body
end
# Tests replace_route
# - using internet gateway
# - using instance id
# - using network interface
#
Fog::Compute[:aws].attach_internet_gateway(@alt_internet_gateway_id, vpc.id).body
tests("#replace_route('#{@route_table_id}', '#{@destination_cidr_block}', {'gatewayId' => '#{@alt_internet_gateway_id}'})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].replace_route(@route_table_id, @destination_cidr_block, {'gatewayId' => @alt_internet_gateway_id}).body
end
instance = Fog::Compute[:aws].servers.create(:image_id => @ami, :flavor_id => 't1.micro', :key_name => key_name, :subnet_id => @subnet_id)
instance.wait_for { state.eql? "running" }
tests("#replace_route('#{@route_table_id}', '10.0.10.0/22', {'instanceId' => '#{instance.id}'})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].replace_route(@route_table_id, '10.0.10.0/22', {'instanceId' => instance.id}).body
end
tests("#replace_route('#{@route_table_id}', '10.0.10.0/21', {'networkInterfaceId' => '#{@network_interface_id}'})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].replace_route(@route_table_id, '10.0.10.0/21', {'networkInterfaceId' => @network_interface_id}).body
end
# Tests describe_route_tables
# - no parameters
# - filter: vpc-id => vpc_id
# - filter: vpc-id => ['all']
#
tests('#describe_route_tables').formats(@route_tables_format) do
Fog::Compute[:aws].describe_route_tables.body
end
tests("#describe_route_tables('vpc-id' => #{vpc.id})").formats(@route_tables_format) do
Fog::Compute[:aws].describe_route_tables('vpc-id' => vpc.id).body
end
tests("#describe_route_tables('vpc-id' => ['all'])").formats(@route_tables_format) do
Fog::Compute[:aws].describe_route_tables('vpc-id' => ['all']).body
end
# Test delete_route(route_table_id, cidr_block)
#
tests("#delete_route('#{@route_table_id}', '10.0.10.0/21')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_route(@route_table_id, '10.0.10.0/21').body
end
tests("#delete_route('#{@route_table_id}', '10.0.10.0/22')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_route(@route_table_id, '10.0.10.0/22').body
end
Fog::Compute[:aws].servers.all('instance-id'=>instance.id).first.destroy
if !Fog.mocking?
instance.wait_for { state.eql? "terminated" }
end
tests("#delete_route('#{@route_table_id}', '#{@destination_cidr_block}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block).body
end
# Test disassociate_route_table(association_id)
#
tests("#disassociate_route_table('#{@association_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].disassociate_route_table(@association_id).body
end
# Test delete_route_table(route_table_id)
#
tests("#delete_route_table('#{@route_table_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_route_table(@route_table_id).body
end
end
tests('failure') do
@route_table_id = Fog::Compute[:aws].create_route_table(vpc.id).body['routeTable'].first['routeTableId']
@association_id = Fog::Compute[:aws].associate_route_table(@route_table_id, @subnet_id).body['associationId']
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id, nil)
instance = Fog::Compute[:aws].servers.create(:image_id => @ami, :flavor_id => 't1.micro', :key_name => key_name, :subnet_id => @subnet_id)
instance.wait_for { state.eql? "running" }
# Tests create_route_table
# - no parameters
# - passing a nonexisting vpc
#
tests('#create_route_table').raises(ArgumentError) do
Fog::Compute[:aws].create_route_table
end
tests("#create_route_table('vpc-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route_table('vpc-00000000')
end
# Tests associate_route_table
# - no parameters
# - passing a nonexisiting route table
# - passing a nonexisiting subnet
#
tests('#associate_route_table').raises(ArgumentError) do
Fog::Compute[:aws].associate_route_table
end
tests("#associate_route_table('rtb-00000000', '#{@subnet_id}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].associate_route_table('rtb-00000000', @subnet_id)
end
tests("#associate_route_table('#{@route_table_id}', 'subnet-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].associate_route_table(@route_table_id, 'subnet-00000000')
end
# Tests create_route
# - no parameters
# - passing a nonexisiting route table and an exisiting internet gateway
# - passing a nonexisiting internet gateway
# - passing a nonexisting route table and an exisiting instance
# - passing a nonexisiting instance
# - passing a nonexsiting route table and an exisiting network interface
# - passing a nonexisiting network interface
# - attempting to add a route at the same destination cidr block as another
# - attempting to add a route at a less specific destination cidr block
#
tests('#create_route').raises(ArgumentError) do
Fog::Compute[:aws].create_route
end
tests("#create_route('rtb-00000000', '#{@destination_cidr_block}', '#{@internet_gateway_id}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, @internet_gateway_id)
end
tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', 'igw-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, 'igw-00000000')
end
tests("#create_route('rtb-00000000', '#{@destination_cidr_block}', 'nil', '#{instance.id}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, instance.id)
end
tests("#create_route('#{@route_table_id}', '#{@destination_cidr_block}', 'nil', 'i-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, 'i-00000000')
end
tests("#create_route('#{@route_table_id}', '#{@destinationCidrBlock}', 'nil', 'nil', 'eni-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, nil, 'eni-00000000')
end
tests("#create_route('#rtb-00000000', '#{@destination_cidr_block}', 'nil, 'nil', '#{@network_interface_id}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].create_route('rtb-00000000', @destination_cidr_block, nil, nil, @network_interface_id)
end
tests("#create_route same destination_cidr_block").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, @internet_gateway_id)
Fog::Compute[:aws].create_route(@route_table_id, @destination_cidr_block, nil, nil, @network_interface_id).body
end
if !Fog.mocking?
tests("#create_route less specific destination_cidr_block").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_route(@route_table_id, '10.0.10.0/25', @internet_gateway_id)
Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block).body
end
end
# Tests replace_route
# - no parameters
# - passing a nonexisiting route table and an exisiting internet gateway
# - passing a nonexisiting route table
# - passing a nonexisting route table and an exisiting instance
# - passing a nonexisiting instance
# - passing a nonexsiting route table and an exisiting network interface
# - passing a nonexisiting network interface
# - attempting to add a route at a less specific destination cidr block
#
tests('#replace_route').raises(ArgumentError) do
Fog::Compute[:aws].replace_route
end
tests("#replace_route('rtb-00000000', '#{@destination_cidr_block}', {'internetGatewayId' => '#{@internet_gateway_id}'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route('rtb-00000000', @destination_cidr_block, {'internetGatewayId' => @internet_gateway_id})
end
tests("#replace_route('rtb-00000000', '#{@destination_cidr_block}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route('rtb-00000000', @destination_cidr_block)
end
tests("#replace_route('#{@route_table_id}', '#{@destination_cidr_block}', {'gatewayId' => 'igw-00000000'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route(@route_table_id, @destination_cidr_block, {'gatewayId' => 'igw-00000000'})
end
tests("#replace_route('rtb-00000000', '#{@destination_cidr_block}', {'instanceId' => '#{instance.id}'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route('rtb-00000000', @destination_cidr_block, {'instanceId' => instance.id})
end
tests("#replace_route('#{@route_table_id}', '#{@destination_cidr_block}', {'instanceId' => 'i-00000000'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route(@route_table_id, @destination_cidr_block, {'instanceId' => 'i-00000000'})
end
tests("#replace_route('#{@route_table_id}', '#{@destination_cidr_block}', {'networkInterfaceId' => 'eni-00000000'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route(@route_table_id, @destination_cidr_block, {'networkInterfaceId' => 'eni-00000000'})
end
tests("#replace_route('rtb-00000000', '#{@destination_cidr_block}', {'networkInterfaceId' => '#{@network_interface_id}'})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].replace_route('rtb-00000000', @destination_cidr_block, {'networkInterfaceId' => @network_interface_id})
end
if !Fog.mocking?
tests("#replace_route less specific destination_cidr_block").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].replace_route(@route_table_id, '10.0.10.0/25', {'gatewayId' => @internet_gateway_id})
end
end
# Test describe_route_tables
# - passing a nonexisiting vpc
#
tests("#describe_route_tables('vpc-id' => 'vpc-00000000").formats({'routeTableSet'=>Array, 'requestId'=>String}) do
Fog::Compute[:aws].describe_route_tables('vpc-id' => 'vpc-00000000').body
end
# Tests delete_route
# - no parameters
# - passing a nonexisiting route table
#
tests('#delete_route').raises(ArgumentError) do
Fog::Compute[:aws].delete_route
end
tests("#delete_route('rtb-00000000', '#{@destination_cidr_block}')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_route('rtb-00000000', @destination_cidr_block)
end
# Tests disassociate_route_table
# - no parameters
# - passing a nonexisiting route table association id
#
tests('#disassociate_route_table').raises(ArgumentError) do
Fog::Compute[:aws].disassociate_route_table
end
tests("#disassociate_route_table('rtbassoc-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].disassociate_route_table('rtbassoc-00000000')
end
# Tests delete_route_table
# - no parameters
# - passing a nonexisiting route table
#
tests('#delete_route_table').raises(ArgumentError) do
Fog::Compute[:aws].delete_route_table
end
tests("#delete_route_table('rtb-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_route_table('rtb-00000000')
end
# Dependency Tests
# - route is depending on route_table, so route_table cannot be deleted
#
tests("#delete_route_table('#{@route_table_id}')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].delete_route_table(@route_table_id)
end
Fog::Compute[:aws].servers.all('instance-id'=>instance.id).first.destroy
if !Fog.mocking?
instance.wait_for { state.eql? "terminated" }
end
Fog::Compute[:aws].delete_route(@route_table_id, @destination_cidr_block)
Fog::Compute[:aws].disassociate_route_table(@association_id)
Fog::Compute[:aws].delete_route_table(@route_table_id)
end
Fog::Compute[:aws].delete_network_interface(@network_interface_id)
Fog::Compute[:aws].detach_internet_gateway(@internet_gateway_id, vpc.id)
Fog::Compute[:aws].delete_internet_gateway(@internet_gateway_id)
Fog::Compute[:aws].delete_subnet(@subnet_id)
vpc.destroy
key.destroy
end
fog-aws-0.7.6/tests/requests/compute/key_pair_tests.rb 0000644 0000041 0000041 00000004606 12576636531 023206 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | key pair requests', ['aws']) do
tests('success') do
@keypair_format = {
'keyFingerprint' => String,
'keyName' => String,
'requestId' => String
}
@keypairs_format = {
'keySet' => [{
'keyFingerprint' => String,
'keyName' => String
}],
'requestId' => String
}
@key_pair_name = 'fog_create_key_pair'
@public_key_material = 'ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA1SL+kgze8tvSFW6Tyj3RyZc9iFVQDiCKzjgwn2tS7hyWxaiDhjfY2mBYSZwFdKN+ZdsXDJL4CPutUg4DKoQneVgIC1zuXrlpPbaT0Btu2aFd4qNfJ85PBrOtw2GrWZ1kcIgzZ1mMbQt6i1vhsySD2FEj+5kGHouNxQpI5dFR5K+nGgcTLFGnzb/MPRBk136GVnuuYfJ2I4va/chstThoP8UwnoapRHcBpwTIfbmmL91BsRVqjXZEUT73nxpxFeXXidYwhHio+5dXwE0aM/783B/3cPG6FVoxrBvjoNpQpAcEyjtRh9lpwHZtSEW47WNzpIW3PhbQ8j4MryznqF1Rhw=='
tests("#create_key_pair('#{@key_pair_name}')").formats(@keypair_format.merge({'keyMaterial' => String})) do
body = Fog::Compute[:aws].create_key_pair(@key_pair_name).body
tests("key material").returns(OpenSSL::PKey::RSA, "is a valid private RSA key") do
OpenSSL::PKey::RSA.new(body['keyMaterial']).class
end
body
end
tests('#describe_key_pairs').formats(@keypairs_format) do
Fog::Compute[:aws].describe_key_pairs.body
end
tests("#describe_key_pairs('key-name' => '#{@key_pair_name}')").formats(@keypairs_format) do
Fog::Compute[:aws].describe_key_pairs('key-name' => @key_pair_name).body
end
tests("#delete_key_pair('#{@key_pair_name}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_key_pair(@key_pair_name).body
end
tests("#import_key_pair('fog_import_key_pair', '#{@public_key_material}')").formats(@keypair_format) do
Fog::Compute[:aws].import_key_pair('fog_import_key_pair', @public_key_material).body
end
tests("#delete_key_pair('fog_import_key_pair)").succeeds do
Fog::Compute[:aws].delete_key_pair('fog_import_key_pair')
end
tests("#delete_key_pair('not_a_key_name')").succeeds do
Fog::Compute[:aws].delete_key_pair('not_a_key_name')
end
end
tests('failure') do
@key_pair = Fog::Compute[:aws].key_pairs.create(:name => 'fog_key_pair')
tests("duplicate #create_key_pair('#{@key_pair.name}')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_key_pair(@key_pair.name)
end
@key_pair.destroy
end
end
fog-aws-0.7.6/tests/requests/compute/dhcp_options_tests.rb 0000644 0000041 0000041 00000002567 12576636531 024100 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | dhcp_options requests', ['aws']) do
@dhcp_options_format = {
'dhcpOptionsSet' => [{
'dhcpOptionsId' => String,
'dhcpConfigurationSet' => Hash,
'tagSet' => Fog::Nullable::Hash,
}],
'requestId' => String
}
tests('success') do
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@vpc_id = @vpc.id
tests('#create_dhcp_options').formats(@dhcp_options_format) do
data = Fog::Compute[:aws].create_dhcp_options({'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}).body
@dopt_id = data['dhcpOptionsSet'].first['dhcpOptionsId']
data
end
tests('#describe_dhcp_options').formats(@dhcp_options_format) do
Fog::Compute[:aws].describe_dhcp_options.body
end
tests("#associate_dhcp_options('#{@dopt_id}, #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].associate_dhcp_options(@dopt_id, @vpc_id).body
end
tests("#associate_default_dhcp_options('default', #{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].associate_dhcp_options('default', @vpc_id).body
end
tests("#delete_dhcp_options('#{@dopt_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_dhcp_options(@dopt_id).body
end
@vpc.destroy
end
end
fog-aws-0.7.6/tests/requests/compute/vpc_tests.rb 0000644 0000041 0000041 00000015503 12576636531 022171 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | vpc requests', ['aws']) do
@create_vpcs_format = {
'vpcSet' => [{
'vpcId' => String,
'state' => String,
'cidrBlock' => String,
'dhcpOptionsId' => String,
'tagSet' => Hash
}],
'requestId' => String
}
@describe_vpcs_classic_link_format = {
'vpcSet' => [{
'vpcId' => String,
'tagSet' => Hash,
'classicLinkEnabled' => Fog::Boolean
}],
'requestId' => String
}
@describe_classic_link_instances = {
'instancesSet' => [{
'vpcId' => String,
'tagSet' => Hash,
'instanceId' => String,
'groups' => [{'groupId' => String, 'groupName' => String}]
}],
'requestId' => String,
'NextToken' => Fog::Nullable::String
}
@describe_vpcs_format = {
'vpcSet' => [{
'vpcId' => String,
'state' => String,
'cidrBlock' => String,
'dhcpOptionsId' => String,
'tagSet' => Hash,
'instanceTenancy' => Fog::Nullable::String,
}],
'requestId' => String
}
tests('success') do
@vpc_id = nil
tests('#create_vpc').formats(@create_vpcs_format) do
data = Fog::Compute[:aws].create_vpc('10.255.254.0/28').body
@vpc_id = data['vpcSet'].first['vpcId']
data
end
tests('#create_vpc').formats(@create_vpcs_format) do
data = Fog::Compute[:aws].create_vpc('10.255.254.0/28',
{'InstanceTenancy' => 'default'}).body
@vpc_id = data['vpcSet'].first['vpcId']
data
end
tests('#describe_vpcs').formats(@describe_vpcs_format) do
Fog::Compute[:aws].describe_vpcs.body
end
[ 'enableDnsSupport', 'enableDnsHostnames'].each do |attrib|
tests("#describe_vpc_attribute('#{@vpc_id}', #{attrib})").returns(@vpc_id) do
Fog::Compute[:aws].describe_vpc_attribute(@vpc_id, attrib).body['vpcId']
end
end
tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsSupport.Value' => false})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsSupport.Value' => false}).body
end
tests("#describe_vpc_attribute(#{@vpc_id}, 'enableDnsSupport')").returns(false) do
Fog::Compute[:aws].describe_vpc_attribute(@vpc_id, 'enableDnsSupport').body["enableDnsSupport"]
end
tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsSupport.Value' => true})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsSupport.Value' => true}).body
end
tests("#describe_vpc_attribute(#{@vpc_id}, 'enableDnsSupport')").returns(true) do
Fog::Compute[:aws].describe_vpc_attribute(@vpc_id, 'enableDnsSupport').body["enableDnsSupport"]
end
tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsHostnames.Value' => true})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsHostnames.Value' => true}).body
end
tests("#describe_vpc_attribute(#{@vpc_id}, 'enableDnsHostnames')").returns(true) do
Fog::Compute[:aws].describe_vpc_attribute(@vpc_id, 'enableDnsHostnames').body["enableDnsHostnames"]
end
tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsHostnames.Value' => false})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsHostnames.Value' => false}).body
end
tests("#describe_vpc_attribute(#{@vpc_id}, 'enableDnsHostnames')").returns(false) do
Fog::Compute[:aws].describe_vpc_attribute(@vpc_id, 'enableDnsHostnames').body["enableDnsHostnames"]
end
tests("#modify_vpc_attribute('#{@vpc_id}')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id).body
end
tests("#modify_vpc_attribute('#{@vpc_id}', {'EnableDnsSupport.Value' => true, 'EnableDnsHostnames.Value' => true})").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].modify_vpc_attribute(@vpc_id, {'EnableDnsSupport.Value' => true, 'EnableDnsHostnames.Value' => true}).body
end
# Create another vpc to test tag filters
test_tags = {'foo' => 'bar'}
@another_vpc = Fog::Compute[:aws].vpcs.create :cidr_block => '1.2.3.4/24', :tags => test_tags
tests("#describe_vpcs('tag-key' => 'foo')").formats(@describe_vpcs_format)do
body = Fog::Compute[:aws].describe_vpcs('tag-key' => 'foo').body
tests("returns 1 vpc").returns(1) { body['vpcSet'].size }
body
end
tests("#describe_vpcs('tag-value' => 'bar')").formats(@describe_vpcs_format)do
body = Fog::Compute[:aws].describe_vpcs('tag-value' => 'bar').body
tests("returns 1 vpc").returns(1) { body['vpcSet'].size }
body
end
tests("#describe_vpcs('tag:foo' => 'bar')").formats(@describe_vpcs_format)do
body = Fog::Compute[:aws].describe_vpcs('tag:foo' => 'bar').body
tests("returns 1 vpc").returns(1) { body['vpcSet'].size }
body
end
tests("describe_vpc_classic_link(:filters => {'tag-key' => 'foo'}").formats(@describe_vpcs_classic_link_format) do
body = Fog::Compute[:aws].describe_vpc_classic_link(:filters => {'tag-key' => 'foo'})
tests("returns 1 vpc").returns(1) { body['vpcSet'].size }
body
end
tests("enable_vpc_classic_link").returns(true) do
Fog::Compute[:aws].enable_vpc_classic_link @vpc_id
body = Fog::Compute[:aws].describe_vpc_classic_link(:vpc_ids => [@vpc_id])
body['vpcSet'].first['classicLinkEnabled']
end
@server = Fog::Compute[:aws].servers.create
@server.wait_for {ready?}
@group = Fog::Compute[:aws].security_groups.create :name => 'test-group', :description => 'vpc security group'
tests("attach_classic_link_vpc") do
Fog::Compute[:aws].attach_classic_link_vpc(@server.id, @vpc_id, [@group])
end
tests('describe_classic_link_instances').formats(@describe_classic_link_instances) do
Fog::Compute[:aws].describe_classic_link_instances().body
end
tests("detach_classic_link_vpc").returns([]) do
Fog::Compute[:aws].detach_classic_link_vpc(@server.id, @vpc_id)
Fog::Compute[:aws].describe_classic_link_instances().body['instancesSet']
end
if !Fog.mocking?
@server.destroy
@server.wait_for {state == 'terminated'}
end
tests("disable_vpc_classic_link").returns(false) do
Fog::Compute[:aws].disable_vpc_classic_link @vpc_id
body = Fog::Compute[:aws].describe_vpc_classic_link(:vpc_ids => [@vpc_id])
body['vpcSet'].first['classicLinkEnabled']
end
tests("#delete_vpc('#{@vpc_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_vpc(@vpc_id).body
end
# Clean up
Fog::Compute[:aws].delete_tags(@another_vpc.id, test_tags)
@another_vpc.destroy
Fog::Compute::AWS::Mock.reset if Fog.mocking?
end
end
fog-aws-0.7.6/tests/requests/compute/volume_tests.rb 0000644 0000041 0000041 00000020223 12576636531 022703 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | volume requests', ['aws']) do
@volume_format = {
'availabilityZone' => String,
'createTime' => Time,
'encrypted' => Fog::Boolean,
'iops' => Fog::Nullable::Integer,
'requestId' => String,
'size' => Integer,
'snapshotId' => Fog::Nullable::String,
'status' => String,
'volumeId' => String,
'volumeType' => String
}
@volume_attachment_format = {
'attachTime' => Time,
'device' => String,
'instanceId' => String,
'requestId' => String,
'status' => String,
'volumeId' => String
}
@volume_status_format = {
'volumeStatusSet' => [{
'availabilityZone' => String,
'volumeId' => String,
'volumeStatus' => {
'status' => String,
'details' => [{
'name' => String,
'status' => String
}]
},
'actionsSet' => [{
'code' => String,
'description' => String,
'eventId' => String,
'eventType' => String
}],
'eventsSet' => [{
'description' => String,
'eventId' => String,
'eventType' => String,
'notBefore' => Time,
'notAfter' => Time
}]
}],
'requestId' => String
}
@volumes_format = {
'volumeSet' => [{
'availabilityZone' => String,
'attachmentSet' => Array,
'createTime' => Time,
'encrypted' => Fog::Boolean,
'iops' => Fog::Nullable::Integer,
'size' => Integer,
'snapshotId' => Fog::Nullable::String,
'kmsKeyId' => Fog::Nullable::String,
'status' => String,
'tagSet' => Hash,
'volumeId' => String,
'volumeType' => String
}],
'requestId' => String
}
@server = Fog::Compute[:aws].servers.create
@server.wait_for { ready? }
tests('success') do
@volume_id = nil
tests('#create_volume').formats(@volume_format) do
data = Fog::Compute[:aws].create_volume(@server.availability_zone, 1).body
@volume_id = data['volumeId']
data
end
Fog::Compute[:aws].delete_volume(@volume_id)
tests('#create_volume from snapshot').formats(@volume_format) do
volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1d', :size => 1)
volume.wait_for { ready? }
snapshot = Fog::Compute[:aws].create_snapshot(volume.identity).body
Fog::Compute[:aws].snapshots.new(snapshot).wait_for { ready? }
data = Fog::Compute[:aws].create_volume(@server.availability_zone, nil, 'SnapshotId' => snapshot['snapshotId']).body
@volume_id = data['volumeId']
data
end
Fog::Compute[:aws].delete_volume(@volume_id)
tests('#create_volume with type and iops').formats(@volume_format) do
data = Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 100).body
@volume_id = data['volumeId']
data
end
Fog::Compute[:aws].delete_volume(@volume_id)
tests('#create_volume with encryption').returns(true) do
volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1d', :size => 1, :encrypted => true)
@volume_id = volume.id
volume.reload.encrypted
end
Fog::Compute[:aws].delete_volume(@volume_id)
tests('#create_volume from snapshot with size').formats(@volume_format) do
volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1d', :size => 1)
volume.wait_for { ready? }
snapshot = Fog::Compute[:aws].create_snapshot(volume.identity).body
Fog::Compute[:aws].snapshots.new(snapshot).wait_for { ready? }
data = Fog::Compute[:aws].create_volume(@server.availability_zone, 1, 'SnapshotId' => snapshot['snapshotId']).body
@volume_id = data['volumeId']
data
end
Fog::Compute[:aws].volumes.get(@volume_id).wait_for { ready? }
tests('#describe_volumes').formats(@volumes_format) do
Fog::Compute[:aws].describe_volumes.body
end
tests("#describe_volumes('volume-id' => #{@volume_id})").formats(@volumes_format) do
Fog::Compute[:aws].describe_volumes('volume-id' => @volume_id).body
end
tests("#attach_volume(#{@server.identity}, #{@volume_id}, '/dev/sdh')").formats(@volume_attachment_format) do
Fog::Compute[:aws].attach_volume(@server.identity, @volume_id, '/dev/sdh').body
end
Fog::Compute[:aws].volumes.get(@volume_id).wait_for { state == 'in-use' }
tests("#describe_volume('attachment.device' => '/dev/sdh')").formats(@volumes_format) do
Fog::Compute[:aws].describe_volumes('attachment.device' => '/dev/sdh').body
end
tests("#describe_volume_status('volume-id' => #{@volume_id})").formats(@volume_status_format) do
pending if Fog.mocking?
Fog::Compute[:aws].describe_volume_status('volume-id' => @volume_id).body
end
tests("#detach_volume('#{@volume_id}')").formats(@volume_attachment_format) do
Fog::Compute[:aws].detach_volume(@volume_id).body
end
Fog::Compute[:aws].volumes.get(@volume_id).wait_for { ready? }
tests("#modify_volume_attribute('#{@volume_id}', true)").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].modify_volume_attribute(@volume_id, true).body
end
tests("#delete_volume('#{@volume_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_volume(@volume_id).body
end
end
tests('failure') do
@volume = Fog::Compute[:aws].volumes.create(:availability_zone => @server.availability_zone, :size => 1)
tests("#attach_volume('i-00000000', '#{@volume.identity}', '/dev/sdh')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].attach_volume('i-00000000', @volume.identity, '/dev/sdh')
end
tests("#attach_volume('#{@server.identity}', 'vol-00000000', '/dev/sdh')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].attach_volume(@server.identity, 'vol-00000000', '/dev/sdh')
end
tests("#detach_volume('vol-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].detach_volume('vol-00000000')
end
tests("#modify_volume_attribute('vol-00000000', true)").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].modify_volume_attribute('vol-00000000', true)
end
tests("#detach_volume('#{@volume.identity}')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].detach_volume(@volume.identity)
end
tests("#delete_volume('vol-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_volume('vol-00000000')
end
# Iops required
tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1')
end
# size too small for iops
tests("#create_volume('#{@server.availability_zone}', 9, 'VolumeType' => 'io1', 'Iops' => 100)").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_volume(@server.availability_zone, 9, 'VolumeType' => 'io1', 'Iops' => 100)
end
# iops:size ratio too big
tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1', 'Iops' => 301)").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 301)
end
# iops invalid value (lower than 100)
tests("#create_volume('#{@server.availability_zone}', 10, 'VolumeType' => 'io1', 'Iops' => 99)").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_volume(@server.availability_zone, 10, 'VolumeType' => 'io1', 'Iops' => 99)
end
# iops invalid value (greater than 4000)
tests("#create_volume('#{@server.availability_zone}', 1024, 'VolumeType' => 'io1', 'Iops' => 4001)").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_volume(@server.availability_zone, 1024, 'VolumeType' => 'io1', 'Iops' => 4001)
end
@volume.destroy
end
@server.destroy
end
fog-aws-0.7.6/tests/requests/compute/tag_tests.rb 0000644 0000041 0000041 00000010333 12576636531 022150 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | tag requests', ['aws']) do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@tags_format = {
'tagSet' => [{
'key' => String,
'resourceId' => String,
'resourceType' => String,
'value' => Fog::Nullable::String
}],
'requestId' => String
}
@volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1)
@volume.wait_for { ready? }
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@network_acl = Fog::Compute[:aws].network_acls.all('vpc-id' => @vpc.id, 'default' => true).first
tests('success') do
if Fog.mocking?
@other_account = Fog::Compute::AWS.new(:aws_access_key_id => 'other', :aws_secret_access_key => 'account')
@image_id = Fog::Compute[:aws].register_image('image', 'image', '/dev/sda1').body['imageId']
end
tests("#create_tags('#{@volume.identity}', 'foo' => 'bar')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_tags(@volume.identity, 'foo' => 'bar').body
end
if Fog.mocking?
tests("#create_tags('#{@image_id}', 'foo' => 'baz')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_tags(@image_id, 'foo' => 'baz').body
end
tests("#create_tags('#{@vpc.id}', 'type' => 'vpc')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_tags(@vpc.id, 'type' => 'vpc').body
end
tests("#create_tags('#{@network_acl.network_acl_id}', 'type' => 'network_acl')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_tags(@network_acl.network_acl_id, 'type' => 'network_acl').body
end
end
tests('#describe_tags').formats(@tags_format) do
Fog::Compute[:aws].describe_tags.body
end
expected_identities = Fog.mocking? ? [@volume.identity, @image_id] : [@volume.identity]
tests('#describe_tags').succeeds do
(expected_identities - Fog::Compute[:aws].describe_tags.body['tagSet'].map {|t| t['resourceId'] }).empty?
end
tests("#describe_tags('key' => 'foo', 'value' => 'bar')").returns([@volume.identity]) do
Fog::Compute[:aws].describe_tags('key' => 'foo', 'value' => 'bar').body['tagSet'].map {|t| t['resourceId'] }
end
if Fog.mocking?
tests("#describe_tags('key' => 'foo', 'value' => 'baz')").returns([@image_id]) do
Fog::Compute[:aws].describe_tags('key' => 'foo', 'value' => 'baz').body['tagSet'].map {|t| t['resourceId'] }
end
Fog::Compute[:aws].modify_image_attribute(@image_id, 'Add.UserId' => [@other_account.data[:owner_id]])
tests("other_account#describe_tags('key' => 'foo', 'value' => 'baz')").returns([]) do
@other_account.describe_tags('key' => 'foo', 'value' => 'baz').body['tagSet'].map {|t| t['resourceId'] }
end
tests("other_account#create_tags('#{@image_id}', 'foo' => 'quux')").formats(AWS::Compute::Formats::BASIC) do
@other_account.create_tags(@image_id, 'foo' => 'quux').body
end
tests("other_account#describe_tags('key' => 'foo', 'value' => 'quux')").returns([@image_id]) do
@other_account.describe_tags('key' => 'foo', 'value' => 'quux').body['tagSet'].map {|t| t['resourceId'] }
end
end
@volume.destroy
tests("#delete_tags('#{@volume.identity}', 'foo' => 'bar')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_tags(@volume.identity, 'foo' => 'bar').body
end
end
tests('failure') do
tests("#create_tags('vol-00000000', 'baz' => 'qux')").raises(Fog::Service::NotFound) do
Fog::Compute[:aws].create_tags('vol-00000000', 'baz' => 'qux')
end
tests("#create_tags('abc-12345678', 'type' => 'fake_type')").raises(Fog::Service::NotFound) do
Fog::Compute[:aws].create_tags('abc-12345678', 'type' => 'fake_type')
end
tests("#create_tags('vpc-12345678', 'type' => 'non-existent_vpc)").raises(Fog::Service::NotFound) do
Fog::Compute[:aws].create_tags('vpc-12345678', 'type' => 'non-existent_vpc')
end
tests("#create_tags('vpc-123', 'type' => 'bad_resource_id)").raises(Fog::Service::NotFound) do
Fog::Compute[:aws].create_tags('vpc-123', 'type' => 'bad_resource_id')
end
end
Fog::Compute::AWS::Mock.reset if Fog.mocking?
end
fog-aws-0.7.6/tests/requests/compute/address_tests.rb 0000644 0000041 0000041 00000010546 12576636531 023030 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | address requests', ['aws']) do
compute = Fog::Compute[:aws]
@addresses_format = {
'addressesSet' => [{
'allocationId' => Fog::Nullable::String,
'associationId' => Fog::Nullable::String,
'domain' => String,
'instanceId' => Fog::Nullable::String,
'publicIp' => String
}],
'requestId' => String
}
@server = compute.servers.create
@server.wait_for { ready? }
@ip_address = @server.public_ip_address
tests('success') do
@public_ip = nil
@vpc_public_ip = nil
@vpc_allocation_id = nil
tests('#allocate_address').formats({'domain' => String, 'publicIp' => String, 'requestId' => String}) do
data = compute.allocate_address.body
@public_ip = data['publicIp']
data
end
tests("#allocate_address('vpc')").formats({'domain' => String, 'publicIp' => String, 'allocationId' => String, 'requestId' => String}) do
data = compute.allocate_address('vpc').body
@vpc_public_ip = data['publicIp']
@vpc_allocation_id = data['allocationId']
data
end
tests('#describe_addresses').formats(@addresses_format) do
compute.describe_addresses.body
end
tests("#describe_addresses('public-ip' => #{@public_ip}')").formats(@addresses_format) do
compute.describe_addresses('public-ip' => @public_ip).body
end
tests("#associate_addresses('#{@server.identity}', '#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do
compute.associate_address(@server.identity, @public_ip).body
end
tests("#associate_addresses({:instance_id=>'#{@server.identity}', :public_ip=>'#{@public_ip}'})").formats(AWS::Compute::Formats::BASIC) do
compute.associate_address({:instance_id=>@server.identity,:public_ip=> @public_ip}).body
end
tests("#dissassociate_address('#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do
compute.disassociate_address(@public_ip).body
end
tests("#associate_addresses('#{@server.id}', nil, nil, '#{@vpc_allocation_id}')").formats(AWS::Compute::Formats::BASIC) do
compute.associate_address(@server.id, nil, nil, @vpc_allocation_id).body
end
tests("#associate_addresses({:instance_id=>'#{@server.id}', :allocation_id=>'#{@vpc_allocation_id}'})").formats(AWS::Compute::Formats::BASIC) do
compute.associate_address({:instance_id=>@server.id, :allocation_id=>@vpc_allocation_id}).body
end
tests("#release_address('#{@public_ip}')").formats(AWS::Compute::Formats::BASIC) do
compute.release_address(@public_ip).body
end
tests("#release_address('#{@vpc_allocation_id}')").formats(AWS::Compute::Formats::BASIC) do
compute.release_address(@vpc_allocation_id).body
end
end
tests('failure') do
@address = compute.addresses.create
@vpc_address = compute.addresses.create(:domain => 'vpc')
tests("#associate_addresses({:instance_id =>'i-00000000', :public_ip => '#{@address.identity}')}").raises(Fog::Compute::AWS::NotFound) do
compute.associate_address({:instance_id => 'i-00000000', :public_ip => @address.identity})
end
tests("#associate_addresses({:instance_id =>'#{@server.identity}', :public_ip => '127.0.0.1'})").raises(Fog::Compute::AWS::Error) do
compute.associate_address({:instance_id => @server.identity, :public_ip => '127.0.0.1'})
end
tests("#associate_addresses({:instance_id =>'i-00000000', :public_ip => '127.0.0.1'})").raises(Fog::Compute::AWS::NotFound) do
compute.associate_address({:instance_id =>'i-00000000', :public_ip =>'127.0.0.1'})
end
tests("#disassociate_addresses('127.0.0.1') raises BadRequest error").raises(Fog::Compute::AWS::Error) do
compute.disassociate_address('127.0.0.1')
end
tests("#release_address('127.0.0.1')").raises(Fog::Compute::AWS::Error) do
compute.release_address('127.0.0.1')
end
tests("#release_address('#{@vpc_address.identity}')").raises(Fog::Compute::AWS::Error) do
compute.release_address(@vpc_address.identity)
end
if Fog.mocking?
old_limit = compute.data[:limits][:addresses]
tests("#allocate_address", "limit exceeded").raises(Fog::Compute::AWS::Error) do
compute.data[:limits][:addresses] = 0
compute.allocate_address
end
compute.data[:limits][:addresses] = old_limit
end
@address.destroy
@vpc_address.destroy
end
@server.destroy
end
fog-aws-0.7.6/tests/requests/compute/instance_tests.rb 0000644 0000041 0000041 00000025216 12576636531 023207 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | instance requests', ['aws']) do
@instance_format = {
'architecture' => String,
'amiLaunchIndex' => Integer,
'associatePublicIP' => Fog::Nullable::Boolean,
'attachmentId' => Fog::Nullable::String,
'blockDeviceMapping' => [Fog::Nullable::Hash],
'networkInterfaces' => [Fog::Nullable::Hash],
'clientToken' => Fog::Nullable::String,
'dnsName' => NilClass,
'ebsOptimized' => Fog::Boolean,
'imageId' => String,
'instanceId' => String,
'instanceState' => {'code' => Integer, 'name' => String},
'instanceType' => String,
'kernelId' => Fog::Nullable::String,
'keyName' => Fog::Nullable::String,
'launchTime' => Time,
'monitoring' => {'state' => Fog::Boolean},
'networkInterfaceId' => Fog::Nullable::String,
'placement' => {
'availabilityZone' => String,
'groupName' => Fog::Nullable::String,
'tenancy' => String
},
'platform' => Fog::Nullable::String,
'privateDnsName' => NilClass,
'productCodes' => Array,
'reason' => Fog::Nullable::String,
'rootDeviceName' => Fog::Nullable::String,
'rootDeviceType' => String,
'sourceDestCheck' => Fog::Nullable::Boolean,
'subnetId' => Fog::Nullable::String,
'vpcId' => Fog::Nullable::String
}
@run_instances_format = {
'groupSet' => [String],
'instancesSet' => [@instance_format],
'ownerId' => Fog::Nullable::String,
'requestId' => String,
'reservationId' => String
}
@describe_instances_format = {
'reservationSet' => [{
'groupSet' => [String],
'groupIds' => [String],
'instancesSet' => [@instance_format.merge(
'architecture' => String,
'dnsName' => Fog::Nullable::String,
'hypervisor' => String,
'iamInstanceProfile' => Hash,
'ipAddress' => Fog::Nullable::String,
'networkInterfaces' => Array,
'ownerId' => String,
'privateDnsName' => Fog::Nullable::String,
'privateIpAddress' => Fog::Nullable::String,
'stateReason' => Hash,
'tagSet' => Hash,
'virtualizationType' => String
)],
'ownerId' => Fog::Nullable::String,
'reservationId' => String
}],
'requestId' => String
}
@get_console_output_format = {
'instanceId' => String,
'output' => Fog::Nullable::String,
'requestId' => String,
'timestamp' => Time
}
@get_password_data_format = {
'instanceId' => String,
'passwordData' => Fog::Nullable::String,
'requestId' => String,
'timestamp' => Time
}
@terminate_instances_format = {
'instancesSet' => [{
'currentState' => {'code' => Integer, 'name' => String},
'instanceId' => String,
'previousState' => {'code' => Integer, 'name' => String},
}],
'requestId' => String
}
@describe_reserved_instances_offerings_format = {
'reservedInstancesOfferingsSet' => [{
'reservedInstancesOfferingId' => String,
'instanceType' => String,
'availabilityZone' => String,
'duration' => Integer,
'fixedPrice' => Float,
'offeringType' => String,
'usagePrice' => Float,
'productDescription' => String,
'instanceTenancy' => String,
'currencyCode' => String
}],
'requestId' => String
}
@purchase_reserved_instances_offering_format = {
'reservedInstancesId' => String,
'requestId' => String
}
@describe_reserved_instances_format = {
'reservedInstancesSet' => [{
'reservedInstancesId' => String,
'instanceType' => String,
'availabilityZone' => String,
'start' => Time,
'end' => Time,
'duration' => Integer,
'fixedPrice' => Float,
'usagePrice' => Float,
'instanceCount' => Integer,
'offeringType' => String,
'productDescription' => String,
'state' => String,
'tagSet' => [{
'key' => String,
'value' => String
}],
'instanceTenancy' => String,
'currencyCode' => String
}],
'requestId' => String
}
@describe_instance_status_format = {
'requestId' => String,
'instanceStatusSet' => [{
'instanceId' => String,
'availabilityZone' => String,
'instanceState' => {
'code' => Integer,
'name' => String
},
'systemStatus' => {
'status' => String,
'details' => [{
'name' => String,
'status' => String
}]
},
'instanceStatus' => {
'status' => String,
'details' => [{
'name' => String,
'status' => String
}]
},
'eventsSet' => [Fog::Nullable::Hash],
}]
}
tests('success') do
@instance_id = nil
@ami = if ENV['FASTER_TEST_PLEASE']
'ami-79c0ae10' # ubuntu 12.04 daily build 20120728
else
# Use a MS Windows AMI to test #get_password_data
'ami-71b50018' # Amazon Public Images - Windows_Server-2008-SP2-English-64Bit-Base-2012.07.11
end
# Create a keypair for decrypting the password
key_name = uniq_id('fog-test-key')
key = Fog::Compute[:aws].key_pairs.create(:name => key_name)
tests("#run_instances").formats(@run_instances_format) do
data = Fog::Compute[:aws].run_instances(@ami, 1, 1, 'InstanceType' => 't1.micro', 'KeyName' => key_name, 'BlockDeviceMapping' => [{"DeviceName" => "/dev/sdp1", "VirtualName" => nil, "Ebs.VolumeSize" => 15}]).body
@instance_id = data['instancesSet'].first['instanceId']
data
end
server = Fog::Compute[:aws].servers.get(@instance_id)
while server.nil? do
# It may take a moment to get the server after launching it
sleep 0.1
server = Fog::Compute[:aws].servers.get(@instance_id)
end
server.wait_for { ready? }
tests("#describe_instances").formats(@describe_instances_format) do
Fog::Compute[:aws].describe_instances('instance-state-name' => 'running').body
end
# Launch another instance to test filters
another_server = Fog::Compute[:aws].servers.create
tests("#describe_instances('instance-id' => '#{@instance_id}'").formats(@describe_instances_format) do
body = Fog::Compute[:aws].describe_instances('instance-id' => "#{@instance_id}").body
tests("returns 1 instance").returns(1) { body['reservationSet'].size }
body
end
# Test network interface attachment
tests('#describe_instances networkInterfaces') do
vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/16')
subnet = Fog::Compute[:aws].subnets.create('vpc_id' => vpc.id, 'cidr_block' => '10.0.10.0/16')
data = Fog::Compute[:aws].create_network_interface(subnet.subnet_id).body
@network_interface_id = data['networkInterface']['networkInterfaceId']
Fog::Compute[:aws].attach_network_interface(@network_interface_id, @instance_id, '1')
body = Fog::Compute[:aws].describe_instances('instance-id' => "#{@instance_id}").body
tests("returns 1 attachment").returns(1) { body['reservationSet'].first['instancesSet'].first['networkInterfaces'].size }
subnet.destroy
vpc.destroy
end
another_server.destroy
tests("#get_console_output('#{@instance_id}')").formats(@get_console_output_format) do
Fog::Compute[:aws].get_console_output(@instance_id).body
end
tests("#get_password_data('#{@instance_id}')").formats(@get_password_data_format) do
result = Fog::Compute[:aws].get_password_data(@instance_id).body
tests("key can decrypt passwordData").returns(true) do
pending if Fog.mocking?
password_data = result['passwordData']
Fog.wait_for do
password_data ||= Fog::Compute[:aws].get_password_data(@instance_id).body['passwordData']
end
decoded_password = Base64.decode64(password_data)
pkey = OpenSSL::PKey::RSA.new(key.private_key)
String === pkey.private_decrypt(decoded_password)
end
result
end unless ENV['FASTER_TEST_PLEASE']
key.destroy
tests("#reboot_instances('#{@instance_id}')").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].reboot_instances(@instance_id).body
end
tests("#terminate_instances('#{@instance_id}')").formats(@terminate_instances_format) do
Fog::Compute[:aws].terminate_instances(@instance_id).body
end
tests("#describe_reserved_instances_offerings").formats(@describe_reserved_instances_offerings_format) do
@reserved_instances = Fog::Compute[:aws].describe_reserved_instances_offerings.body
@reserved_instances
end
tests('#describe_instance_status').formats(@describe_instance_status_format) do
Fog::Compute[:aws].describe_instance_status.body
end
if Fog.mocking?
@reserved_instance_offering_id = @reserved_instances["reservedInstancesOfferingsSet"].first["reservedInstancesOfferingId"]
tests("#purchase_reserved_instances_offering('#{@reserved_instance_offering_id}')").formats(@purchase_reserved_instances_offering_format) do
Fog::Compute[:aws].purchase_reserved_instances_offering(@reserved_instance_offering_id, 1).body
end
tests("#describe_reserved_instances").formats(@describe_reserved_instances_format) do
Fog::Compute[:aws].describe_reserved_instances.body
end
end
end
tests('failure') do
tests("#run_instances(nil, 1, 1, {'SubnetId'=>'subnet-00000000'}").raises(::Fog::Compute::AWS::Error) do
Fog::Compute[:aws].run_instances(nil, 1, 1, {'SubnetId' => 'subnet-000000'})
end
tests("#get_console_output('i-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].get_console_output('i-00000000')
end
tests("#get_password_data('i-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].get_password_data('i-00000000')
end
tests("#reboot_instances('i-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].reboot_instances('i-00000000')
end
tests("#terminate_instances('i-00000000')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].terminate_instances('i-00000000')
end
end
end
fog-aws-0.7.6/tests/requests/compute/network_acl_tests.rb 0000644 0000041 0000041 00000010323 12576636531 023704 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | network acl requests', ['aws']) do
@network_acl_format = {
'networkAclId' => String,
'vpcId' => String,
'default' => Fog::Boolean,
'entrySet' => [{
'ruleNumber' => Integer,
'protocol' => Integer,
'ruleAction' => String,
'egress' => Fog::Boolean,
'cidrBlock' => String,
'icmpTypeCode' => {
'code' => Fog::Nullable::Integer,
'type' => Fog::Nullable::Integer
},
'portRange' => {
'from' => Fog::Nullable::Integer,
'to' => Fog::Nullable::Integer
}
}],
'associationSet' => Array,
'tagSet' => Hash
}
@network_acls_format = {
'requestId' => String,
'networkAclSet' => [ @network_acl_format ]
}
@network_acl_replace_association = {
'requestId' => String,
'newAssociationId' => String
}
tests('success') do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
@network_acl = nil
# Describe network interfaces
tests('#describe_network_acls').formats(@network_acls_format) do
Fog::Compute[:aws].describe_network_acls.body
end
tests('#create_network_acl').formats(@network_acl_format) do
data = Fog::Compute[:aws].create_network_acl(@vpc.id).body
@network_acl = data['networkAcl']
data['networkAcl']
end
tests("#create_network_acl_entry").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].create_network_acl_entry(@network_acl['networkAclId'], 100, 6, 'allow', '0.0.0.0/8', false, 'PortRange.From' => 22, 'PortRange.To' => 22).body
end
tests("#replace_network_acl_entry").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].replace_network_acl_entry(@network_acl['networkAclId'], 100, 6, 'deny', '0.0.0.0/8', false, 'PortRange.From' => 22, 'PortRange.To' => 22).body
end
tests("#delete_network_acl_entry").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_acl_entry(@network_acl['networkAclId'], 100, false).body
end
default_acl = Fog::Compute[:aws].describe_network_acls('vpc-id' => @vpc.id, 'default' => true).body['networkAclSet'].first
@assoc_id = default_acl['associationSet'].first['networkAclAssociationId']
tests("#replace_network_acl_association").formats(@network_acl_replace_association) do
data = Fog::Compute[:aws].replace_network_acl_association(@assoc_id, @network_acl['networkAclId']).body
@assoc_id = data['newAssociationId']
data
end
tests("#replace_network_acl_association").formats(@network_acl_replace_association) do
Fog::Compute[:aws].replace_network_acl_association(@assoc_id, default_acl['networkAclId']).body
end
# Create another network acl to test tag filters
test_tags = {'foo' => 'bar'}
@another_acl = Fog::Compute[:aws].network_acls.create :vpc_id => @vpc.id, :tags => test_tags
tests("#describe_network_acls('tag-key' => 'foo')").formats(@network_acls_format) do
body = Fog::Compute[:aws].describe_network_acls('tag-key' => 'foo').body
tests("returns 1 acl").returns(1) { body['networkAclSet'].size }
body
end
tests("#describe_network_acls('tag-value' => 'bar')").formats(@network_acls_format) do
body = Fog::Compute[:aws].describe_network_acls('tag-value' => 'bar').body
tests("returns 1 acl").returns(1) { body['networkAclSet'].size }
body
end
tests("#describe_network_acls('tag:foo' => 'bar')").formats(@network_acls_format) do
body = Fog::Compute[:aws].describe_network_acls('tag:foo' => 'bar').body
tests("returns 1 acl").returns(1) { body['networkAclSet'].size }
body
end
tests('#delete_network_acl').formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].delete_network_acl(@network_acl['networkAclId']).body
end
# Clean up
Fog::Compute[:aws].delete_tags(@another_acl.identity, test_tags)
@another_acl.destroy
@subnet.destroy
@vpc.destroy
Fog::Compute::AWS::Mock.reset if Fog.mocking?
end
end
fog-aws-0.7.6/tests/requests/compute/assign_private_ip_tests.rb 0000644 0000041 0000041 00000004500 12576636531 025102 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | internet_gateway requests', ['aws']) do
tests('success') do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@vpc_id = @vpc.id
@subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24')
@subnet_id = @subnet.subnet_id
@network_interface = Fog::Compute[:aws].network_interfaces.new(:subnet_id => @subnet_id)
@network_interface.save
@network_interface_id = @network_interface.network_interface_id
@ip_address = Fog::AWS::Mock.ip_address
@second_ip_address = Fog::AWS::Mock.ip_address
tests("#assign_private_ip_addresses('#{@network_interface_id}', {'PrivateIpAddresses'=>['#{@ip_address}','#{@second_ip_address}']})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, { 'PrivateIpAddresses' =>[@ip_address, @second_ip_address]}).body
end
tests("#assign_private_ip_addresses('#{@network_interface_id}', {'SecondaryPrivateIpAddressCount'=>4})").formats(AWS::Compute::Formats::BASIC) do
Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, {'SecondaryPrivateIpAddressCount'=>4}).body
end
@network_interface.destroy
@subnet.destroy
@vpc.destroy
end
tests('failure') do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@vpc_id = @vpc.id
@subnet=Fog::Compute[:aws].subnets.create('vpc_id' => @vpc_id, 'cidr_block' => '10.0.10.0/24')
@subnet_id = @subnet.subnet_id
@network_interface = Fog::Compute[:aws].network_interfaces.new(:subnet_id => @subnet_id)
@network_interface.save
@network_interface_id = @network_interface.network_interface_id
@ip_address = Fog::AWS::Mock.ip_address
tests("#assign_private_ip_addresses('#{@network_interface_id}', {'PrivateIpAddresses'=>['#{@ip_address}','#{@second_ip_address}'], 'SecondaryPrivateIpAddressCount'=>4 })").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].assign_private_ip_addresses(@network_interface_id, { 'PrivateIpAddresses' =>[@ip_address, @second_ip_address], 'SecondaryPrivateIpAddressCount'=>4 }).body
end
@network_interface.destroy
@subnet.destroy
@vpc.destroy
end
end
fog-aws-0.7.6/tests/requests/compute/instance_attrib_tests.rb 0000644 0000041 0000041 00000017002 12576636531 024546 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | describe_instance_attribute request', ['aws']) do
@instance_attributes = [
'instanceType',
'kernel',
'ramdisk',
'userData',
'disableApiTermination',
'instanceInitiatedShutdownBehavior',
'rootDeviceName',
'blockDeviceMapping',
'productCodes',
'groupSet',
'ebsOptimized',
'sourceDestCheck',
'sriovNetSupport'
]
@instance_attribute_common_format = {
"requestId" => String,
"instanceId" => String
}
@instance_attribute_format = {
"instanceType" => Fog::Nullable::String,
"kernelId" => Fog::Nullable::String,
"ramdiskId" => Fog::Nullable::String,
"userData" => Fog::Nullable::String,
"disableApiTermination" => Fog::Nullable::Boolean,
"instanceInitiatedShutdownBehavior" => Fog::Nullable::String,
"rootDeviceName" => Fog::Nullable::String,
"blockDeviceMapping" => [Fog::Nullable::Hash],
"productCodes" => Fog::Nullable::Array,
"ebsOptimized" => Fog::Nullable::Boolean,
"sriovNetSupport" => Fog::Nullable::String,
"sourceDestCheck" => Fog::Nullable::Boolean,
"groupSet" => [Fog::Nullable::Hash]
}
tests('success') do
# In mocking the groupSet attribute is returned as nil
if Fog.mocking?
@instance_attribute_format["groupSet"] = Fog::Nullable::Array
end
# Setting up the environment
@instance_id = nil
@ami = 'ami-79c0ae10'
key_name = uniq_id('fog-test-key')
@key = Fog::Compute[:aws].key_pairs.create(:name => key_name)
instance_type = "t1.micro"
@az = "us-east-1a"
vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/16')
subnet = Fog::Compute[:aws].subnets.create('vpc_id' => vpc.id, 'cidr_block' => '10.0.10.0/16', "availability_zone" => @az)
security_groups = Fog::Compute[:aws].security_groups.all
@launch_config = {
:image_id => @ami,
:flavor_id => instance_type,
:key_name => key_name,
:subnet_id => subnet.subnet_id,
:disable_api_termination => false
}
if !Fog.mocking?
security_group = security_groups.select { |group| group.vpc_id == vpc.id }
security_group_ids = security_group.collect { |group| group.group_id }
@launch_config[:security_group_ids] = security_group_ids
block_device_mapping = [{"DeviceName" => "/dev/sdp1", "VirtualName" => nil, "Ebs.VolumeSize" => 15}]
@launch_config[:block_device_mapping] = block_device_mapping
else
security_group_ids = [nil]
# In mocking the first device provided in block_device_mapping is set as the root device. There is no root device by default. So setting the root device here so that the tests for rootDeviceName and blockDeviceMapping attribute get passed
block_device_mapping = [{"DeviceName" => "/dev/sda1", "VirtualName" => nil, "Ebs.VolumeSize" => 15},{"DeviceName" => "/dev/sdp1", "VirtualName" => nil, "Ebs.VolumeSize" => 15}]
@launch_config[:block_device_mapping] = block_device_mapping
end
server = Fog::Compute[:aws].servers.create(@launch_config)
server.wait_for { ready? }
server.reload
@instance_id = server.id
################
# BEGIN TESTS #
################
@instance_attributes.each do |attrib|
# Creating format schema for each attribute
describe_instance_attribute_format = @instance_attribute_common_format.clone
if attrib == "kernel"
key = "kernelId"
elsif attrib == "ramdisk"
key = "ramdiskId"
else
key = attrib
end
describe_instance_attribute_format[key] = @instance_attribute_format[key]
# Running format check
tests("#describe_instance_attribute('#{@instance_id}', #{attrib})").formats(describe_instance_attribute_format,false) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, attrib).body
end
# Running test to see proper instance Id is get in each response
tests("#describe_instance_attribute('#{@instance_id}', #{attrib})").returns(@instance_id) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, attrib).body['instanceId']
end
end
# Test for instanceType attribute
tests("#describe_instance_attribute(#{@instance_id}, 'instanceType')").returns(instance_type) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'instanceType').body["instanceType"]
end
# Test for disableApiTermination attribute
tests("#describe_instance_attribute(#{@instance_id}, 'disableApiTermination')").returns(false) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'disableApiTermination').body["disableApiTermination"]
end
# Test for instanceInitiatedShutdownBehavior attribute
tests("#describe_instance_attribute(#{@instance_id}, 'instanceInitiatedShutdownBehavior')").returns('stop') do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'instanceInitiatedShutdownBehavior').body["instanceInitiatedShutdownBehavior"]
end
# Test for rootDeviceName attribute
tests("#describe_instance_attribute(#{@instance_id}, 'rootDeviceName')").returns('/dev/sda1') do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'rootDeviceName').body["rootDeviceName"]
end
# Test to see there are two devices for blockDeviceMapping attribute
tests("#describe_instance_attribute(#{@instance_id}, 'blockDeviceMapping')").returns(2) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'blockDeviceMapping').body["blockDeviceMapping"].count
end
# Test to check the device name /dev/sdp1 passed in block_device_mapping is returned correctly
tests("#describe_instance_attribute(#{@instance_id}, 'blockDeviceMapping')").returns("/dev/sdp1") do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'blockDeviceMapping').body["blockDeviceMapping"].last["deviceName"]
end
# Test for groupSet attribute
tests("#describe_instance_attribute(#{@instance_id}, 'groupSet')").returns(security_group_ids) do
group_set = Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'groupSet').body["groupSet"]
group_set.collect { |g| g["groupId"]}
end
# Test for sourceDestCheck attribute (This attribute is set only for VPC instances. So created the instance in a VPC during setup process)
tests("#describe_instance_attribute(#{@instance_id}, 'sourceDestCheck')").returns(true) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'sourceDestCheck').body["sourceDestCheck"]
end
# Test for ebsOptimized attribute
tests("#describe_instance_attribute(#{@instance_id}, 'ebsOptimized')").returns(false) do
Fog::Compute[:aws].describe_instance_attribute(@instance_id, 'ebsOptimized').body["ebsOptimized"]
end
###############
# END OF TEST #
###############
# Tear down
if !Fog.mocking?
@key.destroy
server.destroy
until server.state == "terminated"
sleep 5 #Wait for the server to be terminated
server.reload
end
subnet.destroy
vpc.destroy
end
end
tests('failure') do
@instance_attributes.each do |attrib|
tests("#describe_instance_attribute('i-00000000', #{attrib})").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].describe_instance_attribute('i-00000000', attrib)
end
end
end
end
fog-aws-0.7.6/tests/requests/compute/placement_group_tests.rb 0000644 0000041 0000041 00000003337 12576636531 024567 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | placement group requests', ['aws']) do
@placement_group_format = {
'requestId' => String,
'placementGroupSet' => [{
'groupName' => String,
'state' => String,
'strategy' => String
}]
}
tests('success') do
tests("#create_placement_group('fog_placement_group', 'cluster')").formats(AWS::Compute::Formats::BASIC) do
pending if Fog.mocking?
Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster').body
end
tests("#describe_placement_groups").formats(@placement_group_format) do
pending if Fog.mocking?
Fog::Compute[:aws].describe_placement_groups.body
end
tests("#describe_placement_groups('group-name' => 'fog_placement_group)").formats(@placement_group_format) do
pending if Fog.mocking?
Fog::Compute[:aws].describe_placement_groups('group-name' => 'fog_security_group').body
end
tests("#delete_placement_group('fog_placement_group')").formats(AWS::Compute::Formats::BASIC) do
pending if Fog.mocking?
Fog::Compute[:aws].delete_placement_group('fog_placement_group').body
end
end
tests('failure') do
pending if Fog.mocking?
Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster')
tests("duplicate #create_placement_group('fog_placement_group', 'cluster')").raises(Fog::Compute::AWS::Error) do
Fog::Compute[:aws].create_placement_group('fog_placement_group', 'cluster')
end
tests("#delete_placement_group('not_a_group_name')").raises(Fog::Compute::AWS::NotFound) do
Fog::Compute[:aws].delete_placement_group('not_a_group_name')
end
Fog::Compute[:aws].delete_placement_group('fog_placement_group')
end
end
fog-aws-0.7.6/tests/requests/compute/client_tests.rb 0000644 0000041 0000041 00000002064 12576636531 022655 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | account tests', ['aws']) do
if Fog.mocking?
tests('check for vpc') do
tests('supports both vpc and ec2 in compatibility mode').succeeds do
client = Fog::Compute[:aws]
client.enable_ec2_classic
data = Fog::Compute[:aws].describe_account_attributes.body
data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") && [*s["values"]].include?("EC2") }
end
tests('supports VPC in vpc mode').succeeds do
client = Fog::Compute[:aws]
client.enable_ec2_classic
data = Fog::Compute[:aws].describe_account_attributes.body
data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") }
end
tests('does not support VPC and EC2 in vpc mode').succeeds do
client = Fog::Compute[:aws]
client.disable_ec2_classic
data = Fog::Compute[:aws].describe_account_attributes.body
!data['accountAttributeSet'].any? { |s| [*s["values"]].include?("VPC") && [*s["values"]].include?("EC2") }
end
end
end
end
fog-aws-0.7.6/tests/requests/compute/spot_instance_tests.rb 0000644 0000041 0000041 00000004200 12576636531 024242 0 ustar www-data www-data Shindo.tests('Fog::Compute[:aws] | spot instance requests', ['aws']) do
@spot_instance_requests_format = {
'spotInstanceRequestSet' => [{
'createTime' => Time,
'instanceId' => Fog::Nullable::String,
'launchedAvailabilityZone' => Fog::Nullable::String,
'launchSpecification' => {
'blockDeviceMapping' => [],
'groupSet' => [String],
'keyName' => Fog::Nullable::String,
'imageId' => String,
'instanceType' => String,
'monitoring' => Fog::Boolean,
'ebsOptimized' => Fog::Boolean,
'subnetId' => Fog::Nullable::String,
'iamInstanceProfile' => Fog::Nullable::Hash,
},
'productDescription' => String,
'spotInstanceRequestId' => String,
'spotPrice' => Float,
'state' => String,
'type' => String,
'fault' => Fog::Nullable::Hash,
}],
'requestId' => String
}
@cancel_spot_instance_request_format = {
'spotInstanceRequestSet' => [{
'spotInstanceRequestId' => String,
'state' => String
}],
'requestId' => String
}
tests('success') do
tests("#request_spot_instances('ami-3202f25b', 't1.micro', '0.001')").formats(@spot_instance_requests_format) do
data = Fog::Compute[:aws].request_spot_instances('ami-3202f25b', 't1.micro', '0.001',{'LaunchSpecification.EbsOptimized' => false}).body
@spot_instance_request_id = data['spotInstanceRequestSet'].first['spotInstanceRequestId']
data
end
pending if Fog.mocking?
tests("#describe_spot_instance_requests").formats(@spot_instance_requests_format) do
Fog::Compute[:aws].describe_spot_instance_requests('spot-instance-request-id' => [@spot_instance_request_id]).body
end
tests("#cancel_spot_instance_requests('#{@spot_instance_request_id}')").formats(@cancel_spot_instance_request_format) do
Fog::Compute[:aws].cancel_spot_instance_requests(@spot_instance_request_id).body
end
end
end
fog-aws-0.7.6/tests/requests/federation/ 0000755 0000041 0000041 00000000000 12576636531 020272 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/federation/get_signin_token_tests.rb 0000644 0000041 0000041 00000000433 12576636531 025367 0 ustar www-data www-data Shindo.tests('AWS::Federation | signin tokens', ['aws']) do
@signin_token_format = {
'SigninToken' => String
}
tests("#get_signin_token").formats(@signin_token_format) do
pending unless Fog.mocking?
Fog::AWS[:federation].get_signin_token("test_policy")
end
end
fog-aws-0.7.6/tests/requests/elasticache/ 0000755 0000041 0000041 00000000000 12576636531 020417 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/elasticache/security_group_tests.rb 0000644 0000041 0000041 00000007107 12576636531 025256 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | security group requests', ['aws', 'elasticache']) do
tests('success') do
name = 'fog-test'
description = 'Fog Test Security Group'
tests(
'#create_cache_security_group'
).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do
body = Fog::AWS[:elasticache].create_cache_security_group(name, description).body
group = body['CacheSecurityGroup']
returns(name) { group['CacheSecurityGroupName'] }
returns(description) { group['Description'] }
returns([], "no authorized security group") { group['EC2SecurityGroups'] }
body
end
tests(
'#describe_cache_security_groups without options'
).formats(AWS::Elasticache::Formats::DESCRIBE_SECURITY_GROUPS) do
body = Fog::AWS[:elasticache].describe_cache_security_groups.body
returns(true, "has #{name}") do
body['CacheSecurityGroups'].any? do |group|
group['CacheSecurityGroupName'] == name
end
end
body
end
tests(
'#describe_cache_security_groups with name'
).formats(AWS::Elasticache::Formats::DESCRIBE_SECURITY_GROUPS) do
body = Fog::AWS[:elasticache].describe_cache_security_groups(name).body
returns(1, "size of 1") { body['CacheSecurityGroups'].size }
returns(name, "has #{name}") do
body['CacheSecurityGroups'].first['CacheSecurityGroupName']
end
body
end
tests('authorization') do
ec2_group = Fog::Compute.new(:provider => 'AWS').security_groups.create(
:name => 'fog-test-elasticache', :description => 'Fog Test Elasticache'
)
# Reload to get the owner_id
ec2_group.reload
tests(
'#authorize_cache_security_group_ingress'
).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do
body = Fog::AWS[:elasticache].authorize_cache_security_group_ingress(
name, ec2_group.name, ec2_group.owner_id
).body
group = body['CacheSecurityGroup']
expected_ec2_groups = [{
'Status' => 'authorizing', 'EC2SecurityGroupName' => ec2_group.name,
'EC2SecurityGroupOwnerId' => ec2_group.owner_id
}]
returns(expected_ec2_groups, 'has correct EC2 groups') do
group['EC2SecurityGroups']
end
body
end
# Wait for the state to be active
Fog.wait_for do
response = Fog::AWS[:elasticache].describe_cache_security_groups(name)
group = response.body['CacheSecurityGroups'].first
group['EC2SecurityGroups'].all? {|ec2| ec2['Status'] == 'authorized'}
end
tests(
'#revoke_cache_security_group_ingress'
).formats(AWS::Elasticache::Formats::SINGLE_SECURITY_GROUP) do
pending if Fog.mocking?
body = Fog::AWS[:elasticache].revoke_cache_security_group_ingress(
name, ec2_group.name, ec2_group.owner_id
).body
group = body['CacheSecurityGroup']
expected_ec2_groups = [{
'Status' => 'revoking', 'EC2SecurityGroupName' => ec2_group.name,
'EC2SecurityGroupOwnerId' => ec2_group.owner_id
}]
returns(expected_ec2_groups, 'has correct EC2 groups') do
group['EC2SecurityGroups']
end
body
end
ec2_group.destroy
end
tests(
'#delete_cache_security_group'
).formats(AWS::Elasticache::Formats::BASIC) do
body = Fog::AWS[:elasticache].delete_cache_security_group(name).body
end
end
tests('failure') do
# TODO:
# Create a duplicate security group
# List a missing security group
# Delete a missing security group
end
end
fog-aws-0.7.6/tests/requests/elasticache/helper.rb 0000644 0000041 0000041 00000007526 12576636531 022235 0 ustar www-data www-data class AWS
module Elasticache
module Formats
BASIC = {
'ResponseMetadata' => {'RequestId' => String}
}
# Cache Security Groups
SECURITY_GROUP = {
'EC2SecurityGroups' => Array,
'CacheSecurityGroupName' => String,
'Description' => String,
'OwnerId' => String,
}
SINGLE_SECURITY_GROUP = BASIC.merge('CacheSecurityGroup' => SECURITY_GROUP)
DESCRIBE_SECURITY_GROUPS = {'CacheSecurityGroups' => [SECURITY_GROUP]}
CACHE_SUBNET_GROUP = {
'CacheSubnetGroupName' => String,
'CacheSubnetGroupDescription' => String,
'VpcId' => String,
'Subnets' => [String]
}
CREATE_CACHE_SUBNET_GROUP = BASIC.merge({
'CreateCacheSubnetGroupResult' => {
'CacheSubnetGroup' => CACHE_SUBNET_GROUP
}
})
DESCRIBE_CACHE_SUBNET_GROUPS = BASIC.merge({
'DescribeCacheSubnetGroupsResult' => {
'CacheSubnetGroups' => [CACHE_SUBNET_GROUP]
}
})
# Cache Parameter Groups
PARAMETER_GROUP = {
'CacheParameterGroupFamily' => String,
'CacheParameterGroupName' => String,
'Description' => String,
}
SINGLE_PARAMETER_GROUP = BASIC.merge('CacheParameterGroup' => PARAMETER_GROUP)
DESCRIBE_PARAMETER_GROUPS = BASIC.merge('CacheParameterGroups' => [PARAMETER_GROUP])
MODIFY_PARAMETER_GROUP = {'CacheParameterGroupName' => String }
PARAMETER_SET = {
'Parameters' => Array,
'CacheNodeTypeSpecificParameters' => Array,
}
ENGINE_DEFAULTS = PARAMETER_SET.merge('CacheParameterGroupFamily' => String)
# Cache Clusters - more parameters get added as the lifecycle progresses
CACHE_CLUSTER = {
'AutoMinorVersionUpgrade' => String, # actually TrueClass or FalseClass
'CacheSecurityGroups' => Array,
'CacheClusterId' => String,
'CacheClusterStatus' => String,
'CacheNodeType' => String,
'Engine' => String,
'EngineVersion' => String,
'CacheParameterGroup' => Hash,
'NumCacheNodes' => Integer,
'PreferredMaintenanceWindow' => String,
'CacheNodes' => Array,
'PendingModifiedValues' => Hash,
}
CACHE_CLUSTER_RUNNING = CACHE_CLUSTER.merge({
'CacheClusterCreateTime' => DateTime,
'PreferredAvailabilityZone' => String,
})
CACHE_CLUSTER_MODIFIED = CACHE_CLUSTER_RUNNING.merge({
'NotificationConfiguration' => Hash,
'PendingModifiedValues' => Hash,
})
SINGLE_CACHE_CLUSTER = BASIC.merge('CacheCluster' => CACHE_CLUSTER)
DESCRIBE_CACHE_CLUSTERS = BASIC.merge('CacheClusters' => [CACHE_CLUSTER])
EVENT = {
'Date' => DateTime,
'Message' => String,
'SourceIdentifier' => String,
'SourceType' => String,
}
EVENT_LIST = [EVENT]
RESERVED_CACHE_CLUSTER = {
'CacheNodeCount' => Integer,
'CacheNodeType' => String,
'Duration' => Integer,
'FixedPrice' => Float,
'OfferingType' => String,
'ProductDescription' => String,
'RecurringCharges' => Array,
'ReservedCacheNodeId' => String,
'ReservedCacheNodesOfferingId' => String,
'StartTime' => DateTime,
'State' => String,
'UsagePrice' => Float
}
RESERVED_CACHE_CLUSTER_LIST = [RESERVED_CACHE_CLUSTER]
end
end
end
fog-aws-0.7.6/tests/requests/elasticache/describe_reserved_cache_nodes.rb 0000644 0000041 0000041 00000000627 12576636531 026743 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | describe reserved cache nodes',
['aws', 'elasticache']) do
tests('success') do
pending if Fog.mocking?
tests(
'#describe_reserved_cache_nodes'
).formats(AWS::Elasticache::Formats::RESERVED_CACHE_NODES) do
Fog::AWS[:elasticache].describe_reserved_cache_nodes().body['ReservedCacheNodes']
end
end
tests('failure') do
# TODO:
end
end
fog-aws-0.7.6/tests/requests/elasticache/describe_events.rb 0000644 0000041 0000041 00000000545 12576636531 024114 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | describe cache cluster events',
['aws', 'elasticache']) do
tests('success') do
pending if Fog.mocking?
tests(
'#describe_events'
).formats(AWS::Elasticache::Formats::EVENT_LIST) do
Fog::AWS[:elasticache].describe_events().body['Events']
end
end
tests('failure') do
# TODO:
end
end
fog-aws-0.7.6/tests/requests/elasticache/parameter_group_tests.rb 0000644 0000041 0000041 00000006711 12576636531 025367 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | parameter group requests', ['aws', 'elasticache']) do
tests('success') do
pending if Fog.mocking?
name = 'fog-test'
description = 'Fog Test Parameter Group'
tests(
'#describe_engine_default_parameters'
).formats(AWS::Elasticache::Formats::ENGINE_DEFAULTS) do
response = Fog::AWS[:elasticache].describe_engine_default_parameters
engine_defaults = response.body['EngineDefaults']
returns('memcached1.4') { engine_defaults['CacheParameterGroupFamily'] }
engine_defaults
end
tests(
'#create_cache_parameter_group'
).formats(AWS::Elasticache::Formats::SINGLE_PARAMETER_GROUP) do
body = Fog::AWS[:elasticache].create_cache_parameter_group(name, description).body
group = body['CacheParameterGroup']
returns(name) { group['CacheParameterGroupName'] }
returns(description) { group['Description'] }
returns('memcached1.4') { group['CacheParameterGroupFamily'] }
body
end
tests(
'#describe_cache_parameters'
).formats(AWS::Elasticache::Formats::PARAMETER_SET) do
response = Fog::AWS[:elasticache].describe_cache_parameters(name)
parameter_set = response.body['DescribeCacheParametersResult']
parameter_set
end
tests(
'#describe_cache_parameter_groups without options'
).formats(AWS::Elasticache::Formats::DESCRIBE_PARAMETER_GROUPS) do
body = Fog::AWS[:elasticache].describe_cache_parameter_groups.body
returns(true, "has #{name}") do
body['CacheParameterGroups'].any? do |group|
group['CacheParameterGroupName'] == name
end
end
body
end
tests(
'#reset_cache_parameter_group completely'
).formats('CacheParameterGroupName' => String) do
result = Fog::AWS[:elasticache].reset_cache_parameter_group(
name
).body['ResetCacheParameterGroupResult']
returns(name) {result['CacheParameterGroupName']}
result
end
tests(
'#modify_cache_parameter_group'
).formats('CacheParameterGroupName' => String) do
result = Fog::AWS[:elasticache].modify_cache_parameter_group(
name, {"chunk_size" => 32}
).body['ModifyCacheParameterGroupResult']
returns(name) {result['CacheParameterGroupName']}
result
end
# BUG: returns "MalformedInput - Unexpected complex element termination"
tests(
'#reset_cache_parameter_group with one parameter'
).formats('CacheParameterGroupName' => String) do
pending
result = Fog::AWS[:elasticache].reset_cache_parameter_group(
name, ["chunk_size"]
).body['ResetCacheParameterGroupResult']
returns(name) {result['CacheParameterGroupName']}
result
end
tests(
'#describe_cache_parameter_groups with name'
).formats(AWS::Elasticache::Formats::DESCRIBE_PARAMETER_GROUPS) do
body = Fog::AWS[:elasticache].describe_cache_parameter_groups(name).body
returns(1, "size of 1") { body['CacheParameterGroups'].size }
returns(name, "has #{name}") do
body['CacheParameterGroups'].first['CacheParameterGroupName']
end
body
end
tests(
'#delete_cache_parameter_group'
).formats(AWS::Elasticache::Formats::BASIC) do
body = Fog::AWS[:elasticache].delete_cache_parameter_group(name).body
end
end
tests('failure') do
# TODO:
# Create a duplicate parameter group
# List a missing parameter group
# Delete a missing parameter group
end
end
fog-aws-0.7.6/tests/requests/elasticache/cache_cluster_tests.rb 0000644 0000041 0000041 00000011574 12576636531 025002 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | cache cluster requests', ['aws', 'elasticache']) do
tests('success') do
# Randomize the cluster ID so tests can be fequently re-run
CLUSTER_ID = "fog-test-cluster-#{rand(999).to_s}" # 20 chars max!
NUM_NODES = 2 # Must be > 1, because one of the tests reomves a node!
tests(
'#create_cache_cluster'
).formats(AWS::Elasticache::Formats::SINGLE_CACHE_CLUSTER) do
body = Fog::AWS[:elasticache].create_cache_cluster(CLUSTER_ID,
:num_nodes => NUM_NODES
).body
cluster = body['CacheCluster']
returns(CLUSTER_ID) { cluster['CacheClusterId'] }
returns('creating') { cluster['CacheClusterStatus'] }
body
end
tests(
'#describe_cache_clusters without options'
).formats(AWS::Elasticache::Formats::DESCRIBE_CACHE_CLUSTERS) do
body = Fog::AWS[:elasticache].describe_cache_clusters.body
returns(true, "has #{CLUSTER_ID}") do
body['CacheClusters'].any? do |cluster|
cluster['CacheClusterId'] == CLUSTER_ID
end
end
# The DESCRIBE_CACHE_CLUSTERS format must include only one cluster
# So remove all but the relevant cluster from the response body
test_cluster = body['CacheClusters'].delete_if do |cluster|
cluster['CacheClusterId'] != CLUSTER_ID
end
body
end
tests(
'#describe_cache_clusters with cluster ID'
).formats(AWS::Elasticache::Formats::DESCRIBE_CACHE_CLUSTERS) do
body = Fog::AWS[:elasticache].describe_cache_clusters(CLUSTER_ID).body
returns(1, "size of 1") { body['CacheClusters'].size }
returns(CLUSTER_ID, "has #{CLUSTER_ID}") do
body['CacheClusters'].first['CacheClusterId']
end
body
end
Fog::Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..."
Fog::AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?}
tests(
'#describe_cache_clusters with node info'
).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do
cluster = Fog::AWS[:elasticache].describe_cache_clusters(CLUSTER_ID,
:show_node_info => true
).body['CacheClusters'].first
returns(NUM_NODES, "has #{NUM_NODES} nodes") do
cluster['CacheNodes'].count
end
cluster
end
tests(
'#modify_cache_cluster - change a non-pending cluster attribute'
).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do
body = Fog::AWS[:elasticache].modify_cache_cluster(CLUSTER_ID,
:auto_minor_version_upgrade => false
).body
# now check that parameter change is in place
returns('false') { body['CacheCluster']['AutoMinorVersionUpgrade'] }
body['CacheCluster']
end
tests(
'#reboot_cache_cluster - reboot a node'
).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do
c = Fog::AWS[:elasticache].clusters.get(CLUSTER_ID)
node_id = c.nodes.last['CacheNodeId']
Fog::Formatador.display_line "Rebooting node #{node_id}..."
body = Fog::AWS[:elasticache].reboot_cache_cluster(c.id, [ node_id ]).body
returns('rebooting cache cluster nodes') do
body['CacheCluster']['CacheClusterStatus']
end
body['CacheCluster']
end
Fog::Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..."
Fog::AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?}
tests(
'#modify_cache_cluster - remove a node'
).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do
c = Fog::AWS[:elasticache].clusters.get(CLUSTER_ID)
node_id = c.nodes.last['CacheNodeId']
Fog::Formatador.display_line "Removing node #{node_id}..."
body = Fog::AWS[:elasticache].modify_cache_cluster(c.id,
{
:num_nodes => NUM_NODES - 1,
:nodes_to_remove => [node_id],
:apply_immediately => true,
}).body
returns(node_id) {
body['CacheCluster']['PendingModifiedValues']['CacheNodeId']
}
body['CacheCluster']
end
Fog::Formatador.display_line "Waiting for cluster #{CLUSTER_ID}..."
Fog::AWS[:elasticache].clusters.get(CLUSTER_ID).wait_for {ready?}
tests(
'#delete_cache_clusters'
).formats(AWS::Elasticache::Formats::CACHE_CLUSTER_RUNNING) do
body = Fog::AWS[:elasticache].delete_cache_cluster(CLUSTER_ID).body
# make sure this particular cluster is in the returned list
returns(true, "has #{CLUSTER_ID}") do
body['CacheClusters'].any? do |cluster|
cluster['CacheClusterId'] == CLUSTER_ID
end
end
# now check that it reports itself as 'deleting'
cluster = body['CacheClusters'].find do |cluster|
cluster['CacheClusterId'] == CLUSTER_ID
end
returns('deleting') { cluster['CacheClusterStatus'] }
cluster
end
end
tests('failure') do
# TODO:
# Create a duplicate cluster ID
# List a missing cache cluster
# Delete a missing cache cluster
end
end
fog-aws-0.7.6/tests/requests/elasticache/subnet_group_tests.rb 0000644 0000041 0000041 00000003755 12576636531 024714 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | subnet group requests', ['aws', 'elasticache']) do
# random_differentiator
# Useful when rapidly re-running tests, so we don't have to wait
# serveral minutes for deleted VPCs/subnets to disappear
suffix = rand(65536).to_s(16)
@subnet_group_name = "fog-test-#{suffix}"
vpc_range = rand(245) + 10
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => "10.#{vpc_range}.0.0/16")
# Create 4 subnets in this VPC, each one in a different AZ
subnet_az = 'us-east-1a'
subnet_range = 8
@subnets = (1..4).map do
subnet = Fog::Compute[:aws].create_subnet(@vpc.id, "10.#{vpc_range}.#{subnet_range}.0/24",
'AvailabilityZone' => subnet_az).body['subnet']
subnet_az = subnet_az.succ
subnet_range *= 2
subnet
end
tests('success') do
subnet_ids = @subnets.map { |sn| sn['subnetId'] }.to_a
tests("#create_cache_subnet_group").formats(AWS::Elasticache::Formats::CREATE_CACHE_SUBNET_GROUP) do
result = Fog::AWS[:elasticache].create_cache_subnet_group(@subnet_group_name, subnet_ids, 'A subnet group').body
returns(@subnet_group_name) { result['CreateCacheSubnetGroupResult']['CacheSubnetGroup']['CacheSubnetGroupName'] }
returns('A subnet group') { result['CreateCacheSubnetGroupResult']['CacheSubnetGroup']['CacheSubnetGroupDescription'] }
returns(@vpc.id) { result['CreateCacheSubnetGroupResult']['CacheSubnetGroup']['VpcId'] }
returns(subnet_ids.sort) { result['CreateCacheSubnetGroupResult']['CacheSubnetGroup']['Subnets'].sort }
result
end
tests("#describe_cache_subnet_groups").formats(AWS::Elasticache::Formats::DESCRIBE_CACHE_SUBNET_GROUPS) do
Fog::AWS[:elasticache].describe_cache_subnet_groups.body
end
tests("#delete_cache_subnet_group").formats(AWS::Elasticache::Formats::BASIC) do
Fog::AWS[:elasticache].delete_cache_subnet_group(@subnet_group_name).body
end
end
@subnets.each do |sn|
Fog::Compute[:aws].delete_subnet(sn['subnetId'])
end
@vpc.destroy
end
fog-aws-0.7.6/tests/requests/cloud_formation/ 0000755 0000041 0000041 00000000000 12576636531 021336 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/cloud_formation/stack_tests.rb 0000644 0000041 0000041 00000011413 12576636531 024212 0 ustar www-data www-data Shindo.tests('AWS::CloudFormation | stack requests', ['aws', 'cloudformation']) do
@validate_template_format = {
'Description' => String,
'Parameters' => [
{
'DefaultValue' => Fog::Nullable::String,
'Description' => String,
'NoEcho' => Fog::Boolean,
'ParameterKey' => String,
}
],
'RequestId' => String
}
@create_stack_format = {
'RequestId' => String,
'StackId' => String
}
@update_stack_format = {
'RequestId' => String,
'StackId' => String
}
@get_template_format = {
'RequestId' => String,
'TemplateBody' => String
}
@describe_stacks_format = {
'RequestId' => String,
'Stacks' => [
{
'CreationTime' => Time,
'DisableRollback' => Fog::Boolean,
'Outputs' => [
{
'OutputKey' => String,
'OutputValue' => String
}
],
'Parameters' => [
{
'ParameterKey' => String,
'ParameterValue' => String,
}
],
'StackId' => String,
'StackName' => String,
'StackStatus' => String,
}
]
}
@describe_stack_events_format = {
'RequestId' => String,
'StackEvents' => [
{
'EventId' => String,
'LogicalResourceId' => String,
'PhysicalResourceId' => String,
'ResourceProperties' => String,
'ResourceStatus' => String,
'ResourceStatusReason' => Fog::Nullable::String,
'ResourceType' => String,
'StackId' => String,
'StackName' => String,
'Timestamp' => Time
}
]
}
@describe_stack_resources_format = {
'RequestId' => String,
'StackResources' => [
{
'LogicalResourceId' => String,
'PhysicalResourceId' => String,
'ResourceStatus' => String,
'ResourceType' => String,
'StackId' => String,
'StackName' => String,
'Timestamp' => Time
}
]
}
tests('success') do
unless Fog.mocking?
@stack_name = 'fogstack' << Time.now.to_i.to_s
@keypair = Fog::Compute[:aws].key_pairs.create(:name => 'cloudformation')
@template_url = 'https://s3.amazonaws.com/cloudformation-templates-us-east-1/EC2InstanceSample-1.0.0.template'
end
tests("validate_template('TemplateURL' => '#{@template_url}')").formats(@validate_template_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].validate_template('TemplateURL' => @template_url).body
end
tests("create_stack('#{@stack_name}', 'TemplateURL' => '#{@template_url}', Parameters => {'KeyName' => 'cloudformation'})").formats(@create_stack_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].create_stack(
@stack_name,
'TemplateURL' => @template_url,
'Parameters' => {'KeyName' => 'cloudformation'}
).body
end
tests("update_stack('#{@stack_name}', 'TemplateURL' => '#{@template_url}', Parameters => {'KeyName' => 'cloudformation'})").formats(@update_stack_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].update_stack(
@stack_name,
'TemplateURL' => @template_url,
'Parameters' => {'KeyName' => 'cloudformation'}
).body
end
tests("get_template('#{@stack_name})").formats(@get_template_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].get_template(@stack_name).body
end
tests("describe_stacks").formats(@describe_stacks_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].describe_stacks.body
end
sleep(1) # avoid throttling
tests("describe_stack_events('#{@stack_name}')").formats(@describe_stack_events_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].describe_stack_events(@stack_name).body
end
tests("describe_stack_resources('StackName' => '#{@stack_name}')").formats(@describe_stack_resources_format) do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].describe_stack_resources('StackName' => @stack_name).body
end
tests("delete_stack('#{@stack_name}')").succeeds do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].delete_stack(@stack_name)
end
tests("list_stacks").succeeds do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].list_stacks.body
end
tests("list_stack_resources").succeeds do
pending if Fog.mocking?
Fog::AWS[:cloud_formation].list_stack_resources("StackName"=>@stack_name).body
end
unless Fog.mocking?
@keypair.destroy
end
end
tests('failure') do
end
end
fog-aws-0.7.6/tests/requests/sns/ 0000755 0000041 0000041 00000000000 12576636531 016755 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/sns/helper.rb 0000644 0000041 0000041 00000000162 12576636531 020560 0 ustar www-data www-data class AWS
module SNS
module Formats
BASIC = {
'RequestId' => String
}
end
end
end
fog-aws-0.7.6/tests/requests/sns/topic_tests.rb 0000644 0000041 0000041 00000003561 12576636531 021647 0 ustar www-data www-data Shindo.tests('AWS::SNS | topic lifecycle tests', ['aws', 'sns']) do
tests('success') do
tests("#create_topic('fog_topic_tests')").formats(AWS::SNS::Formats::BASIC.merge('TopicArn' => String)) do
body = Fog::AWS[:sns].create_topic('fog_topic_tests').body
@topic_arn = body["TopicArn"]
body
end
tests("#list_topics").formats(AWS::SNS::Formats::BASIC.merge('Topics' => [String])) do
Fog::AWS[:sns].list_topics.body
end
tests("#set_topic_attributes('#{@topic_arn}', 'DisplayName', 'other-fog_topic_tests')").formats(AWS::SNS::Formats::BASIC) do
Fog::AWS[:sns].set_topic_attributes(@topic_arn, 'DisplayName', 'other-fog_topic_tests').body
end
get_topic_attributes_format = AWS::SNS::Formats::BASIC.merge({
'Attributes' => {
'DisplayName' => String,
'Owner' => String,
'Policy' => String,
'SubscriptionsConfirmed' => Integer,
'SubscriptionsDeleted' => Integer,
'SubscriptionsPending' => Integer,
'TopicArn' => String
}
})
tests("#get_topic_attributes('#{@topic_arn})").formats(get_topic_attributes_format) do
Fog::AWS[:sns].get_topic_attributes(@topic_arn).body
end
tests("#add_permission('#{@topic_arn}')").formats(AWS::SNS::Formats::BASIC) do
Fog::AWS[:sns].add_permission('TopicArn' => @topic_arn, 'Label' => 'Test', 'ActionName.member.1' => 'Subscribe', 'AWSAccountId.member.1' => '1234567890').body
end
tests("#remove_permission('#{@topic_arn}')").formats(AWS::SNS::Formats::BASIC) do
Fog::AWS[:sns].remove_permission('TopicArn' => @topic_arn, 'Label' => 'Test').body
end
tests("#delete_topic('#{@topic_arn}')").formats(AWS::SNS::Formats::BASIC) do
Fog::AWS[:sns].delete_topic(@topic_arn).body
end
end
tests('failure') do
end
end
fog-aws-0.7.6/tests/requests/sns/subscription_tests.rb 0000644 0000041 0000041 00000005313 12576636531 023252 0 ustar www-data www-data Shindo.tests('AWS::SES | topic lifecycle tests', ['aws', 'sns']) do
unless Fog.mocking?
@topic_arn = Fog::AWS[:sns].create_topic('fog_subscription_tests').body['TopicArn']
@queue_url = Fog::AWS[:sqs].create_queue('fog_subscription_tests').body['QueueUrl']
@queue_arn = Fog::AWS[:sqs].get_queue_attributes(@queue_url, 'QueueArn').body['Attributes']['QueueArn']
Fog::AWS[:sqs].set_queue_attributes(
@queue_url,
'Policy',
Fog::JSON.encode({
'Id' => @topic_arn,
'Statement' => {
'Action' => 'sqs:SendMessage',
'Condition' => {
'StringEquals' => { 'aws:SourceArn' => @topic_arn }
},
'Effect' => 'Allow',
'Principal' => { 'AWS' => '*' },
'Resource' => @queue_arn,
'Sid' => "#{@topic_arn}+sqs:SendMessage"
},
'Version' => '2008-10-17'
})
)
end
tests('success') do
tests("#subscribe('#{@topic_arn}', '#{@queue_arn}', 'sqs')").formats(AWS::SNS::Formats::BASIC.merge('SubscriptionArn' => String)) do
pending if Fog.mocking?
body = Fog::AWS[:sns].subscribe(@topic_arn, @queue_arn, 'sqs').body
@subscription_arn = body['SubscriptionArn']
body
end
list_subscriptions_format = AWS::SNS::Formats::BASIC.merge({
'Subscriptions' => [{
'Endpoint' => String,
'Owner' => String,
'Protocol' => String,
'SubscriptionArn' => String,
'TopicArn' => String
}]
})
tests("#list_subscriptions").formats(list_subscriptions_format) do
pending if Fog.mocking?
Fog::AWS[:sns].list_subscriptions.body
end
tests("#list_subscriptions_by_topic('#{@topic_arn}')").formats(list_subscriptions_format) do
pending if Fog.mocking?
body = Fog::AWS[:sns].list_subscriptions_by_topic(@topic_arn).body
end
tests("#publish('#{@topic_arn}', 'message')").formats(AWS::SNS::Formats::BASIC.merge('MessageId' => String)) do
pending if Fog.mocking?
body = Fog::AWS[:sns].publish(@topic_arn, 'message').body
end
tests("#receive_message('#{@queue_url}')...").returns('message') do
pending if Fog.mocking?
message = nil
Fog.wait_for do
message = Fog::AWS[:sqs].receive_message(@queue_url).body['Message'].first
end
Fog::JSON.decode(message['Body'])['Message']
end
tests("#unsubscribe('#{@subscription_arn}')").formats(AWS::SNS::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:sns].unsubscribe(@subscription_arn).body
end
end
tests('failure') do
end
unless Fog.mocking?
Fog::AWS[:sns].delete_topic(@topic_arn)
Fog::AWS[:sqs].delete_queue(@queue_url)
end
end
fog-aws-0.7.6/tests/requests/iam/ 0000755 0000041 0000041 00000000000 12576636531 016720 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/iam/helper.rb 0000644 0000041 0000041 00000014535 12576636531 020534 0 ustar www-data www-data class AWS
module IAM
# A self-signed test keypair. Generated using the command:
# openssl req -new -newkey rsa:1024 -days 3650 -nodes -x509 -keyout server-private.key -out server-public.crt
# NB: Amazon returns an error on extraneous linebreaks
SERVER_CERT = %{-----BEGIN CERTIFICATE-----
MIIDQzCCAqygAwIBAgIJAJaZ8wH+19AtMA0GCSqGSIb3DQEBBQUAMHUxCzAJBgNV
BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazERMA8GA1UEBxMITmV3IFlvcmsxHzAd
BgNVBAoTFkZvZyBUZXN0IFNuYWtlb2lsIENlcnQxHzAdBgNVBAsTFkZvZyBUZXN0
IFNuYWtlb2lsIENlcnQwHhcNMTEwNTA3MTc0MDU5WhcNMjEwNTA0MTc0MDU5WjB1
MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxETAPBgNVBAcTCE5ldyBZ
b3JrMR8wHQYDVQQKExZGb2cgVGVzdCBTbmFrZW9pbCBDZXJ0MR8wHQYDVQQLExZG
b2cgVGVzdCBTbmFrZW9pbCBDZXJ0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPctxPL5U4vaMxQU
boLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUMbZbBQ8PVd9Sd
k+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQABo4HaMIHXMB0G
A1UdDgQWBBRfqBkpU/jEV324748fq6GJM80iVTCBpwYDVR0jBIGfMIGcgBRfqBkp
U/jEV324748fq6GJM80iVaF5pHcwdTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l
dyBZb3JrMREwDwYDVQQHEwhOZXcgWW9yazEfMB0GA1UEChMWRm9nIFRlc3QgU25h
a2VvaWwgQ2VydDEfMB0GA1UECxMWRm9nIFRlc3QgU25ha2VvaWwgQ2VydIIJAJaZ
8wH+19AtMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAUV6NDdLHKNhl
ACtzLycIhlMTmDr0xBeIBx3lpgw2K0+4oefMS8Z17eeZPeNodxnz56juJm81BZwt
DF3qnnPyArLFx0HLB7wQdm9xYVIqQuLO+V6GRuOd+uSX//aDLDZhwbERf35hoyto
Jfk4gX/qwuRFNy0vjQeTzdvhB1igG/w=
-----END CERTIFICATE-----
}
# The public key for SERVER_CERT. Generated using the command:
# openssl x509 -inform pem -in server-public.crt -pubkey -noout > server.pubkey
SERVER_CERT_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPctxPL5U4vaMxQUboLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUMbZbBQ8PVd9Sdk+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQAB"
SERVER_CERT_PRIVATE_KEY = %{-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC0CR76sovjdmpWRmEaf8XaG+nGe7czhpdLKkau2b16VtSjkPct
xPL5U4vaMxQUboLPr+9oL+9fSYN31VzDD4hyaeGoeI5fhnGeqk71kq5uHONBOQUM
bZbBQ8PVd9Sdk+y9JJ6E5fC+GhLL5I+y2DK7syBzyymq1Wi6rPp1XXF7AQIDAQAB
AoGANjjRBbwkeXs+h4Fm2W5GDmx9ufOkt3X/tvmilCKr+F6SaDjO2RAKBaFt62ea
0pR9/UMFnaFiPJaNa9fsuirBcwId+RizruEp+7FGziM9mC5kcE7WKZrXgGGnLtqg
4x5twVLArgp0ji7TA18q/74uTrI4az8H5iTY4n29ORlLmmkCQQDsGMuLEgGHgN5Y
1c9ax1DT/rUXKxnqsIrijRkgbiTncHAArFJ88c3yykWqGvYnSFwMS8DSWiPyPaAI
nNNlb/fPAkEAwzZ4CfvJ+OlE++rTPH9jemC89dnxC7EFGuWJmwdadnev8EYguvve
cdGdGttD7QsZKpcz5mDngOUghbVm8vBELwJAMHfOoVgq9DRicP5DuTEdyMeLSZxR
j7p6aJPqypuR++k7NQgrTvcc/nDD6G3shpf2PZf3l7dllb9M8TewtixMRQJBAIdX
c0AQtoYBTJePxiYyd8i32ypkkK83ar+sFoxKO9jYwD1IkZax2xZ0aoTdMindQPR7
Yjs+QiLmOHcbPqX+GHcCQERsSn0RjzKmKirDntseMB59BB/cEN32+gMDVsZuCfb+
fOy2ZavFl13afnhbh2/AjKeDhnb19x/uXjF7JCUtwpA=
-----END RSA PRIVATE KEY-----
}
# openssl pkcs8 -nocrypt -topk8 -in SERVER_CERT_PRIVATE_KEY.key -outform pem
SERVER_CERT_PRIVATE_KEY_PKCS8 = %{-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQJHvqyi+N2alZG
YRp/xdob6cZ7tzOGl0sqRq7ZvXpW1KOQ9y3E8vlTi9ozFBRugs+v72gv719Jg3fV
XMMPiHJp4ah4jl+GcZ6qTvWSrm4c40E5BQxtlsFDw9V31J2T7L0knoTl8L4aEsvk
j7LYMruzIHPLKarVaLqs+nVdcXsBAgMBAAECgYA2ONEFvCR5ez6HgWbZbkYObH25
86S3df+2+aKUIqv4XpJoOM7ZEAoFoW3rZ5rSlH39QwWdoWI8lo1r1+y6KsFzAh35
GLOu4Sn7sUbOIz2YLmRwTtYpmteAYacu2qDjHm3BUsCuCnSOLtMDXyr/vi5Osjhr
PwfmJNjifb05GUuaaQJBAOwYy4sSAYeA3ljVz1rHUNP+tRcrGeqwiuKNGSBuJOdw
cACsUnzxzfLKRaoa9idIXAxLwNJaI/I9oAic02Vv988CQQDDNngJ+8n46UT76tM8
f2N6YLz12fELsQUa5YmbB1p2d6/wRiC6+95x0Z0a20PtCxkqlzPmYOeA5SCFtWby
8EQvAkAwd86hWCr0NGJw/kO5MR3Ix4tJnFGPunpok+rKm5H76Ts1CCtO9xz+cMPo
beyGl/Y9l/eXt2WVv0zxN7C2LExFAkEAh1dzQBC2hgFMl4/GJjJ3yLfbKmSQrzdq
v6wWjEo72NjAPUiRlrHbFnRqhN0yKd1A9HtiOz5CIuY4dxs+pf4YdwJARGxKfRGP
MqYqKsOe2x4wHn0EH9wQ3fb6AwNWxm4J9v587LZlq8WXXdp+eFuHb8CMp4OGdvX3
H+5eMXskJS3CkA==
-----END PRIVATE KEY-----
}
SERVER_CERT_PRIVATE_KEY_MISMATCHED = %{-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAyITMqYJMzkPMcaC+x0W2hnZVW99RXzLR8RYyD3xo2AotdJKx
1DXR4ryegAjsnAhJVwVtxqzPcBMq/XS0hNtWFfKzf+vMZl7uAqotGjURUV8SRQPA
8tT07MemD929xRSV2vTnVATiPn87vcu5igsZ01+Ewd6rGythmvcZD13vtZ4rx0c8
kQJV3ok/CkFaIgDR6Or1NZBCtcIVK9nvqAmYMp6S5mWUMIsl/1qYPerpefrSJjlk
J2+jyLp0LHarbzjkzzAdOkBRX1hPkk6cisBeQIpx35shLzfCe8U25XNqquP+ftcu
JZ0Wjw+C4pTIzfgdGXmGGtBFY13BwiJvd4/i2wIDAQABAoIBABk8XWWX+IKdFcXX
LSt3IpmZmvSNDniktLday8IXLjrCTSY2sBq9C0U159zFQsIAaPqCvGYcqZ65StfL
MEzoLdVlTiHzUy4vFFVRhYue0icjh/EXn9jv5ENIfSXSCmgbRyDfYZ25X5/t817X
nOo6q21mwBaGJ5KrywTtxEGi2OBKZrIbBrpJLhCXJc5xfuKT6DRa9X/OBSBiGKJP
V9wHcZJkPG1HnC8izvQ37kNN/NyYE+8AGdYXQVNbTHq/emNLbEbdcR3tpGZamM9Q
TwG5WsDPAnXnRsEEYvlVTOBI6DqdvkyBxM35iqd5aAc6i/Iu04Unfhhc5pAXmmIB
a22GHcECgYEA7OheVHDDP8quO2qZjqaTlMbMnXnrFXJ41llFMoivTW9EmlTl9dOC
fnkHEBcFCTPV0m6S2AQjt9QOgPqCFAq1r3J/xvEGBtl/UKnPRmjqXFgl0ENtGn5t
w9wj/CsOPD05KkXXtXP+MyLPRD6gAxiQCTnXjvsLuVfP+E9BO2EQXScCgYEA2K2x
QtcAAalrk3c0KzNVESzyFlf3ddEXThShVblSa7r6Ka9q9sxN/Xe2B+1oemPJm26G
PfqKgxdKX0R0jl4f5pRBWKoarzWtUge/su8rx/xzbY/1hFKVuimtc6oTeU5xsOTS
PVuCz4bxDTVhrbmKqbmMgqy17jfPA4BrF1FMRS0CgYBdMA4i4vQ6fIxKfOUIMsfs
hsJn01RAbHXRwu2wMgnayMDQgEKwjtFO1GaN0rA9bXFXQ/1pET/HiJdn7qIKJihP
aheO9rHrMdSdsx4AUTaWummtYUhiWobsuwRApeMEmQSKd0yhaI3+KVwkOQoSDbBi
oKkE6gUzk7IPt4UuSUD5kwKBgQCjo/IGr8dieegz08gDhF4PfalLdJ4ATaxTHMOH
sVFs6SY7Sy72Ou//qGRCcmsAW9KL35nkvw3S2Ukiz9lTGATxqC/93WIPxvMhy5Zc
dcLT43XtXdanW5OWqBlGDEFu0O6OERIyoqUVRC1Ss2kUwdbWPbq/id5Qjbd7RoYa
cxyt9QKBgF4bFLw1Iw2RBngQxIzoDbElEqme20FUyGGzyFQtxVwmwNr4OY5UzJzX
7G6diyzGrvRX81Yw616ppKJUJVr/zRc13K+eRXXKtNpGkf35B+1NDDjjWZpIHqgx
Xb9WSr07saxZQbxBPQyTlb0Q9Tu2djAq2/o/nYD1/50/fXUTuWMB
-----END RSA PRIVATE KEY-----
}
module Formats
BASIC = {
'RequestId' => String
}
USER = {
'Arn' => String,
'Path' => String,
'UserId' => String,
'UserName' => String,
}
CREATE_USER = BASIC.merge('User' => USER)
GET_USER = BASIC.merge('User' => USER.merge('CreateDate' => Time))
GET_CURRENT_USER = BASIC.merge(
'User' => {
'Arn' => String,
'UserId' => String,
'CreateDate' => Time
}
)
LIST_USER = BASIC.merge(
'Users' => [USER.merge('CreateDate' => Time)],
'IsTruncated' => Fog::Boolean
)
GROUPS = BASIC.merge(
'GroupsForUser' => [{
'Arn' => String,
'GroupId' => String,
'GroupName' => String,
'Path' => String
}],
'IsTruncated' => Fog::Boolean
)
end
end
end
fog-aws-0.7.6/tests/requests/iam/account_policy_tests.rb 0000644 0000041 0000041 00000002326 12576636531 023505 0 ustar www-data www-data Shindo.tests('AWS::IAM | account policy requests', ['aws']) do
tests('success') do
tests("#update_account_password_policy(minimum_password_length, max_password_age, password_reuse_prevention,require_symbols,require_numbers,require_uppercase_characters, require_lowercase_characters,allow_users_to_change_password, hard_expiry, expire_passwords)").formats(AWS::IAM::Formats::BASIC) do
minimum_password_length, password_reuse_prevention, max_password_age = 5
require_symbols, require_numbers, require_uppercase_characters, require_lowercase_characters, allow_users_to_change_password, hard_expiry, expire_passwords = false
Fog::AWS[:iam].update_account_password_policy(minimum_password_length, max_password_age, password_reuse_prevention,require_symbols,require_numbers,require_uppercase_characters, require_lowercase_characters,allow_users_to_change_password, hard_expiry, expire_passwords).body
end
tests("#get_account_password_policy()") do
Fog::AWS[:iam].get_account_password_policy().body['AccountPasswordPolicy']
end
tests("#delete_account_password_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_account_password_policy().body
end
end
end
fog-aws-0.7.6/tests/requests/iam/role_tests.rb 0000644 0000041 0000041 00000011442 12576636531 021432 0 ustar www-data www-data Shindo.tests('AWS::IAM | role requests', ['aws']) do
tests('success') do
@role = {
'Arn' => String,
'AssumeRolePolicyDocument' => String,
'CreateDate' => Time,
'Path' => String,
'RoleId' => String,
'RoleName' => String
}
@role_format = {
'Role' => @role,
'RequestId' => String
}
tests("#create_role('fogrole')").formats(@role_format) do
Fog::AWS[:iam].create_role('fogrole', Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY).body
end
tests("#get_role('fogrole')").formats(@role_format) do
Fog::AWS[:iam].get_role('fogrole').body
end
@list_roles_format = {
'Roles' => [@role],
'RequestId' => String,
'IsTruncated' => Fog::Boolean,
}
tests("#list_roles").formats(@list_roles_format) do
body = Fog::AWS[:iam].list_roles.body
returns(true){!! body['Roles'].find {|role| role['RoleName'] == 'fogrole'}}
body
end
@profile_format = {
'InstanceProfile' => {
'Arn' => String,
'CreateDate' => Time,
'Path' => String,
'InstanceProfileId' => String,
'InstanceProfileName' => String,
'Roles' => [@role]
},
'RequestId' => String
}
tests("#create_instance_profile('fogprofile')").formats(@profile_format) do
pending if Fog.mocking?
Fog::AWS[:iam].create_instance_profile('fogprofile').body
end
tests("#get_instance_profile('fogprofile')").formats(@profile_format) do
pending if Fog.mocking?
Fog::AWS[:iam].get_instance_profile('fogprofile').body
end
tests("#add_role_to_instance_profile('fogprofile','fogrole')").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].add_role_to_instance_profile('fogrole', 'fogprofile').body
end
@profiles_format = {
'InstanceProfiles' => [{
'Arn' => String,
'CreateDate' => Time,
'Path' => String,
'InstanceProfileId' => String,
'InstanceProfileName' => String,
'Roles' => [@role]
}],
'IsTruncated' => Fog::Boolean,
'RequestId' => String
}
tests("list_instance_profiles_for_role('fogrole')").formats(@profiles_format) do
pending if Fog.mocking?
body = Fog::AWS[:iam].list_instance_profiles_for_role('fogrole').body
returns(['fogprofile']) { body['InstanceProfiles'].map {|hash| hash['InstanceProfileName']}}
body
end
tests("list_instance_profiles").formats(@profiles_format) do
pending if Fog.mocking?
Fog::AWS[:iam].list_instance_profiles.body
end
sample_policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
tests("put_role_policy").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].put_role_policy('fogrole', 'fogpolicy', sample_policy).body
end
@get_role_policy_format = {
'Policy' => {
'RoleName' => String,
'PolicyName' => String,
'PolicyDocument' => Hash,
},
'RequestId' => String
}
tests("get_role_policy").formats(@get_role_policy_format) do
pending if Fog.mocking?
body = Fog::AWS[:iam].get_role_policy('fogrole','fogpolicy').body
returns('fogpolicy') {body['Policy']['PolicyName']}
returns(sample_policy){body['Policy']['PolicyDocument']}
body
end
@list_role_policies_format = {
'PolicyNames' => [String],
'IsTruncated' => Fog::Boolean,
'RequestId' => String
}
tests("list_role_policies").formats(@list_role_policies_format) do
pending if Fog.mocking?
body = Fog::AWS[:iam].list_role_policies('fogrole').body
returns(['fogpolicy']) {body['PolicyNames']}
body
end
tests("delete_role_policy").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].delete_role_policy('fogrole', 'fogpolicy').body
end
returns([]) do
pending if Fog.mocking?
Fog::AWS[:iam].list_role_policies('fogrole').body['PolicyNames']
end
tests("remove_role_from_instance_profile").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].remove_role_from_instance_profile('fogrole', 'fogprofile').body
end
returns([]) do
pending if Fog.mocking?
Fog::AWS[:iam].list_instance_profiles_for_role('fogrole').body['InstanceProfiles']
end
tests("#delete_instance_profile('fogprofile'").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].delete_instance_profile('fogprofile').body
end
tests("#delete_role('fogrole'").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_role('fogrole').body
end
end
end
fog-aws-0.7.6/tests/requests/iam/group_policy_tests.rb 0000644 0000041 0000041 00000002773 12576636531 023213 0 ustar www-data www-data Shindo.tests('AWS::IAM | group policy requests', ['aws']) do
Fog::AWS[:iam].create_group('fog_group_policy_tests')
tests('success') do
@policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
tests("#put_group_policy('fog_group_policy_tests', 'fog_policy', #{@policy.inspect})").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].put_group_policy('fog_group_policy_tests', 'fog_policy', @policy).body
end
@group_policies_format = {
'IsTruncated' => Fog::Boolean,
'PolicyNames' => [String],
'RequestId' => String
}
tests("list_group_policies('fog_group_policy_tests')").formats(@group_policies_format) do
pending if Fog.mocking?
Fog::AWS[:iam].list_group_policies('fog_group_policy_tests').body
end
@group_policy_format = {
'GroupName' => String,
'PolicyName' => String,
'PolicyDocument' => Hash,
}
tests("#get_group_policy('fog_group_policy_tests', 'fog_policy'").formats(@group_policy_format) do
Fog::AWS[:iam].get_group_policy('fog_policy', 'fog_group_policy_tests').body['Policy']
end
tests("#delete_group_policy('fog_group_policy_tests', 'fog_policy')").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].delete_group_policy('fog_group_policy_tests', 'fog_policy').body
end
end
tests('failure') do
test('failing conditions')
end
unless Fog.mocking?
Fog::AWS[:iam].delete_group('fog_group_policy_tests')
end
end
fog-aws-0.7.6/tests/requests/iam/login_profile_tests.rb 0000644 0000041 0000041 00000003603 12576636531 023321 0 ustar www-data www-data Shindo.tests('AWS::IAM | user requests', ['aws']) do
unless Fog.mocking?
Fog::AWS[:iam].create_user('fog_user')
end
tests('success') do
@login_profile_format = {
'LoginProfile' => {
'UserName' => String,
'CreateDate' => Time
},
'RequestId' => String
}
tests("#create_login_profile('fog_user')").formats(@login_profile_format) do
pending if Fog.mocking?
Fog::AWS[:iam].create_login_profile('fog_user', 'somepassword').body
end
tests("#get_login_profile('fog_user')").formats(@login_profile_format) do
pending if Fog.mocking?
result = Fog::AWS[:iam].get_login_profile('fog_user').body
returns('fog_user') {result['LoginProfile']['UserName']}
result
end
tests("#update_login_profile('fog_user')").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
begin
Fog::AWS[:iam].update_login_profile('fog_user', 'otherpassword').body
rescue Excon::Errors::Conflict #profile cannot be updated or deleted until it has finished creating; api provides no way of telling whether creation process complete
sleep 5
retry
end
end
tests("#delete_login_profile('fog_user')").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].delete_login_profile('fog_user').body
end
tests("#get_login_profile('fog_user')") do
pending if Fog.mocking?
raises(Excon::Errors::NotFound) {Fog::AWS[:iam].get_login_profile('fog_user')}
end
end
tests('failure') do
tests('get login profile for non existing user') do
pending if Fog.mocking?
raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:iam].get_login_profile('idontexist')}
raises(Fog::AWS::IAM::NotFound) { Fog::AWS[:iam].delete_login_profile('fog_user')}
end
end
unless Fog.mocking?
Fog::AWS[:iam].delete_user('fog_user')
end
end
fog-aws-0.7.6/tests/requests/iam/mfa_tests.rb 0000644 0000041 0000041 00000000763 12576636531 021240 0 ustar www-data www-data Shindo.tests('AWS::IAM | mfa requests', ['aws']) do
tests('success') do
@mfa_devices_format = {
'MFADevices' => [{
'EnableDate' => Time,
'SerialNumber' => String,
'UserName' => String
}],
'IsTruncated' => Fog::Boolean,
'RequestId' => String
}
tests('#list_mfa_devices').formats(@mfa_devices_format) do
Fog::AWS[:iam].list_mfa_devices.body
end
end
tests('failure') do
test('failing conditions')
end
end
fog-aws-0.7.6/tests/requests/iam/access_key_tests.rb 0000644 0000041 0000041 00000003225 12576636531 022602 0 ustar www-data www-data Shindo.tests('AWS::IAM | access key requests', ['aws']) do
Fog::AWS[:iam].create_user('fog_access_key_tests')
tests('success') do
@access_key_format = {
'AccessKey' => {
'AccessKeyId' => String,
'UserName' => String,
'SecretAccessKey' => String,
'Status' => String
},
'RequestId' => String
}
tests("#create_access_key('UserName' => 'fog_access_key_tests')").formats(@access_key_format) do
data = Fog::AWS[:iam].create_access_key('UserName' => 'fog_access_key_tests').body
@access_key_id = data['AccessKey']['AccessKeyId']
data
end
@access_keys_format = {
'AccessKeys' => [{
'AccessKeyId' => String,
'Status' => String
}],
'IsTruncated' => Fog::Boolean,
'RequestId' => String
}
tests("#list_access_keys('Username' => 'fog_access_key_tests')").formats(@access_keys_format) do
Fog::AWS[:iam].list_access_keys('UserName' => 'fog_access_key_tests').body
end
tests("#update_access_key('#{@access_key_id}', 'Inactive', 'UserName' => 'fog_access_key_tests')").formats(AWS::IAM::Formats::BASIC) do
pending if Fog.mocking?
Fog::AWS[:iam].update_access_key(@access_key_id, 'Inactive', 'UserName' => 'fog_access_key_tests').body
end
tests("#delete_access_key('#{@access_key_id}', 'UserName' => 'fog_access_key_tests)").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_access_key(@access_key_id, 'UserName' => 'fog_access_key_tests').body
end
end
tests('failure') do
test('failing conditions')
end
Fog::AWS[:iam].delete_user('fog_access_key_tests')
end
fog-aws-0.7.6/tests/requests/iam/server_certificate_tests.rb 0000644 0000041 0000041 00000011472 12576636531 024344 0 ustar www-data www-data Shindo.tests('AWS::IAM | server certificate requests', ['aws']) do
@key_name = 'fog-test'
@key_name_chained = 'fog-test-chained'
@certificate_format = {
'Arn' => String,
'Path' => String,
'ServerCertificateId' => String,
'ServerCertificateName' => String,
'UploadDate' => Time
}
@upload_format = {
'Certificate' => @certificate_format,
'RequestId' => String
}
@update_format = {
'RequestId' => String
}
@get_server_certificate_format = {
'Certificate' => @certificate_format,
'RequestId' => String
}
@list_format = {
'Certificates' => [@certificate_format]
}
tests('#upload_server_certificate') do
public_key = AWS::IAM::SERVER_CERT
private_key = AWS::IAM::SERVER_CERT_PRIVATE_KEY
private_key_pkcs8 = AWS::IAM::SERVER_CERT_PRIVATE_KEY_PKCS8
private_key_mismatch = AWS::IAM::SERVER_CERT_PRIVATE_KEY_MISMATCHED
tests('empty public key').raises(Fog::AWS::IAM::ValidationError) do
Fog::AWS::IAM.new.upload_server_certificate('', private_key, @key_name)
end
tests('empty private key').raises(Fog::AWS::IAM::ValidationError) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, '', @key_name)
end
tests('invalid public key').raises(Fog::AWS::IAM::MalformedCertificate) do
Fog::AWS::IAM.new.upload_server_certificate('abcde', private_key, @key_name)
end
tests('invalid private key').raises(Fog::AWS::IAM::MalformedCertificate) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, 'abcde', @key_name)
end
tests('non-RSA private key').raises(Fog::AWS::IAM::MalformedCertificate) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key_pkcs8, @key_name)
end
tests('mismatched private key').raises(Fog::AWS::IAM::KeyPairMismatch) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key_mismatch, @key_name)
end
tests('format').formats(@upload_format) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name).body
end
tests('format with chain').formats(@upload_format) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name_chained, { 'CertificateChain' => public_key }).body
end
tests('duplicate name').raises(Fog::AWS::IAM::EntityAlreadyExists) do
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, @key_name)
end
end
tests('#update_server_certificate') do
public_key = AWS::IAM::SERVER_CERT
private_key = AWS::IAM::SERVER_CERT_PRIVATE_KEY
key_name = "update-key"
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, key_name)
tests('duplicate name').raises(Fog::AWS::IAM::EntityAlreadyExists) do
other_key_name = "other-key-name"
Fog::AWS::IAM.new.upload_server_certificate(public_key, private_key, other_key_name)
Fog::AWS::IAM.new.update_server_certificate(key_name, {'NewServerCertificateName' => other_key_name})
end
tests('unknown name').raises(Fog::AWS::IAM::NotFound) do
Fog::AWS::IAM.new.update_server_certificate("unknown-key-name", {'NewServerCertificateName' => "other-keyname"})
end
tests('format').formats(@update_format) do
Fog::AWS::IAM.new.update_server_certificate(key_name).body
end
tests('updates name') do
other_key_name = "successful-update-key-name"
Fog::AWS::IAM.new.update_server_certificate(key_name, {'NewServerCertificateName' => other_key_name})
returns(true) { Fog::AWS::IAM.new.get_server_certificate(other_key_name).body['Certificate']['ServerCertificateName'] == other_key_name }
end
end
tests('#get_server_certificate').formats(@get_server_certificate_format) do
tests('raises NotFound').raises(Fog::AWS::IAM::NotFound) do
Fog::AWS::IAM.new.get_server_certificate("#{@key_name}fake")
end
Fog::AWS::IAM.new.get_server_certificate(@key_name).body
end
tests('#list_server_certificates').formats(@list_format) do
result = Fog::AWS::IAM.new.list_server_certificates.body
tests('includes key name') do
returns(true) { result['Certificates'].any?{|c| c['ServerCertificateName'] == @key_name} }
end
result
end
tests("#list_server_certificates('path-prefix' => '/'").formats(@list_format) do
result = Fog::AWS::IAM.new.list_server_certificates('PathPrefix' => '/').body
tests('includes key name') do
returns(true) { result['Certificates'].any?{|c| c['ServerCertificateName'] == @key_name} }
end
result
end
tests('#delete_server_certificate').formats(AWS::IAM::Formats::BASIC) do
tests('raises NotFound').raises(Fog::AWS::IAM::NotFound) do
Fog::AWS::IAM.new.delete_server_certificate("#{@key_name}fake")
end
Fog::AWS::IAM.new.delete_server_certificate(@key_name).body
end
Fog::AWS::IAM.new.delete_server_certificate(@key_name_chained)
end
fog-aws-0.7.6/tests/requests/iam/group_tests.rb 0000644 0000041 0000041 00000001715 12576636531 021627 0 ustar www-data www-data Shindo.tests('AWS::IAM | group requests', ['aws']) do
tests('success') do
@group_format = {
'Group' => {
'Arn' => String,
'GroupId' => String,
'GroupName' => String,
'Path' => String
},
'RequestId' => String
}
tests("#create_group('fog_group')").formats(@group_format) do
Fog::AWS[:iam].create_group('fog_group').body
end
@groups_format = {
'Groups' => [{
'Arn' => String,
'GroupId' => String,
'GroupName' => String,
'Path' => String
}],
'IsTruncated' => Fog::Boolean,
'RequestId' => String
}
tests("#list_groups").formats(@groups_format) do
Fog::AWS[:iam].list_groups.body
end
tests("#delete_group('fog_group')").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_group('fog_group').body
end
end
tests('failure') do
test('failing conditions')
end
end
fog-aws-0.7.6/tests/requests/iam/managed_policy_tests.rb 0000644 0000041 0000041 00000005474 12576636531 023454 0 ustar www-data www-data Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
pending if Fog.mocking?
Fog::AWS[:iam].create_group('fog_policy_test_group')
Fog::AWS[:iam].create_user('fog_policy_test_user')
Fog::AWS[:iam].create_role('fog_policy_test_role', Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY)
tests('success') do
@policy = {'Version' => '2012-10-17', "Statement" => [{"Effect" => "Deny", "Action" => "*", "Resource" => "*"}]}
@policy_format = {
'Arn' => String,
'AttachmentCount' => Integer,
'Description' => String,
'DefaultVersionId' => String,
'IsAttachable' => Fog::Boolean,
'Path' => String,
'PolicyId' => String,
'PolicyName' => String,
'CreateDate' => Time,
'UpdateDate' => Time
}
create_policy_format = {
'RequestId' => String,
'Policy' => @policy_format
}
list_policies_format = {
'RequestId' => String,
'Policies' => [@policy_format],
'Marker' => String,
'IsTruncated' => Fog::Boolean
}
tests("#create_policy('fog_policy')").formats(create_policy_format) do
body = Fog::AWS[:iam].create_policy('fog_policy', @policy, '/fog/').body
puts body.inspect
@policy_arn = body['Policy']['Arn']
body
end
tests("#list_policies()").formats(list_policies_format) do
body = Fog::AWS[:iam].list_policies('PathPrefix' => '/fog/').body
tests('length 1').returns(1) do
body['Policies'].length
end
body
end
tests("#attach_user_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].attach_user_policy('fog_policy_test_user', @policy_arn).body
end
tests("#detach_user_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].detach_user_policy('fog_policy_test_user', @policy_arn).body
end
tests("#attach_group_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].attach_group_policy('fog_policy_test_group', @policy_arn).body
end
tests("#detach_group_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].detach_group_policy('fog_policy_test_group', @policy_arn).body
end
tests("#attach_role_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].attach_role_policy('fog_policy_test_role', @policy_arn).body
end
tests("#detach_role_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].detach_role_policy('fog_policy_test_role', @policy_arn).body
end
tests("#delete_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_policy(@policy_arn).body
end
end
tests('failure') do
test('failing conditions')
end
Fog::AWS[:iam].delete_group('fog_policy_test_group')
Fog::AWS[:iam].delete_user('fog_policy_test_user')
Fog::AWS[:iam].delete_role('fog_policy_test_role')
end
fog-aws-0.7.6/tests/requests/iam/account_tests.rb 0000644 0000041 0000041 00000002324 12576636531 022124 0 ustar www-data www-data Shindo.tests('AWS::IAM | account requests', ['aws']) do
tests('success') do
@get_account_summary_format = {
'Summary' => {
'AccessKeysPerUserQuota' => Integer,
'AccountMFAEnabled' => Integer,
'AssumeRolePolicySizeQuota' => Fog::Nullable::Integer,
'GroupPolicySizeQuota' => Integer,
'Groups' => Integer,
'GroupsPerUserQuota' => Integer,
'GroupsQuota' => Integer,
'InstanceProfiles' => Fog::Nullable::Integer,
'InstanceProfilesQuota' => Fog::Nullable::Integer,
'MFADevices' => Integer,
'MFADevicesInUse' => Integer,
'Providers' => Fog::Nullable::Integer,
'RolePolicySizeQuota' => Fog::Nullable::Integer,
'Roles' => Fog::Nullable::Integer,
'RolesQuota' => Fog::Nullable::Integer,
'ServerCertificates' => Integer,
'ServerCertificatesQuota' => Integer,
'SigningCertificatesPerUserQuota' => Integer,
'UserPolicySizeQuota' => Integer,
'Users' => Integer,
'UsersQuota' => Integer,
},
'RequestId' => String,
}
tests('#get_account_summary').formats(@get_account_summary_format) do
Fog::AWS[:iam].get_account_summary.body
end
end
end
fog-aws-0.7.6/tests/requests/iam/user_policy_tests.rb 0000644 0000041 0000041 00000002611 12576636531 023024 0 ustar www-data www-data Shindo.tests('AWS::IAM | user policy requests', ['aws']) do
Fog::AWS[:iam].create_user('fog_user_policy_tests')
tests('success') do
@policy = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
tests("#put_user_policy('fog_user_policy_tests', 'fog_policy', #{@policy.inspect})").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].put_user_policy('fog_user_policy_tests', 'fog_policy', @policy).body
end
@user_policies_format = {
'IsTruncated' => Fog::Boolean,
'PolicyNames' => [String],
'RequestId' => String
}
tests("#list_user_policies('fog_user_policy_tests')").formats(@user_policies_format) do
Fog::AWS[:iam].list_user_policies('fog_user_policy_tests').body
end
@user_policy_format = {
'UserName' => String,
'PolicyName' => String,
'PolicyDocument' => Hash,
}
tests("#get_user_policy('fog_user_policy_tests', 'fog_policy'").formats(@user_policy_format) do
Fog::AWS[:iam].get_user_policy('fog_policy', 'fog_user_policy_tests').body['Policy']
end
tests("#delete_user_policy('fog_user_policy_tests', 'fog_policy')").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_user_policy('fog_user_policy_tests', 'fog_policy').body
end
end
tests('failure') do
test('failing conditions')
end
Fog::AWS[:iam].delete_user('fog_user_policy_tests')
end
fog-aws-0.7.6/tests/requests/iam/user_tests.rb 0000644 0000041 0000041 00000004325 12576636531 021451 0 ustar www-data www-data Shindo.tests('AWS::IAM | user requests', ['aws']) do
service = Fog::AWS[:iam]
begin
service.delete_group('fog_user_tests')
rescue Fog::AWS::IAM::NotFound
end
begin
service.delete_user('fog_user').body
rescue Fog::AWS::IAM::NotFound
end
username = 'fog_user'
service.create_group('fog_user_tests')
tests("#create_user('#{username}')").data_matches_schema(AWS::IAM::Formats::CREATE_USER) do
service.create_user(username).body
end
tests("#list_users").data_matches_schema(AWS::IAM::Formats::LIST_USER) do
service.list_users.body
end
tests("#get_user('#{username}')").data_matches_schema(AWS::IAM::Formats::GET_USER) do
service.get_user(username).body
end
tests("#get_user").data_matches_schema(AWS::IAM::Formats::GET_CURRENT_USER) do
body = Fog::AWS[:iam].get_user.body
if Fog.mocking?
tests("correct root arn").returns(true) {
body["User"]["Arn"].end_with?(":root")
}
end
body
end
tests("#create_login_profile") do
service.create_login_profile(username, SecureRandom.base64(10))
end
tests("#get_login_profile") do
service.get_login_profile(username)
end
tests("#update_login_profile") do
# avoids Fog::AWS::IAM::Error: EntityTemporarilyUnmodifiable => Login Profile for User instance cannot be modified while login profile is being created.
if Fog.mocking?
service.update_login_profile(username, SecureRandom.base64(10))
end
end
tests("#delete_login_profile") do
service.delete_login_profile(username)
end
tests("#add_user_to_group('fog_user_tests', '#{username}')").data_matches_schema(AWS::IAM::Formats::BASIC) do
service.add_user_to_group('fog_user_tests', username).body
end
tests("#list_groups_for_user('#{username}')").data_matches_schema(AWS::IAM::Formats::GROUPS) do
service.list_groups_for_user(username).body
end
tests("#remove_user_from_group('fog_user_tests', '#{username}')").data_matches_schema(AWS::IAM::Formats::BASIC) do
service.remove_user_from_group('fog_user_tests', username).body
end
tests("#delete_user('#{username}')").data_matches_schema(AWS::IAM::Formats::BASIC) do
service.delete_user(username).body
end
service.delete_group('fog_user_tests')
end
fog-aws-0.7.6/tests/requests/simpledb/ 0000755 0000041 0000041 00000000000 12576636531 017751 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/simpledb/helper.rb 0000644 0000041 0000041 00000000225 12576636531 021554 0 ustar www-data www-data class AWS
module SimpleDB
module Formats
BASIC = {
'BoxUsage' => Float,
'RequestId' => String
}
end
end
end
fog-aws-0.7.6/tests/requests/simpledb/attributes_tests.rb 0000644 0000041 0000041 00000010427 12576636531 023712 0 ustar www-data www-data Shindo.tests('AWS::SimpleDB | attributes requests', ['aws']) do
@domain_name = "fog_domain_#{Time.now.to_f.to_s.gsub('.','')}"
Fog::AWS[:simpledb].create_domain(@domain_name)
tests('success') do
tests("#batch_put_attributes('#{@domain_name}', { 'a' => { 'b' => 'c', 'd' => 'e' }, 'x' => { 'y' => 'z' } }).body").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].batch_put_attributes(@domain_name, { 'a' => { 'b' => 'c', 'd' => 'e' }, 'x' => { 'y' => 'z' } }).body
end
tests("#get_attributes('#{@domain_name}', 'a', {'ConsistentRead' => true}).body['Attributes']").returns({'b' => ['c'], 'd' => ['e']}) do
Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'ConsistentRead' => true}).body['Attributes']
end
tests("#get_attributes('#{@domain_name}', 'AttributeName' => 'notanattribute')").succeeds do
Fog::AWS[:simpledb].get_attributes(@domain_name, 'AttributeName' => 'notanattribute')
end
tests("#select('select * from #{@domain_name}', {'ConsistentRead' => true}).body['Items']").returns({'a' => { 'b' => ['c'], 'd' => ['e']}, 'x' => { 'y' => ['z'] } }) do
pending if Fog.mocking?
Fog::AWS[:simpledb].select("select * from #{@domain_name}", {'ConsistentRead' => true}).body['Items']
end
tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '1' }).body").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '1' }).body
end
tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version']).body").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version']).body
end
# Verify that we can delete individual attributes.
tests("#delete_attributes('#{@domain_name}', 'a', {'d' => []})").succeeds do
Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a', {'d' => []}).body
end
# Verify that individually deleted attributes are actually removed.
tests("#get_attributes('#{@domain_name}', 'a', {'AttributeName' => ['d'], 'ConsistentRead' => true}).body['Attributes']").returns({}) do
Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'AttributeName' => ['d'], 'ConsistentRead' => true}).body['Attributes']
end
tests("#delete_attributes('#{@domain_name}', 'a').body").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a').body
end
# Verify that we can delete entire domain, item combinations.
tests("#delete_attributes('#{@domain_name}', 'a').body").succeeds do
Fog::AWS[:simpledb].delete_attributes(@domain_name, 'a').body
end
# Verify that deleting a domain, item combination removes all related attributes.
tests("#get_attributes('#{@domain_name}', 'a', {'ConsistentRead' => true}).body['Attributes']").returns({}) do
Fog::AWS[:simpledb].get_attributes(@domain_name, 'a', {'ConsistentRead' => true}).body['Attributes']
end
end
tests('failure') do
tests("#batch_put_attributes('notadomain', { 'a' => { 'b' => 'c' }, 'x' => { 'y' => 'z' } })").raises(Excon::Errors::BadRequest) do
Fog::AWS[:simpledb].batch_put_attributes('notadomain', { 'a' => { 'b' => 'c' }, 'x' => { 'y' => 'z' } })
end
tests("#get_attributes('notadomain', 'a')").raises(Excon::Errors::BadRequest) do
Fog::AWS[:simpledb].get_attributes('notadomain', 'a')
end
tests("#put_attributes('notadomain', 'conditional', { 'version' => '1' })").raises(Excon::Errors::BadRequest) do
Fog::AWS[:simpledb].put_attributes('notadomain', 'foo', { 'version' => '1' })
end
tests("#put_attributes('#{@domain_name}', 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version'])").raises(Excon::Errors::Conflict) do
Fog::AWS[:simpledb].put_attributes(@domain_name, 'conditional', { 'version' => '2' }, :expect => { 'version' => '1' }, :replace => ['version'])
end
tests("#delete_attributes('notadomain', 'a')").raises(Excon::Errors::BadRequest) do
Fog::AWS[:simpledb].delete_attributes('notadomain', 'a')
end
end
Fog::AWS[:simpledb].delete_domain(@domain_name)
end
fog-aws-0.7.6/tests/requests/simpledb/domain_tests.rb 0000644 0000041 0000041 00000003037 12576636531 022772 0 ustar www-data www-data Shindo.tests('AWS::SimpleDB | domain requests', ['aws']) do
@domain_metadata_format = AWS::SimpleDB::Formats::BASIC.merge({
'AttributeNameCount' => Integer,
'AttributeNamesSizeBytes' => Integer,
'AttributeValueCount' => Integer,
'AttributeValuesSizeBytes' => Integer,
'ItemCount' => Integer,
'ItemNamesSizeBytes' => Integer,
'Timestamp' => Time
})
@domain_name = "fog_domain_#{Time.now.to_f.to_s.gsub('.','')}"
tests('success') do
tests("#create_domain(#{@domain_name})").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].create_domain(@domain_name).body
end
tests("#create_domain(#{@domain_name})").succeeds do
Fog::AWS[:simpledb].create_domain(@domain_name)
end
tests("#domain_metadata(#{@domain_name})").formats(@domain_metadata_format) do
Fog::AWS[:simpledb].domain_metadata(@domain_name).body
end
tests("#list_domains").formats(AWS::SimpleDB::Formats::BASIC.merge('Domains' => [String])) do
Fog::AWS[:simpledb].list_domains.body
end
tests("#delete_domain(#{@domain_name})").formats(AWS::SimpleDB::Formats::BASIC) do
Fog::AWS[:simpledb].delete_domain(@domain_name).body
end
tests("#delete_domain(#{@domain_name})").succeeds do
Fog::AWS[:simpledb].delete_domain(@domain_name)
end
end
tests('failure') do
tests("#domain_metadata('notadomain')").raises(Excon::Errors::BadRequest) do
Fog::AWS[:simpledb].domain_metadata('notadomain')
end
end
end
fog-aws-0.7.6/tests/requests/kinesis/ 0000755 0000041 0000041 00000000000 12576636531 017617 5 ustar www-data www-data fog-aws-0.7.6/tests/requests/kinesis/helper.rb 0000644 0000041 0000041 00000005230 12576636531 021423 0 ustar www-data www-data class AWS
module Kinesis
def wait_for(&block)
Fog.wait_for do
block.call.tap do
print '.'
end
end
end
def wait_for_status(stream_name, status)
wait_for do
Fog::AWS[:kinesis].describe_stream("StreamName" => stream_name).body["StreamDescription"]["StreamStatus"] == status
end
end
def delete_if_exists(stream_name)
if Fog::AWS[:kinesis].list_streams.body["StreamNames"].include?(stream_name)
wait_for_status(stream_name, "ACTIVE")
Fog::AWS[:kinesis].delete_stream("StreamName" => @stream_id)
wait_for do
begin
Fog::AWS[:kinesis].describe_stream("StreamName" => stream_name)
false
rescue Fog::AWS::Kinesis::ResourceNotFound
true
end
end
end
end
module Formats # optional keys are commented out
LIST_STREAMS_FORMAT = {
"HasMoreStreams" => Fog::Boolean,
"StreamNames" => [
String
]
}
DESCRIBE_STREAM_FORMAT = {
"StreamDescription" => {
"HasMoreShards" => Fog::Boolean,
"Shards" => [
{
#"AdjacentParentShardId" => String,
"HashKeyRange" => {
"EndingHashKey" => String,
"StartingHashKey" => String
},
#"ParentShardId" => String,
"SequenceNumberRange" => {
# "EndingSequenceNumber" => String,
"StartingSequenceNumber" => String
},
"ShardId" => String
}
],
"StreamARN" => String,
"StreamName" => String,
"StreamStatus" => String
}
}
GET_SHARD_ITERATOR_FORMAT = {
"ShardIterator" => String
}
PUT_RECORDS_FORMAT = {
"FailedRecordCount" => Integer,
"Records" => [
{
# "ErrorCode" => String,
# "ErrorMessage" => String,
"SequenceNumber" => String,
"ShardId" => String
}
]
}
PUT_RECORD_FORMAT = {
"SequenceNumber" => String,
"ShardId" => String
}
GET_RECORDS_FORMAT = {
"MillisBehindLatest" => Integer,
"NextShardIterator" => String,
"Records" => [
{
"Data" => String,
"PartitionKey" => String,
"SequenceNumber" => String
}
]
}
LIST_TAGS_FOR_STREAM_FORMAT = {
"HasMoreTags" => Fog::Boolean,
"Tags" => [
{
"Key" => String,
"Value" => String
}
]
}
end
end
end
fog-aws-0.7.6/tests/requests/kinesis/stream_tests.rb 0000644 0000041 0000041 00000015536 12576636531 022673 0 ustar www-data www-data include AWS::Kinesis
Shindo.tests('AWS::Kinesis | stream requests', ['aws', 'kinesis']) do
Fog::AWS[:kinesis].reset_data if Fog.mocking?
@stream_id = 'fog-test-stream'
delete_if_exists(@stream_id) # ensure we start from a clean slate
tests("#create_stream").returns("") do
Fog::AWS[:kinesis].create_stream("StreamName" => @stream_id).body.tap do
wait_for_status(@stream_id, "ACTIVE")
end
end
tests("#list_streams").formats(Formats::LIST_STREAMS_FORMAT, false) do
Fog::AWS[:kinesis].list_streams.body.tap do
returns(true) {
Fog::AWS[:kinesis].list_streams.body["StreamNames"].include?(@stream_id)
}
end
end
tests("#describe_stream") do
tests("success").formats(AWS::Kinesis::Formats::DESCRIBE_STREAM_FORMAT) do
Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body
end
tests("ResourceNotFound").raises(Fog::AWS::Kinesis::ResourceNotFound) do
Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id + "-foo").body
end
end
tests("#put_records") do
records = [
{
"Data" => Base64.encode64("foo").chomp!,
"PartitionKey" => "1"
},
{
"Data" => Base64.encode64("bar").chomp!,
"PartitionKey" => "1"
}
]
tests("success").formats(AWS::Kinesis::Formats::PUT_RECORDS_FORMAT, false) do
Fog::AWS[:kinesis].put_records("StreamName" => @stream_id, "Records" => records).body
end
tests("ResourceNotFound").raises(Fog::AWS::Kinesis::ResourceNotFound) do
Fog::AWS[:kinesis].put_records("StreamName" => @stream_id + "-foo", "Records" => records).body
end
end
tests("#put_record").formats(AWS::Kinesis::Formats::PUT_RECORD_FORMAT) do
Fog::AWS[:kinesis].put_record("StreamName" => @stream_id, "Data" => Base64.encode64("baz").chomp!, "PartitionKey" => "1").body
end
tests("#get_shard_iterator").formats(AWS::Kinesis::Formats::GET_SHARD_ITERATOR_FORMAT) do
first_shard_id = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"].first["ShardId"]
Fog::AWS[:kinesis].get_shard_iterator("StreamName" => @stream_id, "ShardId" => first_shard_id, "ShardIteratorType" => "TRIM_HORIZON").body
end
tests("#get_records").formats(AWS::Kinesis::Formats::GET_RECORDS_FORMAT) do
first_shard_id = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"].first["ShardId"]
shard_iterator = Fog::AWS[:kinesis].get_shard_iterator("StreamName" => @stream_id, "ShardId" => first_shard_id, "ShardIteratorType" => "TRIM_HORIZON").body["ShardIterator"]
Fog::AWS[:kinesis].get_records("ShardIterator" => shard_iterator, "Limit" => 1).body
end
tests("#get_records").returns(["foo", "bar"]) do
first_shard_id = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"].first["ShardId"]
shard_iterator = Fog::AWS[:kinesis].get_shard_iterator("StreamName" => @stream_id, "ShardId" => first_shard_id, "ShardIteratorType" => "TRIM_HORIZON").body["ShardIterator"]
data = []
2.times do
response = Fog::AWS[:kinesis].get_records("ShardIterator" => shard_iterator, "Limit" => 1).body
response["Records"].each do |record|
data << Base64.decode64(record["Data"])
end
shard_iterator = response["NextShardIterator"]
end
data
end
tests("#split_shard").returns("") do
shard = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"].first
shard_id = shard["ShardId"]
ending_hash_key = shard["HashKeyRange"]["EndingHashKey"]
new_starting_hash_key = (ending_hash_key.to_i / 2).to_s
result = Fog::AWS[:kinesis].split_shard("StreamName" => @stream_id, "ShardToSplit" => shard_id, "NewStartingHashKey" => new_starting_hash_key).body
wait_for_status(@stream_id, "ACTIVE")
shards = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"]
parent_shard = shards.detect{ |shard| shard["ShardId"] == shard_id }
child_shards = shards.select{ |shard| shard["ParentShardId"] == shard_id }.sort_by{ |shard| shard["ShardId"] }
returns(3) { shards.size }
returns(2) { child_shards.size }
# parent is closed
returns(false) { parent_shard["SequenceNumberRange"]["EndingSequenceNumber"].nil? }
# ensure new ranges are what we expect (mostly for testing the mock)
returns([
{
"StartingHashKey" => "0",
"EndingHashKey" => (new_starting_hash_key.to_i - 1).to_s
},
{
"StartingHashKey" => new_starting_hash_key,
"EndingHashKey" => ending_hash_key
}
]) { child_shards.map{ |shard| shard["HashKeyRange"] } }
result
end
tests("#merge_shards").returns("") do
shards = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"]
child_shard_ids = shards.reject{ |shard| shard["SequenceNumberRange"].has_key?("EndingSequenceNumber") }.map{ |shard| shard["ShardId"] }.sort
result = Fog::AWS[:kinesis].merge_shards("StreamName" => @stream_id, "ShardToMerge" => child_shard_ids[0], "AdjacentShardToMerge" => child_shard_ids[1]).body
wait_for_status(@stream_id, "ACTIVE")
shards = Fog::AWS[:kinesis].describe_stream("StreamName" => @stream_id).body["StreamDescription"]["Shards"]
parent_shards = shards.select{ |shard| child_shard_ids.include?(shard["ShardId"]) }
child_shard = shards.detect{ |shard|
shard["ParentShardId"] == child_shard_ids[0] &&
shard["AdjacentParentShardId"] == child_shard_ids[1]
}
returns(2) { parent_shards.size }
returns(false) { child_shard.nil? }
returns({
"EndingHashKey" => "340282366920938463463374607431768211455",
"StartingHashKey" => "0"
}) {
child_shard["HashKeyRange"]
}
result
end
tests("#add_tags_to_stream").returns("") do
Fog::AWS[:kinesis].add_tags_to_stream("StreamName" => @stream_id, "Tags" => {"a" => "1", "b" => "2"}).body
end
tests("#list_tags_for_stream").formats(AWS::Kinesis::Formats::LIST_TAGS_FOR_STREAM_FORMAT) do
Fog::AWS[:kinesis].list_tags_for_stream("StreamName" => @stream_id).body.tap do |body|
returns({"a" => "1", "b" => "2"}) {
body["Tags"].inject({}){ |m, tag| m.merge(tag["Key"] => tag["Value"]) }
}
end
end
tests("#remove_tags_from_stream").returns("") do
Fog::AWS[:kinesis].remove_tags_from_stream("StreamName" => @stream_id, "TagKeys" => %w[b]).body.tap do
returns({"a" => "1"}) {
body = Fog::AWS[:kinesis].list_tags_for_stream("StreamName" => @stream_id).body
body["Tags"].inject({}){ |m, tag| m.merge(tag["Key"] => tag["Value"]) }
}
end
end
tests("#delete_stream").returns("") do
Fog::AWS[:kinesis].delete_stream("StreamName" => @stream_id).body
end
end
fog-aws-0.7.6/tests/parsers/ 0000755 0000041 0000041 00000000000 12576636531 015756 5 ustar www-data www-data fog-aws-0.7.6/tests/parsers/elb/ 0000755 0000041 0000041 00000000000 12576636531 016520 5 ustar www-data www-data fog-aws-0.7.6/tests/parsers/elb/describe_load_balancers.rb 0000644 0000041 0000041 00000004556 12576636531 023650 0 ustar www-data www-data require 'fog/xml'
require 'fog/aws/parsers/elb/describe_load_balancers'
DESCRIBE_LOAD_BALANCERS_RESULT = <<-EOF
2013-08-01T15:47:20.930Z
fog-test-elb
30
TCP:80
10
5
2
HTTP
80
HTTP
80
us-east-1a
fog-test-elb-1965660309.us-east-1.elb.amazonaws.com
Z3DZXE0Q79N41H
internet-facing
amazon-elb
amazon-elb-sg
fog-test-elb-1965660309.us-east-1.elb.amazonaws.com
a6ea2117-fac1-11e2-abd3-1740ab4ef14e
EOF
Shindo.tests('AWS::ELB | parsers | describe_load_balancers', ['aws', 'elb', 'parser']) do
tests('parses the xml').formats(AWS::ELB::Formats::DESCRIBE_LOAD_BALANCERS) do
parser = Nokogiri::XML::SAX::Parser.new(Fog::Parsers::AWS::ELB::DescribeLoadBalancers.new)
parser.parse(DESCRIBE_LOAD_BALANCERS_RESULT)
parser.document.response
end
end
fog-aws-0.7.6/tests/credentials_tests.rb 0000644 0000041 0000041 00000004167 12576636531 020353 0 ustar www-data www-data Shindo.tests('AWS | credentials', ['aws']) do
old_mock_value = Excon.defaults[:mock]
Excon.stubs.clear
begin
Excon.defaults[:mock] = true
default_credentials = Fog::Compute::AWS.fetch_credentials({})
Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/"}, {:status => 200, :body => 'arole'})
expires_at = Time.at(Time.now.to_i + 500)
credentials = {
'AccessKeyId' => 'dummykey',
'SecretAccessKey' => 'dummysecret',
'Token' => 'dummytoken',
'Expiration' => expires_at.xmlschema
}
Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/arole"}, {:status => 200, :body => Fog::JSON.encode(credentials)})
tests("#fetch_credentials") do
returns({:aws_access_key_id => 'dummykey',
:aws_secret_access_key => 'dummysecret',
:aws_session_token => 'dummytoken',
:aws_credentials_expire_at => expires_at}) { Fog::Compute::AWS.fetch_credentials(:use_iam_profile => true) }
end
compute = Fog::Compute::AWS.new(:use_iam_profile => true)
tests("#refresh_credentials_if_expired") do
returns(nil){compute.refresh_credentials_if_expired}
end
credentials['AccessKeyId'] = 'newkey'
credentials['SecretAccessKey'] = 'newsecret'
credentials['Expiration'] = (expires_at + 10).xmlschema
Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/arole"}, {:status => 200, :body => Fog::JSON.encode(credentials)})
Fog::Time.now = expires_at + 1
tests("#refresh_credentials_if_expired") do
returns(true){compute.refresh_credentials_if_expired}
returns("newkey"){ compute.instance_variable_get(:@aws_access_key_id)}
end
Fog::Time.now = Time.now
tests("#fetch_credentials when the url 404s") do
Excon.stub({:method => :get, :path => "/latest/meta-data/iam/security-credentials/"}, {:status => 404, :body => 'not bound'})
returns(default_credentials) {Fog::Compute::AWS.fetch_credentials(:use_iam_profile => true)}
end
ensure
Excon.stubs.clear
Excon.defaults[:mock] = old_mock_value
end
end
fog-aws-0.7.6/tests/models/ 0000755 0000041 0000041 00000000000 12576636531 015562 5 ustar www-data www-data fog-aws-0.7.6/tests/models/storage/ 0000755 0000041 0000041 00000000000 12576636531 017226 5 ustar www-data www-data fog-aws-0.7.6/tests/models/storage/versions_tests.rb 0000644 0000041 0000041 00000003301 12576636531 022642 0 ustar www-data www-data Shindo.tests("Storage[:aws] | versions", ["aws"]) do
file_attributes = {
:key => 'fog_file_tests',
:body => lorem_file,
:public => true
}
directory_attributes = {
:key => uniq_id('fogfilestests')
}
model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do
@instance.versioning = true
versions = []
versions << @instance.service.put_object(@instance.key, 'one', 'abcde').headers['x-amz-version-id']
puts versions.first
versions << @instance.service.put_object(@instance.key, 'one', '32423').headers['x-amz-version-id']
versions << @instance.service.delete_object(@instance.key, 'one').headers['x-amz-version-id']
versions.reverse!
puts versions.first
versions << @instance.service.put_object(@instance.key, 'two', 'aoeu').headers['x-amz-version-id']
tests('#versions') do
tests('#versions.size includes versions (including DeleteMarkers) for all keys').returns(4) do
@instance.versions.all.size
end
tests('#versions returns the correct versions').returns(versions) do
@instance.versions.all.map(&:version)
end
end
tests("#all") do
tests("#all for a directory returns all versions, regardless of key").returns(versions) do
@instance.versions.all.map(&:version)
end
tests("#all for file returns only versions for that file").returns(1) do
@instance.files.get('two').versions.all.map(&:version).size
end
tests("#all for file returns only versions for that file").returns(versions.last) do
@instance.files.get('two').versions.all.map(&:version).first
end
end
@instance.versions.each(&:destroy)
end
end
fog-aws-0.7.6/tests/models/storage/file_tests.rb 0000644 0000041 0000041 00000007040 12576636531 021715 0 ustar www-data www-data Shindo.tests("Storage[:aws] | file", ["aws"]) do
require 'tempfile'
file_attributes = {
:key => 'fog_file_tests',
:body => lorem_file,
:public => true
}
directory_attributes = {
:key => uniq_id("fogfilestests")
}
@directory = Fog::Storage[:aws].directories.create(directory_attributes)
model_tests(@directory.files, file_attributes, Fog.mocking?) do
tests("#version") do
tests("#version should be null if versioning isn't enabled").returns(nil) do
@instance.version
end
end
end
@directory.versioning = true
model_tests(@directory.files, file_attributes, Fog.mocking?) do
tests("#version") do
tests("#version should not be null if versioning is enabled").returns(false) do
@instance.version == nil
end
end
@directory.files.create(:key => @instance.key)
@instance.destroy
tests("#versions") do
tests('#versions.size includes versions (including DeleteMarkers) for all keys').returns(3) do
@instance.versions.size
end
tests('#versions are all for the correct key').returns(true) do
# JRuby 1.7.5+ issue causes a SystemStackError: stack level too deep
# https://github.com/jruby/jruby/issues/1265
pending if RUBY_PLATFORM == "java" and JRUBY_VERSION =~ /1\.7\.[5-8]/
@instance.versions.all? { |v| v.key == @instance.key }
end
end
tests("#destroy") do
tests("#destroy a specific version should delete the version, not create a DeleteMarker").returns(2) do
@instance.destroy('versionId' => @instance.version)
@instance.versions.all.size
end
end
tests("multipart upload") do
pending if Fog.mocking?
# A 6MB file
@large_file = Tempfile.new("fog-test-aws-s3-multipart")
6.times { @large_file.write("x" * (1024**2)) }
@large_file.rewind
tests("#save(:multipart_chunk_size => 5242880)").succeeds do
@directory.files.create(:key => 'multipart-upload', :body => @large_file, :multipart_chunk_size => 5242880)
end
@large_file.close
end
tests("multipart upload with customer encryption").returns(true) do
pending if Fog.mocking?
encryption_key = OpenSSL::Cipher.new("AES-256-ECB").random_key
# A 6MB file
@large_file = Tempfile.new("fog-test-aws-s3-multipart")
6.times { @large_file.write("x" * (1024**2)) }
@large_file.rewind
tests("#save(:multipart_chunk_size => 5242880)").succeeds do
@directory.files.create(
:key => 'multipart-encrypted-upload',
:body => @large_file,
:multipart_chunk_size => 5242880,
:encryption => "AES256",
:encryption_key => encryption_key
)
end
@large_file.close
@directory.files.get('multipart-encrypted-upload',
'x-amz-server-side-encryption-customer-algorithm' => 'AES256',
'x-amz-server-side-encryption-customer-key' => Base64.encode64(encryption_key).chomp!,
'x-amz-server-side-encryption-customer-key-MD5' => Base64.encode64(Digest::MD5.digest(encryption_key.to_s)).chomp!
).body == "x" * 6*1024**2
end
acl = Fog::Storage[:aws].get_object_acl(@directory.key, @instance.key).body["AccessControlList"]
tests("#acl").returns(acl) do
@instance.acl
end
tests("#public?").returns(acl.any? {|grant| grant['Grantee']['URI'] == 'http://acs.amazonaws.com/groups/global/AllUsers' && grant['Permission'] == 'READ'}) do
@instance.public?
end
end
@directory.versions.each(&:destroy)
@directory.destroy
end
fog-aws-0.7.6/tests/models/storage/directory_tests.rb 0000644 0000041 0000041 00000004620 12576636531 023003 0 ustar www-data www-data Shindo.tests("Storage[:aws] | directory", ["aws"]) do
directory_attributes = {
:key => uniq_id('fogdirectorytests')
}
model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do
tests("#public_url").returns(nil) do
@instance.public_url
end
@instance.acl = 'public-read'
@instance.save
tests("#public_url").returns(true) do
if @instance.public_url =~ %r[\Ahttps://fogdirectorytests-[\da-f]+\.s3\.amazonaws\.com/\z]
true
else
@instance.public_url
end
end
end
directory_attributes = {
:key => uniq_id('different-region'),
:location => 'eu-west-1',
}
model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do
tests("#location").returns('eu-west-1') do
@instance.location
end
tests("#location").returns('eu-west-1') do
Fog::Storage[:aws].directories.get(@instance.identity).location
end
end
directory_attributes = {
:key => uniq_id('fogdirectorytests')
}
model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do
tests("#versioning=") do
tests("#versioning=(true)").succeeds do
@instance.versioning = true
end
tests("#versioning=(true) sets versioning to 'Enabled'").returns('Enabled') do
@instance.versioning = true
@instance.service.get_bucket_versioning(@instance.key).body['VersioningConfiguration']['Status']
end
tests("#versioning=(false)").succeeds do
(@instance.versioning = false).equal? false
end
tests("#versioning=(false) sets versioning to 'Suspended'").returns('Suspended') do
@instance.versioning = false
@instance.service.get_bucket_versioning(@instance.key).body['VersioningConfiguration']['Status']
end
end
end
model_tests(Fog::Storage[:aws].directories, directory_attributes, Fog.mocking?) do
tests("#versioning?") do
tests("#versioning? false if not enabled").returns(false) do
@instance.versioning?
end
tests("#versioning? true if enabled").returns(true) do
@instance.service.put_bucket_versioning(@instance.key, 'Enabled')
@instance.versioning?
end
tests("#versioning? false if suspended").returns(false) do
@instance.service.put_bucket_versioning(@instance.key, 'Suspended')
@instance.versioning?
end
end
end
end
fog-aws-0.7.6/tests/models/storage/files_tests.rb 0000644 0000041 0000041 00000003543 12576636531 022104 0 ustar www-data www-data Shindo.tests("Storage[:aws] | files", ["aws"]) do
file_attributes = {
:key => 'fog_file_tests',
:body => lorem_file,
:public => true
}
directory_attributes = {
:key => uniq_id('fogfilestests')
}
@directory = Fog::Storage[:aws].directories.create(directory_attributes)
@directory.versioning = true
model_tests(@directory.files, file_attributes, Fog.mocking?) do
v1 = @instance.version
v2 = @directory.service.put_object(@directory.key, @instance.key, 'version 2 content').headers['x-amz-version-id']
v3 = @directory.service.delete_object(@directory.key, @instance.key).headers['x-amz-version-id']
v4 = @directory.service.put_object(@directory.key, @instance.key, 'version 3 content').headers['x-amz-version-id']
tests("#get") do
tests("#get without version fetches the latest version").returns(v4) do
@directory.files.get(@instance.key).version
end
tests("#get with version fetches that exact version").returns(v2) do
@directory.files.get(@instance.key, 'versionId' => v2).version
end
tests("#get with a deleted version returns nil").returns(nil) do
pending # getting 405 Method Not Allowed
@directory.files.get(@instance.key, 'versionId' => v3)
end
end
tests("#head") do
tests("#head without version fetches the latest version").returns(v4) do
@directory.files.head(@instance.key).version
end
tests("#head with version fetches that exact version").returns(v2) do
@directory.files.head(@instance.key, 'versionId' => v2).version
end
tests("#head with a deleted version returns nil").returns(nil) do
pending # getting 405 Method Not Allowed
@directory.files.head(@instance.key, 'versionId' => v3)
end
end
end
@directory.versions.each(&:destroy)
@directory.destroy
end
fog-aws-0.7.6/tests/models/storage/url_tests.rb 0000644 0000041 0000041 00000003030 12576636531 021573 0 ustar www-data www-data # encoding: utf-8
Shindo.tests('AWS | url', ["aws"]) do
@storage = Fog::Storage.new(
:provider => 'AWS',
:aws_access_key_id => '123',
:aws_secret_access_key => 'abc',
:region => 'us-east-1'
)
@file = @storage.directories.new(:key => 'fognonbucket').files.new(:key => 'test.txt')
now = Fog::Time.now
if RUBY_VERSION > '1.8.7' # ruby 1.8.x doesn't provide hash ordering
tests('#v4 url w/ response-cache-control').returns(
"https://fognonbucket.s3.amazonaws.com/test.txt?response-cache-control=No-cache&X-Amz-Expires=500&X-Amz-Date=#{now.to_iso8601_basic}&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=123/#{now.utc.strftime('%Y%m%d')}/us-east-1/s3/aws4_request&X-Amz-SignedHeaders=host&X-Amz-Signature="
) do
@file.url(now + 500, :query => { 'response-cache-control' => 'No-cache' }).gsub(/(X-Amz-Signature=)[0-9a-f]+\z/,'\\1')
end
end
@storage = Fog::Storage.new(
:provider => 'AWS',
:aws_access_key_id => '123',
:aws_secret_access_key => 'abc',
:aws_signature_version => 2,
:region => 'us-east-1'
)
@file = @storage.directories.new(:key => 'fognonbucket').files.new(:key => 'test.txt')
if RUBY_VERSION > '1.8.7' # ruby 1.8.x doesn't provide hash ordering
tests('#v2 url w/ response-cache-control').returns(
"https://fognonbucket.s3.amazonaws.com/test.txt?response-cache-control=No-cache&AWSAccessKeyId=123&Signature=foo&Expires=#{now.to_i + 500}"
) do
@file.url(now + 500, :query => { 'response-cache-control' => 'No-cache' })
end
end
end
fog-aws-0.7.6/tests/models/storage/version_tests.rb 0000644 0000041 0000041 00000002612 12576636531 022463 0 ustar www-data www-data Shindo.tests("Storage[:aws] | version", ["aws"]) do
file_attributes = {
:key => 'fog_file_tests',
:body => lorem_file,
:public => true
}
directory_attributes = {
:key => uniq_id('fogfilestests')
}
@directory = Fog::Storage[:aws].directories.create(directory_attributes)
@directory.versioning = true
model_tests(@directory.files, file_attributes, Fog.mocking?) do
@version_instance = @instance.versions.first
@directory.service.put_object(@directory.key, @instance.key, 'second version content')
tests("#file") do
tests("#file should return the object associated with the version").returns(@version_instance.version) do
@version_instance.file.version
end
end
tests("#delete_marker") do
tests("#delete_marker should be false if the version isn't a DeleteMarker'").returns(false) do
@version_instance.delete_marker
end
tests("#delete_marker should be true if the version is a DeleteMarker'").returns(true) do
@instance.destroy
@instance.versions.all.first.delete_marker
end
end
tests("#destroy") do
tests("#destroy removes the specific version").returns(false) do
@version_instance.destroy
@instance.versions.all.map(&:version).include?(@version_instance.version)
end
end
end
@directory.versions.each(&:destroy)
@directory.destroy
end
fog-aws-0.7.6/tests/models/auto_scaling/ 0000755 0000041 0000041 00000000000 12576636531 020232 5 ustar www-data www-data fog-aws-0.7.6/tests/models/auto_scaling/groups_test.rb 0000644 0000041 0000041 00000001271 12576636531 023136 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | group', ['aws', 'auto_scaling_m']) do
params = {
:id => uniq_id,
:auto_scaling_group_name => "name",
:availability_zones => [],
:launch_configuration_name => "lc"
}
lc_params = {
:id => params[:launch_configuration_name],
:image_id => "image-id",
:instance_type => "instance-type",
}
Fog::AWS[:auto_scaling].configurations.new(lc_params).save
model_tests(Fog::AWS[:auto_scaling].groups, params, true) do
@instance.update
end
test("setting attributes in the constructor") do
group = Fog::AWS[:auto_scaling].groups.new(:min_size => 1, :max_size => 2)
group.min_size == 1 && group.max_size == 2
end
end
fog-aws-0.7.6/tests/models/auto_scaling/helper.rb 0000644 0000041 0000041 00000000000 12576636531 022024 0 ustar www-data www-data fog-aws-0.7.6/tests/models/auto_scaling/instances_tests.rb 0000644 0000041 0000041 00000000303 12576636531 023764 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | instances', ['aws', 'auto_scaling_m']) do
pending # FIXME: instance#save is not defined
#collection_tests(Fog::AWS[:auto_scaling].instances, {}, false)
end
fog-aws-0.7.6/tests/models/auto_scaling/configurations_tests.rb 0000644 0000041 0000041 00000000410 12576636531 025026 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | configurations', ['aws', 'auto_scaling_m']) do
params = {
:id => uniq_id,
:image_id => 'ami-8c1fece5',
:instance_type => 't1.micro'
}
collection_tests(Fog::AWS[:auto_scaling].configurations, params, false)
end
fog-aws-0.7.6/tests/models/auto_scaling/configuration_test.rb 0000644 0000041 0000041 00000000455 12576636531 024471 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | configuration', ['aws', 'auto_scaling_m']) do
params = {
:id => uniq_id,
:image_id => 'ami-8c1fece5',
:instance_type => 't1.micro'
}
model_tests(Fog::AWS[:auto_scaling].configurations, params, false) do
@instance.wait_for { ready? }
end
end
fog-aws-0.7.6/tests/models/auto_scaling/activities_tests.rb 0000644 0000041 0000041 00000000310 12576636531 024137 0 ustar www-data www-data Shindo.tests('AWS::AutoScaling | activities', ['aws', 'auto_scaling_m']) do
pending # FIXME: activity#save is not implemented
collection_tests(Fog::AWS[:auto_scaling].activities, {}, false)
end
fog-aws-0.7.6/tests/models/auto_scaling/instance_tests.rb 0000644 0000041 0000041 00000000574 12576636531 023613 0 ustar www-data www-data require 'fog/aws/models/auto_scaling/instance'
Shindo.tests("Fog::AWS::AutoScaling::Instance", 'aws') do
@instance = Fog::AWS::AutoScaling::Instance.new
test('#healthy? = true') do
@instance.health_status = 'Healthy'
@instance.healthy? == true
end
test('#heatlhy? = false') do
@instance.health_status = 'Unhealthy'
@instance.healthy? == false
end
end
fog-aws-0.7.6/tests/models/beanstalk/ 0000755 0000041 0000041 00000000000 12576636531 017526 5 ustar www-data www-data fog-aws-0.7.6/tests/models/beanstalk/versions_tests.rb 0000644 0000041 0000041 00000002530 12576636531 023145 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | versions", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@version_name = uniq_id('fog-test-version')
@version_description = 'A nice description'
@application = @beanstalk.applications.create({:name => @application_name})
params = {
:application_name => @application_name,
:label => @version_name,
:description => @version_description
}
collection = @beanstalk.versions
tests('success') do
tests("#new(#{params.inspect})").succeeds do
pending if Fog.mocking?
collection.new(params)
end
tests("#create(#{params.inspect})").succeeds do
pending if Fog.mocking?
@instance = collection.create(params)
end
tests("#all").succeeds do
pending if Fog.mocking?
collection.all
end
tests("#get(#{@application_name}, #{@version_name})").succeeds do
pending if Fog.mocking?
collection.get(@application_name, @version_name)
end
if !Fog.mocking?
@instance.destroy
end
end
tests('failure') do
tests("#get(#{@application_name}, #{@version_name})").returns(nil) do
pending if Fog.mocking?
collection.get(@application_name, @version_name)
end
end
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/beanstalk/environment_tests.rb 0000644 0000041 0000041 00000006462 12576636531 023651 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | environment", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@environment_name = uniq_id('fog-test-env')
@version_names = []
# Create two unique version names
2.times {
@version_names << uniq_id('fog-test-version')
}
@application = @beanstalk.applications.create({:name => @application_name})
@versions = []
@version_names.each { |name|
@versions << @beanstalk.versions.create({
:label => name,
:application_name => @application_name,
})
}
@environment_opts = {
:application_name => @application_name,
:name => @environment_name,
:version_label => @version_names[0],
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
}
# Note: These model tests can take quite a bit of time to run, about 10 minutes typically.
model_tests(@beanstalk.environments, @environment_opts, false) do
# Wait for initial ready before next tests.
tests("#ready?").succeeds do
@instance.wait_for { ready? }
end
tests("#healthy?").succeeds do
@instance.wait_for { healthy? }
end
test("#events") do
# There should be some events now.
@instance.events.length > 0
end
test("#version") do
@instance.version.label == @version_names[0]
end
test("#version= string") do
# Set to version 2
@instance.version = @version_names[1]
count = 0
if @instance.version.label == @version_names[1]
@instance.events.each { |event|
if event.message == "Environment update is starting."
count = count + 1
end
}
end
count == 1
end
tests("#ready? after version= string").succeeds do
@instance.wait_for { ready? }
end
test("#version= version object") do
# reset back to first version using version object
@instance.version = @versions[0]
count = 0
if @instance.version.label == @version_names[0]
@instance.events.each { |event|
if event.message == "Environment update is starting."
count = count + 1
end
}
end
# Pass if we have two environment updating events
count == 2
end
tests("#ready? after version= version object").succeeds do
@instance.wait_for { ready? }
end
test('#restart_app_server') do
@instance.restart_app_server
passed = false
@instance.events.each { |event|
if event.message == "restartAppServer is starting."
passed = true
end
}
passed
end
test('#rebuild') do
@instance.rebuild
passed = false
@instance.events.each { |event|
if event.message == "rebuildEnvironment is starting."
passed = true
end
}
passed
end
# Wait for ready or next tests may fail
tests("#ready? after rebuild").succeeds do
@instance.wait_for { ready? }
end
end
# Wait for instance to terminate before deleting application
tests('#terminated?').succeeds do
@instance.wait_for { terminated? }
end
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/beanstalk/template_tests.rb 0000644 0000041 0000041 00000002443 12576636531 023113 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | template", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@template_name = uniq_id('fog-test-template')
@template_description = 'A nice description'
@application = @beanstalk.applications.create({:name => @application_name})
@template_opts = {
:application_name => @application_name,
:name => @template_name,
:description => @template_description,
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
}
model_tests(@beanstalk .templates, @template_opts, false) do
test("#attributes") do
@instance.name == @template_name &&
@instance.description == @template_description &&
@instance.application_name == @application_name &&
@instance.solution_stack_name == @template_opts[:solution_stack_name]
end
test("#options") do
options = @instance.options
passed = false
if options.each { |option|
# See if we recognize at least one option
if option["Name"] == 'LoadBalancerHTTPPort' && option["Namespace"] == 'aws:elb:loadbalancer'
passed = true
end
}
end
passed
end
end
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/beanstalk/application_tests.rb 0000644 0000041 0000041 00000003521 12576636531 023601 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | application", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@application_opts = {
:name => uniq_id('fog-test-app'),
:description => 'A nice description.'
}
model_tests(Fog::AWS[:beanstalk].applications, @application_opts, false) do
test("#attributes") do
@instance.name == @application_opts[:name] &&
@instance.description == @application_opts[:description]
end
test("#events") do
# There should be some events now.
@instance.events.length > 0
end
version_name = uniq_id('fog-test-ver')
@instance.versions.create(
:application_name => @instance.name,
:label => version_name
)
test("#versions") do
# We should have one version.
@instance.versions.length == 1
end
template_name = uniq_id('fog-test-template')
@instance.templates.create(
:application_name => @instance.name,
:name => template_name,
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
)
test('#templates') do
# We should have one template now.
@instance.templates.length == 1
end
environment_name = uniq_id('fog-test-env')
environment = @instance.environments.create(
:application_name => @instance.name,
:name => environment_name,
:version_label => version_name,
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
)
# Go ahead an terminate immediately.
environment.destroy
# Create an environment
test("#environments") do
# We should have one environment now.
@instance.environments.length == 1
end
# Must wait for termination before destroying application
tests("waiting for test environment to terminate").succeeds do
environment.wait_for { terminated? }
end
end
end
fog-aws-0.7.6/tests/models/beanstalk/applications_tests.rb 0000644 0000041 0000041 00000000317 12576636531 023764 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | applications", ['aws', 'beanstalk']) do
pending if Fog.mocking?
collection_tests(Fog::AWS[:beanstalk].applications, {:name => uniq_id('fog-test-app')}, false)
end
fog-aws-0.7.6/tests/models/beanstalk/templates_tests.rb 0000644 0000041 0000041 00000002650 12576636531 023276 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | templates", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@template_name = uniq_id('fog-test-template')
@template_description = 'A nice description'
@application = @beanstalk.applications.create({:name => @application_name})
params = {
:application_name => @application_name,
:name => @template_name,
:description => @template_description,
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
}
collection = @beanstalk.templates
tests('success') do
tests("#new(#{params.inspect})").succeeds do
pending if Fog.mocking?
collection.new(params)
end
tests("#create(#{params.inspect})").succeeds do
pending if Fog.mocking?
@instance = collection.create(params)
end
tests("#all").succeeds do
pending if Fog.mocking?
collection.all
end
tests("#get(#{@application_name}, #{@template_name})").succeeds do
pending if Fog.mocking?
collection.get(@application_name, @template_name)
end
if !Fog.mocking?
@instance.destroy
end
end
tests('failure') do
tests("#get(#{@application_name}, #{@template_name})").returns(nil) do
pending if Fog.mocking?
collection.get(@application_name, @template_name)
end
end
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/beanstalk/environments_tests.rb 0000644 0000041 0000041 00000002005 12576636531 024021 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | environments", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@environment_name = uniq_id('fog-test-env')
@version_name = uniq_id('fog-test-version')
# Create an application/version to use for testing.
@version = @beanstalk.versions.create({
:label => @version_name,
:application_name => @application_name,
:auto_create_application => true
})
@application = @beanstalk.applications.get(@application_name)
@environment_opts = {
:application_name => @application_name,
:name => @environment_name,
:version_label => @version_name,
:solution_stack_name => '32bit Amazon Linux running Tomcat 7'
}
collection_tests(@beanstalk.environments, @environment_opts, false)
# Wait for instance to terminate before deleting application
@instance.wait_for { terminated? }
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/beanstalk/version_tests.rb 0000644 0000041 0000041 00000003477 12576636531 022775 0 ustar www-data www-data Shindo.tests("Fog::AWS[:beanstalk] | version", ['aws', 'beanstalk']) do
pending if Fog.mocking?
@beanstalk = Fog::AWS[:beanstalk]
@application_name = uniq_id('fog-test-app')
@version_name = uniq_id('fog-test-version')
@version_description = 'A nice description'
@application = @beanstalk.applications.create({:name => @application_name})
@version_opts = {
:application_name => @application_name,
:label => @version_name,
:description => @version_description
}
model_tests(@beanstalk.versions, @version_opts, false) do
test("attributes") do
@instance.label == @version_name &&
@instance.description == @version_description &&
@instance.application_name == @application_name
end
test("#events") do
# There should be some events now.
@instance.events.length > 0
end
test("#update description") do
new_description = "A completely new description."
@instance.description = new_description
@instance.update
passed = false
if @instance.description == new_description
# reload version from AWS to verify save is committed to server, not just on local object
if @beanstalk.versions.get(@application_name, @version_name).description == new_description
passed = true
end
end
passed
end
test("#update description empty") do
@instance.description = '' # Set to empty to nil out
@instance.update
passed = false
if @instance.description == nil
# reload version from AWS to verify save is committed to server, not just on local object
if @beanstalk.versions.get(@application_name, @version_name).description == nil
passed = true
end
end
passed
end
end
# delete application
@application.destroy
end
fog-aws-0.7.6/tests/models/cloud_watch/ 0000755 0000041 0000041 00000000000 12576636531 020056 5 ustar www-data www-data fog-aws-0.7.6/tests/models/cloud_watch/alarm_data_tests.rb 0000644 0000041 0000041 00000002135 12576636531 023713 0 ustar www-data www-data Shindo.tests("AWS::CloudWatch | alarm_data", ['aws', 'cloudwatch']) do
pending if Fog.mocking?
tests('success') do
tests("#all").succeeds do
Fog::AWS[:cloud_watch].alarm_data.all
end
alarm_name_prefix = {'AlarmNamePrefix'=>'tmp'}
tests("#all_by_prefix").succeeds do
Fog::AWS[:cloud_watch].alarm_data.all(alarm_name_prefix)
end
namespace = 'AWS/EC2'
metric_name = 'CPUUtilization'
tests("#get").succeeds do
Fog::AWS[:cloud_watch].alarm_data.get(namespace, metric_name).to_json
end
new_attributes = {
:alarm_name => 'tmp-alarm',
:comparison_operator => 'GreaterThanOrEqualToThreshold',
:evaluation_periods => 1,
:metric_name => 'tmp-metric-alarm',
:namespace => 'fog-0.11.0',
:period => 60,
:statistic => 'Sum',
:threshold => 5
}
tests('#new').returns(new_attributes) do
Fog::AWS[:cloud_watch].alarm_data.new(new_attributes).attributes
end
tests('#create').returns(new_attributes) do
Fog::AWS[:cloud_watch].alarm_data.create(new_attributes).attributes
end
end
end
fog-aws-0.7.6/tests/models/cloud_watch/metrics_tests.rb 0000644 0000041 0000041 00000001700 12576636531 023271 0 ustar www-data www-data Shindo.tests("AWS::CloudWatch | metrics", ['aws', 'cloudwatch']) do
tests('success') do
pending # FIXME: the hardcoded instance id won't be available
tests("#all").succeeds do
Fog::AWS[:cloud_watch].metrics.all
end
instanceId = 'i-fd713391'
metricName = 'CPUUtilization'
namespace = 'AWS/EC2'
tests("#get").returns({:dimensions=>[{"Name"=>"InstanceId", "Value"=>instanceId}], :name=>metricName, :namespace=>namespace}) do
Fog::AWS[:cloud_watch].metrics.get(namespace, metricName, {'InstanceId' => instanceId}).attributes
end
end
tests('#each') do
Fog.mock!
tests("handle NextToken").returns(1001) do
count = 0
Fog::AWS[:cloud_watch].metrics.each {|e| count += 1 }
count
end
tests("yields Metrics instances").succeeds do
all = []
Fog::AWS[:cloud_watch].metrics.each {|e| all << e }
all.all? {|e| e.is_a?(Fog::AWS::CloudWatch::Metric) }
end
end
end
fog-aws-0.7.6/tests/models/cloud_watch/metric_statistics_tests.rb 0000644 0000041 0000041 00000003103 12576636531 025357 0 ustar www-data www-data Shindo.tests("AWS::CloudWatch | metric_statistics", ['aws', 'cloudwatch']) do
tests('success') do
pending if Fog.mocking?
instanceId = 'i-420c352f'
metricName = 'DiskReadBytes'
namespace = 'AWS/EC2'
startTime = (Time.now-600).iso8601
endTime = Time.now.iso8601
period = 60
statisticTypes = ['Minimum','Maximum','Sum','SampleCount','Average']
tests("#all").succeeds do
@statistics = Fog::AWS[:cloud_watch].metric_statistics.all({'Statistics' => statisticTypes, 'StartTime' => startTime, 'EndTime' => endTime, 'Period' => period, 'MetricName' => metricName, 'Namespace' => namespace, 'Dimensions' => [{'Name' => 'InstanceId', 'Value' => instanceId}]})
end
tests("#all_not_empty").returns(true) do
@statistics.length > 0
end
new_attributes = {
:namespace => 'Custom/Test',
:metric_name => 'ModelTest',
:value => 9,
:unit => 'None'
}
tests('#new').returns(new_attributes) do
Fog::AWS[:cloud_watch].metric_statistics.new(new_attributes).attributes
end
tests('#create').returns(new_attributes) do
Fog::AWS[:cloud_watch].metric_statistics.create(new_attributes).attributes
end
stats_set_attributes = {
:namespace => 'Custom/Test',
:metric_name => 'ModelTest',
:minimum => 0,
:maximum => 4,
:sum => 10,
:sample_count => 5,
:average => 2,
:unit => 'None'
}
tests('#create_stats_set').returns(stats_set_attributes) do
Fog::AWS[:cloud_watch].metric_statistics.create(stats_set_attributes).attributes
end
end
end
fog-aws-0.7.6/tests/models/cloud_watch/alarm_history_tests.rb 0000644 0000041 0000041 00000001022 12576636531 024475 0 ustar www-data www-data Shindo.tests("AWS::CloudWatch | alarm_histories", ['aws', 'cloudwatch']) do
pending if Fog.mocking?
tests('success') do
tests("#all").succeeds do
Fog::AWS[:cloud_watch].alarm_histories.all
end
new_attributes = {
:alarm_name => 'tmp-alarm',
:end_date => '',
:history_item_type => 'StateUpdate',
:max_records => 1,
:start_date => ''
}
tests('#new').returns(new_attributes) do
Fog::AWS[:cloud_watch].alarm_histories.new(new_attributes).attributes
end
end
end
fog-aws-0.7.6/tests/models/glacier/ 0000755 0000041 0000041 00000000000 12576636531 017170 5 ustar www-data www-data fog-aws-0.7.6/tests/models/glacier/model_tests.rb 0000644 0000041 0000041 00000002747 12576636531 022051 0 ustar www-data www-data Shindo.tests('AWS::Glacier | models', ['aws', 'glacier']) do
pending if Fog.mocking?
tests('success') do
tests('vaults') do
tests('getting a missing vault') do
returns(nil) { Fog::AWS[:glacier].vaults.get('no-such-vault') }
end
vault = nil
tests('creating a vault') do
vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault'
tests("id is Fog-Test-Vault").returns('Fog-Test-Vault') {vault.id}
end
tests('all') do
tests('contains vault').returns(true) { Fog::AWS[:glacier].vaults.map {|vault| vault.id}.include?(vault.id)}
end
tests('destroy') do
vault.destroy
tests('removes vault').returns(nil) {Fog::AWS[:glacier].vaults.get(vault.id)}
end
end
tests("archives") do
vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault-upload'
tests('create') do
archive = vault.archives.create(:body => 'data')
tests('sets id').returns(true) {!archive.id.nil?}
archive.destroy
end
tests('create multipart') do
body = StringIO.new('x'*1024*1024*2)
body.rewind
archive = vault.archives.create(:body => body, :multipart_chunk_size => 1024*1024)
tests('sets id').returns(true) {!archive.id.nil?}
archive.destroy
end
end
vault = Fog::AWS[:glacier].vaults.create :id => 'Fog-Test-Vault'
tests("jobs") do
tests('all').returns([]) {vault.jobs}
end
vault.destroy
end
end
fog-aws-0.7.6/tests/models/dns/ 0000755 0000041 0000041 00000000000 12576636531 016346 5 ustar www-data www-data fog-aws-0.7.6/tests/models/dns/zones_tests.rb 0000644 0000041 0000041 00000000237 12576636531 021255 0 ustar www-data www-data Shindo.tests("Fog::DNS[:aws] | zones", ['aws', 'dns']) do
params = {:domain => generate_unique_domain }
collection_tests(Fog::DNS[:aws].zones, params)
end
fog-aws-0.7.6/tests/models/dns/zone_tests.rb 0000644 0000041 0000041 00000000231 12576636531 021064 0 ustar www-data www-data Shindo.tests("Fog::DNS[:aws] | zone", ['aws', 'dns']) do
params = {:domain => generate_unique_domain }
model_tests(Fog::DNS[:aws].zones, params)
end
fog-aws-0.7.6/tests/models/dns/records_tests.rb 0000644 0000041 0000041 00000002064 12576636531 021560 0 ustar www-data www-data Shindo.tests("Fog::DNS[:aws] | records", ['aws', 'dns']) do
tests("zones#create").succeeds do
@zone = Fog::DNS[:aws].zones.create(:domain => generate_unique_domain)
end
param_groups = [
# A record
{ :name => @zone.domain, :type => 'A', :ttl => 3600, :value => ['1.2.3.4'] },
# CNAME record
{ :name => "www.#{@zone.domain}", :type => "CNAME", :ttl => 300, :value => @zone.domain}
]
param_groups.each do |params|
collection_tests(@zone.records, params)
end
records = []
100.times do |i|
records << @zone.records.create(:name => "#{i}.#{@zone.domain}", :type => "A", :ttl => 3600, :value => ['1.2.3.4'])
end
records << @zone.records.create(:name => "*.#{@zone.domain}", :type => "A", :ttl => 3600, :value => ['1.2.3.4'])
tests("#all!").returns(101) do
@zone.records.all!.size
end
tests("#all wildcard parsing").returns(true) do
@zone.records.map(&:name).include?("*.#{@zone.domain}")
end
records.each do |record|
record.destroy
end
tests("zones#destroy").succeeds do
@zone.destroy
end
end
fog-aws-0.7.6/tests/models/dns/record_tests.rb 0000644 0000041 0000041 00000001610 12576636531 021371 0 ustar www-data www-data Shindo.tests("Fog::Dns[:aws] | record", ['aws', 'dns']) do
tests("zones#create").succeeds do
@zone = Fog::DNS[:aws].zones.create(:domain => generate_unique_domain)
end
params = { :name => @zone.domain, :type => 'A', :ttl => 3600, :value => ['1.2.3.4'] }
model_tests(@zone.records, params) do
# Newly created records should have a change id
tests("#change_id") do
returns(true) { @instance.change_id != nil }
end
# Waits for changes to sync to all Route 53 DNS servers. Usually takes ~30 seconds to complete.
tests("#ready? - may take a minute to complete...").succeeds do
@instance.wait_for { ready? }
end
tests("#modify") do
new_value = ['5.5.5.5']
returns(true) { @instance.modify(:value => new_value) }
returns(new_value) { @instance.value }
end
end
tests("zones#destroy").succeeds do
@zone.destroy
end
end
fog-aws-0.7.6/tests/models/elb/ 0000755 0000041 0000041 00000000000 12576636531 016324 5 ustar www-data www-data fog-aws-0.7.6/tests/models/elb/tagging_tests.rb 0000644 0000041 0000041 00000001041 12576636531 021507 0 ustar www-data www-data Shindo.tests("AWS::ELB | tagging", ['aws', 'elb']) do
@elb5 = Fog::AWS[:elb].load_balancers.create(:id => "fog-test-elb-tagging")
tags1 = {'key1' => 'val1'}
tags2 = {'key2' => 'val2'}
tests "add and remove tags from an ELB" do
returns({}) { @elb5.tags }
returns(tags1) { @elb5.add_tags tags1 }
returns(tags1.merge tags2) { @elb5.add_tags tags2 }
returns(tags2) { @elb5.remove_tags tags1.keys }
returns(tags2) { @elb5.tags }
@elb5.destroy
end
end
fog-aws-0.7.6/tests/models/elb/model_tests.rb 0000644 0000041 0000041 00000033772 12576636531 021207 0 ustar www-data www-data Shindo.tests('AWS::ELB | models', ['aws', 'elb']) do
Fog::Compute::AWS::Mock.reset if Fog.mocking?
@availability_zones = Fog::Compute[:aws].describe_availability_zones('state' => 'available').body['availabilityZoneInfo'].map{ |az| az['zoneName'] }
@key_name = 'fog-test-model'
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@vpc_id = @vpc.id
@subnet = Fog::Compute[:aws].subnets.create({:vpc_id => @vpc_id, :cidr_block => '10.0.10.0/24'})
@subnet_id = @subnet.subnet_id
@scheme = 'internal'
@igw = Fog::Compute[:aws].internet_gateways.create
@igw_id = @igw.id
@igw.attach(@vpc_id)
tests('success') do
tests('load_balancers') do
tests('getting a missing elb') do
returns(nil) { Fog::AWS[:elb].load_balancers.get('no-such-elb') }
end
end
tests('listeners') do
tests("default attributes") do
listener = Fog::AWS[:elb].listeners.new
tests('instance_port is 80').returns(80) { listener.instance_port }
tests('instance_protocol is HTTP').returns('HTTP') { listener.instance_protocol }
tests('lb_port is 80').returns(80) { listener.lb_port }
tests('protocol is HTTP').returns('HTTP') { listener.protocol }
tests('policy_names is empty').returns([]) { listener.policy_names }
end
tests("specifying attributes") do
attributes = {:instance_port => 2000, :instance_protocol => 'SSL', :lb_port => 2001, :protocol => 'SSL', :policy_names => ['fake'] }
listener = Fog::AWS[:elb].listeners.new(attributes)
tests('instance_port is 2000').returns(2000) { listener.instance_port }
tests('instance_protocol is SSL').returns('SSL') { listener.instance_protocol }
tests('lb_port is 2001').returns(2001) { listener.lb_port }
tests('protocol is SSL').returns('SSL') { listener.protocol }
tests('policy_names is [ fake ]').returns(['fake']) { listener.policy_names }
end
end
elb = nil
elb_id = 'fog-test'
tests('create') do
tests('without availability zones') do
elb = Fog::AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => @availability_zones)
tests("availability zones are correct").returns(@availability_zones.sort) { elb.availability_zones.sort }
tests("dns names is set").returns(true) { elb.dns_name.is_a?(String) }
tests("created_at is set").returns(true) { Time === elb.created_at }
tests("policies is empty").returns([]) { elb.policies }
tests("default listener") do
tests("1 listener").returns(1) { elb.listeners.size }
tests("params").returns(Fog::AWS[:elb].listeners.new.to_params) { elb.listeners.first.to_params }
end
end
tests('with vpc') do
elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :subnet_ids => [@subnet_id])
tests("elb source group should be default").returns('default') { elb2.source_group["GroupName"] }
tests("subnet ids are correct").returns(@subnet_id) { elb2.subnet_ids.first }
elb2.destroy
end
tests('with vpc internal') do
elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :subnet_ids => [@subnet_id], :scheme => 'internal')
tests("scheme is internal").returns(@scheme) { elb2.scheme }
elb2.destroy
end
tests('with default vpc') do
Fog::Compute[:aws].disable_ec2_classic if Fog.mocking?
if Fog::Compute[:aws].supported_platforms.include?("EC2")
Fog::Formatador.display_line("[yellow]Skipping test [bold]with default vpc[/][yellow] due to AWS account having EC2 available[/]")
else
elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :availability_zones => @availability_zones[0])
tests("elb source group should start with default_elb_").returns(true) { !!(elb2.source_group["GroupName"] =~ /default_elb_/) }
elb2.destroy
end
Fog::Compute[:aws].enable_ec2_classic if Fog.mocking?
end
if !Fog.mocking?
@igw.detach(@vpc_id)
@igw.destroy
@subnet.destroy
sleep 5
@vpc.destroy
end
tests('with availability zones') do
azs = @availability_zones[1..-1]
elb2 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-2", :availability_zones => azs)
if Fog::Compute[:aws].supported_platforms.include?("EC2")
tests("elb source group should be amazon-elb-sg").returns('amazon-elb-sg') { elb2.source_group["GroupName"] }
else
tests("elb source group should match default_elb_").returns(true) { !!(elb2.source_group["GroupName"] =~ /default_elb_/) }
end
tests("availability zones are correct").returns(azs.sort) { elb2.availability_zones.sort }
elb2.destroy
end
# Need to sleep here for IAM changes to propgate
tests('with ListenerDescriptions') do
@certificate = Fog::AWS[:iam].upload_server_certificate(AWS::IAM::SERVER_CERT, AWS::IAM::SERVER_CERT_PRIVATE_KEY, @key_name).body['Certificate']
sleep(10) unless Fog.mocking?
listeners = [{
'Listener' => {
'LoadBalancerPort' => 2030, 'InstancePort' => 2030, 'Protocol' => 'HTTP'
},
'PolicyNames' => []
}, {
'Listener' => {
'LoadBalancerPort' => 443, 'InstancePort' => 443, 'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS',
'SSLCertificateId' => @certificate['Arn']
},
'PolicyNames' => []
}]
elb3 = Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-3", 'ListenerDescriptions' => listeners, :availability_zones => @availability_zones)
tests('there are 2 listeners').returns(2) { elb3.listeners.count }
tests('instance_port is 2030').returns(2030) { elb3.listeners.first.instance_port }
tests('lb_port is 2030').returns(2030) { elb3.listeners.first.lb_port }
tests('protocol is HTTP').returns('HTTP') { elb3.listeners.first.protocol }
tests('protocol is HTTPS').returns('HTTPS') { elb3.listeners.last.protocol }
tests('instance_protocol is HTTPS').returns('HTTPS') { elb3.listeners.last.instance_protocol }
elb3.destroy
end
tests('with invalid Server Cert ARN').raises(Fog::AWS::IAM::NotFound) do
listeners = [{
'Listener' => {
'LoadBalancerPort' => 443, 'InstancePort' => 80, 'Protocol' => 'HTTPS', 'InstanceProtocol' => 'HTTPS', "SSLCertificateId" => "fakecert"}
}]
Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-4", "ListenerDescriptions" => listeners, :availability_zones => @availability_zones)
end
end
tests('all') do
elb_ids = Fog::AWS[:elb].load_balancers.all.map{|e| e.id}
tests("contains elb").returns(true) { elb_ids.include? elb_id }
end
if Fog.mocking?
tests('all marker support') do
extra_elb_ids = (1..1000).map {|n| Fog::AWS[:elb].load_balancers.create(:id => "#{elb_id}-extra-#{n}").id }
tests('returns all elbs').returns(true) { (extra_elb_ids - Fog::AWS[:elb].load_balancers.all.map {|e| e.id }).empty? }
end
end
tests('get') do
tests('ids match').returns(elb_id) { Fog::AWS[:elb].load_balancers.get(elb_id).id }
tests('nil id').returns(nil) { Fog::AWS[:elb].load_balancers.get(nil) }
end
tests('creating a duplicate elb') do
raises(Fog::AWS::ELB::IdentifierTaken) do
Fog::AWS[:elb].load_balancers.create(:id => elb_id, :availability_zones => ['us-east-1d'])
end
end
tests('registering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.register_instances('i-00000000') }
end
tests('deregistering an invalid instance') do
raises(Fog::AWS::ELB::InvalidInstance) { elb.deregister_instances('i-00000000') }
end
server = Fog::Compute[:aws].servers.create
server.wait_for { ready? }
tests('register instance') do
begin
elb.register_instances(server.id)
rescue Fog::AWS::ELB::InvalidInstance
# It may take a moment for a newly created instances to be visible to ELB requests
raise if @retried_registered_instance
@retried_registered_instance = true
sleep 1
retry
end
returns([server.id]) { elb.instances }
end
tests('instance_health') do
returns('OutOfService') do
elb.instance_health.find{|hash| hash['InstanceId'] == server.id}['State']
end
returns([server.id]) { elb.instances_out_of_service }
end
tests('deregister instance') do
elb.deregister_instances(server.id)
returns([]) { elb.instances }
end
server.destroy
tests('disable_availability_zones') do
elb.disable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones[0..0]) { elb.availability_zones.sort }
end
tests('enable_availability_zones') do
elb.enable_availability_zones(@availability_zones[1..-1])
returns(@availability_zones) { elb.availability_zones.sort }
end
tests('connection_draining') do
returns(false) { elb.connection_draining? }
returns(300) { elb.connection_draining_timeout }
elb.set_connection_draining(true, 60)
returns(true) { elb.connection_draining? }
returns(60) { elb.connection_draining_timeout }
end
tests('cross_zone_load_balancing') do
returns(false) {elb.cross_zone_load_balancing?}
elb.cross_zone_load_balancing = true
returns(true) {elb.cross_zone_load_balancing?}
end
tests('idle_connection_settings') do
returns(60) { elb.connection_settings_idle_timeout }
elb.set_connection_settings_idle_timeout(180)
returns(180) { elb.connection_settings_idle_timeout }
end
tests('default health check') do
default_health_check = {
"HealthyThreshold"=>10,
"Timeout"=>5,
"UnhealthyThreshold"=>2,
"Interval"=>30,
"Target"=>"TCP:80"
}
returns(default_health_check) { elb.health_check }
end
tests('configure_health_check') do
new_health_check = {
"HealthyThreshold"=>5,
"Timeout"=>10,
"UnhealthyThreshold"=>3,
"Interval"=>15,
"Target"=>"HTTP:80/index.html"
}
elb.configure_health_check(new_health_check)
returns(new_health_check) { elb.health_check }
end
tests('listeners') do
tests('default') do
returns(1) { elb.listeners.size }
listener = elb.listeners.first
returns([80,80,'HTTP','HTTP', []]) { [listener.instance_port, listener.lb_port, listener.protocol, listener.instance_protocol, listener.policy_names] }
end
tests('#get') do
returns(80) { elb.listeners.get(80).lb_port }
end
tests('create') do
elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'TCP', :instance_protocol => 'TCP')
returns(2) { elb.listeners.size }
returns(443) { elb.listeners.get(443).lb_port }
end
tests('destroy') do
elb.listeners.get(443).destroy
returns(nil) { elb.listeners.get(443) }
end
end
tests('policies') do
app_policy_id = 'my-app-policy'
tests 'are empty' do
returns([]) { elb.policies.to_a }
end
tests('#all') do
returns([]) { elb.policies.all.to_a }
end
tests('create app policy') do
elb.policies.create(:id => app_policy_id, :cookie => 'my-app-cookie', :cookie_stickiness => :app)
returns(app_policy_id) { elb.policies.first.id }
returns("my-app-cookie") { elb.policies.get(app_policy_id).cookie }
end
tests('get policy') do
returns(app_policy_id) { elb.policies.get(app_policy_id).id }
end
tests('destroy app policy') do
elb.policies.first.destroy
returns([]) { elb.policies.to_a }
end
lb_policy_id = 'my-lb-policy'
tests('create lb policy') do
elb.policies.create(:id => lb_policy_id, :expiration => 600, :cookie_stickiness => :lb)
returns(lb_policy_id) { elb.policies.first.id }
end
tests('setting a listener policy') do
elb.set_listener_policy(80, lb_policy_id)
returns([lb_policy_id]) { elb.listeners.get(80).policy_names }
returns(600) { elb.policies.get(lb_policy_id).expiration }
end
tests('unsetting a listener policy') do
elb.unset_listener_policy(80)
returns([]) { elb.listeners.get(80).policy_names }
end
public_key_policy_id = 'fog-public-key-policy'
tests('create public key policy') do
elb.policies.create(:id => public_key_policy_id, :type_name => 'PublicKeyPolicyType', :policy_attributes => {'PublicKey' => AWS::IAM::SERVER_CERT_PUBLIC_KEY})
policy = elb.policies.get(public_key_policy_id)
returns(public_key_policy_id) { policy.id }
returns("PublicKeyPolicyType") { policy.type_name }
returns(AWS::IAM::SERVER_CERT_PUBLIC_KEY) { policy.policy_attributes["PublicKey"] }
end
tests('a malformed policy') do
raises(ArgumentError) { elb.policies.create(:id => 'foo', :cookie_stickiness => 'invalid stickiness') }
end
end
tests('backend server descriptions') do
tests('default') do
returns(0) { elb.backend_server_descriptions.size }
end
tests('with a backend policy') do
policy = "EnableProxyProtocol"
port = 80
elb.policies.create(:id => policy, :type_name => 'ProxyProtocolPolicyType', :policy_attributes => { "ProxyProtocol" => true })
Fog::AWS[:elb].set_load_balancer_policies_for_backend_server(elb.id, port, [policy]).body
elb.reload
returns([policy]) { elb.backend_server_descriptions.get(port).policy_names }
end
end
tests('setting a new ssl certificate id') do
elb.listeners.create(:instance_port => 443, :lb_port => 443, :protocol => 'HTTPS', :instance_protocol => 'HTTPS', :ssl_id => @certificate['Arn'])
elb.set_listener_ssl_certificate(443, @certificate['Arn'])
end
tests('destroy') do
elb.destroy
end
Fog::AWS[:iam].delete_server_certificate(@key_name)
end
end
fog-aws-0.7.6/tests/models/data_pipeline/ 0000755 0000041 0000041 00000000000 12576636531 020360 5 ustar www-data www-data fog-aws-0.7.6/tests/models/data_pipeline/pipeline_tests.rb 0000644 0000041 0000041 00000000451 12576636531 023734 0 ustar www-data www-data Shindo.tests("AWS::DataPipeline | pipelines", ['aws', 'data_pipeline']) do
pending if Fog.mocking?
unique_id = uniq_id
model_tests(Fog::AWS[:data_pipeline].pipelines, { :id => unique_id, :name => "#{unique_id}-name", :unique_id => unique_id }) do
@instance.wait_for { state }
end
end
fog-aws-0.7.6/tests/models/data_pipeline/pipelines_tests.rb 0000644 0000041 0000041 00000000456 12576636531 024124 0 ustar www-data www-data Shindo.tests("AWS::DataPipeline | pipelines", ['aws', 'data_pipeline']) do
pending if Fog.mocking?
unique_id = uniq_id
collection_tests(Fog::AWS[:data_pipeline].pipelines, { :id => unique_id, :name => "#{unique_id}-name", :unique_id => unique_id }) do
@instance.wait_for { state }
end
end
fog-aws-0.7.6/tests/models/cdn/ 0000755 0000041 0000041 00000000000 12576636531 016326 5 ustar www-data www-data fog-aws-0.7.6/tests/models/cdn/streaming_distribution_tests.rb 0000644 0000041 0000041 00000001136 12576636531 024666 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | streaming_distribution", ['aws', 'cdn']) do
params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true }
model_tests(Fog::CDN[:aws].streaming_distributions, params, true) do
# distribution needs to be ready before being disabled
tests("#ready? - may take 15 minutes to complete...").succeeds do
@instance.wait_for { ready? }
end
# and disabled before being distroyed
tests("#disable - may take 15 minutes to complete...").succeeds do
@instance.disable
@instance.wait_for { ready? }
end
end
end
fog-aws-0.7.6/tests/models/cdn/streaming_distributions_tests.rb 0000644 0000041 0000041 00000001143 12576636531 025047 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | streaming_distributions", ['aws', 'cdn']) do
params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true}
collection_tests(Fog::CDN[:aws].streaming_distributions, params, true) do
# distribution needs to be ready before being disabled
tests("#ready? - may take 15 minutes to complete...").succeeds do
@instance.wait_for { ready? }
end
# and disabled before being distroyed
tests("#disable - may take 15 minutes to complete...").succeeds do
@instance.disable
@instance.wait_for { ready? }
end
end
end
fog-aws-0.7.6/tests/models/cdn/distribution_tests.rb 0000644 0000041 0000041 00000001112 12576636531 022607 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | distribution", ['aws', 'cdn']) do
params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true }
model_tests(Fog::CDN[:aws].distributions, params, true) do
# distribution needs to be ready before being disabled
tests("#ready? - may take 15 minutes to complete...").succeeds do
@instance.wait_for { ready? }
end
# and disabled before being distroyed
tests("#disable - may take 15 minutes to complete...").succeeds do
@instance.disable
@instance.wait_for { ready? }
end
end
end
fog-aws-0.7.6/tests/models/cdn/distributions_tests.rb 0000644 0000041 0000041 00000001117 12576636531 022777 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | distributions", ['aws', 'cdn']) do
params = { :s3_origin => { 'DNSName' => 'fog_test_cdn.s3.amazonaws.com'}, :enabled => true}
collection_tests(Fog::CDN[:aws].distributions, params, true) do
# distribution needs to be ready before being disabled
tests("#ready? - may take 15 minutes to complete...").succeeds do
@instance.wait_for { ready? }
end
# and disabled before being distroyed
tests("#disable - may take 15 minutes to complete...").succeeds do
@instance.disable
@instance.wait_for { ready? }
end
end
end
fog-aws-0.7.6/tests/models/cdn/invalidations_tests.rb 0000644 0000041 0000041 00000001053 12576636531 022740 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | invalidations", ['aws', 'cdn']) do
tests("distributions#create").succeeds do
@distribution = Fog::CDN[:aws].distributions.create(:s3_origin => {'DNSName' => 'fog_test.s3.amazonaws.com'}, :enabled => true)
end
collection_tests(@distribution.invalidations, { :paths => [ '/index.html' ]}, true)
tests("distribution#destroy - may take 15/20 minutes to complete").succeeds do
@distribution.wait_for { ready? }
@distribution.disable
@distribution.wait_for { ready? }
@distribution.destroy
end
end
fog-aws-0.7.6/tests/models/cdn/invalidation_tests.rb 0000644 0000041 0000041 00000001635 12576636531 022563 0 ustar www-data www-data Shindo.tests("Fog::CDN[:aws] | invalidation", ['aws', 'cdn']) do
tests("distributions#create").succeeds do
@distribution = Fog::CDN[:aws].distributions.create(:s3_origin => {'DNSName' => 'fog_test.s3.amazonaws.com'}, :enabled => true)
end
params = { :paths => [ '/index.html', '/path/to/index.html' ] }
model_tests(@distribution.invalidations, params, true) do
tests("#id") do
returns(true) { @instance.identity != nil }
end
tests("#paths") do
returns([ '/index.html', '/path/to/index.html' ].sort) { @instance.paths.sort }
end
tests("#ready? - may take 15 minutes to complete...").succeeds do
@instance.wait_for { ready? }
end
end
tests("distribution#destroy - may take around 15/20 minutes to complete...").succeeds do
@distribution.wait_for { ready? }
@distribution.disable
@distribution.wait_for { ready? }
@distribution.destroy
end
end
fog-aws-0.7.6/tests/models/rds/ 0000755 0000041 0000041 00000000000 12576636531 016352 5 ustar www-data www-data fog-aws-0.7.6/tests/models/rds/security_group_tests.rb 0000644 0000041 0000041 00000003354 12576636531 023211 0 ustar www-data www-data Shindo.tests("AWS::RDS | security_group", ['aws', 'rds']) do
group_name = 'fog-test'
params = {:id => group_name, :description => 'fog test'}
model_tests(Fog::AWS[:rds].security_groups, params) do
tests("#description").returns('fog test') { @instance.description }
tests("#authorize_ec2_security_group").succeeds do
@ec2_sec_group = Fog::Compute[:aws].security_groups.create(:name => 'fog-test', :description => 'fog test')
@instance.authorize_ec2_security_group(@ec2_sec_group.name)
returns('authorizing') do
@instance.ec2_security_groups.find{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name}['Status']
end
end
@instance.wait_for { ready? }
tests("#revoke_ec2_security_group").succeeds do
pending if Fog.mocking?
@instance.revoke_ec2_security_group(@ec2_sec_group.name)
returns('revoking') do
@instance.ec2_security_groups.find{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name}['Status']
end
@instance.wait_for { ready? }
returns(false) { @instance.ec2_security_groups.any?{|h| h['EC2SecurityGroupName'] == @ec2_sec_group.name} }
@ec2_sec_group.destroy
end
tests("#authorize_cidrip").succeeds do
@cidr = '127.0.0.1/32'
@instance.authorize_cidrip(@cidr)
returns('authorizing') { @instance.ip_ranges.find{|h| h['CIDRIP'] == @cidr}['Status'] }
end
tests("#revoke_cidrip").succeeds do
pending if Fog.mocking?
@instance.wait_for { ready? }
@instance.revoke_cidrip(@cidr)
returns('revoking') { @instance.ip_ranges.find{|h| h['CIDRIP'] == @cidr}['Status'] }
@instance.wait_for { ready? }
returns(false) { @instance.ip_ranges.any?{|h| h['CIDRIP'] == @cidr} }
end
end
end
fog-aws-0.7.6/tests/models/rds/snapshots_tests.rb 0000644 0000041 0000041 00000000514 12576636531 022143 0 ustar www-data www-data Shindo.tests("AWS::RDS | snapshots", ['aws', 'rds']) do
@server = Fog::AWS[:rds].servers.create(rds_default_server_params)
@server.wait_for { ready? }
params = {:id => uniq_id, :instance_id => @server.id}
collection_tests(Fog::AWS[:rds].snapshots, params) do
@instance.wait_for { ready? }
end
@server.destroy
end
fog-aws-0.7.6/tests/models/rds/helper.rb 0000644 0000041 0000041 00000000566 12576636531 020165 0 ustar www-data www-data def rds_default_server_params
{
:allocated_storage => 5,
:backup_retention_period => 0,
:engine => 'mysql',
:version => '5.6.22',
:id => uniq_id,
:master_username => 'foguser',
:password => 'fogpassword',
:flavor_id => 'db.m3.medium',
}
end
fog-aws-0.7.6/tests/models/rds/event_subscription_tests.rb 0000644 0000041 0000041 00000000413 12576636531 024044 0 ustar www-data www-data Shindo.tests("AWS::RDS | event_subscription", ['aws', 'rds']) do
pending unless Fog.mocking?
name = 'fog'
params = {:id => name, :sns_topic_arn => 'arn:aws:sns:us-east-1:12345678910:fog'}
model_tests(Fog::AWS[:rds].event_subscriptions, params) do
end
end
fog-aws-0.7.6/tests/models/rds/parameter_groups_tests.rb 0000644 0000041 0000041 00000000416 12576636531 023501 0 ustar www-data www-data Shindo.tests("AWS::RDS | parameter_groups", ['aws', 'rds']) do
group_name = 'fog-test'
params = {:id => group_name, :family => 'mysql5.1', :description => group_name}
pending if Fog.mocking?
collection_tests(Fog::AWS[:rds].parameter_groups, params, false)
end
fog-aws-0.7.6/tests/models/rds/server_tests.rb 0000644 0000041 0000041 00000010722 12576636531 021431 0 ustar www-data www-data Shindo.tests("AWS::RDS | server", ['aws', 'rds']) do
model_tests(Fog::AWS[:rds].servers, rds_default_server_params) do
# We'll need this later; create it early to avoid waiting
@instance_with_final_snapshot = Fog::AWS[:rds].servers.create(rds_default_server_params.merge(:id => uniq_id("fog-snapshot-test"), :backup_retention_period => 1))
@instance_with_encrypted_storage = Fog::AWS[:rds].servers.create(rds_default_server_params.merge(:storage_encrypted => true))
@instance.wait_for(20*60) { ready? }
@instance_with_encrypted_storage.wait_for(20*60) { ready? }
tests("#storage_encrypted") do
returns(true) { @instance_with_encrypted_storage.storage_encrypted }
end
test('#read_replica_identifiers is []') do
returns([]) { @instance.read_replica_identifiers }
end
tests('#snapshots') do
snapshot = nil
tests('#create').succeeds do
snapshot = @instance.snapshots.create(:id => uniq_id('fog-snapshot-test'))
end
snapshot.wait_for { ready?}
@instance.wait_for { ready? }
returns(true) { @instance.snapshots.map{ |s| s.id }.include?(snapshot.id) }
snapshot.destroy
end
tests("#modify").succeeds do
pending if Fog.mocking?
engine = rds_default_server_params.fetch(:engine)
version = rds_default_server_params.fetch(:version).match(/\d+\.\d+/).to_s
orig_parameter_group = @instance.db_parameter_groups.first['DBParameterGroupName']
parameter_group = Fog::AWS[:rds].parameter_groups.create(:id => uniq_id, :family => "#{engine}#{version}", :description => 'fog-test')
orig_security_groups = @instance.db_security_groups.map{|h| h['DBSecurityGroupName']}
security_group = Fog::AWS[:rds].security_groups.create(:id => uniq_id, :description => 'fog-test')
modify_options = {
'DBParameterGroupName' => parameter_group.id,
'DBSecurityGroups' => orig_security_groups + [security_group.id]
}
@instance.modify(true, modify_options)
@instance.wait_for { ready? }
returns(parameter_group.id, 'new parameter group') do
@instance.db_parameter_groups.first['DBParameterGroupName']
end
returns(true, "new security group") do
@instance.db_security_groups.any?{|hash| hash['DBSecurityGroupName'] == security_group.id}
end
@instance.reboot
@instance.wait_for { state == 'rebooting' }
@instance.wait_for { ready? }
# Restore back to original state using symbols
restore_options = {
:parameter_group_name => orig_parameter_group,
:security_group_names => orig_security_groups
}
@instance.modify(true, restore_options)
@instance.reboot
@instance.wait_for { state == 'rebooting' }
@instance.wait_for do
ready? &&
db_security_groups.all? {|hash| hash['Status'] == 'active'} &&
db_parameter_groups.all? {|hash| hash['ParameterApplyStatus'] == 'in-sync' }
end
parameter_group.destroy
security_group.destroy
end
tests("#reboot").succeeds do
@instance.reboot
end
@instance.wait_for { state == 'rebooting' }
@instance.wait_for { ready? }
replica = nil
tests('#create_read_replica').succeeds do
replica = @instance_with_final_snapshot.create_read_replica(uniq_id('fog-replica'))
@instance_with_final_snapshot.reload
returns([replica.id]) { @instance_with_final_snapshot.read_replica_identifiers }
returns(@instance_with_final_snapshot.id) { replica.read_replica_source }
replica.wait_for { ready? }
# FinalDBSnapshotIdentifier can not be specified when deleting a replica instance
raises(Fog::AWS::RDS::Error) { replica.destroy("foobar") }
end
tests('#promote_read_replica').succeeds do
replica.promote.wait_for { state != "modifying" }
replica.read_replica_source == nil
end
tests('#promote_read_replica', 'master').raises(Fog::AWS::RDS::Error) {
@instance_with_final_snapshot.promote
}
replica && replica.destroy
test("Destroying with a final snapshot") do
final_snapshot_id = uniq_id('fog-test-snapshot')
@instance_with_final_snapshot.wait_for { ready? }
@instance_with_final_snapshot.destroy(final_snapshot_id)
returns(true, "Final snapshot created") do
@final_snapshot = Fog::AWS[:rds].snapshots.get(final_snapshot_id)
!@final_snapshot.nil?
end
@final_snapshot.wait_for { ready? }
@final_snapshot.destroy
end
end
end
fog-aws-0.7.6/tests/models/rds/tagging_tests.rb 0000644 0000041 0000041 00000001336 12576636531 021544 0 ustar www-data www-data Shindo.tests("AWS::RDS | tagging", ['aws', 'rds']) do
@server = Fog::AWS[:rds].servers.create(rds_default_server_params)
Fog::Formatador.display_line "Creating RDS instance #{@server.id}"
Fog::Formatador.display_line "Waiting for instance #{@server.id} to be ready"
@server.wait_for { ready? }
tags1 = {'key1' => 'val1'}
tags2 = {'key2' => 'val2'}
tests "add and remove tags from a running RDS model" do
returns({}) { @server.tags }
returns(tags1) { @server.add_tags tags1 }
returns(tags1.merge tags2) { @server.add_tags tags2 }
returns(tags2) { @server.remove_tags tags1.keys }
returns(tags2) { @server.tags }
end
@server.destroy
end
fog-aws-0.7.6/tests/models/rds/security_groups_tests.rb 0000644 0000041 0000041 00000000271 12576636531 023367 0 ustar www-data www-data Shindo.tests("AWS::RDS | security groups", ['aws', 'rds']) do
params = {:id => 'fog-test', :description => 'fog test'}
collection_tests(Fog::AWS[:rds].security_groups, params)
end
fog-aws-0.7.6/tests/models/rds/event_subscriptions_tests.rb 0000644 0000041 0000041 00000000371 12576636531 024232 0 ustar www-data www-data Shindo.tests("AWS::RDS | event subscriptions", ['aws', 'rds']) do
pending unless Fog.mocking?
params = {:id => "fog", :sns_topic_arn => 'arn:aws:sns:us-east-1:12345678910:fog'}
collection_tests(Fog::AWS[:rds].event_subscriptions, params)
end
fog-aws-0.7.6/tests/models/rds/snapshot_tests.rb 0000644 0000041 0000041 00000000506 12576636531 021761 0 ustar www-data www-data Shindo.tests("AWS::RDS | snapshot", ['aws', 'rds']) do
@server = Fog::AWS[:rds].servers.create(rds_default_server_params)
@server.wait_for { ready? }
params = {:id => uniq_id, :instance_id => @server.id}
model_tests(Fog::AWS[:rds].snapshots, params) do
@instance.wait_for { ready? }
end
@server.destroy
end
fog-aws-0.7.6/tests/models/rds/servers_tests.rb 0000644 0000041 0000041 00000000254 12576636531 021613 0 ustar www-data www-data Shindo.tests("AWS::RDS | servers", ['aws', 'rds']) do
collection_tests(Fog::AWS[:rds].servers, rds_default_server_params) do
@instance.wait_for { ready? }
end
end
fog-aws-0.7.6/tests/models/rds/parameter_group_tests.rb 0000644 0000041 0000041 00000001374 12576636531 023322 0 ustar www-data www-data Shindo.tests("AWS::RDS | parameter_group", ['aws', 'rds']) do
group_name = 'fog-test'
params = {:id => group_name, :family => 'mysql5.1', :description => group_name}
pending if Fog.mocking?
model_tests(Fog::AWS[:rds].parameter_groups, params, false) do
tests('#parameters') do
#search for a sample parameter
tests 'contains parameters' do
returns(true){ @instance.parameters.any? {|p| p.name == 'query_cache_size'}}
end
end
tests('#modify') do
@instance.modify([{:name => 'query_cache_size', :value => '6553600', :apply_method => 'immediate'}])
tests 'parameter has changed' do
returns('6553600'){@instance.parameters.find {|p| p.name == 'query_cache_size'}.value}
end
end
end
end
fog-aws-0.7.6/tests/models/rds/instance_option_tests.rb 0000644 0000041 0000041 00000000473 12576636531 023321 0 ustar www-data www-data Shindo.tests("AWS::RDS | db instance options", ['aws', 'rds']) do
params = {:engine => 'mysql'}
pending if Fog.mocking?
tests('#options') do
tests 'contains options' do
@instance = Fog::AWS[:rds].instance_options.new(params)
returns(true) { @instance.engine == 'mysql' }
end
end
end
fog-aws-0.7.6/tests/models/compute/ 0000755 0000041 0000041 00000000000 12576636531 017236 5 ustar www-data www-data fog-aws-0.7.6/tests/models/compute/security_group_tests.rb 0000644 0000041 0000041 00000004665 12576636531 024103 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | security_group", ['aws']) do
model_tests(Fog::Compute[:aws].security_groups, {:description => 'foggroupdescription', :name => 'foggroupname'}, true)
tests("authorize and revoke helpers") do
@group = Fog::Compute[:aws].security_groups.create(:name => "foggroup", :description => "fog group desc")
@other_group = Fog::Compute[:aws].security_groups.create(:name => 'fog other group', :description => 'another fog group')
@other_group.reload
@other_user_id = Fog::AWS::Mock.owner_id
@other_users_group_id = Fog::AWS::Mock.security_group_id
test("authorize access by another security group") do
@group.authorize_group_and_owner(@other_group.name)
@group.reload
@group.ip_permissions.size == 3
end
test("revoke access from another security group") do
@group.revoke_group_and_owner(@other_group.name)
@group.reload
@group.ip_permissions.empty?
end
test("authorize access to a port range") do
@group.authorize_port_range(5000..6000)
@group.reload
@group.ip_permissions.size == 1
end
test("revoke access to a port range") do
@group.revoke_port_range(5000..6000)
@group.reload
@group.ip_permissions.empty?
end
group_forms = [
"#{@other_group.owner_id}:#{@other_group.group_id}", # deprecated form
@other_group.group_id,
{@other_group.owner_id => @other_group.group_id},
]
group_forms.each do |group_arg|
test("authorize port range access by another security group #{group_arg.inspect}") do
@other_group.reload
@group.authorize_port_range(5000..6000, {:group => group_arg})
@group.reload
@group.ip_permissions.size == 1
end
test("revoke port range access by another security group") do
@other_group.reload
@group.revoke_port_range(5000..6000, {:group => group_arg})
@group.reload
@group.ip_permissions.empty?
end
end
[
{ @other_user_id => @other_users_group_id }
].each do |group_arg|
test("does not authorize port range access by an invalid security group #{group_arg.inspect}") do
raises(Fog::Compute::AWS::NotFound, "The security group '#{@other_users_group_id}' does not exist") {
@other_group.reload
@group.authorize_port_range(5000..6000, {:group => group_arg})
}
end
end
@other_group.destroy
@group.destroy
end
end
fog-aws-0.7.6/tests/models/compute/network_acls_tests.rb 0000644 0000041 0000041 00000001113 12576636531 023474 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | network_acls", ['aws']) do
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
collection_tests(Fog::Compute[:aws].network_acls, { :vpc_id => @vpc.id }, true)
tests('tags') do
test_tags = {'foo' => 'bar'}
@acl = Fog::Compute[:aws].network_acls.create(:vpc_id => @vpc.id, :tags => test_tags)
tests('@acl.tags').returns(test_tags) do
@acl.reload.tags
end
unless Fog.mocking?
Fog::Compute[:aws].tags.all('resource-id' => @acl.identity).each {|tag| tag.destroy}
end
end
@vpc.destroy
end
fog-aws-0.7.6/tests/models/compute/snapshots_tests.rb 0000644 0000041 0000041 00000000452 12576636531 023030 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | snapshots", ['aws']) do
@volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1)
@volume.wait_for { ready? }
collection_tests(Fog::Compute[:aws].snapshots, {:volume_id => @volume.identity}, true)
@volume.destroy
end
fog-aws-0.7.6/tests/models/compute/vpcs_tests.rb 0000644 0000041 0000041 00000000771 12576636531 021765 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | vpcs", ['aws']) do
collection_tests(Fog::Compute[:aws].vpcs, {:cidr_block => '10.0.10.0/28'}, true)
tests('tags') do
test_tags = {'foo' => 'bar'}
@vpc = Fog::Compute[:aws].vpcs.create(:cidr_block => '1.2.3.4/24', :tags => test_tags)
tests('@vpc.tags').returns(test_tags) do
@vpc.reload.tags
end
unless Fog.mocking?
Fog::Compute[:aws].tags.all('resource-id' => @vpc.id).each {|tag| tag.destroy}
end
@vpc.destroy
end
end
fog-aws-0.7.6/tests/models/compute/server_tests.rb 0000644 0000041 0000041 00000003743 12576636531 022322 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | monitor", ['aws']) do
@instance = Fog::Compute[:aws].servers.new
[:addresses, :flavor, :key_pair, :key_pair=, :volumes, :associate_public_ip].each do |association|
responds_to(association)
end
tests('new instance') do
test('#monitor = true') do
@instance.monitor = true
@instance.attributes[:monitoring] == true
end
test('#monitor = false') do
@instance.monitor = false
@instance.attributes[:monitoring] == false
end
test('#associate_public_ip = true') do
@instance.associate_public_ip = true
@instance.attributes[:associate_public_ip] == true
end
test('#associate_public_ip = false') do
@instance.associate_public_ip = false
@instance.associate_public_ip == false
end
end
tests('existing instance') do
@instance.save
[:id, :availability_zone, :flavor_id, :kernel_id, :image_id, :state].each do |attr|
test("instance##{attr} should not contain whitespace") do
nil == @instance.send(attr).match(/\s/)
end
end
test('#monitor = true') do
@instance.monitor = true
@instance.monitoring == true
end
test('#monitor = false') do
@instance.monitor = false
@instance.monitoring == false
end
test('#associate_public_ip = true') do
@instance.associate_public_ip = true
@instance.attributes[:associate_public_ip] == true
end
test('#associate_public_ip = false') do
@instance.associate_public_ip = false
@instance.associate_public_ip == false
end
end
@instance.destroy
tests('tags') do
@instance = Fog::Compute[:aws].servers.create(:tags => {'key' => 'value'})
@instance.wait_for { ready? }
tests('@instance.reload.tags').returns({'key' => 'value'}) do
@instance.reload.tags
end
unless Fog.mocking?
Fog::Compute[:aws].tags.all('resource-id' => @instance.identity).each {|tag| tag.destroy}
end
@instance.destroy
end
end
fog-aws-0.7.6/tests/models/compute/security_groups_tests.rb 0000644 0000041 0000041 00000000306 12576636531 024252 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | security_groups", ['aws']) do
collection_tests(Fog::Compute[:aws].security_groups, {:description => 'foggroupdescription', :name => 'foggroupname'}, true)
end
fog-aws-0.7.6/tests/models/compute/subnet_tests.rb 0000644 0000041 0000041 00000000432 12576636531 022304 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | subnet", ['aws']) do
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
model_tests(Fog::Compute[:aws].subnets, {:vpc_id => @vpc.id, :cidr_block => '10.0.10.0/28', :availability_zone => 'us-east-1b'}, true)
@vpc.destroy
end
fog-aws-0.7.6/tests/models/compute/snapshot_tests.rb 0000644 0000041 0000041 00000000444 12576636531 022646 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | snapshot", ['aws']) do
@volume = Fog::Compute[:aws].volumes.create(:availability_zone => 'us-east-1a', :size => 1)
@volume.wait_for { ready? }
model_tests(Fog::Compute[:aws].snapshots, {:volume_id => @volume.identity}, true)
@volume.destroy
end
fog-aws-0.7.6/tests/models/compute/volumes_tests.rb 0000644 0000041 0000041 00000000276 12576636531 022504 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | volumes", ['aws']) do
collection_tests(Fog::Compute[:aws].volumes, {:availability_zone => 'us-east-1a', :size => 1, :device => '/dev/sdz1'}, true)
end
fog-aws-0.7.6/tests/models/compute/dhcp_option_tests.rb 0000644 0000041 0000041 00000000337 12576636531 023316 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | dhcp_options", ['aws']) do
model_tests(Fog::Compute[:aws].dhcp_options, {'dhcp_configuration_set' => {'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}}, true)
end
fog-aws-0.7.6/tests/models/compute/internet_gateway_tests.rb 0000644 0000041 0000041 00000000205 12576636531 024353 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | internet_gateway", ['aws']) do
model_tests(Fog::Compute[:aws].internet_gateways , {}, true)
end
fog-aws-0.7.6/tests/models/compute/key_pair_tests.rb 0000644 0000041 0000041 00000001077 12576636531 022615 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | key_pair", ['aws']) do
model_tests(Fog::Compute[:aws].key_pairs, {:name => 'fogkeyname'}, true)
after do
@keypair.destroy
end
tests("new keypair") do
@keypair = Fog::Compute[:aws].key_pairs.create(:name => 'testkey')
test ("writable?") do
@keypair.writable? == true
end
end
tests("existing keypair") do
Fog::Compute[:aws].key_pairs.create(:name => 'testkey')
@keypair = Fog::Compute[:aws].key_pairs.get('testkey')
test("writable?") do
@keypair.writable? == false
end
end
end
fog-aws-0.7.6/tests/models/compute/key_pairs_tests.rb 0000644 0000041 0000041 00000000221 12576636531 022766 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | key_pairs", ['aws']) do
collection_tests(Fog::Compute[:aws].key_pairs, {:name => 'fogkeyname'}, true)
end
fog-aws-0.7.6/tests/models/compute/dhcp_options_tests.rb 0000644 0000041 0000041 00000000344 12576636531 023477 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | dhcp_options", ['aws']) do
collection_tests(Fog::Compute[:aws].dhcp_options, {'dhcp_configuration_set' => {'domain-name' => 'example.com', 'domain-name-servers' => '10.10.10.10'}}, true)
end
fog-aws-0.7.6/tests/models/compute/subnets_tests.rb 0000644 0000041 0000041 00000000441 12576636531 022467 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | subnets", ['aws']) do
@vpc=Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/28')
collection_tests(Fog::Compute[:aws].subnets, { :vpc_id => @vpc.id, :cidr_block => '10.0.10.0/28', :availability_zone => 'us-east-1c'}, true)
@vpc.destroy
end
fog-aws-0.7.6/tests/models/compute/vpc_tests.rb 0000644 0000041 0000041 00000000210 12576636531 021566 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | vpc", ['aws']) do
model_tests(Fog::Compute[:aws].vpcs, {:cidr_block => '10.0.10.0/28'}, true)
end
fog-aws-0.7.6/tests/models/compute/volume_tests.rb 0000644 0000041 0000041 00000001737 12576636531 022324 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | volume", ['aws']) do
@server = Fog::Compute[:aws].servers.create
@server.wait_for { ready? }
model_tests(Fog::Compute[:aws].volumes, {:availability_zone => @server.availability_zone, :size => 1, :device => '/dev/sdz1', :tags => {"key" => "value"}}, true) do
@instance.wait_for { ready? }
tests('#server = @server').succeeds do
@instance.server = @server
end
@instance.wait_for { state == 'in-use' }
tests('#server').succeeds do
@instance.server.id == @server.id
end
tests('#server = nil').succeeds do
(@instance.server = nil).nil?
end
@instance.wait_for { ready? }
@instance.server = @server
@instance.wait_for { state == 'in-use' }
tests('#force_detach').succeeds do
@instance.force_detach
end
@instance.wait_for { ready? }
tests('@instance.reload.tags').returns({'key' => 'value'}) do
@instance.reload.tags
end
end
@server.destroy
end
fog-aws-0.7.6/tests/models/compute/addresses_tests.rb 0000644 0000041 0000041 00000000174 12576636531 022764 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | addresses", ['aws']) do
collection_tests(Fog::Compute[:aws].addresses, {}, true)
end
fog-aws-0.7.6/tests/models/compute/address_tests.rb 0000644 0000041 0000041 00000001032 12576636531 022426 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | address", ['aws']) do
model_tests(Fog::Compute[:aws].addresses, {}, true) do
@server = Fog::Compute[:aws].servers.create
@server.wait_for { ready? }
tests('#server=').succeeds do
@instance.server = @server
end
tests('#server') do
test(' == @server') do
@server.reload
@instance.server.public_ip_address == @instance.public_ip
end
end
@server.destroy
end
model_tests(Fog::Compute[:aws].addresses, { :domain => "vpc" }, true)
end
fog-aws-0.7.6/tests/models/compute/internet_gateways_tests.rb 0000644 0000041 0000041 00000000212 12576636531 024534 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | internet_gateways", ['aws']) do
collection_tests(Fog::Compute[:aws].internet_gateways, {}, true)
end
fog-aws-0.7.6/tests/models/compute/network_acl_tests.rb 0000644 0000041 0000041 00000006742 12576636531 023326 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | network_acl", ['aws']) do
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
model_tests(Fog::Compute[:aws].network_acls, { :vpc_id => @vpc.id }, true)
tests("associate_with") do
@new_nacl = Fog::Compute[:aws].network_acls.create(:vpc_id => @vpc.id)
@default_nacl = Fog::Compute[:aws].network_acls.all('vpc-id' => @vpc.id, 'default' => true).first
test("associate_with new_nacl") do
@new_nacl.associate_with(@subnet)
end
@new_nacl.reload
test("associate_with correctly updates new_nacl") do
@new_nacl.associations.map { |a| a['subnetId'] } == [@subnet.subnet_id]
end
@default_nacl.associate_with(@subnet)
@new_nacl.reload
@default_nacl.reload
test("associate_with correctly updates new_nacl after removal") do
@new_nacl.associations.map { |a| a['subnetId'] } == []
end
test("associate_with correctly updates default_nacl after removal") do
@default_nacl.associations.map { |a| a['subnetId'] } == [@subnet.subnet_id]
end
@new_nacl.destroy
end
tests("add_rule and remove_rule") do
@new_nacl = Fog::Compute[:aws].network_acls.create(:vpc_id => @vpc.id)
default_rules = @new_nacl.entries.dup
test("add a new inbound rule") do
@new_nacl.add_inbound_rule(100, Fog::Compute::AWS::NetworkAcl::TCP, 'allow', '0.0.0.0/0', 'PortRange.From' => 22, 'PortRange.To' => 22)
@new_nacl.reload
(@new_nacl.entries - default_rules) == [{
"icmpTypeCode" => {},
"portRange" => {
"from" => 22,
"to" => 22
},
"ruleNumber" => 100,
"protocol" => 6,
"ruleAction" => "allow",
"egress" => false,
"cidrBlock" => "0.0.0.0/0"
}]
end
test("remove inbound rule") do
@new_nacl.remove_inbound_rule(100)
@new_nacl.reload
@new_nacl.entries == default_rules
end
test("add a new outbound rule") do
@new_nacl.add_outbound_rule(100, Fog::Compute::AWS::NetworkAcl::TCP, 'allow', '0.0.0.0/0', 'PortRange.From' => 22, 'PortRange.To' => 22)
@new_nacl.reload
(@new_nacl.entries - default_rules) == [{
"icmpTypeCode" => {},
"portRange" => {
"from" => 22,
"to" => 22
},
"ruleNumber" => 100,
"protocol" => 6,
"ruleAction" => "allow",
"egress" => true,
"cidrBlock" => "0.0.0.0/0"
}]
end
test("remove outbound rule") do
@new_nacl.remove_outbound_rule(100)
@new_nacl.reload
@new_nacl.entries == default_rules
end
test("update rule") do
@new_nacl.add_inbound_rule(100, Fog::Compute::AWS::NetworkAcl::TCP, 'allow', '0.0.0.0/0', 'PortRange.From' => 22, 'PortRange.To' => 22)
@new_nacl.update_inbound_rule(100, Fog::Compute::AWS::NetworkAcl::TCP, 'allow', '10.0.0.0/8', 'PortRange.From' => 22, 'PortRange.To' => 22)
@new_nacl.reload
(@new_nacl.entries - default_rules) == [{
"icmpTypeCode" => {},
"portRange" => {
"from" => 22,
"to" => 22
},
"ruleNumber" => 100,
"protocol" => 6,
"ruleAction" => "allow",
"egress" => false,
"cidrBlock" => "10.0.0.0/8"
}]
end
@new_nacl.destroy
end
@subnet.destroy
@vpc.destroy
end
fog-aws-0.7.6/tests/models/compute/network_interfaces_test.rb 0000644 0000041 0000041 00000000764 12576636531 024525 0 ustar www-data www-data Shindo.tests("Fog::Compute[:aws] | network_interfaces", ['aws']) do
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => '10.0.10.0/24')
@subnet = Fog::Compute[:aws].subnets.create('vpc_id' => @vpc.id, 'cidr_block' => '10.0.10.16/28')
@subnet_id = @subnet.subnet_id
collection_tests(Fog::Compute[:aws].network_interfaces,
{:description => 'nic_desc', :name => 'nic_name', :subnet_id => @subnet_id},
true)
@subnet.destroy
@vpc.destroy
end
fog-aws-0.7.6/tests/models/elasticache/ 0000755 0000041 0000041 00000000000 12576636531 020027 5 ustar www-data www-data fog-aws-0.7.6/tests/models/elasticache/subnet_groups_tests.rb 0000644 0000041 0000041 00000002606 12576636531 024501 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | subnet group', ['aws', 'elasticache']) do
# random_differentiator
# Useful when rapidly re-running tests, so we don't have to wait
# serveral minutes for deleted VPCs/subnets to disappear
suffix = rand(65536).to_s(16)
@subnet_group_name = "fog-test-#{suffix}"
vpc_range = rand(245) + 10
@vpc = Fog::Compute[:aws].vpcs.create('cidr_block' => "10.#{vpc_range}.0.0/16")
# Create 4 subnets in this VPC, each one in a different AZ
subnet_az = 'us-east-1a'
subnet_range = 8
@subnets = (1..3).map do
result = Fog::Compute[:aws].create_subnet(@vpc.id, "10.#{vpc_range}.#{subnet_range}.0/24",
'AvailabilityZone' => subnet_az)
puts result
subnet = result.body['subnet']
subnet_az = subnet_az.succ
subnet_range *= 2
subnet
end
tests('success') do
group_name = 'fog-test'
description = 'Fog Test'
subnet_ids = @subnets.map { |sn| sn['subnetId'] }.to_a
model_tests(
Fog::AWS[:elasticache].subnet_groups,
{:name => group_name, :subnet_ids => subnet_ids, :description => description}, true
)
collection_tests(
Fog::AWS[:elasticache].subnet_groups,
{:name => group_name, :subnet_ids => subnet_ids, :description => description}, true
)
end
@subnets.each do |sn|
Fog::Compute[:aws].delete_subnet(sn['subnetId'])
end
@vpc.destroy
end
fog-aws-0.7.6/tests/models/elasticache/parameter_groups_tests.rb 0000644 0000041 0000041 00000000606 12576636531 025157 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | parameter groups', ['aws', 'elasticache']) do
group_name = 'fog-test'
description = 'Fog Test'
model_tests(
Fog::AWS[:elasticache].parameter_groups,
{:id => group_name, :description => description}, true
)
collection_tests(
Fog::AWS[:elasticache].parameter_groups,
{:id => group_name, :description => description}, true
)
end
fog-aws-0.7.6/tests/models/elasticache/security_groups_tests.rb 0000644 0000041 0000041 00000002550 12576636531 025046 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | security groups', ['aws', 'elasticache']) do
group_name = 'fog-test'
description = 'Fog Test'
pending if Fog.mocking?
model_tests(
Fog::AWS[:elasticache].security_groups,
{:id => group_name, :description => description}, false
) do
# An EC2 group to authorize
ec2_group = Fog::Compute.new(:provider => 'AWS').security_groups.create(
:name => 'fog-test-elasticache', :description => 'fog test'
)
# Reload to get the instance owner_id
@instance.reload
tests('#authorize_ec2_group') do
@instance.authorize_ec2_group(ec2_group.name)
returns('authorizing') do
group = @instance.ec2_groups.find do |g|
g['EC2SecurityGroupName'] == ec2_group.name
end
group['Status']
end
returns(false, 'not ready') { @instance.ready? }
end
@instance.wait_for { ready? }
tests('#revoke_ec2_group') do
@instance.revoke_ec2_group(ec2_group.name)
returns('revoking') do
group = @instance.ec2_groups.find do |g|
g['EC2SecurityGroupName'] == ec2_group.name
end
group['Status']
end
returns(false, 'not ready') { @instance.ready? }
end
ec2_group.destroy
end
collection_tests(
Fog::AWS[:elasticache].security_groups,
{:id => group_name, :description => description}, false
)
end
fog-aws-0.7.6/tests/models/elasticache/cluster_tests.rb 0000644 0000041 0000041 00000002300 12576636531 023252 0 ustar www-data www-data Shindo.tests('AWS::Elasticache | cache clusters', ['aws', 'elasticache']) do
cluster_params = {
:id => "fog-test-cluster-#{rand(999).to_s}",
:node_type => 'cache.m1.large',
:security_groups => ['default'],
:engine => 'memcached',
:num_nodes => 1
}
pending if Fog.mocking?
Fog::Formatador.display_line "Creating cluster #{cluster_params[:id]}..."
model_tests(Fog::AWS[:elasticache].clusters, cluster_params, false) do
@instance.reload # Reload to get the cluster info from AWS
Fog::Formatador.display_line "Waiting for #{@instance.id} "+
"to become available (#{@instance.status})..."
@instance.wait_for {ready?}
end
# Single model is still deleting, so re-randomize the cluster ID
cluster_params[:id] = "fog-test-cluster-#{rand(999).to_s}"
Fog::Formatador.display_line "Creating cluster #{cluster_params[:id]}..."
collection_tests(Fog::AWS[:elasticache].clusters, cluster_params, false) do
@instance.reload # Reload to get the cluster info from AWS
Fog::Formatador.display_line "Waiting for #{@instance.id} "+
"to become available (#{@instance.status})..."
@instance.wait_for {ready?}
end
end
fog-aws-0.7.6/tests/models/sns/ 0000755 0000041 0000041 00000000000 12576636531 016365 5 ustar www-data www-data fog-aws-0.7.6/tests/models/sns/topics_tests.rb 0000644 0000041 0000041 00000000306 12576636531 021434 0 ustar www-data www-data Shindo.tests("AWS::SNS | topics", ['aws', 'sns']) do
pending unless Fog.mocking?
params = {:id => 'arn:aws:sns:us-east-1:12345678910:fog'}
collection_tests(Fog::AWS[:sns].topics, params)
end
fog-aws-0.7.6/tests/models/sns/topic_tests.rb 0000644 0000041 0000041 00000000657 12576636531 021262 0 ustar www-data www-data Shindo.tests("AWS::SNS | topic", ['aws', 'sns']) do
params = {:id => 'fog'}
model_tests(Fog::AWS[:sns].topics, params) do
@instance.wait_for { ready? }
tests("#display_name").returns('fog') { @instance.display_name }
tests("#update_topic_attribute") do
@instance.update_topic_attribute("DisplayName", "new-fog")
tests("#display_name").returns('new-fog') { @instance.display_name }
end
end
end
fog-aws-0.7.6/tests/models/iam/ 0000755 0000041 0000041 00000000000 12576636531 016330 5 ustar www-data www-data fog-aws-0.7.6/tests/models/iam/managed_policies_tests.rb 0000644 0000041 0000041 00000002630 12576636531 023363 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | managed_policies", ['aws','iam']) do
iam = Fog::AWS[:iam]
tests('#all').succeeds do
iam.managed_policies.size == 100
end
tests('#each').succeeds do
policies = []
iam.managed_policies.each { |policy| policies << policy }
policies.size > 100
end
policy = iam.managed_policies.get("arn:aws:iam::aws:policy/IAMReadOnlyAccess")
tests("#document").succeeds do
policy.document == {
"Version" => "2012-10-17",
"Statement" => [
{
"Effect" => "Allow",
"Action" => [ "iam:GenerateCredentialReport", "iam:Get*", "iam:List*" ],
"Resource" => "*"
}
]
}
end
tests("users") do
user = iam.users.create(:id => uniq_id("fog-test-user"))
tests("#attach").succeeds do
user.attach(policy)
user.attached_policies.map(&:identity) == [policy.identity]
end
tests("#detach").succeeds do
user.detach(policy)
user.attached_policies.map(&:identity) == []
end
user.destroy
end
tests("groups") do
group = iam.groups.create(:name => uniq_id("fog-test-group"))
tests("#attach").succeeds do
group.attach(policy)
group.attached_policies.map(&:identity) == [policy.identity]
end
tests("#detach").succeeds do
group.detach(policy)
group.attached_policies.map(&:identity) == []
end
group.destroy
end
end
fog-aws-0.7.6/tests/models/iam/users_tests.rb 0000644 0000041 0000041 00000005676 12576636531 021256 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | users", ['aws','iam']) do
iam = Fog::AWS[:iam]
user_one_name = 'fake_user_one'
user_two_name = 'fake_user_two'
user_three_name = 'fake_user_three'
user_three_path = '/path/to/fake_user_three/'
user_four_name = 'fake_user_four'
def all_users
Fog::AWS[:iam].users.all.select{|user| user.id =~ /^fake_user/ }
end
tests('#create').succeeds do
user_one = iam.users.create(:id => user_one_name)
user_one.id == user_one_name
end
tests('#all','there is only one user').succeeds do
all_users.size == 1
end
tests('#all','the only user should match').succeeds do
all_users.first.id == user_one_name
end
tests('#create','a second user').succeeds do
user_two = iam.users.create(:id => user_two_name)
user_two.id == user_two_name
end
tests('#all','there are two users').succeeds do
all_users.size == 2
end
user = iam.users.get(user_one_name)
tests('#get','an existing user').succeeds do
user.id == user_one_name
end
tests('#current').succeeds do
iam.users.current
end
tests('#get',"returns nil if the user doesn't exists").succeeds do
iam.users.get('non-exists') == nil
end
tests('#policies','it has no policies').succeeds do
user.policies.empty?
end
tests('#access_keys','it has no keys').succeeds do
user.access_keys.empty?
end
# test that users create in mock and be signed in via access key and share data
if Fog.mocking?
tests("mocking access key usage") do
access_key = user.access_keys.create
user_client = Fog::AWS::IAM.new(
:aws_access_key_id => access_key.identity,
:aws_secret_access_key => access_key.secret_access_key
)
tests("sets correct data").succeeds do
user_client.users.size > 1
end
tests("set current user name").succeeds do
user_client.current_user_name == user.identity
end
end
end
tests('#password=nil', 'without a password').succeeds do
user.password = nil
user.password_created_at.nil?
end
tests('#password=(password)').succeeds do
user.password = SecureRandom.base64(10)
user.password_created_at.is_a?(Time)
end
tests('#password=(update_password)').succeeds do
user.password = SecureRandom.base64(10)
user.password_created_at.is_a?(Time)
end
tests('#password=nil', 'with a password').succeeds do
user.password = nil
user.password_created_at.nil?
end
tests('#create', 'assigns path').succeeds do
user_three = iam.users.create(:id => user_three_name, :path => user_three_path)
user_three.path == user_three_path
end
tests('#create', 'defaults path to /').succeeds do
user_four = iam.users.create(:id => user_four_name)
user_four.path == '/'
end
tests('#destroy','an existing user').succeeds do
iam.users.get(user_one_name).destroy
end
tests('#destroy','clean up remaining user').succeeds do
iam.users.get(user_two_name).destroy
end
end
fog-aws-0.7.6/tests/models/iam/access_keys_tests.rb 0000644 0000041 0000041 00000002521 12576636531 022373 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | access_keys", ['aws','iam']) do
iam = Fog::AWS[:iam]
@username = 'fake_user'
@user = iam.users.create(:id => @username)
tests('#all', 'there are no access keys for a new user').succeeds do
@user.access_keys.empty?
end
tests('#create','an access key').succeeds do
access_key = @user.access_keys.create
access_key.id =~ /[A-Z0-9]{20}/
access_key.secret_access_key =~ /[\S]{40}/
access_key.status == "Active"
access_key.username == @username
@access_key_id = access_key.id
end
@user.access_keys.create
tests('#all','there are two access keys').succeeds do
@user.access_keys.size == 2
end
tests('#get') do
tests('a valid access key id').succeeds do
access_key = @user.access_keys.get(@access_key_id)
access_key.id == @access_key_id
access_key.secret_access_key == nil
access_key.status == "Active"
access_key.username == @username
end
tests('an invalid access key').succeeds do
@user.access_keys.get('non-existing') == nil
end
end
tests('#destroy', 'decrease by one the number of access keys').succeeds do
size = @user.access_keys.size
@user.access_keys.get(@access_key_id).destroy
@user.access_keys.size == ( size - 1 )
end
# clean up
@user.access_keys.map(&:destroy)
@user.destroy
end
fog-aws-0.7.6/tests/models/iam/groups_tests.rb 0000644 0000041 0000041 00000002533 12576636531 021421 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | groups", ['aws','iam']) do
service = Fog::AWS[:iam]
group_name = uniq_id('fog-test-group')
policy_name = uniq_id('fog-test-policy')
group = nil
document = {"Statement" => [{"Effect" => "Allow", "Action" => "*", "Resource" => "*"}]}
tests('#create').succeeds do
group = service.groups.create(:name => group_name)
group.name == group_name
end
tests('#all').succeeds do
service.groups.all.map(&:name).include?(group_name)
end
tests('update').succeeds do
new_path = group.path = "/newpath/"
group.save
group.reload.path == new_path
end
tests('group') do
policy = nil
tests('#policies', '#create') do
policy = group.policies.create(:id => policy_name, :document => document)
end
tests('#policies', '#get').succeeds do
group.policies.get(policy_name) != nil
end
tests('#policies', '#all').succeeds do
group.policies.all.map(&:id).include?(policy.id)
end
tests('#users', 'when none').succeeds do
group.users.empty?
end
user = nil
tests('#add_user').succeeds do
user = service.users.create(:id => 'fog-test')
group.add_user(user)
group.users.include?(user)
end
tests('#users').succeeds do
group.reload.users.map(&:identity).include?(user.identity)
end
end
end
fog-aws-0.7.6/tests/models/iam/roles_tests.rb 0000644 0000041 0000041 00000003345 12576636531 021230 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | roles", ['aws','iam']) do
pending if Fog.mocking?
@iam = Fog::AWS[:iam]
@role_one_name = 'fake_role_one'
@role_two_name = 'fake_role_two'
@role_three_name = 'fake_role_three'
@role_three_path = '/path/to/fake_role_three/'
@role_four_name = 'fake_role_four'
tests('#create').succeeds do
@role_one = @iam.roles.create(:rolename => @role_one_name)
@role_one.rolename == @role_one_name
end
tests('#all','there is only one role').succeeds do
@iam.roles.size == 1
end
tests('#all','the only role should match').succeeds do
@iam.roles.first.rolename == @role_one_name
end
tests('#create','a second role').succeeds do
@role_two = @iam.roles.create(:rolename => @role_two_name)
@role_two.rolename == @role_two_name
end
tests('#all','there are two roles').succeeds do
@iam.roles.size == 2
end
tests('#get','an existing role').succeeds do
@iam.roles.get(@role_one_name).rolename == @role_one_name
end
tests('#get',"returns nil if the role doesn't exists").succeeds do
@iam.roles.get('non-exists') == nil
end
tests('#create', 'assigns path').succeeds do
@role_three = @iam.roles.create(:rolename => @role_three_name, :path => @role_three_path)
@role_three.path == @role_three_path
end
tests('#create', 'defaults path to /').succeeds do
@role_four = @iam.roles.create(:rolename => @role_four_name)
@role_four.path == '/'
end
tests('#destroy','an existing role').succeeds do
@iam.roles.get(@role_one_name).destroy
end
tests('#destroy','clean up remaining roles').succeeds do
@iam.roles.get(@role_two_name).destroy
@iam.roles.get(@role_three_name).destroy
@iam.roles.get(@role_four_name).destroy
end
end
fog-aws-0.7.6/tests/models/iam/policies_tests.rb 0000644 0000041 0000041 00000003026 12576636531 021707 0 ustar www-data www-data Shindo.tests("Fog::Compute[:iam] | policies", ['aws','iam']) do
iam = Fog::AWS[:iam]
@username = 'fake_user'
@user = iam.users.create(:id => @username)
@policy_document = {"Statement"=>[{"Action"=>["sqs:*"], "Effect"=>"Allow", "Resource"=>"*"}]}
@policy_name = 'fake-sqs-policy'
tests('#all', 'there is no policies').succeeds do
@user.policies.empty?
end
tests('#create') do
tests('a valid policy').succeeds do
policy = @user.policies.create(:id => @policy_name, :document => @policy_document)
policy.id == @policy_name
policy.username == @username
policy.document == @policy_document
end
# The mocking doesn't validate the document policy
#tests('an invalid valid policy').succeeds do
# raises(Fog::AWS::IAM::Error) { @user.policies.create(id: 'non-valid-document', document: 'invalid json blob') }
#end
end
@user.policies.create(:id => 'another-policy', :document => {})
tests('#all','there are two policies').succeeds do
@user.policies.size == 2
end
tests('#get') do
tests('a valid policy').succeeds do
policy = @user.policies.get(@policy_name)
policy.id == @polic_name
policy.username == @username
policy.document == @policy_document
end
tests('an invalid policy').succeeds do
@user.policies.get('non-existing') == nil
end
end
tests('#destroy').succeeds do
@user.policies.get(@policy_name).destroy
end
# clean up
@user.access_keys.map(&:destroy)
@user.policies.map(&:destroy)
@user.destroy
end
fog-aws-0.7.6/tests/helpers/ 0000755 0000041 0000041 00000000000 12576636531 015741 5 ustar www-data www-data fog-aws-0.7.6/tests/helpers/responds_to_helper.rb 0000644 0000041 0000041 00000000374 12576636531 022170 0 ustar www-data www-data module Shindo
class Tests
def responds_to(method_names)
for method_name in [*method_names]
tests("#respond_to?(:#{method_name})").returns(true) do
@instance.respond_to?(method_name)
end
end
end
end
end
fog-aws-0.7.6/tests/helpers/dns_helper.rb 0000644 0000041 0000041 00000002121 12576636531 020405 0 ustar www-data www-data def dns_providers
{
:aws => {
:mocked => false
},
:bluebox => {
:mocked => false,
:zone_attributes => {
:ttl => 60
}
},
:dnsimple => {
:mocked => false
},
:dnsmadeeasy => {
:mocked => false
},
:dynect => {
:mocked => false,
:zone_attributes => {
:email => 'fog@example.com'
}
},
:linode => {
:mocked => false,
:zone_attributes => {
:email => 'fog@example.com'
}
},
:zerigo => {
:mocked => false
},
:rackspace => {
:mocked => false,
:zone_attributes => {
:email => 'fog@example.com'
}
},
:rage4 => {
:mocked => false
}
}
end
def generate_unique_domain( with_trailing_dot = false)
#get time (with 1/100th of sec accuracy)
#want unique domain name and if provider is fast, this can be called more than once per second
time= (Time.now.to_f * 100).to_i
domain = 'test-' + time.to_s + '.com'
if with_trailing_dot
domain+= '.'
end
domain
end
fog-aws-0.7.6/tests/helpers/formats_helper.rb 0000644 0000041 0000041 00000007056 12576636531 021310 0 ustar www-data www-data require "fog/schema/data_validator"
# format related hackery
# allows both true.is_a?(Fog::Boolean) and false.is_a?(Fog::Boolean)
# allows both nil.is_a?(Fog::Nullable::String) and ''.is_a?(Fog::Nullable::String)
module Fog
module Boolean; end
module Nullable
module Boolean; end
module Integer; end
module String; end
module Time; end
module Float; end
module Hash; end
module Array; end
end
end
[FalseClass, TrueClass].each {|klass| klass.send(:include, Fog::Boolean)}
[FalseClass, TrueClass, NilClass, Fog::Boolean].each {|klass| klass.send(:include, Fog::Nullable::Boolean)}
[NilClass, String].each {|klass| klass.send(:include, Fog::Nullable::String)}
[NilClass, Time].each {|klass| klass.send(:include, Fog::Nullable::Time)}
[Integer, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Integer)}
[Float, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Float)}
[Hash, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Hash)}
[Array, NilClass].each {|klass| klass.send(:include, Fog::Nullable::Array)}
module Shindo
class Tests
# Generates a Shindo test that compares a hash schema to the result
# of the passed in block returning true if they match.
#
# The schema that is passed in is a Hash or Array of hashes that
# have Classes in place of values. When checking the schema the
# value should match the Class.
#
# Strict mode will fail if the data has additional keys. Setting
# +strict+ to +false+ will allow additional keys to appear.
#
# @param [Hash] schema A Hash schema
# @param [Hash] options Options to change validation rules
# @option options [Boolean] :allow_extra_keys
# If +true+ does not fail when keys are in the data that are
# not specified in the schema. This allows new values to
# appear in API output without breaking the check.
# @option options [Boolean] :allow_optional_rules
# If +true+ does not fail if extra keys are in the schema
# that do not match the data. Not recommended!
# @yield Data to check with schema
#
# @example Using in a test
# Shindo.tests("comparing welcome data against schema") do
# data = {:welcome => "Hello" }
# data_matches_schema(:welcome => String) { data }
# end
#
# comparing welcome data against schema
# + data matches schema
#
# @example Example schema
# {
# "id" => String,
# "ram" => Integer,
# "disks" => [
# {
# "size" => Float
# }
# ],
# "dns_name" => Fog::Nullable::String,
# "active" => Fog::Boolean,
# "created" => DateTime
# }
#
# @return [Boolean]
def data_matches_schema(schema, options = {})
test('data matches schema') do
validator = Fog::Schema::DataValidator.new
valid = validator.validate(yield, schema, options)
@message = validator.message unless valid
valid
end
end
# @deprecated #formats is deprecated. Use #data_matches_schema instead
def formats(format, strict = true)
test('has proper format') do
if strict
options = {:allow_extra_keys => false, :allow_optional_rules => true}
else
options = {:allow_extra_keys => true, :allow_optional_rules => true}
end
validator = Fog::Schema::DataValidator.new
valid = validator.validate(yield, format, options)
@message = validator.message unless valid
valid
end
end
end
end
fog-aws-0.7.6/tests/helpers/succeeds_helper.rb 0000644 0000041 0000041 00000000206 12576636531 021421 0 ustar www-data www-data module Shindo
class Tests
def succeeds
test('succeeds') do
!!instance_eval(&Proc.new)
end
end
end
end
fog-aws-0.7.6/tests/helpers/collection_helper.rb 0000644 0000041 0000041 00000005027 12576636531 021764 0 ustar www-data www-data def collection_tests(collection, params = {}, mocks_implemented = true)
tests('success') do
tests("#new(#{params.inspect})").succeeds do
pending if Fog.mocking? && !mocks_implemented
collection.new(params)
end
tests("#create(#{params.inspect})").succeeds do
pending if Fog.mocking? && !mocks_implemented
@instance = collection.create(params)
end
# FIXME: work around for timing issue on AWS describe_instances mocks
if Fog.mocking? && @instance.respond_to?(:ready?)
@instance.wait_for { ready? }
end
tests("#all").succeeds do
pending if Fog.mocking? && !mocks_implemented
collection.all
end
if !Fog.mocking? || mocks_implemented
@identity = @instance.identity
end
tests("#get(#{@identity})").succeeds do
pending if Fog.mocking? && !mocks_implemented
collection.get(@identity)
end
tests('Enumerable') do
pending if Fog.mocking? && !mocks_implemented
methods = [
'all?', 'any?', 'find', 'detect', 'collect', 'map',
'find_index', 'flat_map', 'collect_concat', 'group_by',
'none?', 'one?'
]
# JRuby 1.7.5+ issue causes a SystemStackError: stack level too deep
# https://github.com/jruby/jruby/issues/1265
if RUBY_PLATFORM == "java" and JRUBY_VERSION =~ /1\.7\.[5-8]/
methods.delete('all?')
end
methods.each do |enum_method|
if collection.respond_to?(enum_method)
tests("##{enum_method}").succeeds do
block_called = false
collection.send(enum_method) {|x| block_called = true }
block_called
end
end
end
[
'max_by','min_by'
].each do |enum_method|
if collection.respond_to?(enum_method)
tests("##{enum_method}").succeeds do
block_called = false
collection.send(enum_method) {|x| block_called = true; 0 }
block_called
end
end
end
end
if block_given?
yield(@instance)
end
if !Fog.mocking? || mocks_implemented
@instance.destroy
end
end
tests('failure') do
if !Fog.mocking? || mocks_implemented
@identity = @identity.to_s
@identity = @identity.gsub(/[a-zA-Z]/) { Fog::Mock.random_letters(1) }
@identity = @identity.gsub(/\d/) { Fog::Mock.random_numbers(1) }
@identity
end
tests("#get('#{@identity}')").returns(nil) do
pending if Fog.mocking? && !mocks_implemented
collection.get(@identity)
end
end
end
fog-aws-0.7.6/tests/helpers/compute/ 0000755 0000041 0000041 00000000000 12576636531 017415 5 ustar www-data www-data fog-aws-0.7.6/tests/helpers/compute/servers_helper.rb 0000644 0000041 0000041 00000000410 12576636531 022765 0 ustar www-data www-data def servers_tests(connection, params = {}, mocks_implemented = true)
collection_tests(connection.servers, params, mocks_implemented) do
if !Fog.mocking? || mocks_implemented
@instance.wait_for { ready? }
yield if block_given?
end
end
end
fog-aws-0.7.6/tests/helpers/compute/server_helper.rb 0000644 0000041 0000041 00000001246 12576636531 022612 0 ustar www-data www-data def server_tests(connection, params = {}, mocks_implemented = true)
model_tests(connection.servers, params, mocks_implemented) do
tests('#reload').returns(true) do
pending if Fog.mocking? && !mocks_implemented
@instance.wait_for { ready? }
identity = @instance.identity
!identity.nil? && identity == @instance.reload.identity
end
responds_to([:ready?, :state])
yield if block_given?
tests('#reboot').succeeds do
pending if Fog.mocking? && !mocks_implemented
@instance.wait_for { ready? }
@instance.reboot
end
if !Fog.mocking? || mocks_implemented
@instance.wait_for { ready? }
end
end
end
fog-aws-0.7.6/tests/helpers/compute/flavors_helper.rb 0000644 0000041 0000041 00000001463 12576636531 022761 0 ustar www-data www-data def flavors_tests(connection, params = {}, mocks_implemented = true)
tests('success') do
tests("#all").succeeds do
pending if Fog.mocking? && !mocks_implemented
connection.flavors.all
end
if !Fog.mocking? || mocks_implemented
@identity = connection.flavors.first.identity
end
tests("#get('#{@identity}')").succeeds do
pending if Fog.mocking? && !mocks_implemented
connection.flavors.get(@identity)
end
end
tests('failure') do
if !Fog.mocking? || mocks_implemented
invalid_flavor_identity = connection.flavors.first.identity.to_s.gsub(/\w/, '0')
end
tests("#get('#{invalid_flavor_identity}')").returns(nil) do
pending if Fog.mocking? && !mocks_implemented
connection.flavors.get(invalid_flavor_identity)
end
end
end
fog-aws-0.7.6/tests/helpers/model_helper.rb 0000644 0000041 0000041 00000001414 12576636531 020725 0 ustar www-data www-data def model_tests(collection, params = {}, mocks_implemented = true)
tests('success') do
@instance = collection.new(params)
tests("#save").succeeds do
pending if Fog.mocking? && !mocks_implemented
@instance.save
end
if block_given?
yield(@instance)
end
tests("#destroy").succeeds do
pending if Fog.mocking? && !mocks_implemented
@instance.destroy
end
end
end
# Generates a unique identifier with a random differentiator.
# Useful when rapidly re-running tests, so we don't have to wait
# serveral minutes for deleted objects to disappear from the API
# E.g. 'fog-test-1234'
def uniq_id(base_name = 'fog-test')
# random_differentiator
suffix = rand(65536).to_s(16).rjust(4, '0')
[base_name, suffix] * '-'
end
fog-aws-0.7.6/tests/helpers/formats_helper_tests.rb 0000644 0000041 0000041 00000007020 12576636531 022521 0 ustar www-data www-data Shindo.tests('test_helper', 'meta') do
tests('comparing welcome data against schema') do
data = {:welcome => "Hello" }
data_matches_schema(:welcome => String) { data }
end
tests('#data_matches_schema') do
tests('when value matches schema expectation') do
data_matches_schema({"key" => String}) { {"key" => "Value"} }
end
tests('when values within an array all match schema expectation') do
data_matches_schema({"key" => [Integer]}) { {"key" => [1, 2]} }
end
tests('when nested values match schema expectation') do
data_matches_schema({"key" => {:nested_key => String}}) { {"key" => {:nested_key => "Value"}} }
end
tests('when collection of values all match schema expectation') do
data_matches_schema([{"key" => String}]) { [{"key" => "Value"}, {"key" => "Value"}] }
end
tests('when collection is empty although schema covers optional members') do
data_matches_schema([{"key" => String}], {:allow_optional_rules => true}) { [] }
end
tests('when additional keys are passed and not strict') do
data_matches_schema({"key" => String}, {:allow_extra_keys => true}) { {"key" => "Value", :extra => "Bonus"} }
end
tests('when value is nil and schema expects NilClass') do
data_matches_schema({"key" => NilClass}) { {"key" => nil} }
end
tests('when value and schema match as hashes') do
data_matches_schema({}) { {} }
end
tests('when value and schema match as arrays') do
data_matches_schema([]) { [] }
end
tests('when value is a Time') do
data_matches_schema({"time" => Time}) { {"time" => Time.now} }
end
tests('when key is missing but value should be NilClass (#1477)') do
data_matches_schema({"key" => NilClass}, {:allow_optional_rules => true}) { {} }
end
tests('when key is missing but value is nullable (#1477)') do
data_matches_schema({"key" => Fog::Nullable::String}, {:allow_optional_rules => true}) { {} }
end
end
tests('#formats backwards compatible changes') do
tests('when value matches schema expectation') do
formats({"key" => String}) { {"key" => "Value"} }
end
tests('when values within an array all match schema expectation') do
formats({"key" => [Integer]}) { {"key" => [1, 2]} }
end
tests('when nested values match schema expectation') do
formats({"key" => {:nested_key => String}}) { {"key" => {:nested_key => "Value"}} }
end
tests('when collection of values all match schema expectation') do
formats([{"key" => String}]) { [{"key" => "Value"}, {"key" => "Value"}] }
end
tests('when collection is empty although schema covers optional members') do
formats([{"key" => String}]) { [] }
end
tests('when additional keys are passed and not strict') do
formats({"key" => String}, false) { {"key" => "Value", :extra => "Bonus"} }
end
tests('when value is nil and schema expects NilClass') do
formats({"key" => NilClass}) { {"key" => nil} }
end
tests('when value and schema match as hashes') do
formats({}) { {} }
end
tests('when value and schema match as arrays') do
formats([]) { [] }
end
tests('when value is a Time') do
formats({"time" => Time}) { {"time" => Time.now} }
end
tests('when key is missing but value should be NilClass (#1477)') do
formats({"key" => NilClass}) { {} }
end
tests('when key is missing but value is nullable (#1477)') do
formats({"key" => Fog::Nullable::String}) { {} }
end
end
end
fog-aws-0.7.6/tests/helpers/mock_helper.rb 0000644 0000041 0000041 00000014154 12576636531 020563 0 ustar www-data www-data # Use so you can run in mock mode from the command line
#
# FOG_MOCK=true fog
if ENV["FOG_MOCK"] == "true"
Fog.mock!
end
# if in mocked mode, fill in some fake credentials for us
if Fog.mock?
Fog.credentials = {
:aws_access_key_id => 'aws_access_key_id',
:aws_secret_access_key => 'aws_secret_access_key',
:ia_access_key_id => 'aws_access_key_id',
:ia_secret_access_key => 'aws_secret_access_key',
:bluebox_api_key => 'bluebox_api_key',
:bluebox_customer_id => 'bluebox_customer_id',
:brightbox_client_id => 'brightbox_client_id',
:brightbox_secret => 'brightbox_secret',
:cloudstack_disk_offering_id => '',
:cloudstack_host => 'http://cloudstack.example.org',
:cloudstack_network_ids => '',
:cloudstack_service_offering_id => '4437ac6c-9fe3-477a-57ec-60a5a45896a4',
:cloudstack_template_id => '8a31cf9c-f248-0588-256e-9dbf58785216',
:cloudstack_zone_id => 'c554c592-e09c-9df5-7688-4a32754a4305',
:cloudstack_project_id => 'f1f1f1f1-f1f1-f1f1-f1f1-f1f1f1f1f1f1',
:clodo_api_key => 'clodo_api_key',
:clodo_username => 'clodo_username',
:digitalocean_api_key => 'digitalocean_api_key',
:digitalocean_client_id => 'digitalocean_client_id',
:dnsimple_email => 'dnsimple_email',
:dnsimple_password => 'dnsimple_password',
:dnsmadeeasy_api_key => 'dnsmadeeasy_api_key',
:dnsmadeeasy_secret_key => 'dnsmadeeasy_secret_key',
:glesys_username => 'glesys_username',
:glesys_api_key => 'glesys_api_key',
:go_grid_api_key => 'go_grid_api_key',
:go_grid_shared_secret => 'go_grid_shared_secret',
:google_storage_access_key_id => 'google_storage_access_key_id',
:google_storage_secret_access_key => 'google_storage_secret_access_key',
:google_project => 'google_project_name',
:google_client_email => 'fake@developer.gserviceaccount.com',
:google_key_location => '~/fake.p12',
:hp_access_key => 'hp_access_key',
:hp_secret_key => 'hp_secret_key',
:hp_tenant_id => 'hp_tenant_id',
:hp_avl_zone => 'hp_avl_zone',
:os_account_meta_temp_url_key => 'os_account_meta_temp_url_key',
:ibm_username => 'ibm_username',
:ibm_password => 'ibm_password',
:joyent_username => "joyentuser",
:joyent_password => "joyentpass",
:linode_api_key => 'linode_api_key',
:local_root => '~/.fog',
:bare_metal_cloud_password => 'bare_metal_cloud_password',
:bare_metal_cloud_username => 'bare_metal_cloud_username',
:ninefold_compute_key => 'ninefold_compute_key',
:ninefold_compute_secret => 'ninefold_compute_secret',
:ninefold_storage_secret => 'ninefold_storage_secret',
:ninefold_storage_token => 'ninefold_storage_token',
# :public_key_path => '~/.ssh/id_rsa.pub',
# :private_key_path => '~/.ssh/id_rsa',
:opennebula_endpoint => 'http://opennebula:2633/RPC2',
:opennebula_username => 'oneadmin',
:opennebula_password => 'oneadmin',
:openstack_api_key => 'openstack_api_key',
:openstack_username => 'openstack_username',
:openstack_tenant => 'openstack_tenant',
:openstack_auth_url => 'http://openstack:35357/v2.0/tokens',
:ovirt_url => 'http://ovirt:8080/api',
:ovirt_username => 'admin@internal',
:ovirt_password => '123123',
:profitbricks_username => 'profitbricks_username',
:profitbricks_password => 'profitbricks_password',
:libvirt_uri => 'qemu://libvirt/system',
:rackspace_api_key => 'rackspace_api_key',
:rackspace_region => 'dfw',
:rackspace_username => 'rackspace_username',
:riakcs_access_key_id => 'riakcs_access_key_id',
:riakcs_secret_access_key => 'riakcs_secret_access_key',
:sakuracloud_api_token => 'sakuracloud_api_token',
:sakuracloud_api_token_secret => 'sakuracloud_api_token_secret',
:storm_on_demand_username => 'storm_on_demand_username',
:storm_on_demand_password => 'storm_on_demand_password',
:vcloud_host => 'vcloud_host',
:vcloud_password => 'vcloud_password',
:vcloud_username => 'vcloud_username',
:vcloud_director_host => 'vcloud-director-host',
:vcloud_director_password => 'vcloud_director_password',
:vcloud_director_username => 'vcd_user@vcd_org_name',
:zerigo_email => 'zerigo_email',
:zerigo_token => 'zerigo_token',
:dynect_customer => 'dynect_customer',
:dynect_username => 'dynect_username',
:dynect_password => 'dynect_password',
:vsphere_server => 'virtualcenter.lan',
:vsphere_username => 'apiuser',
:vsphere_password => 'apipassword',
:vsphere_expected_pubkey_hash => 'abcdef1234567890',
:libvirt_username => 'root',
:libvirt_password => 'password',
:cloudsigma_username => 'csuname',
:cloudsigma_password => 'cspass',
:docker_username => 'docker-fan',
:docker_password => 'i<3docker',
:docker_email => 'dockerfan@gmail.com',
:docker_url => 'unix://var/run/docker.sock'
}.merge(Fog.credentials)
end
fog-aws-0.7.6/tests/helpers/schema_validator_tests.rb 0000644 0000041 0000041 00000007231 12576636531 023020 0 ustar www-data www-data Shindo.tests('Fog::Schema::DataValidator', 'meta') do
validator = Fog::Schema::DataValidator.new
tests('#validate') do
tests('returns true') do
returns(true, 'when value matches schema expectation') do
validator.validate({"key" => "Value"}, {"key" => String})
end
returns(true, 'when values within an array all match schema expectation') do
validator.validate({"key" => [1, 2]}, {"key" => [Integer]})
end
returns(true, 'when nested values match schema expectation') do
validator.validate({"key" => {:nested_key => "Value"}}, {"key" => {:nested_key => String}})
end
returns(true, 'when collection of values all match schema expectation') do
validator.validate([{"key" => "Value"}, {"key" => "Value"}], [{"key" => String}])
end
returns(true, 'when collection is empty although schema covers optional members') do
validator.validate([], [{"key" => String}])
end
returns(true, 'when additional keys are passed and not strict') do
validator.validate({"key" => "Value", :extra => "Bonus"}, {"key" => String}, {:allow_extra_keys => true})
end
returns(true, 'when value is nil and schema expects NilClass') do
validator.validate({"key" => nil}, {"key" => NilClass})
end
returns(true, 'when value and schema match as hashes') do
validator.validate({}, {})
end
returns(true, 'when value and schema match as arrays') do
validator.validate([], [])
end
returns(true, 'when value is a Time') do
validator.validate({"time" => Time.now}, {"time" => Time})
end
returns(true, 'when key is missing but value should be NilClass (#1477)') do
validator.validate({}, {"key" => NilClass}, {:allow_optional_rules => true})
end
returns(true, 'when key is missing but value is nullable (#1477)') do
validator.validate({}, {"key" => Fog::Nullable::String}, {:allow_optional_rules => true})
end
end
tests('returns false') do
returns(false, 'when value does not match schema expectation') do
validator.validate({"key" => nil}, {"key" => String})
end
returns(false, 'when key formats do not match') do
validator.validate({"key" => "Value"}, {:key => String})
end
returns(false, 'when additional keys are passed and strict') do
validator.validate({"key" => "Missing"}, {})
end
returns(false, 'when some keys do not appear') do
validator.validate({}, {"key" => String})
end
returns(false, 'when collection contains a member that does not match schema') do
validator.validate([{"key" => "Value"}, {"key" => 5}], [{"key" => String}])
end
returns(false, 'when collection has multiple schema patterns') do
validator.validate([{"key" => "Value"}], [{"key" => Integer}, {"key" => String}])
end
returns(false, 'when hash and array are compared') do
validator.validate({}, [])
end
returns(false, 'when array and hash are compared') do
validator.validate([], {})
end
returns(false, 'when a hash is expected but another data type is found') do
validator.validate({"key" => {:nested_key => []}}, {"key" => {:nested_key => {}}})
end
returns(false, 'when key is missing but value should be NilClass (#1477)') do
validator.validate({}, {"key" => NilClass}, {:allow_optional_rules => false})
end
returns(false, 'when key is missing but value is nullable (#1477)') do
validator.validate({}, {"key" => Fog::Nullable::String}, {:allow_optional_rules => false})
end
end
end
end
fog-aws-0.7.6/tests/signed_params_tests.rb 0000644 0000041 0000041 00000001072 12576636531 020662 0 ustar www-data www-data # encoding: utf-8
Shindo.tests('AWS | signed_params', ['aws']) do
returns( Fog::AWS.escape( "'Stöp!' said Fred_-~./" ) ) { "%27St%C3%B6p%21%27%20said%20Fred_-~.%2F" }
tests('Unicode characters should be escaped') do
unicode = ["00E9".to_i(16)].pack("U*")
escaped = "%C3%A9"
returns( escaped ) { Fog::AWS.escape( unicode ) }
end
tests('Unicode characters with combining marks should be escaped') do
unicode = ["0065".to_i(16), "0301".to_i(16)].pack("U*")
escaped = "e%CC%81"
returns( escaped ) { Fog::AWS.escape( unicode ) }
end
end
fog-aws-0.7.6/tests/storage_tests.rb 0000644 0000041 0000041 00000000373 12576636531 017515 0 ustar www-data www-data # encoding: utf-8
Shindo.tests('AWS Storage | escape', ['aws']) do
tests('Keys can contain a hierarchical prefix which should not be escaped') do
returns( Fog::Storage::AWS.new.send(:escape, "key/with/prefix") ) { "key/with/prefix" }
end
end
fog-aws-0.7.6/CONTRIBUTORS.md 0000644 0000041 0000041 00000000272 12576636531 015415 0 ustar www-data www-data * Frederick Cheung
* Josh Lane
* Josh Lane
* Wesley Beary
* geemus