rubocop fixes

This commit is contained in:
Samuel Beaulieu 2021-12-09 18:43:36 -06:00
parent 662f965c0f
commit 5c67073dad
No known key found for this signature in database
GPG key ID: 12030F74136D0F34
5 changed files with 342 additions and 339 deletions

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
# this file is used to Mock the GCE objects, for example the main ComputeService object
MockResult = Struct.new(
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Operation.html
@ -7,7 +9,7 @@ MockResult = Struct.new(
keyword_init: true
)
MockOperationError = Array.new
MockOperationError = [].freeze
MockOperationErrorError = Struct.new(
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Operation/Error/Error.html
@ -27,19 +29,19 @@ MockInstance = Struct.new(
)
MockInstanceList = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/InstanceList.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/InstanceList.html
:id, :items, :kind, :next_page_token, :self_link, :warning,
keyword_init: true
)
MockDiskList = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/DiskList.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/DiskList.html
:id, :items, :kind, :next_page_token, :self_link, :warning,
keyword_init: true
)
MockDisk = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Disk.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Disk.html
:creation_timestamp, :description, :disk_encryption_key, :guest_os_features, :id, :kind, :label_fingerprint, :labels,
:last_attach_timestamp, :last_detach_timestamp, :license_codes, :licenses, :name, :options,
:physical_block_size_bytes, :region, :replica_zones, :resource_policies, :self_link, :size_gb, :source_disk,
@ -49,13 +51,13 @@ MockDisk = Struct.new(
)
MockSnapshotList = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/DiskList.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/DiskList.html
:id, :items, :kind, :next_page_token, :self_link, :warning,
keyword_init: true
)
MockSnapshot = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Snapshot.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/Snapshot.html
:auto_created, :chain_name, :creation_timestamp, :description, :disk_size_gb, :download_bytes, :id, :kind,
:label_fingerprint, :labels, :license_codes, :licenses, :name, :self_link, :snapshot_encryption_key, :source_disk,
:source_disk_encryption_key, :source_disk_id, :status, :storage_bytes, :storage_bytes_status, :storage_locations,
@ -63,7 +65,7 @@ MockSnapshot = Struct.new(
)
MockAttachedDisk = Struct.new(
#https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/AttachedDisk.html
# https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ComputeV1/AttachedDisk.html
:auto_delete, :boot, :device_name, :disk_encryption_key, :disk_size_gb, :guest_os_features, :index,
:initialize_params, :interface, :kind, :licenses, :mode, :shielded_instance_initial_state, :source, :type,
keyword_init: true
@ -80,6 +82,7 @@ MockComputeServiceConnection = Struct.new(
def get_instance
MockInstance.new
end
# Alias to serviceContent.propertyCollector
def insert_instance
MockResult.new
@ -90,20 +93,18 @@ end
# Mocking Methods
# -------------------------------------------------------------------------------------------------------------
=begin
def mock_RbVmomi_VIM_ClusterComputeResource(options = {})
options[:name] = 'Cluster' + rand(65536).to_s if options[:name].nil?
mock = MockClusterComputeResource.new()
mock.name = options[:name]
# All cluster compute resources have a root Resource Pool
mock.resourcePool = mock_RbVmomi_VIM_ResourcePool({:name => options[:name]})
allow(mock).to receive(:is_a?) do |expected_type|
expected_type == RbVmomi::VIM::ClusterComputeResource
end
mock
end
=end
# def mock_RbVmomi_VIM_ClusterComputeResource(options = {})
# options[:name] = 'Cluster' + rand(65536).to_s if options[:name].nil?
#
# mock = MockClusterComputeResource.new()
#
# mock.name = options[:name]
# # All cluster compute resources have a root Resource Pool
# mock.resourcePool = mock_RbVmomi_VIM_ResourcePool({:name => options[:name]})
#
# allow(mock).to receive(:is_a?) do |expected_type|
# expected_type == RbVmomi::VIM::ClusterComputeResource
# end
#
# mock
# end

View file

@ -1,23 +1,22 @@
# frozen_string_literal: true
require 'mock_redis'
def redis
unless @redis
@redis = MockRedis.new
end
@redis ||= MockRedis.new
@redis
end
# Mock an object which represents a Logger. This stops the proliferation
# of allow(logger).to .... expectations in tests.
class MockLogger
def log(_level, string)
end
def log(_level, string); end
end
def expect_json(ok = true, http = 200)
expect(last_response.header['Content-Type']).to eq('application/json')
if (ok == true) then
if ok == true
expect(JSON.parse(last_response.body)['ok']).to eq(true)
else
expect(JSON.parse(last_response.body)['ok']).to eq(false)
@ -35,7 +34,7 @@ def get_token_data(token)
redis.hgetall("vmpooler__token__#{token}")
end
def token_exists?(token)
def token_exists?(_token)
result = get_token_data
result && !result.empty?
end
@ -43,7 +42,7 @@ end
def create_ready_vm(template, name, redis, token = nil)
create_vm(name, redis, token)
redis.sadd("vmpooler__ready__#{template}", name)
redis.hset("vmpooler__vm__#{name}", "template", template)
redis.hset("vmpooler__vm__#{name}", 'template', template)
end
def create_running_vm(template, name, redis, token = nil, user = nil)
@ -57,7 +56,7 @@ end
def create_pending_vm(template, name, redis, token = nil)
create_vm(name, redis, token)
redis.sadd("vmpooler__pending__#{template}", name)
redis.hset("vmpooler__vm__#{name}", "template", template)
redis.hset("vmpooler__vm__#{name}", 'template', template)
end
def create_vm(name, redis, token = nil, user = nil)
@ -100,12 +99,12 @@ end
def snapshot_revert_vm(vm, snapshot = '12345678901234567890123456789012', redis)
redis.sadd('vmpooler__tasks__snapshot-revert', "#{vm}:#{snapshot}")
redis.hset("vmpooler__vm__#{vm}", "snapshot:#{snapshot}", "1")
redis.hset("vmpooler__vm__#{vm}", "snapshot:#{snapshot}", '1')
end
def snapshot_vm(vm, snapshot = '12345678901234567890123456789012', redis)
redis.sadd('vmpooler__tasks__snapshot', "#{vm}:#{snapshot}")
redis.hset("vmpooler__vm__#{vm}", "snapshot:#{snapshot}", "1")
redis.hset("vmpooler__vm__#{vm}", "snapshot:#{snapshot}", '1')
end
def disk_task_vm(vm, disk_size = '10', redis)
@ -127,7 +126,7 @@ def vm_reverted_to_snapshot?(vm, redis, snapshot = nil)
end
def pool_has_ready_vm?(pool, vm, redis)
!!redis.sismember('vmpooler__ready__' + pool, vm)
!!redis.sismember("vmpooler__ready__#{pool}", vm)
end
def create_ondemand_request_for_test(request_id, score, platforms_string, redis, user = nil, token = nil)

View file

@ -1,9 +1,9 @@
=begin
require 'simplecov'
SimpleCov.start do
add_filter '/spec/'
end
=end
# frozen_string_literal: true
# require 'simplecov'
# SimpleCov.start do
# add_filter '/spec/'
# end
require 'helpers'
require 'rspec'
require 'vmpooler'
@ -19,16 +19,16 @@ def fixtures_dir
File.join(project_root_dir, 'spec', 'fixtures')
end
def create_google_client_error(status_code, message, reason="notFound")
Google::Apis::ClientError.new(Google::Apis::ClientError, status_code:status_code, body:'{
def create_google_client_error(status_code, message, reason = 'notFound')
Google::Apis::ClientError.new(Google::Apis::ClientError, status_code: status_code, body: '{
"error": {
"code": '+status_code.to_s+',
"message": "'+message+'",
"code": ' + status_code.to_s + ',
"message": "' + message + '",
"errors": [
{
"message": "'+message+'",
"message": "' + message + '",
"domain": "global",
"reason": "'+reason+'"
"reason": "' + reason + '"
}
]
}

View file

@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'spec_helper'
require 'mock_redis'
require 'vmpooler/providers/gce'
@ -12,42 +14,44 @@ describe 'Vmpooler::PoolManager::Provider::Gce' do
let(:poolname) { 'debian-9' }
let(:provider_options) { { 'param' => 'value' } }
let(:project) { 'dio-samuel-dev' }
let(:zone){ 'us-west1-b' }
let(:config) { YAML.load(<<-EOT
---
:config:
max_tries: 3
retry_factor: 10
:providers:
:gce:
connection_pool_timeout: 1
project: '#{project}'
zone: '#{zone}'
network_name: 'global/networks/default'
:pools:
- name: '#{poolname}'
alias: [ 'mockpool' ]
template: 'projects/debian-cloud/global/images/family/debian-9'
size: 5
timeout: 10
ready_ttl: 1440
provider: 'gce'
network_name: 'default'
machine_type: 'zones/#{zone}/machineTypes/e2-micro'
EOT
)
}
let(:zone) { 'us-west1-b' }
let(:config) do
YAML.safe_load(<<~EOT
---
:config:
max_tries: 3
retry_factor: 10
:providers:
:gce:
connection_pool_timeout: 1
project: '#{project}'
zone: '#{zone}'
network_name: 'global/networks/default'
:pools:
- name: '#{poolname}'
alias: [ 'mockpool' ]
template: 'projects/debian-cloud/global/images/family/debian-9'
size: 5
timeout: 10
ready_ttl: 1440
provider: 'gce'
network_name: 'default'
machine_type: 'zones/#{zone}/machineTypes/e2-micro'
EOT
)
end
let(:vmname) { 'vm16' }
let(:connection) { MockComputeServiceConnection.new }
let(:redis_connection_pool) { Vmpooler::PoolManager::GenericConnectionPool.new(
metrics: metrics,
connpool_type: 'redis_connection_pool',
connpool_provider: 'testprovider',
size: 1,
timeout: 5
) { MockRedis.new }
}
let(:redis_connection_pool) do
Vmpooler::PoolManager::GenericConnectionPool.new(
metrics: metrics,
connpool_type: 'redis_connection_pool',
connpool_provider: 'testprovider',
size: 1,
timeout: 5
) { MockRedis.new }
end
subject { Vmpooler::PoolManager::Provider::Gce.new(config, logger, metrics, redis_connection_pool, 'gce', provider_options) }
@ -59,26 +63,26 @@ EOT
describe '#manual tests live' do
skip 'runs in gce' do
puts "creating"
puts 'creating'
result = subject.create_vm(poolname, vmname)
subject.get_vm(poolname, vmname)
subject.vms_in_pool(poolname)
puts "create snapshot w/ one disk"
result = subject.create_snapshot(poolname, vmname, "sams")
puts "create disk"
puts 'create snapshot w/ one disk'
result = subject.create_snapshot(poolname, vmname, 'sams')
puts 'create disk'
result = subject.create_disk(poolname, vmname, 10)
puts "create snapshot w/ 2 disks"
result = subject.create_snapshot(poolname, vmname, "sams2")
puts "revert snapshot"
result = subject.revert_snapshot(poolname, vmname, "sams")
puts 'create snapshot w/ 2 disks'
result = subject.create_snapshot(poolname, vmname, 'sams2')
puts 'revert snapshot'
result = subject.revert_snapshot(poolname, vmname, 'sams')
result = subject.destroy_vm(poolname, vmname)
end
skip 'runs existing' do
#result = subject.create_snapshot(poolname, vmname, "sams")
#result = subject.revert_snapshot(poolname, vmname, "sams")
#puts subject.get_vm(poolname, vmname)
# result = subject.create_snapshot(poolname, vmname, "sams")
# result = subject.revert_snapshot(poolname, vmname, "sams")
# puts subject.get_vm(poolname, vmname)
result = subject.destroy_vm(poolname, vmname)
end
@ -105,11 +109,13 @@ EOT
end
context 'Given a pool folder with many VMs' do
let(:expected_vm_list) {[
{ 'name' => 'vm1'},
{ 'name' => 'vm2'},
{ 'name' => 'vm3'}
]}
let(:expected_vm_list) do
[
{ 'name' => 'vm1' },
{ 'name' => 'vm2' },
{ 'name' => 'vm3' }
]
end
before(:each) do
instance_list = MockInstanceList.new(items: [])
expected_vm_list.each do |vm_hash|
@ -126,7 +132,6 @@ EOT
expect(result).to eq(expected_vm_list)
end
end
end
describe '#get_vm' do
@ -136,8 +141,8 @@ EOT
context 'when VM does not exist' do
it 'should return nil' do
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404,"The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
expect(subject.get_vm(poolname,vmname)).to be_nil
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404, "The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
expect(subject.get_vm(poolname, vmname)).to be_nil
end
end
@ -147,18 +152,18 @@ EOT
end
it 'should return a hash' do
expect(subject.get_vm(poolname,vmname)).to be_kind_of(Hash)
expect(subject.get_vm(poolname, vmname)).to be_kind_of(Hash)
end
it 'should return the VM name' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['name']).to eq(vmname)
end
['hostname','boottime','zone','status'].each do |testcase|
%w[hostname boottime zone status].each do |testcase|
it "should return nil for #{testcase}" do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result[testcase]).to be_nil
end
@ -168,52 +173,53 @@ EOT
context 'when VM exists and contains all information' do
let(:vm_hostname) { "#{vmname}.demo.local" }
let(:boot_time) { Time.now }
let(:vm_object) { MockInstance.new(
let(:vm_object) do
MockInstance.new(
name: vmname,
hostname: vm_hostname,
labels: {'pool' => poolname},
labels: { 'pool' => poolname },
creation_timestamp: boot_time,
status: 'RUNNING',
zone: zone,
machine_type: "zones/#{zone}/machineTypes/e2-micro"
)
}
let(:pool_info) { config[:pools][0]}
end
let(:pool_info) { config[:pools][0] }
before(:each) do
allow(connection).to receive(:get_instance).and_return(vm_object)
end
it 'should return a hash' do
expect(subject.get_vm(poolname,vmname)).to be_kind_of(Hash)
expect(subject.get_vm(poolname, vmname)).to be_kind_of(Hash)
end
it 'should return the VM name' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['name']).to eq(vmname)
end
it 'should return the VM hostname' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['hostname']).to eq(vm_hostname)
end
it 'should return the template name' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['template']).to eq(pool_info['template'])
end
it 'should return the pool name' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['poolname']).to eq(pool_info['name'])
end
it 'should return the boot time' do
result = subject.get_vm(poolname,vmname)
result = subject.get_vm(poolname, vmname)
expect(result['boottime']).to eq(boot_time)
end
@ -227,33 +233,30 @@ EOT
context 'Given an invalid pool name' do
it 'should raise an error' do
expect{ subject.create_vm('missing_pool', vmname) }.to raise_error(/missing_pool does not exist/)
expect { subject.create_vm('missing_pool', vmname) }.to raise_error(/missing_pool does not exist/)
end
end
context 'Given a template VM that does not exist' do
before(:each) do
config[:pools][0]['template'] = 'Templates/missing_template'
=begin
result = MockResult.new
result.status = "PENDING"
errors = MockOperationError
errors << MockOperationErrorError.new(code: "foo", message: "it's missing")
result.error = errors
=end
allow(connection).to receive(:insert_instance).and_raise(create_google_client_error(404,'The resource \'Templates/missing_template\' was not found'))
# result = MockResult.new
# result.status = "PENDING"
# errors = MockOperationError
# errors << MockOperationErrorError.new(code: "foo", message: "it's missing")
# result.error = errors
allow(connection).to receive(:insert_instance).and_raise(create_google_client_error(404, 'The resource \'Templates/missing_template\' was not found'))
end
it 'should raise an error' do
expect{ subject.create_vm(poolname, vmname) }.to raise_error(Google::Apis::ClientError)
expect { subject.create_vm(poolname, vmname) }.to raise_error(Google::Apis::ClientError)
end
end
context 'Given a successful creation' do
before(:each) do
result = MockResult.new
result.status = "DONE"
result.status = 'DONE'
allow(connection).to receive(:insert_instance).and_return(result)
end
@ -264,7 +267,6 @@ EOT
expect(result.is_a?(Hash)).to be true
end
it 'should have the new VM name' do
instance = MockInstance.new(name: vmname)
allow(connection).to receive(:get_instance).and_return(instance)
@ -282,7 +284,7 @@ EOT
context 'Given a missing VM name' do
before(:each) do
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404,"The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404, "The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
disk_list = MockDiskList.new(items: nil)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(subject).to receive(:find_all_snapshots).and_return(nil)
@ -299,7 +301,7 @@ EOT
instance = MockInstance.new(name: vmname)
allow(connection).to receive(:get_instance).and_return(instance)
result = MockResult.new
result.status = "DONE"
result.status = 'DONE'
allow(subject).to receive(:wait_for_operation).and_return(result)
allow(connection).to receive(:delete_instance).and_return(result)
end
@ -333,7 +335,6 @@ EOT
subject.destroy_vm(poolname, vmname)
end
end
end
describe '#vm_ready?' do
@ -344,17 +345,17 @@ EOT
end
it 'should return true' do
expect(subject.vm_ready?(poolname,vmname)).to be true
expect(subject.vm_ready?(poolname, vmname)).to be true
end
end
context 'When an error occurs connecting to the VM' do
before(:each) do
expect(subject).to receive(:open_socket).and_raise(RuntimeError,'MockError')
expect(subject).to receive(:open_socket).and_raise(RuntimeError, 'MockError')
end
it 'should return false' do
expect(subject.vm_ready?(poolname,vmname)).to be false
expect(subject.vm_ready?(poolname, vmname)).to be false
end
end
end
@ -367,17 +368,17 @@ EOT
context 'Given an invalid pool name' do
it 'should raise an error' do
expect{ subject.create_disk('missing_pool',vmname,disk_size) }.to raise_error(/missing_pool does not exist/)
expect { subject.create_disk('missing_pool', vmname, disk_size) }.to raise_error(/missing_pool does not exist/)
end
end
context 'when VM does not exist' do
before(:each) do
expect(connection).to receive(:get_instance).and_raise(create_google_client_error(404,"The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
expect(connection).to receive(:get_instance).and_raise(create_google_client_error(404, "The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
end
it 'should raise an error' do
expect{ subject.create_disk(poolname,vmname,disk_size) }.to raise_error(/VM #{vmname} .+ does not exist/)
expect { subject.create_disk(poolname, vmname, disk_size) }.to raise_error(/VM #{vmname} .+ does not exist/)
end
end
@ -386,11 +387,11 @@ EOT
disk = MockDisk.new(name: vmname)
instance = MockInstance.new(name: vmname, disks: [disk])
allow(connection).to receive(:get_instance).and_return(instance)
expect(connection).to receive(:insert_disk).and_raise(RuntimeError,'Mock Disk Error')
expect(connection).to receive(:insert_disk).and_raise(RuntimeError, 'Mock Disk Error')
end
it 'should raise an error' do
expect{ subject.create_disk(poolname,vmname,disk_size) }.to raise_error(/Mock Disk Error/)
expect { subject.create_disk(poolname, vmname, disk_size) }.to raise_error(/Mock Disk Error/)
end
end
@ -400,7 +401,7 @@ EOT
instance = MockInstance.new(name: vmname, disks: [disk])
allow(connection).to receive(:get_instance).and_return(instance)
result = MockResult.new
result.status = "DONE"
result.status = 'DONE'
allow(connection).to receive(:insert_disk).and_return(result)
allow(subject).to receive(:wait_for_operation).and_return(result)
new_disk = MockDisk.new(name: "#{vmname}-disk1", self_link: "/foo/bar/baz/#{vmname}-disk1")
@ -409,7 +410,7 @@ EOT
end
it 'should return true' do
expect(subject.create_disk(poolname,vmname,disk_size)).to be true
expect(subject.create_disk(poolname, vmname, disk_size)).to be true
end
end
end
@ -423,11 +424,11 @@ EOT
context 'when VM does not exist' do
before(:each) do
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404,"The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404, "The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
end
it 'should raise an error' do
expect{ subject.create_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/VM #{vmname} .+ does not exist/)
expect { subject.create_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/VM #{vmname} .+ does not exist/)
end
end
@ -438,7 +439,7 @@ EOT
allow(connection).to receive(:get_instance).and_return(instance)
snapshots = [MockSnapshot.new(name: snapshot_name)]
allow(subject).to receive(:find_snapshot).and_return(snapshots)
expect{ subject.create_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/Snapshot #{snapshot_name} .+ already exists /)
expect { subject.create_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/Snapshot #{snapshot_name} .+ already exists /)
end
end
@ -449,11 +450,11 @@ EOT
allow(connection).to receive(:get_instance).and_return(instance)
snapshots = nil
allow(subject).to receive(:find_snapshot).and_return(snapshots)
allow(connection).to receive(:create_disk_snapshot).and_raise(RuntimeError,'Mock Snapshot Error')
allow(connection).to receive(:create_disk_snapshot).and_raise(RuntimeError, 'Mock Snapshot Error')
end
it 'should raise an error' do
expect{ subject.create_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/Mock Snapshot Error/)
expect { subject.create_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/Mock Snapshot Error/)
end
end
@ -465,12 +466,12 @@ EOT
snapshots = nil
allow(subject).to receive(:find_snapshot).and_return(snapshots)
result = MockResult.new
result.status = "DONE"
result.status = 'DONE'
allow(connection).to receive(:create_disk_snapshot).and_return(result)
end
it 'should return true' do
expect(subject.create_snapshot(poolname,vmname,snapshot_name)).to be true
expect(subject.create_snapshot(poolname, vmname, snapshot_name)).to be true
end
it 'should snapshot each attached disk' do
@ -480,7 +481,7 @@ EOT
allow(connection).to receive(:get_instance).and_return(instance)
expect(connection.should_receive(:create_disk_snapshot).twice)
subject.create_snapshot(poolname,vmname,snapshot_name)
subject.create_snapshot(poolname, vmname, snapshot_name)
end
end
end
@ -494,11 +495,11 @@ EOT
context 'when VM does not exist' do
before(:each) do
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404,"The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
allow(connection).to receive(:get_instance).and_raise(create_google_client_error(404, "The resource 'projects/#{project}/zones/#{zone}/instances/#{vmname}' was not found"))
end
it 'should raise an error' do
expect{ subject.revert_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/VM #{vmname} .+ does not exist/)
expect { subject.revert_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/VM #{vmname} .+ does not exist/)
end
end
@ -509,7 +510,7 @@ EOT
allow(connection).to receive(:get_instance).and_return(instance)
snapshots = nil
allow(subject).to receive(:find_snapshot).and_return(snapshots)
expect{ subject.revert_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/Snapshot #{snapshot_name} .+ does not exist /)
expect { subject.revert_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/Snapshot #{snapshot_name} .+ does not exist /)
end
end
@ -524,7 +525,7 @@ EOT
allow(connection).to receive(:start_instance)
expect(subject).not_to receive(:detach_disk)
expect(subject).not_to receive(:delete_disk)
subject.revert_snapshot(poolname,vmname,snapshot_name)
subject.revert_snapshot(poolname, vmname, snapshot_name)
end
end
@ -537,11 +538,11 @@ EOT
allow(subject).to receive(:find_snapshot).and_return(snapshots)
allow(connection).to receive(:stop_instance)
allow(subject).to receive(:wait_for_operation)
expect(connection).to receive(:detach_disk).and_raise(RuntimeError,'Mock Snapshot Error')
expect(connection).to receive(:detach_disk).and_raise(RuntimeError, 'Mock Snapshot Error')
end
it 'should raise an error' do
expect{ subject.revert_snapshot(poolname,vmname,snapshot_name) }.to raise_error(/Mock Snapshot Error/)
expect { subject.revert_snapshot(poolname, vmname, snapshot_name) }.to raise_error(/Mock Snapshot Error/)
end
end
@ -550,7 +551,7 @@ EOT
attached_disk = MockAttachedDisk.new(device_name: vmname, source: "foo/bar/baz/#{vmname}")
instance = MockInstance.new(name: vmname, disks: [attached_disk])
allow(connection).to receive(:get_instance).and_return(instance)
snapshots = [MockSnapshot.new(name: snapshot_name, self_link: "foo/bar/baz/snapshot/#{snapshot_name}", labels: {"diskname" => vmname})]
snapshots = [MockSnapshot.new(name: snapshot_name, self_link: "foo/bar/baz/snapshot/#{snapshot_name}", labels: { 'diskname' => vmname })]
allow(subject).to receive(:find_snapshot).and_return(snapshots)
allow(connection).to receive(:stop_instance)
allow(subject).to receive(:wait_for_operation)
@ -564,7 +565,7 @@ EOT
end
it 'should return true' do
expect(subject.revert_snapshot(poolname,vmname,snapshot_name)).to be true
expect(subject.revert_snapshot(poolname, vmname, snapshot_name)).to be true
end
end
end
@ -581,7 +582,7 @@ EOT
allow(subject).to receive(:wait_for_zone_operation)
end
it 'should attempt to delete unconfigured instances when they dont have a label' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo")])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo')])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
# the instance_list is filtered in the real code, and should only return non-configured VMs based on labels
@ -593,7 +594,7 @@ EOT
subject.purge_unconfigured_resources(nil)
end
it 'should attempt to delete unconfigured instances when they have a label that is not a configured pool' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"pool" => "foobar"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'pool' => 'foobar' })])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
allow(connection).to receive(:list_instances).and_return(instance_list)
@ -604,8 +605,8 @@ EOT
end
it 'should attempt to delete unconfigured disks and snapshots when they do not have a label' do
instance_list = MockInstanceList.new(items: nil)
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo")])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo")])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo')])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo')])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -618,10 +619,10 @@ EOT
context 'with allowlist containing a pool name' do
before(:each) do
allow(subject).to receive(:wait_for_zone_operation)
$allowlist = ["allowed"]
$allowlist = ['allowed']
end
it 'should attempt to delete unconfigured instances when they dont have the allowlist label' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"pool" => "not_this"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'pool' => 'not_this' })])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
allow(connection).to receive(:list_instances).and_return(instance_list)
@ -631,7 +632,7 @@ EOT
subject.purge_unconfigured_resources($allowlist)
end
it 'should ignore unconfigured instances when they have a label that is allowed' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"pool" => "allowed"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'pool' => 'allowed' })])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
allow(connection).to receive(:list_instances).and_return(instance_list)
@ -642,8 +643,8 @@ EOT
end
it 'should ignore unconfigured disks and snapshots when they have a label that is allowed' do
instance_list = MockInstanceList.new(items: nil)
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo", labels: {"pool" => "allowed"})])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo", labels: {"pool" => "allowed"})])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo', labels: { 'pool' => 'allowed' })])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo', labels: { 'pool' => 'allowed' })])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -652,10 +653,10 @@ EOT
subject.purge_unconfigured_resources($allowlist)
end
it 'should ignore unconfigured item when they have the empty label that is allowed, which means we allow the pool label to not be set' do
$allowlist = ["allowed", ""]
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"some" => "not_important"})])
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo", labels: {"other" => "thing"})])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo")])
$allowlist = ['allowed', '']
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'some' => 'not_important' })])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo', labels: { 'other' => 'thing' })])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo')])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -669,10 +670,10 @@ EOT
context 'with allowlist containing a pool name and the empty string' do
before(:each) do
allow(subject).to receive(:wait_for_zone_operation)
$allowlist = ["allowed", ""]
$allowlist = ['allowed', '']
end
it 'should attempt to delete unconfigured instances when they dont have the allowlist label' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"pool" => "not_this"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'pool' => 'not_this' })])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
allow(connection).to receive(:list_instances).and_return(instance_list)
@ -683,8 +684,8 @@ EOT
end
it 'should ignore unconfigured disks and snapshots when they have a label that is allowed' do
instance_list = MockInstanceList.new(items: nil)
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo", labels: {"pool" => "allowed"})])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo", labels: {"pool" => "allowed"})])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo', labels: { 'pool' => 'allowed' })])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo', labels: { 'pool' => 'allowed' })])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -693,9 +694,9 @@ EOT
subject.purge_unconfigured_resources($allowlist)
end
it 'should ignore unconfigured item when they have the empty label that is allowed, which means we allow the pool label to not be set' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"some" => "not_important"})])
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo", labels: {"other" => "thing"})])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo")])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'some' => 'not_important' })])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo', labels: { 'other' => 'thing' })])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo')])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -709,10 +710,10 @@ EOT
context 'with allowlist containing a a fully qualified label that is not pool' do
before(:each) do
allow(subject).to receive(:wait_for_zone_operation)
$allowlist = ["user=Bob"]
$allowlist = ['user=Bob']
end
it 'should attempt to delete unconfigured instances when they dont have the allowlist label' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"pool" => "not_this"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'pool' => 'not_this' })])
disk_list = MockDiskList.new(items: nil)
snapshot_list = MockSnapshotList.new(items: nil)
allow(connection).to receive(:list_instances).and_return(instance_list)
@ -722,9 +723,9 @@ EOT
subject.purge_unconfigured_resources($allowlist)
end
it 'should ignore unconfigured item when they match the fully qualified label' do
instance_list = MockInstanceList.new(items: [MockInstance.new(name: "foo", labels: {"some" => "not_important", "user" => "bob"})])
disk_list = MockDiskList.new(items: [MockDisk.new(name: "diskfoo", labels: {"other" => "thing", "user" => "bob"})])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: "snapfoo", labels: {"user" => "bob"})])
instance_list = MockInstanceList.new(items: [MockInstance.new(name: 'foo', labels: { 'some' => 'not_important', 'user' => 'bob' })])
disk_list = MockDiskList.new(items: [MockDisk.new(name: 'diskfoo', labels: { 'other' => 'thing', 'user' => 'bob' })])
snapshot_list = MockSnapshotList.new(items: [MockSnapshot.new(name: 'snapfoo', labels: { 'user' => 'bob' })])
allow(connection).to receive(:list_instances).and_return(instance_list)
allow(connection).to receive(:list_disks).and_return(disk_list)
allow(connection).to receive(:list_snapshots).and_return(snapshot_list)
@ -737,23 +738,22 @@ EOT
it 'should raise any errors' do
expect(subject).to receive(:provided_pools).and_throw('mockerror')
expect{ subject.purge_unconfigured_resources(nil) }.to raise_error(/mockerror/)
expect { subject.purge_unconfigured_resources(nil) }.to raise_error(/mockerror/)
end
end
describe '#get_current_user' do
it 'should downcase and replace invalid chars with dashes' do
redis_connection_pool.with_metrics do |redis|
redis.hset("vmpooler__vm__#{vmname}", 'token:user', "BOBBY.PUPPET")
expect(subject.get_current_user(vmname)).to eq("bobby-puppet")
redis.hset("vmpooler__vm__#{vmname}", 'token:user', 'BOBBY.PUPPET')
expect(subject.get_current_user(vmname)).to eq('bobby-puppet')
end
end
it 'returns "" for nil values' do
redis_connection_pool.with_metrics do |redis|
expect(subject.get_current_user(vmname)).to eq("")
redis_connection_pool.with_metrics do |_redis|
expect(subject.get_current_user(vmname)).to eq('')
end
end
end
end