repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb.rb
<filename>lib/puppet/face/azure_sqldb.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/sql_database' Puppet::Face.define(:azure_sqldb, '1.0.0') do summary 'View and manage Window Azure database servers.' description <<-'EOT' This subcommand provides a command line interface to work with Microsoft Azure machine instances. The goal of these actions are to easily create new database servers. EOT end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_servicebus/delete_topic.rb
<filename>lib/puppet/face/azure_servicebus/delete_topic.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_servicebus, '1.0.0' do action :delete_topic do summary 'Delete a topic using service bus object.' description <<-'EOT' Delete a topic using service bus object. EOT Puppet::ServiceBus.add_servicebus_topic_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_service_bus = Azure::ServiceBusService.new azure_service_bus.delete_topic(options[:topic_name]) end returns 'NONE' examples <<-'EOT' $ puppet azure_servicebus delete_topic --sb-namespace busname \ --topic-name topic-name --sb-access-key <KEY> EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vm/add_disk.rb
<filename>lib/puppet/face/azure_vm/add_disk.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_vm, '1.0.0' do action :add_disk do summary 'adds a data disk to a virtual machine.' description <<-'EOT' The add_disk action adds a data disk to a windows azure node instances. EOT Puppet::VirtualMachine.add_data_disk_options(self) when_invoked do |options| Puppet::VirtualMachine.initialize_env_variable(options) virtual_machine_service = Azure::VirtualMachineManagementService.new others = { import: options[:import], disk_label: options[:disk_label], disk_size: options[:disk_size], disk_name: options[:disk_name] } virtual_machine_service.add_data_disk( options[:vm_name], options[:cloud_service_name], others ) nil end returns 'NONE' examples <<-'EOT' $ puppet azure_vm add_disk --vm-name vmname --import true \ --cloud-service-name cloudname --disk-name disk_name \ --management-certificate path-to-azure-certificate \ --subscription-id YOUR-SUBSCRIPTION-ID \ $ puppet azure_vm add_disk --cloud-service-name cloud_name \ --management-certificate path-to-azure-certificate --vm-name vmname \ --subscription-id YOUR-SUBSCRIPTION-ID EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_affinitygroup/create.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_affinitygroup, '1.0.0' do action :create do summary 'Create affinity group.' description 'The create action create a affinity group.' Puppet::AffinityGroup.add_create_options(self) when_invoked do |options| Puppet::AffinityGroup.initialize_env_variable(options) affinity_group_service = Azure::BaseManagementService.new others = { description: options[:description] } begin affinity_group_service.create_affinity_group( options[:affinity_group_name], options[:location], options[:label], others ) rescue => e puts e.message end end examples <<-'EOT' $ puppet azure_affinitygroup create --label aglabel \ --azure-subscription-id YOUR-SUBSCRIPTION-ID --location 'West Us' \ --affinity-group-name agname --description 'Some Description' \ --management-certificate path-to-azure-certificate EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/application/azure_servicebus.rb
require 'puppet/application/face_base' class Puppet::Application::AzureServicebus < Puppet::Application::FaceBase end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_vm/update_endpoint_spec.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_vm, :current] do let(:vms) { Azure::VirtualMachineManagementService } before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') @options = { management_certificate: mgmtcertfile, azure_subscription_id: 'Subscription-id', vm_name: 'test-vm', cloud_service_name: 'cloud-name', endpoint_name: 'endpoint_name', public_port: '8080', local_port: '8080', protocol: 'tcp', direct_server_return: 'false', load_balancer_name: 'lb-name', load_balancer_protocol: 'tcp', load_balancer_port: '100' } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end vms.any_instance.stubs(:update_endpoints).with( anything, anything, anything ) end describe 'option validation' do describe 'valid options' do it 'should not raise any exception' do expect { subject.update_endpoint(@options) }.to_not raise_error end end describe '(vm_name)' do it 'should require a vm name' do @options.delete(:vm_name) expect { subject.update_endpoint(@options) }.to raise_error( ArgumentError, /required: vm_name/ ) end end describe '(cloud_service_name)' do it 'should require a cloud service name' do @options.delete(:cloud_service_name) expect { subject.update_endpoint(@options) }.to raise_error( ArgumentError, /required: cloud_service_name/ ) end end describe '(endpoint_name)' do it 'should require endpoint name' do @options.delete(:endpoint_name) expect { subject.update_endpoint(@options) }.to raise_error( ArgumentError, /required: endpoint_name/ ) end end describe '(public_port)' do it 'should require public port' do @options.delete(:public_port) expect { subject.update_endpoint(@options) }.to raise_error( ArgumentError, /required: public_port/ ) end end describe '(local_port)' do it 'should require local port' do @options.delete(:local_port) expect { subject.update_endpoint(@options) }.to raise_error( ArgumentError, /required: local_port/ ) end end describe '(protocol)' do it 'should validate the protocol' do @options.delete(:protocol) expect { subject.update_endpoint(@options) }.to_not raise_error end it 'should not allow wrong protocol value' do @options[:protocol] = 'wrong-value' expect { subject.update_endpoint(@options) }.to raise_error( RuntimeError, /Protocol is invalid. Allowed values are tcp,udp/ ) end end describe '(load_balancer_name)' do it 'should validate the load_balancer_name' do @options.delete(:load_balancer_name) expect { subject.update_endpoint(@options) }.to_not raise_error end end describe '(direct_server_return)' do it 'should validate direct_server_return' do @options.delete(:direct_server_return) expect { subject.update_endpoint(@options) }.to_not raise_error end it 'should not allow wrong direct_server_return value' do @options[:direct_server_return] = 'wrong-value' expect { subject.update_endpoint(@options) }.to raise_error( RuntimeError, /direct_server_return is invalid. Allowed values are true,false/ ) end end describe '(load_balancer_protocol)' do it 'should validate load_balancer_protocol' do @options.delete(:load_balancer_protocol) expect { subject.update_endpoint(@options) }.to_not raise_error end end describe '(load_balancer_port)' do it 'should validate load_balancer_port' do @options.delete(:load_balancer_port) expect { subject.update_endpoint(@options) }.to_not raise_error end end describe '(load_balancer_path)' do it 'should require load_balancer_path when protocol is http' do @options[:load_balancer_protocol] = 'http' @options.delete(:load_balancer_path) expect { subject.update_endpoint(@options) }.to raise_error( RuntimeError, /Load balancer path is required if load balancer protocol is http/ ) end it 'should not required load_balancer_path when protocol is tcp' do @options[:load_balancer_protocol] = 'tcp' @options.delete(:load_balancer_path) expect { subject.update_endpoint(@options) }.to_not raise_error end it 'should validate load_balancer_ protocol' do @options[:load_balancer_protocol] = 'wrong-value' expect { subject.update_endpoint(@options) }.to raise_error( RuntimeError, /Load balancer protocol is invalid. Allowed values are http,tcp/ ) end end it_behaves_like 'validate authentication credential', :update_endpoint end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_storage/list_spec.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_storage, :current] do let(:storage_service) { Azure::StorageManagementService } let(:storage_account_obj) do Azure::StorageManagement::StorageAccount.new do |sa| sa.name = 'cs-1' sa.location = 'West US' end end before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') @options = { management_certificate: mgmtcertfile, azure_subscription_id: 'Subscription-id' } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end end describe 'option validation' do before :each do storage_service.any_instance.stubs( :list_storage_accounts ).returns([storage_account_obj]) end describe 'valid options' do it 'should not raise any exception' do expect { subject.list(@options) }.to_not raise_error end it 'should print storage account details' do cs_services = subject.list(@options) name = "#{'Name'.fix(20)}: #{storage_account_obj.name}" location = "#{'Locaton'.fix(20)}: #{storage_account_obj.location}" expect(cs_services).to match(/#{name}/) expect(cs_services).to match(/#{location}/) end end it_behaves_like 'validate authentication credential', :list end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vnet/list.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_vnet, '1.0.0' do action :list do summary 'List virtual networks.' arguments 'list' description <<-'EOT' The list action obtains a list of virtual networks and displays them on the console output. EOT Puppet::VirtualNetwork.add_default_options(self) when_invoked do |options| Puppet::VirtualNetwork.initialize_env_variable(options) virtual_network_service = Azure::VirtualNetworkManagementService.new virtual_networks = virtual_network_service.list_virtual_networks template = Tilt.new(Puppet::VirtualNetwork.views('virtual_networks.erb')) template.render(nil, vnets: virtual_networks) end returns 'Array of virtual network objets.' examples <<-'EOT' $ puppet azure_vnet list --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID Listing virtual networks Virtual Network: 1 Server Name : vnet-AG Address Space : 172.16.0.0/12, 10.0.0.0/8, 192.168.0.0/24 Subnets: Name Address Prefix Subnet-1 172.16.0.0/12 Subnet-2 10.0.0.0/8 Subnet-4 192.168.0.0/26 Dns Servers: Name Ip Address google 8.8.8.8 google-2 8.8.4.4 EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb/delete_firewall.rb
<filename>lib/puppet/face/azure_sqldb/delete_firewall.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_sqldb, '1.0.0' do action :delete_firewall do summary 'Delete Microsoft Azure sql database firewall rule on server' description <<-'EOT' The delete action delete windows azure sql database firewall on server. EOT Puppet::SqlDatabase.add_delete_firewall_options(self) when_invoked do |options| Puppet::SqlDatabase.initialize_env_variable(options) db = Azure::SqlDatabaseManagementService.new db.delete_sql_server_firewall_rule( options[:server_name], options[:rule_name] ) nil end returns 'NONE' examples <<-'EOT' $ puppet azure_sqldb delete_firewall --server-name=xlykw0su08 \ --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID --rule-name rule1 \ --management-endpoint=https://management.database.windows.net:8443/ \ EOT end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_vm/servers_spec.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_vm, :current] do let(:vms) { Azure::VirtualMachineManagementService } let(:vm) { Azure::VirtualMachineManagement::VirtualMachine } let(:vm_name) { 'windows-instance' } let(:ip_address) { '192.168.1.1' } let(:os_type) { 'Windows' } let(:virtual_machine_obj) do vm.new do |virtual_machine| virtual_machine.vm_name = vm_name virtual_machine.ipaddress = ip_address virtual_machine.os_type = os_type end end before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') @options = { management_certificate: mgmtcertfile, management_endpoint: 'management.core.windows.net', azure_subscription_id: 'Subscription-id' } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end end describe 'option validation' do before :each do vms.any_instance.stubs(:list_virtual_machines).with( anything, anything ).returns([virtual_machine_obj]) end describe 'valid options' do it 'should not raise any exception' do expect { subject.servers(@options) }.to_not raise_error end it 'should print server details' do servers = subject.servers(@options) expect(servers).to match(/Role : #{vm_name}/) expect(servers).to match(/IP Address : #{ip_address}/) end end it_behaves_like 'validate authentication credential', :servers end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_cloudservice/delete_deployment.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_cloudservice, '1.0.0' do action :delete_deployment do summary 'deletes the specified deployment of hosted service.' description <<-'EOT' The delete_deployment action deletes the specified deployment of a hosted service. EOT Puppet::CloudService.add_delete_deployment_options(self) when_invoked do |options| Puppet::CloudService.initialize_env_variable(options) cloud_service = Azure::CloudServiceManagementService.new csn = options[:cloud_service_name] cloud_service.delete_cloud_service_deployment(csn) rescue nil nil end examples <<-'EOT' $ puppet azure_cloudservice upload_certificate \ --cloud-service-name cloudservice1 \ --azure-subscription-id YOUR-SUBSCRIPTION-ID \ --management-certificate path-to-azure-certificate EOT end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_vm/bootstrap_spec.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_vm, :current] do before :each do @options = { ssh_user: 'root', winrm_user: 'Administrator', password: '<PASSWORD>', winrm_port: 5985, ssh_port: 22, node_ipaddress: '192.168.3.11', puppet_master_ip: '127.0.0.1', winrm_transport: 'http', private_key_file: File.expand_path('spec/fixtures/private_key.key') } end describe 'option validation' do before :each do Puppet::AzurePack::BootStrap.stubs(:start).with(anything) end describe 'valid options' do it 'should raise exception when ssh_user and winrm_user is present' do expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Either winrm_user or ssh_user is required/ ) end it 'should not raise error when ssh_user is given' do @options.delete(:winrm_user) expect { subject.bootstrap(@options) }.to_not raise_error end it 'should not raise error when winrm_user is given' do @options.delete(:ssh_user) expect { subject.bootstrap(@options) }.to_not raise_error end it 'should raise error when winrm_user and ssh_user is empty' do @options.delete(:ssh_user) @options.delete(:winrm_user) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Either winrm_user or ssh_user is required/ ) end end describe 'optional parameter validation' do describe '(puppet_master_ip)' do before :each do Puppet::AzurePack::BootStrap.stubs(:start).with(anything) end it 'puppet_master_ip should be optional' do @options.delete(:puppet_master_ip) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /required: puppet_master_ip/ ) end end describe '(node_ipaddress)' do before :each do Puppet::AzurePack::BootStrap.stubs(:start).with(anything) end it 'puppet_master_ip should be optional' do @options.delete(:node_ipaddress) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /required: node_ipaddress/ ) end end describe '(linux)' do before :each do @options = { ssh_user: 'root', password: '<PASSWORD>', ssh_port: 22, node_ipaddress: '192.168.3.11', puppet_master_ip: '127.0.0.1', private_key_file: File.expand_path('spec/fixtures/private_key.key') } Puppet::AzurePack::BootStrap.stubs(:start).with(anything) end describe '(ssh_user)' do it 'should be mandatory' do @options.delete(:ssh_user) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Either winrm_user or ssh_user is required/ ) end end describe '(ssh_port)' do it 'should validate the ssh_port' do expect { subject.bootstrap(@options) }.to_not raise_error end end describe '(agent_environment)' do it 'should validate the agent_environment' do @options.delete(:agent_environment) expect { subject.bootstrap(@options) }.to_not raise_error end it 'should validate the agent_environment' do @options[:agent_environment] = 'development' expect { subject.bootstrap(@options) }.to_not raise_error end end describe '(private_key_file)' do it 'should be optional' do @options.delete(:private_key_file) expect { subject.bootstrap(@options) }.to_not raise_error end it 'private key or password is required for Linux' do @options.delete(:password) @options.delete(:private_key_file) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Password or Private key is require for bootstrap/ ) end end end describe '(windows)' do before :each do @options = { winrm_user: 'Administrator', password: '<PASSWORD>', winrm_port: 5985, node_ipaddress: '192.168.3.11', puppet_master_ip: '127.0.0.1', winrm_transport: 'http' } Puppet::AzurePack::BootStrap.stubs(:start).with(anything) end describe '(password)' do it 'password is required for windows' do @options.delete(:password) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Password is require for windows vm bootstrap/ ) end end describe '(winrm_user)' do it 'should not be optional' do @options.delete(:winrm_user) expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /Either winrm_user or ssh_user is required/ ) end end describe '(winrm_transport)' do it 'winrm_transport should be optional' do @options.delete(:winrm_transport) expect { subject.bootstrap(@options) }.to_not raise_error end it 'should validate the winrm_transport' do @options[:winrm_transport] = 'ftp' expect { subject.bootstrap(@options) }.to raise_error( ArgumentError, /The winrm transport is not valid/ ) end it 'should validate the winrm_transport' do @options[:winrm_transport] = 'http' expect { subject.bootstrap(@options) }.to_not raise_error end it 'should validate the winrm_transport' do @options[:winrm_transport] = 'https' expect { subject.bootstrap(@options) }.to_not raise_error end end describe '(winrm_port)' do it 'should validate the winrm_port' do @options.delete(:winrm_port) expect { subject.bootstrap(@options) }.to_not raise_error end end end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_servicebus/create_topic.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_servicebus, '1.0.0' do action :create_topic do summary 'Create topic with service bus object.' description <<-'EOT' Create topic with service bus object. EOT Puppet::ServiceBus.add_servicebus_topic_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_service_bus = Azure::ServiceBusService.new azure_service_bus.create_topic(options[:topic_name]).inspect end returns 'NONE' examples <<-'EOT' $ puppet azure_servicebus create_topic --sb-namespace busname \ --topic-name topicname --sb-access-key <KEY> EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/application/azure_queue.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet require 'puppet/application/face_base' class Puppet::Application::AzureQueue < Puppet::Application::FaceBase end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vm/bootstrap.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet<filename>lib/puppet/face/azure_vm/bootstrap.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'puppet/azurepack/bootstrap' Puppet::Face.define :azure_vm, '1.0.0' do action :bootstrap do summary 'Install puppet node on Microsoft Azure VM' description 'Install puppet node on Microsoft Azure Virtual Machine.' Puppet::VirtualMachine.add_bootstrap_options(self) when_invoked do |options| Puppet::AzurePack::BootStrap.start(options) nil end examples <<-'EOT' $ puppet azure_vm bootstrap --node-ip-address=domain.cloudapp.net \ --vm-user username --puppet-master-ip 172.16.58.3 --password <PASSWORD> \ --agent-environment development EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb/list.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_sqldb, '1.0.0' do action :list do summary 'List SQL database servers.' arguments 'list' description <<-'EOT' The list action obtains a list of sql database servers and displays them on the console output. EOT Puppet::SqlDatabase.add_default_options(self) when_invoked do |options| Puppet::SqlDatabase.initialize_env_variable(options) sql_service = Azure::SqlDatabaseManagementService.new servers = sql_service.list_servers template = Tilt.new(Puppet::SqlDatabase.views('servers.erb')) template.render(nil, db_servers: servers) end returns 'Array of database server objets.' examples <<-'EOT' $ puppet azure_sqldb list --azure-subscription-id=YOUR-SUBSCRIPTION-ID \ --management-certificate azure-certificate-path \ --management-endpoint=https://management.database.windows.net:8443/ Listing Servers Server: 1 Server Name : esinlp9bav Administrator login : puppet3 Location : West US Server: 2 Server Name : estkonosnv Administrator login : puppet Location : West US Server: 3 Server Name : ezprthvj9w Administrator login : puppet Location : West US EOT end end
Bhaskers-Blu-Org2/azure-puppet
spec/support/credential_validation.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 shared_examples 'validate authentication credential' do |service_method| describe '(management_certificate)' do it 'should require a management_certificate' do @options.delete(:management_certificate) expect { subject.send(service_method, @options) }.to raise_error( ArgumentError, /required: management_certificate/ ) end it 'management_certificate doesn\'t exist' do @options[:management_certificate] = 'FileNotExist' expect { subject.send(service_method, @options) }.to raise_error( ArgumentError, /Could not find file 'FileNotExist'/ ) end it 'management_certificate extension is not valid' do file_path = File.expand_path('spec/fixtures/invalid_file.txt') @options[:management_certificate] = file_path expect { subject.send(service_method, @options) }.to raise_error( RuntimeError, /Management certificate expects a .pem or .pfx file/ ) end end describe '(azure_subscription_id)' do it 'should require a azure_subscription_id' do @options.delete(:azure_subscription_id) expect { subject.send(service_method, @options) }.to raise_error( ArgumentError, /required: azure_subscription_id/ ) end end describe '(management_endpoint)' do it 'management_endpoint should be optional' do @options.delete(:management_endpoint) expect { subject.send(service_method, @options) }.to_not raise_error end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_cloudservice/create.rb
<filename>lib/puppet/face/azure_cloudservice/create.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_cloudservice, '1.0.0' do action :create do summary 'Create cloud service.' description 'The create action create a cloud service.' Puppet::CloudService.add_create_options(self) when_invoked do |options| Puppet::CloudService.initialize_env_variable(options) cloud_service = Azure::CloudServiceManagementService.new others = { description: options[:description], label: options[:label], affinity_group_name: options[:affinity_group_name], location: options[:location], extended_properties: options[:extended_properties] } cloud_service.create_cloud_service( options[:cloud_service_name], others ) nil end examples <<-'EOT' $ puppet azure_cloudservice create --label aglabel \ --azure-subscription-id YOUR-SUBSCRIPTION-ID --location 'West Us' \ --affinity-group-name agname --description 'Some Description' \ --management-certificate path-to-azure-certificate \ --cloud-service-name cloudservice1 EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb/create_firewall.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_sqldb, '1.0.0' do action :create_firewall do summary 'Create SQL database firewall rule on a server.' description <<-'EOT' The create action create a SQL database firewall rule on a server. EOT Puppet::SqlDatabase.add_create_firewall_options(self) when_invoked do |options| Puppet::SqlDatabase.initialize_env_variable(options) db_server = Azure::SqlDatabaseManagementService.new ip_range = { start_ip_address: options[:start_ip_address], end_ip_address: options[:end_ip_address] } db_server.set_sql_server_firewall_rule( options[:server_name], options[:rule_name], ip_range ) end examples <<-'EOT' $ puppet azure_sqldb create_firewall --end-ip-address 10.10.0.255 \ --management-certificate path-to-azure-certificate \ --azure-subscription-id YOUR-SUBSCRIPTION-ID --rule-name ranjan \ --management-endpoint=https://management.database.windows.net:8443/\ --server-name=g2jxhsbk0w --start-ip-address 10.10.0.0 $ puppet azure_sqldb create_firewall --server-name=g2jxhsbk0w\ --management-certificate path-to-azure-certificate \ --azure-subscription-id YOUR-SUBSCRIPTION-ID --rule-name ranjan EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_servicebus/list_topics.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'tilt' require 'puppet/core/utility' Puppet::Face.define :azure_servicebus, '1.0.0' do action :list_topics do summary 'List topics' description 'List topics' Puppet::ServiceBus.add_default_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_service_bus = Azure::ServiceBusService.new topics = azure_service_bus.list_topics template = Tilt.new(Puppet::ServiceBus.views('topics.erb')) template.render(nil, topics: topics) end returns 'NONE' examples <<-'EOT' $ puppet azure_servicebus list_topics --sb-namespace busname \ --sb-access-key <KEY> EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_cloudservice/list.rb
<filename>lib/puppet/face/azure_cloudservice/list.rb<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_cloudservice, '1.0.0' do action :list do summary 'List cloud services.' description <<-'EOT' The list action obtains a list of cloud services and displays them on the console output. EOT Puppet::CloudService.add_default_options(self) when_invoked do |options| Puppet::CloudService.initialize_env_variable(options) cloud_service = Azure::CloudServiceManagementService.new cloud_services = cloud_service.list_cloud_services template = Tilt.new(Puppet::CloudService.views('cloud_services.erb')) template.render(nil, cloud_services: cloud_services) end returns 'Array of cloud service objets.' examples <<-'EOT' $ puppet azure_cloudservice list \ --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID Listing cloud services Cloud Service: 1 Name : azure-puppet Locaton : West US Status : Created Winrm Thumbprint : Cloud Service: 2 Name : puppet-dashboard-service-oiurf Locaton : West US Status : Created Winrm Thumbprint : Cloud Service: 3 Name : puppet-master Locaton : West US Status : Created Winrm Thumbprint : EOT end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_cloudservice/list_spec.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_cloudservice, :current] do let(:cloud_service) { Azure::CloudServiceManagementService } let(:cloud_service_obj) do Azure::CloudServiceManagement::CloudService.new do |cs| cs.name = 'cs-1' cs.location = 'West US' end end before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') @options = { management_certificate: mgmtcertfile, azure_subscription_id: 'Subscription-id' } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end end describe 'option validation' do before :each do cloud_service.any_instance.stubs( :list_cloud_services ).returns([cloud_service_obj]) end describe 'valid options' do it 'should not raise any exception' do expect { subject.list(@options) }.to_not raise_error end it 'should print affinity groups details' do cs_services = subject.list(@options) name = "#{'Name'.fix(20)}: #{cloud_service_obj.name}" location = "#{'Locaton'.fix(20)}: #{cloud_service_obj.location}" expect(cs_services).to match(/#{name}/) expect(cs_services).to match(/#{location}/) end end it_behaves_like 'validate authentication credential', :list end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_vnet/set_xml_schema_spec.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_vnet, :current] do let(:vnet_service) { Azure::VirtualNetworkManagementService } before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') netowork_schema = File.expand_path('spec/fixtures/vnet_schema.xml') @options = { management_certificate: mgmtcertfile, azure_subscription_id: 'Subscription-id', management_endpoint: 'management.core.windows.net', xml_schema_file: netowork_schema } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end vnet_service.any_instance.stubs(:set_network_configuration).with( anything ) end describe 'option validation' do describe 'valid options' do it 'should not raise any exception' do expect { subject.set_xml_schema(@options) }.to_not raise_error end end describe '(xml_schema_file)' do it 'should validate the xml schema file' do @options.delete(:xml_schema_file) expect { subject.set_xml_schema(@options) }.to raise_error( ArgumentError, /required: xml_schema_file/ ) end it 'xml_schema_file doesn\'t exist' do @options[:xml_schema_file] = 'FileNotExist' expect { subject.set_xml_schema(@options) }.to raise_error( ArgumentError, /Could not find file 'FileNotExist'/ ) end it 'xml_schema_file extension is not valid' do file_path = File.expand_path('spec/fixtures/invalid_file.txt') @options[:xml_schema_file] = file_path expect { subject.set_xml_schema(@options) }.to raise_error( RuntimeError, /Network schema expects a .xml file/ ) end end it_behaves_like 'validate authentication credential', :set_xml_schema end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_affinitygroup/list.rb
<filename>lib/puppet/face/azure_affinitygroup/list.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_affinitygroup, '1.0.0' do action :list do summary 'List affinity groups.' arguments 'list' description <<-'EOT' The list action obtains a list of affinity groups and displays them on the console output. EOT Puppet::AffinityGroup.add_default_options(self) when_invoked do |options| Puppet::AffinityGroup.initialize_env_variable(options) affinity_group_service = Azure::BaseManagementService.new affinity_groups = affinity_group_service.list_affinity_groups template = Tilt.new(Puppet::AffinityGroup.views('affinity_groups.erb')) template.render(nil, affinity_groups: affinity_groups) end returns 'Array of affinity group objets.' examples <<-'EOT' $ puppet affinity_group list \ --management-certificate path-to-azure-certificate \ --azure-subscription-id YOUR-SUBSCRIPTION-ID \ --management-endpoint=https://management.core.windows.net Listing affinity groups Affinity Group: 1 Name : integration-test-affinity-group Label : Label Locaton : East Asia Description : Description Capability : PersistentVMRole, HighMemory Affinity Group: 2 Name : Test Label : this is update operation Locaton : West US Description : My Description Capability : PersistentVMRole, HighMemory EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_cloudservice/upload_certificate.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_cloudservice, '1.0.0' do action :upload_certificate do summary 'adds a certificate to a hosted service.' description <<-'EOT' The upload_certificate action adds a certificate to a hosted service. EOT Puppet::CloudService.add_certificate_options(self) when_invoked do |options| Puppet::CloudService.initialize_env_variable(options) cloud_service = Azure::CloudServiceManagementService.new certificate = {} cert_file = File.read(options[:certificate_file]) key_file = File.read(options[:private_key_file]) csn = options[:cloud_service_name] certificate[:key] = OpenSSL::PKey.read key_file certificate[:cert] = OpenSSL::X509::Certificate.new cert_file cloud_service.upload_certificate(csn, certificate) nil end examples <<-'EOT' $ puppet azure_cloudservice upload_certificate \ --cloud-service-name cloudservice1 --certificate-file cert_file_path \ --azure-subscription-id YOUR-SUBSCRIPTION-ID \ --management-certificate path-to-azure-certificate \ --private-key-file private_key_file_path EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vm/locations.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_vm, '1.0.0' do action :locations do summary 'List Microsoft Azure locations' description <<-'EOT' The locations action obtains a list of locatons from the cloud provider and displays them on the console output. EOT Puppet::VirtualMachine.add_default_options(self) when_invoked do |options| Puppet::VirtualMachine.initialize_env_variable(options) base_management = Azure::BaseManagementService.new locations = base_management.list_locations template = Tilt.new(Puppet::VirtualMachine.views('locations.erb')) template.render(nil, locations: locations) end returns <<-'EOT' Array of attribute hashes containing information about Microsoft Azure locations.' EOT examples <<-'EOT' $ puppet azure_vm locations --azure-subscription-id YOUR-SUBSCRIPTION-ID\ --management-certificate path-to-azure-certificate Location Name Available Service West US : Compute, Storage, PersistentVMRole East US : Compute, Storage, PersistentVMRole East Asia : Compute, Storage, PersistentVMRole Southeast Asia : Compute, Storage, PersistentVMRole North Europe : Compute, Storage, PersistentVMRole West Europe : Compute, Storage, PersistentVMRole EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/virtual_network.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/application_config' require 'puppet/core/utility' include Puppet::ApplicationConfig module Puppet::VirtualNetwork class << self def views(name) File.join(File.dirname(__FILE__), 'face/azure_vnet/views', name) end def add_set_virtual_network_options(action) add_default_options(action) add_virtual_network_name_option(action) add_location_option(action) add_address_space_option(action) add_subnet_option(action) add_dns_server_option(action) end def add_set_xml_schema_options(action) add_default_options(action) add_xml_schema_file_option(action) end def add_xml_schema_file_option(action) action.option '--xml-schema-file=' do summary 'Xml schema file path' description 'Xml schema file path of virtual network.' required before_action do |act, args, options| filepath = options[:xml_schema_file] validate_file(filepath, 'Network schema', ['xml']) end end end def add_virtual_network_name_option(action) action.option '--virtual-network-name=' do summary 'The virtual network name.' description 'Name of virtual network.' required before_action do |act, args, options| if options[:virtual_network_name].empty? fail ArgumentError, 'Virtual network name is required' end end end end def add_address_space_option(action) action.option '--address-space=' do summary 'The address space for virtual network.' description 'Address space for virtual network.' required before_action do |act, args, options| if options[:address_space].empty? fail ArgumentError, 'Virtual network address space is required' end end end end def add_subnet_option(action) action.option '--subnets=' do summary 'Subnet of virtual network.' description <<-EOT Contains the specification for the subnets that you want to create within the address space of your virtual network sites. EOT end end def add_dns_server_option(action) action.option '--dns-servers=' do summary 'Dns server for virtual network.' description 'Contains the collection of DNS servers.' end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb/list_firewall.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_sqldb, '1.0.0' do action :list_firewall do summary 'List firewall of SQL database servers.' arguments 'list' description <<-'EOT' The list_firewall action retrieves a list of all the server-level firewall rules for a SQL Database server that belongs to a subscription. EOT Puppet::SqlDatabase.add_delete_options(self) when_invoked do |options| Puppet::SqlDatabase.initialize_env_variable(options) db_server = Azure::SqlDatabaseManagementService.new firewalls = db_server.list_sql_server_firewall_rules( options[:server_name] ) template = Tilt.new(Puppet::SqlDatabase.views('server_firewalls.erb')) template.render(nil, firewalls: firewalls) end examples <<-'EOT' $ puppet azure_sqldb list_firewall --server-name=g2jxhsbk0w \ --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID \ --management-endpoint=https://management.database.windows.net:8443/ \ Listing Firewall Firewall: 1 Rule name : ClientIPAddress_2013-08-20_15:37:41 Start IP address : 172.16.17.32 End Ip Address : 172.16.17.32 Firewall: 2 Rule name : ranjan Start IP address : 10.10.0.0 End Ip Address : 10.10.0.0 Firewall: 3 Rule name : rule2 Start IP address : 192.168.1.1 End Ip Address : 192.168.1.1 EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_servicebus/list_queues.rb
<reponame>Bhaskers-Blu-Org2/azure-puppet #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'tilt' require 'puppet/core/utility' Puppet::Face.define :azure_servicebus, '1.0.0' do action :list_queues do summary 'List queues' description 'List queues' Puppet::ServiceBus.add_default_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_service_bus = Azure::ServiceBusService.new queues = azure_service_bus.list_queues template = Tilt.new(Puppet::ServiceBus.views('queues.erb')) template.render(nil, queues: queues) end returns 'NONE' examples <<-'EOT' $ puppet azure_servicebus list_queues --sb-namespace busname \ --sb-access-key <KEY> EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vm/update_endpoint.rb
<filename>lib/puppet/face/azure_vm/update_endpoint.rb<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_vm, '1.0.0' do action :update_endpoint do summary 'update existing endpoint of a virtual machine.' description <<-'EOT' The update_endpoint action update existing endpoint of a virtual machine. EOT Puppet::VirtualMachine.update_endpoint_options(self) when_invoked do |options| Puppet::VirtualMachine.initialize_env_variable(options) virtual_machine_service = Azure::VirtualMachineManagementService.new options[:protocol] ||= 'TCP' options[:direct_server_return] ||= 'false' ep = { name: options[:endpoint_name], public_port: options[:public_port], local_port: options[:local_port], protocol: options[:protocol], load_balancer_name: options[:load_balancer_name], direct_server_return: options[:direct_server_return], load_balancer: { port: options[:load_balancer_port], protocol: options[:load_balancer_protocol], path: options[:load_balancer_path] } } virtual_machine_service.update_endpoints( options[:vm_name], options[:cloud_service_name], ep ) nil end returns 'NONE' examples <<-'EOT' $ puppet azure_vm update_endpoint --subscription-id YOUR-SUBSCRIPTION-ID \ --cloud-service-name cloudname --vm-name vmname --endpoint-name epname \ --local-port 90 --public-port 91 --direct-server-return true \ --load-balancer-name lbname --protocol udp $ puppet azure_vm update_endpoint --subscription-id YOUR-SUBSCRIPTION-ID \ --cloud-service-name cloudname --vm-name vmname --endpoint-name epname --local-port 90 --public-port 91 EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_storage/list.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_storage, '1.0.0' do action :list do summary 'List storage accounts.' description <<-'EOT' The list action obtains a list of storage accounts and displays them on the console output. EOT Puppet::StorageAccount.add_default_options(self) when_invoked do |options| Puppet::StorageAccount.initialize_env_variable(options) strage_service = Azure::StorageManagementService.new storage_accounts = strage_service.list_storage_accounts template = Tilt.new(Puppet::StorageAccount.views('storage_accounts.erb')) template.render(nil, storage_accounts: storage_accounts) end returns 'Array of storage account objets.' examples <<-'EOT' $ puppet azure_storage list \ --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID Listing storage accounts Storage Account: 1 Name : azure-puppet Locaton : West US Status : Created Winrm Thumbprint : Storage Account: 2 Name : puppet-dashboard-service-oiurf Locaton : West US Status : Created Winrm Thumbprint : Storage Account: 3 Name : puppet-master Locaton : West US Status : Created Winrm Thumbprint : EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vm/servers.rb
<filename>lib/puppet/face/azure_vm/servers.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'tilt' Puppet::Face.define :azure_vm, '1.0.0' do action :servers do summary 'List Microsoft Azure node instances' arguments 'list' description <<-'EOT' The list action obtains a list of instances from the cloud provider and displays them on the console output. For Azure instances, only the instances in a specific region are provided. EOT Puppet::VirtualMachine.add_default_options(self) when_invoked do |options| Puppet::VirtualMachine.initialize_env_variable(options) virtual_machine_service = Azure::VirtualMachineManagementService.new servers = virtual_machine_service.list_virtual_machines template = Tilt.new(Puppet::VirtualMachine.views('servers.erb')) template.render(nil, roles: servers) end returns 'Array of attribute hashes containing information about each Azure instance.' examples <<-'EOT' $ puppet azure_vm servers --publish-settings-file azure-certificate-path --azure-subscription-id YOUR-SUBSCRIPTION-ID Server: 1 Service: cloudserver1 Deployment: deployment1 Role: windows Host: akwindows Deployment Status: Running Role Status: ReadyRole IP Address: 172.16.31.10 EOT end end
Bhaskers-Blu-Org2/azure-puppet
spec/spec_helper.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'puppet' require 'puppet/face' require 'azure' require 'mocha/api' gem 'rspec', '>=2.0.0' Dir['./spec/support/**/*.rb'].sort.each { |f| require f } RSpec.configure do |config| config.mock_with :mocha config.after :each do Puppet.settings.clear Puppet::Node::Environment.clear Puppet::Util::Storage.clear Puppet::Util::Log.close_all end config.before :each do $puppet_application_mode = nil $puppet_application_name = nil Puppet[:confdir] = '/dev/null' Puppet[:vardir] = '/dev/null' Puppet.settings[:bindaddress] = '127.0.0.1' @logs = [] Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(@logs)) end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_sqldb/create.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_sqldb, '1.0.0' do action :create do summary 'Create SQL database server.' description 'The create action create a SQL database server.' Puppet::SqlDatabase.add_create_options(self) when_invoked do |options| Puppet::SqlDatabase.initialize_env_variable(options) db = Azure::SqlDatabaseManagementService.new sql_server = db.create_server( options[:login], options[:password], options[:location] ) template = Tilt.new(Puppet::SqlDatabase.views('servers.erb')) template.render(nil, db_servers: sql_server) if sql_server end examples <<-'EOT' $ puppet azure_sqldb create --login puppet --location 'West Us' \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID --password <PASSWORD> \ --management-endpoint=https://management.database.windows.net:8443/ \ --management-certificate path-to-azure-certificate EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_queue.rb
<filename>lib/puppet/face/azure_queue.rb require 'puppet/service_bus' Puppet::Face.define(:azure_queue, '1.0.0') do summary 'View and manage Window Azure database servers.' description <<-'EOT' This subcommand provides a command line interface to work with Windows Azure machine instances. The goal of these actions are to easily create new database servers. EOT end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/sql_database.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/core/utility' require 'puppet/application_config' include Puppet::ApplicationConfig module Puppet::SqlDatabase class << self def initialize_env_variable(options) sql_db_endpoint = 'https://management.database.windows.net:8443/' options[:management_endpoint] ||= sql_db_endpoint ENV['azure_management_certificate'.upcase] = options[:management_certificate] ENV['azure_subscription_id'.upcase] = options[:azure_subscription_id] ENV['azure_management_endpoint'.upcase] = options[:management_endpoint] require 'azure' end def views(name) File.join(File.dirname(__FILE__), 'face/azure_sqldb/views', name) end def add_create_options(action) add_default_options(action) add_login_option(action) add_password_option(action) add_location_option(action) end def add_delete_options(action) add_default_options(action) add_server_name_option(action) end def add_reset_password_options(action) add_default_options(action) add_server_name_option(action) add_password_option(action) end def add_create_firewall_options(action) add_default_options(action) add_server_name_option(action) add_rule_name_option(action) add_start_ip_address_option(action) add_end_ip_address_option(action) end def add_delete_firewall_options(action) add_default_options(action) add_server_name_option(action) add_rule_name_option(action) end def add_login_option(action) action.option '--login=' do summary 'The login username for the Microsoft Azure sql database server.' description 'The login username of Microsoft Azure sql database server.' required before_action do |act, args, options| if options[:login].empty? fail ArgumentError, 'Login is required.' end end end end def add_password_option(action) action.option '--password=' do summary 'The pasword for the Microsoft Azure sql database server.' description 'The password for the Microsoft Azure sql database server.' required before_action do |act, args, options| if options[:password].empty? fail ArgumentError, 'Password is required.' end end end end def add_server_name_option(action) action.option '--server-name=' do summary 'The server name for the Microsoft Azure sql database server.' description 'The server name for the Microsoft Azure sql database server.' required before_action do |act, args, options| if options[:server_name].empty? fail ArgumentError, 'Server name is required.' end end end end def add_rule_name_option(action) action.option '--rule-name=' do summary 'The rule name for the sql database server firewall.' description 'The rule name for the sql database server firewall.' required before_action do |act, args, options| if options[:rule_name].empty? fail ArgumentError, 'Firewall rule name is required.' end end end end def add_start_ip_address_option(action) action.option '--start-ip-address=' do summary 'The start ip address for the sql database server firewall.' description 'The start ip address of sql database server firewall.' end end def add_end_ip_address_option(action) action.option '--end-ip-address=' do summary 'The end ip address for the sql database server firewall.' description 'The end ip address for the sql database server firewall.' end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/option_validation.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 module Puppet module OptionValidation def validate_bootstrap_options(options) if options[:ssh_user] && options[:winrm_user] os = nil elsif options[:ssh_user] os = 'Linux' elsif options[:winrm_user] os = 'Windows' end case os when 'Linux' case when options[:private_key_file].nil? && options[:password].nil? fail ArgumentError, 'Password or Private key is require for bootstrap.' end when 'Windows' case when options[:password].nil? fail ArgumentError, 'Password is require for windows vm bootstrap.' end else fail ArgumentError, 'Either winrm_user or ssh_user is required' end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_vnet/set_xml_schema.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- Puppet::Face.define :azure_vnet, '1.0.0' do action :set_xml_schema do summary 'set_xml_schema Network configures the virtual network using xml schema' description <<-'EOT' The set_xml_schema Network Configuration operation asynchronously configures the virtual network. EOT Puppet::VirtualNetwork.add_set_xml_schema_options(self) when_invoked do |options| Puppet::VirtualNetwork.initialize_env_variable(options) virtual_network_service = Azure::VirtualNetworkManagementService.new virtual_network_service.set_network_configuration(options[:xml_schema_file]) nil end returns 'None ' examples <<-'EOT' $ puppet azure_vnet set --management-certificate path-to-azure-certificate \ --azure-subscription-id=YOUR-SUBSCRIPTION-ID --management-endpoint=https://management.database.windows.net:8443/ EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/application_config.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/core/utility' include Puppet::Core::Utility module Puppet module ApplicationConfig def initialize_env_variable(options) ENV['azure_management_certificate'.upcase] = options[:management_certificate] ENV['azure_subscription_id'.upcase] = options[:azure_subscription_id] ENV['azure_management_endpoint'.upcase] = options[:management_endpoint] gem "azure", '=0.6.4' require 'azure' end def add_default_options(action) add_management_certificate_option(action) add_subscription_id_option(action) add_management_endpoint_option(action) end def add_management_certificate_option(action) action.option '--management-certificate=' do summary 'The subscription identifier for the Microsoft Azure portal.' description 'The subscription identifier for the Microsoft Azure portal.' required before_action do |act, args, options| file = options[:management_certificate] validate_file(file, 'Management certificate', %w(pem pfx)) end end end def add_subscription_id_option(action) action.option '--azure-subscription-id=' do summary 'The subscription identifier for the Microsoft Azure portal.' description 'The subscription identifier for the Microsoft Azure portal.' required before_action do |act, args, options| if options[:azure_subscription_id].empty? fail ArgumentError, 'Subscription id is required.' end end end end def add_management_endpoint_option(action) action.option '--management-endpoint=' do summary 'The management endpoint for the Microsoft Azure portal.' description 'The management endpoint for the Microsoft Azure portal.' end end def add_location_option(action, optional = false) action.option '--location=' do summary 'The location identifier for the Microsoft Azure portal.' description <<-EOT The location identifier for the Microsoft Azure portal. valid choices are ('West US', 'East US', 'Southeast Asia', 'North Europe', 'West Europe', 'East Asia' ...). EOT required unless optional before_action do |act, args, options| if options[:location].empty? fail ArgumentError, 'Location is required' end end end end def add_affinity_group_name_option(action, optional = false) action.option '--affinity-group-name=' do summary 'The affinity group name.' description 'The affinity group name.' required unless optional before_action do |act, args, options| if options[:affinity_group_name].empty? fail ArgumentError, 'Affinity group name is required' end end end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/virtual_machine.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/application_config' require 'puppet/option_validation' include Puppet::ApplicationConfig include Puppet::OptionValidation module Puppet module VirtualMachine class << self def views(name) File.join(File.dirname(__FILE__), 'face/azure_vm/views', name) end def add_list_images_options(action) add_default_options(action) add_location_option(action, true) end def add_data_disk_options(action) add_default_options(action) add_cloud_service_name_option(action, false) add_vm_name_option(action, false) add_disk_import_option(action) add_disk_name_option(action) add_disk_size_option(action) add_disk_label_option(action) end def update_endpoint_options(action) add_default_options(action) add_cloud_service_name_option(action, false) add_vm_name_option(action, false) add_endpoint_name_option(action) add_public_port_option(action) add_local_port_option(action) add_protocol_option(action) add_load_balancer_name_option(action) add_direct_server_return_option(action) add_load_balancer_port_option(action) add_load_balancer_protocol_option(action) add_load_balancer_path_option(action) end def delete_endpoint_options(action) add_default_options(action) add_cloud_service_name_option(action, false) add_vm_name_option(action, false) add_endpoint_name_option(action) end def add_shutdown_options(action) add_default_options(action) add_cloud_service_name_option(action, false) add_vm_name_option(action, false) end def add_delete_options(action) add_default_options(action) add_vm_name_option(action, false) add_cloud_service_name_option(action, false) end def add_bootstrap_options(action) add_node_ipaddress_options(action) add_password_option(action) add_ssh_user_option(action) add_ssh_port_option(action) add_winrm_user_option(action) add_winrm_port_option(action) add_puppet_master_ip_option(action, false) add_private_key_file_option(action) add_bootstrap_winrm_transport_option(action) add_agent_environment_options(action) end def add_create_options(action, add_role = false) add_default_options(action) if add_role add_cloud_service_name_option(action, false) else add_cloud_service_name_option(action) add_deployment_name_option(action) add_location_option(action) end add_image_option(action) add_vm_name_option(action, false) add_storage_account_option(action) add_vm_user_option(action, false) add_password_option(action) add_puppet_master_ip_option(action) add_end_points_option(action) add_vm_size_option(action) add_ssh_port_option(action) add_winrm_http_port_option(action) add_winrm_https_port_option(action) add_certificate_file_option(action) add_private_key_file_option(action) add_winrm_transport_option(action) add_virtual_network_option(action) add_subnet_option(action) add_affinity_group_option(action) add_availability_set_options(action) end def add_vm_name_option(action, optional = true) action.option '--vm-name=' do summary 'The name of the virtual machine.' description 'The name of the virtual machine.' required unless optional before_action do |act, args, options| if options[:vm_name].empty? fail ArgumentError, 'VM Name is required.' end end end end def add_image_option(action) action.option '--image=' do summary 'The name of the disk image that will be used to create the virtual machine' description <<-EOT The name of the disk image that will be used to create the virtual machine EOT required before_action do |act, args, options| if options[:image].empty? fail ArgumentError, 'Source image name is required' else Puppet::VirtualMachine.initialize_env_variable(options) image_service = Azure::VirtualMachineImageManagementService.new images = image_service.list_virtual_machine_images os_image = images.select { |x| x.name == options[:image] }.first fail ArgumentError, 'Source image name is invalid' unless os_image @os_type = os_image.os_type end end end end def add_storage_account_option(action) action.option '--storage-account-name=' do summary 'The name of the storage account used with the cloud service.' description <<-EOT The name of the storage account used with the cloud service EOT end end def add_cloud_service_name_option(action, optional = true) action.option '--cloud-service-name=' do summary 'The name of the cloud service.' description 'The name of the cloud service.' required unless optional before_action do |act, args, options| if options[:cloud_service_name].empty? fail ArgumentError, 'Cloud service name is required.' end end end end def add_vm_user_option(action, optional = true) action.option '--vm-user=' do summary 'The VM user name.' description <<-EOT The VM user name. It mandatory incase of liunx VM installation. EOT required unless optional before_action do |act, args, options| if options[:vm_user].empty? fail ArgumentError, 'The VM user name is required.' end end end end def add_puppet_master_ip_option(action, optional = true) action.option '--puppet-master-ip=' do summary 'The puppet master ip address.' description <<-EOT The puppet master ip address. It mandatory incase of puppet node installation. EOT required unless optional before_action do |act, args, options| if options[:puppet_master_ip].empty? fail ArgumentError, 'The pupet master ip address is required.' end end end end def add_deployment_name_option(action, optional = true) action.option '--deployment-name=' do summary 'The vm instance deployment name.' description 'The vm instance deployment name.' required unless optional before_action do |act, args, options| if options[:deployment_name].empty? fail ArgumentError, 'Deployment name is required.' end end end end def add_password_option(action) action.option '--password=' do summary 'Authentication password for vm.' description 'Authentication password for vm.' required if @os_type == 'Windows' before_action do |act, args, options| if options[:password].empty? fail ArgumentError, 'The password is required.' end end end end def add_end_points_option(action) action.option '--tcp-endpoints=' do summary 'Tcp end points. ' description 'Add Tcp end points. example --tcp-endpoints="80,3889:3889"' end end def add_node_ipaddress_options(action) action.option '--node-ipaddress=' do summary 'Node Ip address. ' description 'The ip address where puppet need to install.' required before_action do |act, args, options| validate_bootstrap_options(options) if options[:node_ipaddress].empty? fail ArgumentError, 'The Node ip address is require.' end end end end def add_certificate_file_option(action) action.option '--certificate-file=' do summary 'Authentication using certificate instead of password.' description 'Authentication using certificate instead of password.' before_action do |act, args, options| file_path = options[:certificate_file] unless test 'f', file_path fail ArgumentError, "Could not find file '#{file_path}'" end unless test 'r', file_path fail ArgumentError, "Could not read from file '#{file_path}'" end end end end def add_private_key_file_option(action) action.option '--private-key-file=' do summary 'Authentication using certificate instead of password.' description 'Authentication using certificate instead of password.' before_action do |act, args, options| file_path = options[:private_key_file] unless test 'f', file_path fail ArgumentError, "Could not find file '#{file_path}'" end unless test 'r', file_path fail ArgumentError, "Could not read from file '#{file_path}'" end end end end def add_winrm_transport_option(action) action.option '--winrm-transport=' do summary 'Winrm authentication protocol default is http.' description <<-EOT Winrm authentication protocol. Valid choices are http or https or http,https. EOT before_action do |act, args, options| winrm_transport = options[:winrm_transport].split(',') winrm_transport_size = winrm_transport.select do |x| x.downcase == 'http' || x.downcase == 'https' end.size unless !winrm_transport.nil? && (winrm_transport_size > 0) fail ArgumentError, 'The winrm transport is not valid. Valid choices are http or https or http,https' end options[:winrm_transport] = winrm_transport end end end def add_ssh_port_option(action) action.option '--ssh-port=' do summary 'Port for ssh server.' description 'Port for ssh server.' end end def add_vm_size_option(action) action.option '--vm-size=' do role_sizes = %w(ExtraSmall Small Medium Large ExtraLarge A5 A6 A7 Basic_A0 Basic_A1 Basic_A2 Basic_A3 Basic_A4) summary "The instance size. valid choice are #{role_sizes.join(', ')}" description <<-EOT The instance size. valid choice are #{role_sizes.join(', ')} EOT before_action do |act, args, options| if options[:vm_size] && !role_sizes.include?(options[:vm_size]) fail ArgumentError, "The vm-size is not valid. Valid choice are #{role_sizes.join(', ')}" end end end end def add_virtual_network_option(action) action.option '--virtual-network-name=' do summary 'The virtual network name.' description 'The name of virtual network.' end end def add_subnet_option(action) action.option '--virtual-network-subnet=' do summary 'The virtual network subnet.' description 'The subnet of virtual network.' end end def add_affinity_group_option(action) action.option '--affinity-group-name=' do summary 'The affinity group name.' description 'The name of affinity group.' end end def add_ssh_user_option(action) action.option '--ssh-user=' do summary 'The VM user name.' description <<-EOT The ssh user name. It mandatory incase of liunx VM installation. EOT required if @os_type == 'Linux' before_action do |act, args, options| if options[:ssh_user].empty? fail ArgumentError, 'The ssh username is required.' end end end end def add_winrm_user_option(action) action.option '--winrm-user=' do summary 'The winrm user name.' description <<-EOT The winrm user name. It mandatory incase of Windows puppet agent installation. EOT required if @os_type == 'Windows' before_action do |act, args, options| if options[:winrm_user].empty? fail ArgumentError, 'The winrm username is required.' end end end end def add_winrm_port_option(action) action.option '--winrm-port=' do summary 'Port for winrm.' description 'Port for winrm.' end end def add_bootstrap_winrm_transport_option(action) action.option '--winrm-transport=' do summary 'Winrm authentication protocol. Valid choices are http or https' description <<-EOT Winrm authentication protocol. Valid choices are http or https. EOT before_action do |act, args, options| winrm_transport = options[:winrm_transport] unless ['http', 'https', nil].include?(winrm_transport) fail ArgumentError, 'The winrm transport is not valid. Valid choices are http or https' end end end end def add_agent_environment_options(action) action.option '--agent-environment=' do summary 'Pupppet agent environment. default is production' description 'Pupppet agent environment. default is production' end end def add_availability_set_options(action) action.option '--availability-set-name=' do summary 'Availability set name of virtual machine' description 'Availability set name of virtual machine' end end def add_disk_name_option(action) action.option '--disk-name=' do summary 'Specifies the name of the disk' description <<-EOT Specifies the name of the disk. Reqruied if import is set to true. EOT end end def add_disk_import_option(action) action.option '--import=' do summary 'if true, then allows to use an existing disk by disk name. if false, then create and attach new data disk.' description <<-EOT if true, then allows to use an existing disk by disk name. if false, then create and attach new data disk. EOT before_action do |act, args, options| options[:import] ||= 'false' unless ['true', 'false', nil].include?(options[:import]) fail ArgumentError, 'Disk import option is not valid. Valid choices are true or false' end if options[:disk_name].nil? && options[:import] == 'true' fail ArgumentError, 'Disk name is required when import is true.' end end end end def add_disk_size_option(action) action.option '--disk-size=' do summary 'Specifies the size of disk in GB' description <<-EOT Specifies the size of disk in GB EOT end end def add_disk_label_option(action) action.option '--disk-label=' do summary 'Specifies the label of the data disk.' description <<-EOT Specifies the description of the data disk. EOT end end def add_endpoint_name_option(action) action.option '--endpoint-name=' do summary 'Name of endpoint.' description 'Name of endpoint' required before_action do |act, args, options| if options[:endpoint_name].empty? fail ArgumentError, 'Endpoint name is required.' end end end end def add_public_port_option(action) action.option '--public-port=' do summary 'Specifies the external port to use for the endpoint.' description 'Specifies the external port to use for the endpoint.' required before_action do |act, args, options| if options[:public_port].empty? fail ArgumentError, 'Public port is required.' end end end end def add_local_port_option(action) action.option '--local-port=' do summary 'Specifies the internal port on which the Virtual Machine is listening.' description 'Specifies the internal port on which the Virtual Machine is listening.' required before_action do |act, args, options| if options[:local_port].empty? fail ArgumentError, 'Local port is required.' end end end end def add_protocol_option(action) action.option '--protocol=' do summary 'pecifies the transport protocol for the endpoint.' description <<-EOT Specifies the transport protocol for the endpoint. Possible values are: TCP, UDP. Default is TCP EOT before_action do |act, args, options| unless %w(tcp udp).include?(options[:protocol].downcase) fail 'Protocol is invalid. Allowed values are tcp,udp' end end end end def add_load_balancer_name_option(action) action.option '--load-balancer-name=' do summary 'Specifies a name for a load-balanced endpoint.' description 'Specifies a name for a load-balanced endpoint.' end end def add_direct_server_return_option(action) action.option '--direct-server-return=' do summary 'Specifies whether the endpoint uses Direct Server Return' description <<-EOT Specifies whether the endpoint uses Direct Server Return. Possible values are: true, false. Default is false. EOT before_action do |act, args, options| unless %w(true false).include?(options[:direct_server_return].downcase) fail 'direct_server_return is invalid. Allowed values are true,false' end end end end def add_load_balancer_port_option(action) action.option '--load-balancer-port=' do summary 'Specifies the internal port on which the Virtual Machine is listening.' description <<-EOT Specifies the internal port on which the Virtual Machine is listening. EOT end end def add_load_balancer_protocol_option(action) action.option '--load-balancer-protocol=' do summary 'Possible values are: HTTP TCP. Default is TCP.' description <<-EOT Specifies the protocol to use to inspect the availability status of the Virtual Machine. Possible values are: HTTP TCP. Default is TCP. EOT before_action do |act, args, options| lbp = options[:load_balancer_protocol].downcase unless %w(http tcp).include?(lbp) fail 'Load balancer protocol is invalid. Allowed values are http,tcp' end if lbp == 'http' && options[:load_balancer_path].nil? fail 'Load balancer path is required if load balancer protocol is http.' end end end end def add_load_balancer_path_option(action) action.option '--load-balancer-path=' do summary 'Specifies the relative path to determine the availability status' description <<-EOT Specifies the relative path to inspect to determine the availability status of the Virtual Machine. If Protocol is set to TCP, this value must be NULL. EOT end end def add_winrm_http_port_option(action) action.option '--winrm-http-port=' do summary 'Specifies the WinRM HTTP port number.' description 'Specifies the WinRM HTTP port number.' end end def add_winrm_https_port_option(action) action.option '--winrm-https-port=' do summary 'Specifies the WinRM HTTPS port number.' description 'Specifies the WinRM HTTPS port number.' end end end end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/affinity_group.rb
<filename>lib/puppet/affinity_group.rb #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/application_config' include Puppet::ApplicationConfig module Puppet::AffinityGroup class << self def views(name) File.join(File.dirname(__FILE__), 'face/azure_affinitygroup/views', name) end def add_create_options(action) add_default_options(action) add_affinity_group_name_option(action) add_location_option(action) add_description_option(action) add_label_option(action) end def add_delete_options(action) add_default_options(action) add_affinity_group_name_option(action) end def add_update_options(action) add_default_options(action) add_affinity_group_name_option(action) add_label_option(action) add_description_option(action) end def add_description_option(action) action.option '--description=' do summary 'Description of affinity group' description 'Description of affinity group.' end end def add_label_option(action) action.option '--label=' do summary 'Label of affinity group' description 'Label of affinity group.' required before_action do |act, args, options| fail ArgumentError, 'Label is required' if options[:label].empty? end end end end end
Bhaskers-Blu-Org2/azure-puppet
spec/unit/puppet/face/azure_vnet/list_spec.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 require 'spec_helper' describe Puppet::Face[:azure_vnet, :current] do let(:vnet_service) { Azure::VirtualNetworkManagementService } let(:vnet) do v = Azure::VirtualNetworkManagement::VirtualNetwork.new v.name = 'vnet-name' v.affinity_group = 'test' v.address_space = %w(172.16.0.0/12 10.0.0.0/8 192.168.0.0/24) v.dns_servers = [ { name: 'dns-1', ip_address: '8.8.8.8' }, { name: 'dns-2', ip_address: '192.168.127.12' } ] v.subnets = [ { name: 'Subnet-2', address_prefix: '10.0.0.0/8' }, { name: 'Subnet-4', address_prefix: '192.168.0.0/26' } ] v end before :each do mgmtcertfile = File.expand_path('spec/fixtures/management_certificate.pem') @options = { management_certificate: mgmtcertfile, management_endpoint: 'management.core.windows.net', azure_subscription_id: 'Subscription-id' } Azure.configure do |config| config.management_certificate = @options[:management_certificate] config.subscription_id = @options[:azure_subscription_id] end end describe 'option validation' do before :each do vnet_service.any_instance.stubs( :list_virtual_networks ).returns([vnet]) end describe 'valid options' do it 'should not raise any exception' do expect { subject.list(@options) }.to_not raise_error end it 'should print affinity groups details' do vnets = subject.list(@options) expect(vnets).to match(/#{"Server Name".fix(20)}: #{vnet.name}/) address_spaces = vnet.address_space.join(', ') expect(vnets).to match(/Address Space : #{address_spaces}/) expect(vnets).to match(/Subnet-2 10.0.0.0\/8/) expect(vnets).to match(/dns-2 192.168.127.12/) end end it_behaves_like 'validate authentication credential', :list end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_queue/create.rb
<gh_stars>1-10 #------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_queue, '1.0.0' do action :create do summary 'Creates a queue with a valid name.' arguments 'list' description <<-'EOT' The create action creates a queue under the given account. EOT Puppet::ServiceBus.add_create_queue_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_queue_service = Azure::QueueService.new azure_queue_service.create_queue(options[:queue_name]) end returns 'NONE' examples <<-'EOT' $ puppet azure_queue create --storage-account-name mystorageacc \ --storage-access-key '<KEY> --queue-name queuename EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/face/azure_queue/create_message.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- # encoding: UTF-8 Puppet::Face.define :azure_queue, '1.0.0' do action :create_message do summary 'Creates a message in the specified queue.' arguments 'list' description <<-'EOT' Creates a message in the specified queue. EOT Puppet::ServiceBus.add_create_message_options(self) when_invoked do |options| Puppet::ServiceBus.initialize_env_variable(options) azure_queue_service = Azure::QueueService.new azure_queue_service.create_queue(options[:queue_name]) azure_queue_service.create_message(options[:queue_name], options[:queue_message]) end returns 'NONE' examples <<-'EOT' $ puppet azure_queue create_message --storage-account-name mystorageacc \ --storage-access-key '<KEY> --queue-name queuename --queue-message 'Text Message' EOT end end
Bhaskers-Blu-Org2/azure-puppet
lib/puppet/application/azure_storage.rb
#------------------------------------------------------------------------- # Copyright (c) Microsoft Open Technologies, Inc. # All Rights Reserved. Licensed under the Apache 2.0 License. #-------------------------------------------------------------------------- require 'puppet/application/face_base' class Puppet::Application::AzureStorage < Puppet::Application::FaceBase end
ged/pluginfactory
lib/pluginfactory.rb
#!/usr/bin/env ruby -w require 'logger' ### An exception class for PluginFactory specific errors. class FactoryError < RuntimeError; end # This module contains the PluginFactory mixin. Including PluginFactory in your # class turns it into a factory for its derivatives, capable of searching for # and loading them by name. This is useful when you have an abstract base class # which defines an interface and basic functionality for a part of a larger # system, and a collection of subclasses which implement the interface for # different underlying functionality. # # An example of where this might be useful is in a program which talks to a # database. To avoid coupling it to a specific database, you use a Driver class # which encapsulates your program's interaction with the database behind a # useful interface. Now you can create a concrete implementation of the Driver # class for each kind of database you wish to talk to. If you make the base # Driver class a PluginFactory, too, you can add new drivers simply by dropping # them in a directory and using the Driver's <tt>create</tt> method to # instantiate them: # # == Creation Argument Variants # # The +create+ class method added to your class by PluginFactory searches for your module using # # == Synopsis # # in driver.rb: # # require "PluginFactory" # # class Driver # include PluginFactory # def self::derivative_dirs # ["drivers"] # end # end # # in drivers/mysql.rb: # # require 'driver' # # class MysqlDriver < Driver # ...implementation... # end # # in /usr/lib/ruby/1.8/PostgresDriver.rb: # # require 'driver' # # class PostgresDriver < Driver # ...implementation... # end # # elsewhere # # require 'driver' # # config[:driver_type] #=> "mysql" # driver = Driver.create( config[:driver_type] ) # driver.class #=> MysqlDriver # pgdriver = Driver.create( "PostGresDriver" ) # # == Authors # # * <NAME> <<EMAIL>> # * <NAME> <<EMAIL>> # # == License # # Copyright (c) 2008-2012 <NAME> and <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the author/s, nor the names of the project's # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # module PluginFactory # Library version VERSION = '1.0.7' ### Logging @default_logger = Logger.new( $stderr ) @default_logger.level = $DEBUG ? Logger::DEBUG : Logger::WARN @logger = @default_logger class << self # The logger that will be used when the logging subsystem is reset attr_accessor :default_logger # The logger that's currently in effect attr_accessor :logger alias_method :log, :logger alias_method :log=, :logger= end ### Deprecated: use the Logger object at #log to manipulate logging instead of this ### method. def self::logger_callback=( callback ) if callback.nil? self.logger.formatter = nil else self.logger.formatter = lambda {|lvl, _, _, msg| callback.call(lvl.downcase.to_sym, msg) '' } end end ### Reset the global logger object to the default def self::reset_logger self.logger = self.default_logger self.logger.level = Logger::WARN end ### Returns +true+ if the global logger has not been set to something other than ### the default one. def self::using_default_logger? return self.logger == self.default_logger end ### Inclusion callback -- extends the including class. This is here so you can ### either 'include' or 'extend'. def self::included( klass ) klass.extend( self ) end ### Add the @derivatives instance variable to including classes. def self::extend_object( obj ) obj.instance_variable_set( :@derivatives, {} ) super end ############################################################# ### M I X I N M E T H O D S ############################################################# ### Return the Hash of derivative classes, keyed by various versions of ### the class name. def derivatives ancestors.each do |klass| if klass.instance_variables.include?( :@derivatives ) || klass.instance_variables.include?( "@derivatives" ) return klass.instance_variable_get( :@derivatives ) end end end ### Returns the type name used when searching for a derivative. def factory_type base = nil self.ancestors.each do |klass| if klass.instance_variables.include?( :@derivatives ) || klass.instance_variables.include?( "@derivatives" ) base = klass break end end raise FactoryError, "Couldn't find factory base for #{self.name}" if base.nil? if base.name =~ /^.*::(.*)/ return $1 else return base.name end end alias_method :factoryType, :factory_type ### Inheritance callback -- Register subclasses in the derivatives hash ### so that ::create knows about them. def inherited( subclass ) keys = [ subclass ] # If it's not an anonymous class, make some keys out of variants of its name if subclass.name simple_name = subclass.name.sub( /#<Class:0x[[:xdigit:]]+>::/i, '' ) keys << simple_name << simple_name.downcase # Handle class names like 'FooBar' for 'Bar' factories. PluginFactory.log.debug "Inherited %p for %p-type plugins" % [ subclass, self.factory_type ] if subclass.name.match( /(?:.*::)?(\w+)(?:#{self.factory_type})/i ) keys << Regexp.last_match[1].downcase else keys << subclass.name.sub( /.*::/, '' ).downcase end else PluginFactory.log.debug " no name-based variants for anonymous subclass %p" % [ subclass ] end keys.compact.uniq.each do |key| PluginFactory.log.info "Registering %s derivative of %s as %p" % [ subclass.name, self.name, key ] self.derivatives[ key ] = subclass end super end ### Returns an Array of registered derivatives def derivative_classes self.derivatives.values.uniq end alias_method :derivativeClasses, :derivative_classes ### Given the <tt>class_name</tt> of the class to instantiate, and other ### arguments bound for the constructor of the new object, this method ### loads the derivative class if it is not loaded already (raising a ### LoadError if an appropriately-named file cannot be found), and ### instantiates it with the given <tt>args</tt>. The <tt>class_name</tt> ### may be the the fully qualified name of the class, the class object ### itself, or the unique part of the class name. The following examples ### would all try to load and instantiate a class called "FooListener" ### if Listener included Factory ### obj = Listener.create( 'FooListener' ) ### obj = Listener.create( FooListener ) ### obj = Listener.create( 'Foo' ) def create( class_name, *args, &block ) subclass = get_subclass( class_name ) begin return subclass.new( *args, &block ) rescue => err nicetrace = err.backtrace.reject {|frame| /#{__FILE__}/ =~ frame} msg = "When creating '#{class_name}': " + err.message Kernel.raise( err, msg, nicetrace ) end end ### Given a <tt>class_name</tt> like that of the first argument to ### #create, attempt to load the corresponding class if it is not ### already loaded and return the class object. def get_subclass( class_name ) return self if ( self.name == class_name || class_name == '' ) if class_name.is_a?( Class ) return class_name if class_name <= self raise ArgumentError, "%s is not a descendent of %s" % [class_name, self] end class_name = class_name.to_s # If the derivatives hash doesn't already contain the class, try to load it unless self.derivatives.has_key?( class_name.downcase ) self.load_derivative( class_name ) subclass = self.derivatives[ class_name.downcase ] unless subclass.is_a?( Class ) raise FactoryError, "load_derivative(%s) added something other than a class "\ "to the registry for %s: %p" % [ class_name, self.name, subclass ] end end return self.derivatives[ class_name.downcase ] end alias_method :getSubclass, :get_subclass ### Calculates an appropriate filename for the derived class using the ### name of the base class and tries to load it via <tt>require</tt>. If ### the including class responds to a method named ### <tt>derivativeDirs</tt>, its return value (either a String, or an ### array of Strings) is added to the list of prefix directories to try ### when attempting to require a modules. Eg., if ### <tt>class.derivativeDirs</tt> returns <tt>['foo','bar']</tt> the ### require line is tried with both <tt>'foo/'</tt> and <tt>'bar/'</tt> ### prepended to it. def load_derivative( class_name ) PluginFactory.log.debug "Loading derivative #{class_name}" # Get the unique part of the derived class name and try to # load it from one of the derivative subdirs, if there are # any. mod_name = self.get_module_name( class_name ) result = self.require_derivative( mod_name ) # Check to see if the specified listener is now loaded. If it # is not, raise an error to that effect. unless self.derivatives[ class_name.downcase ] errmsg = "Require of '%s' succeeded, but didn't load a %s named '%s' for some reason." % [ result, self.factory_type, class_name.downcase, ] PluginFactory.log.error( errmsg ) raise FactoryError, errmsg, caller(3) end end alias_method :loadDerivative, :load_derivative ### Build and return the unique part of the given <tt>class_name</tt> ### either by stripping leading namespaces if the name already has the ### name of the factory type in it (eg., 'My::FooService' for Service, ### or by appending the factory type if it doesn't. def get_module_name( class_name ) if class_name =~ /\w+#{self.factory_type}/ mod_name = class_name.sub( /(?:.*::)?(\w+)(?:#{self.factory_type})/, "\\1" ) else mod_name = class_name end return mod_name end alias_method :getModuleName, :get_module_name ### If the factory responds to the #derivative_dirs method, call ### it and use the returned array as a list of directories to ### search for the module with the specified <tt>mod_name</tt>. def require_derivative( mod_name ) # See if we have a list of special subdirs that derivatives # live in if ( self.respond_to?(:derivative_dirs) ) subdirs = self.derivative_dirs elsif ( self.respond_to?(:derivativeDirs) ) subdirs = self.derivativeDirs # If not, just try requiring it from $LOAD_PATH else subdirs = [''] end subdirs = [ subdirs ] unless subdirs.is_a?( Array ) PluginFactory.log.debug "Subdirs are: %p" % [subdirs] fatals = [] tries = [] # Iterate over the subdirs until we successfully require a # module. subdirs.collect {|dir| dir.strip}.each do |subdir| self.make_require_path( mod_name, subdir ).each do |path| PluginFactory.log.debug "Trying #{path}..." tries << path # Try to require the module, saving errors and jumping # out of the catch block on success. begin require( path.untaint ) rescue LoadError => err PluginFactory.log.debug "No module at '%s', trying the next alternative: '%s'" % [ path, err.message ] rescue Exception => err fatals << err PluginFactory.log.error "Found '#{path}', but encountered an error: %s\n\t%s" % [ err.message, err.backtrace.join("\n\t") ] else PluginFactory.log.info "Loaded '#{path}' without error." return path end end end PluginFactory.log.debug "fatals = %p" % [ fatals ] # Re-raise is there was a file found, but it didn't load for # some reason. if fatals.empty? errmsg = "Couldn't find a %s named '%s': tried %p" % [ self.factory_type, mod_name, tries ] PluginFactory.log.error( errmsg ) raise FactoryError, errmsg else PluginFactory.log.debug "Re-raising first fatal error" Kernel.raise( fatals.first ) end end alias_method :requireDerivative, :require_derivative ### Make a list of permutations of the given +modname+ for the given ### +subdir+. Called on a +DataDriver+ class with the arguments 'Socket' and ### 'drivers', returns: ### ["drivers/socketdatadriver", "drivers/socketDataDriver", ### "drivers/SocketDataDriver", "drivers/socket", "drivers/Socket"] def make_require_path( modname, subdir ) path = [] myname = self.factory_type # Make permutations of the two parts path << modname path << modname.downcase path << modname + myname path << modname.downcase + myname path << modname.downcase + myname.downcase path << modname + '_' + myname path << modname.downcase + '_' + myname path << modname.downcase + '_' + myname.downcase # If a non-empty subdir was given, prepend it to all the items in the # path unless subdir.nil? or subdir.empty? path.collect! {|m| File.join(subdir, m)} end PluginFactory.log.debug "Path is: #{path.uniq.reverse.inspect}..." return path.uniq.reverse end alias_method :makeRequirePath, :make_require_path end # module Factory
ged/pluginfactory
spec/pluginfactory_spec.rb
<gh_stars>1-10 #!/usr/bin/env ruby BEGIN { require 'pathname' basedir = Pathname.new( __FILE__ ).dirname.parent libdir = basedir + "lib" $LOAD_PATH.unshift( basedir ) unless $LOAD_PATH.include?( basedir ) $LOAD_PATH.unshift( libdir ) unless $LOAD_PATH.include?( libdir ) } require 'rspec' require 'logger' require 'pluginfactory' require 'spec/lib/helpers' class Plugin extend PluginFactory def self::derivative_dirs [ 'plugins', 'plugins/private' ] end end class SubPlugin < Plugin; end class TestingPlugin < Plugin; end class BlackSheep < Plugin; end module Test class LoadablePlugin < Plugin; end end describe PluginFactory do before( :each ) do setup_logging( :fatal ) end after( :each ) do reset_logging() end it "calls its logging callback with the level and joined message if set" do level = nil; msg = nil PluginFactory.logger_callback = lambda {|l, m| level = l; msg = m } PluginFactory.logger.level = Logger::DEBUG PluginFactory.log.debug( 'message' ) level.should == :debug msg.should == 'message' end it "doesn't error when its log method is called if no logging callback is set" do PluginFactory.logger_callback = nil expect { PluginFactory.log.debug("msg") }.to_not raise_error() end context "-extended class" do it "knows about all of its derivatives" do Plugin.derivatives.keys.should include( 'sub' ) Plugin.derivatives.keys.should include( 'subplugin' ) Plugin.derivatives.keys.should include( 'SubPlugin' ) Plugin.derivatives.keys.should include( SubPlugin ) end it "returns derivatives directly if they're already loaded" do class AlreadyLoadedPlugin < Plugin; end Kernel.should_not_receive( :require ) Plugin.create( 'alreadyloaded' ).should be_an_instance_of( AlreadyLoadedPlugin ) Plugin.create( 'AlreadyLoaded' ).should be_an_instance_of( AlreadyLoadedPlugin ) Plugin.create( 'AlreadyLoadedPlugin' ).should be_an_instance_of( AlreadyLoadedPlugin ) Plugin.create( AlreadyLoadedPlugin ).should be_an_instance_of( AlreadyLoadedPlugin ) end it "filters errors that happen when creating an instance of derivatives so they " + "point to the right place" do class PugilistPlugin < Plugin def initialize raise "Oh noes -- an error!" end end exception = nil begin Plugin.create('pugilist') rescue ::RuntimeError => err exception = err else fail "Expected an exception to be raised." end exception.backtrace.first.should =~ /#{__FILE__}/ end it "will refuse to create an object other than one of its derivatives" do class Doppelgaenger; end expect { Plugin.create(Doppelgaenger) }.to raise_error( ArgumentError, /is not a descendent of/ ) end it "will load new plugins from the require path if they're not loaded yet" do loaded_class = nil Plugin.should_receive( :require ).with( 'plugins/dazzle_plugin' ).and_return do |*args| loaded_class = Class.new( Plugin ) # Simulate a named class, since we're not really requiring Plugin.derivatives['dazzle'] = loaded_class true end Plugin.create( 'dazzle' ).should be_an_instance_of( loaded_class ) end it "will output a sensible description of what it tried to load if requiring a " + "derivative fails" do # at least 6 -> 3 variants * 2 paths Plugin.should_receive( :require ). at_least(6).times. and_return {|path| raise LoadError, "path" } expect { Plugin.create('scintillating') }.to raise_error( FactoryError, /couldn't find a \S+ named \S+.*tried \[/i ) end it "will output a sensible description when a require succeeds, but it loads something unintended" do # at least 6 -> 3 variants * 2 paths Plugin.should_receive( :require ).and_return( true ) expect { Plugin.create('corruscating') }.to raise_error( FactoryError, /Require of '\S+' succeeded, but didn't load a Plugin/i ) end it "will re-raise the first exception raised when attempting to load a " + "derivative if none of the paths work" do # at least 6 -> 3 variants * 2 paths Plugin.should_receive( :require ).at_least(6).times.and_return {|path| raise ScriptError, "error while parsing #{path}" } expect { Plugin.create('portable') }.to raise_error( ScriptError, /error while parsing/ ) end end context "derivative of an extended class" do it "knows what type of factory loads it" do TestingPlugin.factory_type.should == 'Plugin' end it "raises a FactoryError if it can't figure out what type of factory loads it" do TestingPlugin.stub!( :ancestors ).and_return( [] ) expect { TestingPlugin.factory_type }.to raise_error( FactoryError, /couldn't find factory base/i ) end end context "derivative of an extended class that isn't named <Something>Plugin" do it "is still creatable via its full name" do Plugin.create( 'blacksheep' ).should be_an_instance_of( BlackSheep ) end end context "derivative of an extended class in another namespace" do it "is still creatable via its derivative name" do Plugin.create( 'loadable' ).should be_an_instance_of( Test::LoadablePlugin ) end end end
ged/pluginfactory
spec/lib/helpers.rb
#!/usr/bin/ruby # coding: utf-8 BEGIN { require 'pathname' basedir = Pathname.new( __FILE__ ).dirname.parent libdir = basedir + "lib" $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'rspec' require 'pluginfactory' ### RSpec helper functions. module PluginFactory # An alternate formatter for Logger instances that outputs +div+ HTML # fragments. # @private class HtmlLogFormatter < Logger::Formatter include ERB::Util # for html_escape() # The default HTML fragment that'll be used as the template for each log message. HTML_LOG_FORMAT = %q{ <div class="log-message %5$s"> <span class="log-time">%1$s.%2$06d</span> [ <span class="log-pid">%3$d</span> / <span class="log-tid">%4$s</span> ] <span class="log-level">%5$s</span> : <span class="log-name">%6$s</span> <span class="log-message-text">%7$s</span> </div> } ### Override the logging formats with ones that generate HTML fragments def initialize( logger, format=HTML_LOG_FORMAT ) # :notnew: @logger = logger @format = format super() end ###### public ###### # The HTML fragment that will be used as a format() string for the log attr_accessor :format ### Return a log message composed out of the arguments formatted using the ### formatter's format string def call( severity, time, progname, msg ) args = [ time.strftime( '%Y-%m-%d %H:%M:%S' ), # %1$s time.usec, # %2$d Process.pid, # %3$d Thread.current == Thread.main ? 'main' : Thread.object_id, # %4$s severity.downcase, # %5$s progname, # %6$s html_escape( msg ).gsub(/\n/, '<br />') # %7$s ] return self.format % args end end # class HtmlLogFormatter ### Spec helper functions module SpecHelpers class ArrayLogger ### Create a new ArrayLogger that will append content to +array+. def initialize( array ) @array = array end ### Write the specified +message+ to the array. def write( message ) @array << message end ### No-op -- this is here just so Logger doesn't complain def close; end end # class ArrayLogger unless defined?( LEVEL ) LEVEL = { :debug => Logger::DEBUG, :info => Logger::INFO, :warn => Logger::WARN, :error => Logger::ERROR, :fatal => Logger::FATAL, } end ############### module_function ############### ### Make an easily-comparable version vector out of +ver+ and return it. def vvec( ver ) return ver.split('.').collect {|char| char.to_i }.pack('N*') end ### Reset the logging subsystem to its default state. def reset_logging PluginFactory.reset_logger end ### Alter the output of the default log formatter to be pretty in SpecMate output def setup_logging( level=Logger::FATAL ) # Turn symbol-style level config into Logger's expected Fixnum level if LEVEL.key?( level ) level = LEVEL[ level ] end logger = Logger.new( $stderr ) PluginFactory.logger = logger PluginFactory.logger.level = level # Only do this when executing from a spec in TextMate if ENV['HTML_LOGGING'] || (ENV['TM_FILENAME'] && ENV['TM_FILENAME'] =~ /_spec\.rb/) Thread.current['logger-output'] = [] logdevice = ArrayLogger.new( Thread.current['logger-output'] ) PluginFactory.logger = Logger.new( logdevice ) # PluginFactory.logger.level = level PluginFactory.logger.formatter = PluginFactory::HtmlLogFormatter.new( logger ) end end end # module SpecHelpers end # module PluginFactory ### Mock with Rspec RSpec.configure do |c| c.mock_with :rspec c.include( PluginFactory::SpecHelpers ) end # vim: set nosta noet ts=4 sw=4:
ged/pluginfactory
experiments/logger_output.rb
<filename>experiments/logger_output.rb #!/usr/bin/env ruby # This is a short demo of the logging output generated by PluginFactory's logger_callback. BEGIN { require 'pathname' basedir = Pathname.new( __FILE__ ).dirname.parent libdir = basedir + 'lib' $LOAD_PATH.unshift( libdir.to_s ) unless $LOAD_PATH.include?( libdir.to_s ) } require 'pluginfactory' require 'logger' class DataDriver include PluginFactory @logger = Logger.new( $stderr ) @logger.level = Logger::DEBUG PluginFactory.logger_callback = lambda do |severity, msg| @logger.send(severity, msg) end end DataDriver.create( 'ringbuffer' ) # $ ruby experiments/logger_output.rb # D, [2008-03-19T18:16:29.861565 #70418] DEBUG -- : Loading derivative ringbuffer # D, [2008-03-19T18:16:29.862118 #70418] DEBUG -- : Subdirs are: [""] # D, [2008-03-19T18:16:29.862186 #70418] DEBUG -- : Path is: ["ringbufferdatadriver", "ringbufferDataDriver", "ringbuffer"]... # D, [2008-03-19T18:16:29.862235 #70418] DEBUG -- : Trying ringbufferdatadriver... # D, [2008-03-19T18:16:29.862383 #70418] DEBUG -- : No module at 'ringbufferdatadriver', trying the next alternative: 'no such file to load -- ringbufferdatadriver' # D, [2008-03-19T18:16:29.862422 #70418] DEBUG -- : Trying ringbufferDataDriver... # D, [2008-03-19T18:16:29.862546 #70418] DEBUG -- : No module at 'ringbufferDataDriver', trying the next alternative: 'no such file to load -- ringbufferDataDriver' # D, [2008-03-19T18:16:29.862581 #70418] DEBUG -- : Trying ringbuffer... # D, [2008-03-19T18:16:29.862707 #70418] DEBUG -- : No module at 'ringbuffer', trying the next alternative: 'no such file to load -- ringbuffer' # D, [2008-03-19T18:16:29.862746 #70418] DEBUG -- : fatals = [] # E, [2008-03-19T18:16:29.862793 #70418] ERROR -- : Couldn't find a DataDriver named 'ringbuffer': tried ["ringbufferdatadriver", "ringbufferDataDriver", "ringbuffer"] # ./lib/pluginfactory.rb:348:in `require_derivative': Couldn't find a DataDriver named 'ringbuffer': tried ["ringbufferdatadriver", "ringbufferDataDriver", "ringbuffer"] (FactoryError) # from ./lib/pluginfactory.rb:252:in `load_derivative' # from ./lib/pluginfactory.rb:220:in `get_subclass' # from ./lib/pluginfactory.rb:194:in `create' # from experiments/logger_output.rb:27
jianyuan/wallgig-discourse-integration-plugin
config/routes.rb
<gh_stars>1-10 Wallgig::Engine.routes.draw do resources :users, only: [:show, :create, :update] do member do get 'auth_token' end end end
jianyuan/wallgig-discourse-integration-plugin
app/controllers/wallgig/users_controller.rb
module Wallgig class UsersController < Wallgig::ApplicationController before_filter :set_user, only: [:show, :update, :auth_token] def show respond_with @user.to_json end def create @user = User.new(user_params) @user.save! respond_with @user.to_json end def update if @user.update(user_params) respond_with @user.to_json else respond_with @user.errors, status: :unprocessable_entity end end def auth_token @user.auth_token = SecureRandom.hex(16) @user.save! payload = { auth_token_param: Discourse.current_user_provider::TOKEN_COOKIE, auth_token_value: @user.auth_token } respond_with payload end private def set_user if params[:using_main_id].present? && params[:using_main_id] == 'true' @user = Oauth2UserInfo.find_by!(provider: 'wallgig', user_id: params[:id]).user else @user = User.find(params[:id]) end end def user_params params.require(:user).permit(:username, :email, :name) end end end
jianyuan/wallgig-discourse-integration-plugin
app/controllers/wallgig/application_controller.rb
module Wallgig class ApplicationController < ::ApplicationController skip_before_filter :verify_authenticity_token before_filter :exclude_user_root_in_json respond_to :json private def exclude_user_root_in_json User.include_root_in_json = false end end end
jianyuan/wallgig-discourse-integration-plugin
plugin.rb
# name: wallgig integration # about: user integration with main app # version: 0.1 # author: <NAME> module ::Wallgig class Engine < ::Rails::Engine engine_name 'wallgig' isolate_namespace Wallgig end end after_initialize do # # require File.expand_path('../api/users_controller', __FILE__) load File.expand_path('../lib/auth/wallgig_current_user_provider.rb', __FILE__) Discourse::Application.routes.prepend do mount ::Wallgig::Engine => '/api' end Discourse.current_user_provider = ::Auth::WallgigCurrentUserProvider end
jianyuan/wallgig-discourse-integration-plugin
lib/auth/wallgig_current_user_provider.rb
require_dependency 'auth/current_user_provider' class Auth::WallgigCurrentUserProvider < Auth::DefaultCurrentUserProvider TOKEN_COOKIE = ' _forums_auth_token' end
OpenSource-THG/logstash-filter-json
spec/filters/thgjson_spec.rb
# encoding: utf-8 require "logstash/devutils/rspec/spec_helper" require "insist" require "logstash/filters/json" require "logstash/timestamp" require 'rubygems' describe LogStash::Filters::ThgJson do describe "parse message into the event" do config <<-CONFIG filter { thgjson { # Parse message as JSON source => "message" } } CONFIG sample '{ "hello": "world", "list": [ 1, 2, 3 ], "hash": { "k": "v" } }' do insist { subject.get("hello") } == "world" insist { subject.get("list" ).to_a } == [1,2,3] # to_a for JRuby + JrJacksom which creates Java ArrayList insist { subject.get("hash") } == { "k" => "v" } end end describe "parse message into a target field" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" } } CONFIG sample '{ "hello": "world", "list": [ 1, 2, 3 ], "hash": { "k": "v" }, "badMap[123]": "stock[asfa] asfad[]"}' do insist { subject.get("data")["hello"] } == "world" insist { subject.get("data")["list" ].to_a } == [1,2,3] # to_a for JRuby + JrJacksom which creates Java ArrayList insist { subject.get("data")["hash"] } == { "k" => "v" } insist { subject.get("data")["badMap[123]"] } == "stock[asfa] asfad[]" end end describe "replace specific characters in the keys of items when processing a hash" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" key_replacements => { "[" => "(" "]" => ")" } } } CONFIG sample '[{ "hello": "world", "list": [ 1, 2, 3 ], "hash": { "k": "v" }, "badMap[123]": "IStillHaveThese[]", "worstMap[321]": {"small[1]": 123, "large[(2)]": "123[]"}}]' do insist { subject.get("data")[0]["hello"] } == "world" insist { subject.get("data")[0]["list" ].to_a } == [1,2,3] # to_a for JRuby + JrJacksom which creates Java ArrayList insist { subject.get("data")[0]["hash"] } == { "k" => "v" } insist { subject.get("data")[0]["badMap(123)"] } == "IStillHaveThese[]" insist { subject.get("data")[0]["worstMap(321)"] } == { "small(1)" => 123, "large((2))" => "123[]" } end end describe "replace specific characters in the keys of items when processing an array" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" key_replacements => { "[" => "(" "]" => ")" } } } CONFIG sample '{ "hello": "world", "list": [ 1, 2, 3 ], "hash": { "k": "v" }, "badMap[123]": "IStillHaveThese[]", "worstMap[321]": {"small[1]": 123, "large[(2)]": "123[]"}}' do insist { subject.get("data")["hello"] } == "world" insist { subject.get("data")["list" ].to_a } == [1,2,3] # to_a for JRuby + JrJacksom which creates Java ArrayList insist { subject.get("data")["hash"] } == { "k" => "v" } insist { subject.get("data")["badMap(123)"] } == "IStillHaveThese[]" insist { subject.get("data")["worstMap(321)"] } == { "small(1)" => 123, "large((2))" => "123[]" } end end describe "tag invalid json" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" tag_on_failure => ["_jsonparsefailure","_custom_failure_tag"] } } CONFIG sample "invalid json" do insist { subject.get("tags") }.include?("_jsonparsefailure") insist { subject.get("tags") }.include?("_custom_failure_tag") end end logstash_version = Gem::Version.create(LOGSTASH_VERSION) if (Gem::Requirement.create('>= 7.0').satisfied_by?(logstash_version) || (Gem::Requirement.create('~> 6.4').satisfied_by?(logstash_version) && LogStash::SETTINGS.get('config.field_reference.parser') == 'STRICT')) describe "unsupported field name using `target`" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" tag_on_failure => ["_jsonparsefailure","_custom_failure_tag"] } } CONFIG sample '{"okay":true, "un[sup]]ported": "foo", "another": "okay"}' do insist { subject.get("tags") }.include?("_jsonparsefailure") insist { subject.get("tags") }.include?("_custom_failure_tag") # it does not partially apply insist { subject.include?('[data][okay]') } == false insist { subject.include?('[data][another]') } == false end end describe "unsupported field name without target" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" tag_on_failure => ["_jsonparsefailure","_custom_failure_tag"] } } CONFIG sample '{"okay":true, "un[sup]]ported": "foo", "another": "okay"}' do insist { subject.get("tags") }.include?("_jsonparsefailure") insist { subject.get("tags") }.include?("_custom_failure_tag") # we can make no guarantees about partial application in this case. end end end describe "fixing @timestamp (#pull 733)" do config <<-CONFIG filter { thgjson { source => "message" } } CONFIG sample "{ \"@timestamp\": \"2013-10-19T00:14:32.996Z\" }" do insist { subject.get("@timestamp") }.is_a?(LogStash::Timestamp) insist { LogStash::Json.dump(subject.get("@timestamp")) } == "\"2013-10-19T00:14:32.996Z\"" end end describe "source == target" do config <<-CONFIG filter { thgjson { source => "example" target => "example" } } CONFIG sample({ "example" => "{ \"hello\": \"world\" }" }) do insist { subject.get("example") }.is_a?(Hash) insist { subject.get("example")["hello"] } == "world" end end describe "parse JSON array into target field" do config <<-CONFIG filter { thgjson { # Parse message as JSON, store the results in the 'data' field' source => "message" target => "data" } } CONFIG sample '[ { "k": "v" }, { "l": [1, 2, 3] } ]' do insist { subject.get("data")[0]["k"] } == "v" insist { subject.get("data")[1]["l"].to_a } == [1,2,3] # to_a for JRuby + JrJacksom which creates Java ArrayList end end context "using message field source" do subject(:filter) { LogStash::Filters::ThgJson.new(config) } let(:config) { {"source" => "message"} } let(:event) { LogStash::Event.new("message" => message) } before(:each) do filter.register filter.filter(event) end context "when json could not be parsed" do let(:message) { "random_message" } it "add the failure tag" do expect(event).to include("tags") end it "uses an array to store the tags" do expect(event.get('tags')).to be_a(Array) end it "add a json parser failure tag" do expect(event.get('tags')).to include("_jsonparsefailure") end context "there are two different errors added" do let(:event) { LogStash::Event.new("message" => message, "tags" => ["_anotherkinfoffailure"] ) } it "pile the different error messages" do expect(event.get('tags')).to include("_jsonparsefailure") end it "keep the former error messages on the list" do expect(event.get('tags')).to include("_anotherkinfoffailure") end end end context "the JSON is an ArrayList" do let(:message) { "[1, 2, 3]" } it "adds the failure tag" do expect(event.get('tags')).to include("_jsonparsefailure") end end context "json contains valid timestamp" do let(:message) { "{\"foo\":\"bar\", \"@timestamp\":\"2015-12-02T17:40:00.666Z\"}" } it "should set json timestamp" do expect(event.timestamp).to be_a(LogStash::Timestamp) expect(event.timestamp.to_s).to eq("2015-12-02T17:40:00.666Z") end end context "json contains invalid timestamp" do let(:message) { "{\"foo\":\"bar\", \"@timestamp\":\"foobar\"}" } it "should set timestamp to current time" do expect(event.timestamp).to be_a(LogStash::Timestamp) expect(event.get("tags")).to include(LogStash::Event::TIMESTAMP_FAILURE_TAG) expect(event.get(LogStash::Event::TIMESTAMP_FAILURE_FIELD)).to eq("foobar") end end end describe "parse mixture of json an non-json content (skip_on_invalid_json)" do subject(:filter) { LogStash::Filters::ThgJson.new(config) } let(:config) { {"source" => "message", "remove_field" => ["message"], "skip_on_invalid_json" => skip_on_invalid_json} } let(:event) { LogStash::Event.new("message" => message) } before(:each) do allow(filter.logger).to receive(:warn) filter.register filter.filter(event) end let(:message) { "this is not a json message" } context "with `skip_on_invalid_json` set to false" do let(:skip_on_invalid_json) { false } it "sends a warning to the logger" do expect(filter.logger).to have_received(:warn).with("Error parsing json", anything()) end it "keeps the source field" do expect(event.get("message")).to eq message end it "adds a parse-error tag" do expect(event.get("tags")).to eq ["_jsonparsefailure"] end end context "with `skip_on_invalid_json` set to true" do let(:skip_on_invalid_json) { true } it "sends no warning" do expect(filter.logger).to_not have_received(:warn) end it "keeps the source field" do expect(event.get("message")).to eq message end it "does not add a parse-error tag" do expect(event.get("tags")).to be_nil end end end end
icleversoft/marc_json
lib/marc_json/field_breaker.rb
<gh_stars>1-10 module MARCJson class FieldBreaker def initialize(marc) @marc = marc @files = [] end def execute!(path=nil) @marc.each do |record| record.each_part_in_djson do |tag, value| fname = path ? File.join(path, "#{tag}.json") : "#{tag}.json" unless File.exist?(fname) out = File.open(fname, 'a+') out.write("{\n") comma = "\n" else out = File.open(fname, 'a+') comma = ",\n" end value = value.is_a?(String) ? "\"#{value}\"" : value.to_json out.write("\"#{record.record_no}\":#{value}#{comma}") out.close @files << fname unless @files.include?(fname) end end @files.each do |file| File.open(file, 'a+') do |f| f.write('}') end end end end end
icleversoft/marc_json
lib/marc_json/reader.rb
<gh_stars>1-10 module MARCJson class Reader def initialize( json_data = {} ) @marc = MARC::Record.new to_hash( json_data ) build_record end def to_marc @marc end private def build_record unless @json.empty? @marc.leader = @json.delete("000") @json.each{|t, v| @marc.append_tag_value(t, v)} end end def to_hash( json_data ) @json = json_data.is_a?(Hash) ? json_data : JSON.parse( json_data ) rescue @json = {} end end end
icleversoft/marc_json
lib/marc_json.rb
<filename>lib/marc_json.rb require "marc_json/version" require 'marc_json/marc_ext' require 'marc_json/renderer' require 'marc_json/reader' require 'marc_json/field_breaker' require 'json'
icleversoft/marc_json
spec/support/assets.rb
<reponame>icleversoft/marc_json require 'spec_helper' require 'json' shared_context "shared_data" do let(:marc){MARC::Reader.new(File.join(File.dirname(__FILE__), 'data/1.mrc')).first} let(:json){JSON.parse(File.open(File.join(File.dirname(__FILE__), 'data/1.json')).read)} end
icleversoft/marc_json
spec/spec_helper.rb
<reponame>icleversoft/marc_json $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'marc_json' require_relative 'support/assets.rb'
icleversoft/marc_json
spec/marc_json_spec.rb
<reponame>icleversoft/marc_json require 'spec_helper' require 'marc' describe MARCJson do include_context 'shared_data' it 'has a version number' do expect(MARCJson::VERSION).not_to be nil end it 'converts a marc record to hash' do m = MARCJson::Renderer.new( marc ) expect(m.to_hash).to eq(json) end context '#to_json' do let(:rec){ MARCJson::Renderer.new( marc ) } it 'is a string' do expect(rec.to_json).to be_an String end it 'is a valid json' do expect(JSON.parse(rec.to_json)).to be_an Hash end it 'contains the valid content' do expect(JSON.parse(rec.to_json)).to eq( json ) end end it 'converts a hash back to marc record' do m = MARCJson::Reader.new( json ) expect(m.to_marc).to eq marc end it 'converts a json string to marc record' do m = MARCJson::Reader.new( json.to_json ) expect(m.to_marc).to eq marc end it 'returns an empty marc record when json is invalid' do m = MARCJson::Reader.new( "blalbdx" ) expect(m.to_marc).to eq MARC::Record.new end end
icleversoft/marc_json
lib/marc_json/marc_ext.rb
<reponame>icleversoft/marc_json require 'marc' module MARCJson class MARC::DataField def to_fjson [indicators_as_string].concat(subfields_as_arrays) end def indicators_as_string [indicator1, indicator2].join end def subfields_as_arrays subfields.map{|s| s.to_fjson}.delete_if{|i| i.nil?} end def subfield_hashes ->(subfield){ { subfield.code.to_s => subfield.value } } end def to_djson { ind: indicators_as_string, count: subfields_stats, subfields: subfields.map(&subfield_hashes) } end def subfields_stats ret_val = {} subfields.each do |subfield| k = ret_val[subfield.code] || 0 ret_val[subfield.code] = k + 1 end ret_val end class << self def from_tag_array(tag, arr) indicators = arr.delete_at( 0 ) MARC::DataField.new( tag, indicators[0], indicators[1], *arr ) end end end class MARC::Subfield def to_fjson stripped_value.empty? ? nil : [code.to_s, stripped_value] end def stripped_value value.strip end end class MARC::Record def each_part_in_djson yield 'LDR', leader tags.each do |tag| yield tag, to_djson(tag) end end def to_djson(tag) (self[tag] ? djson_for_field(self[tag]) : {}) end def append_tag_value( tag, value ) if value.is_a? String append( controlfield_from_pair( tag, value ) ) else value.each do |v| append( datafield_from_pair(tag, v) ) end end end def controlfields fields.select{ |field| field.is_a?(MARC::ControlField) } end def grouped_datafields fields.select{ |field| field.is_a?(MARC::DataField) }.group_by(&:tag) end def record_no (self['001'] ? self['001'].value : Time.current.to_i).to_s end private def djson_for_field(field) field.is_a?(MARC::ControlField) ? field.value : djson_for_datafield(field) end def djson_for_datafield(field) dfields = grouped_datafields[field.tag] { count: dfields.size, fields: dfields.collect{ |field| field.to_djson } } end def controlfield_from_pair( tag, value ) MARC::ControlField.new( tag, value ) end def datafield_from_pair( tag, value ) MARC::DataField.from_tag_array(tag, value) end end end
icleversoft/marc_json
spec/field_breaker_spec.rb
<reponame>icleversoft/marc_json require 'spec_helper' describe 'FieldBreaker' do let(:marc) { MARC::Reader.new(File.join(File.dirname(__FILE__), 'support/data/1.mrc')) } it 'breaks a record to fields in json files' do MARCJson::FieldBreaker.new(marc).execute! end end
icleversoft/marc_json
lib/marc_json/renderer.rb
module MARCJson class Renderer include MARC def initialize( marc ) throw ArgumentError.new("Record should be a MARC::Record instance") unless marc.is_a? MARC::Record @data = {} @data["000"] = marc.leader process_fields( marc.fields ) end def to_hash @data end def to_json @data.to_json end private def process_fields( fields ) fields.each(&field_processor) end def field_processor ->(field){field.is_a?(ControlField) ? controlfield( field ) : datafield( field )} end def controlfield( field ) @data[field.tag] = field.value end def datafield( field ) @data[field.tag] ||= [] @data[field.tag] << field.to_fjson end end end
icleversoft/marc_json
spec/marc_ext_spec.rb
require 'spec_helper' describe 'marc_ext' do include_context 'shared_data' context 'subfield' do it 'returns an array' do subfield = MARC::Subfield.new('a', 'value') expect(subfield.to_fjson).to eq ['a', 'value'] end it 'returns nil if value is empty' do subfield = MARC::Subfield.new('a', ' ') expect(subfield.to_fjson).to eq nil end end context 'datafield' do let(:datafield){MARC::DataField.new('100', '1', '2', ['a', 'Subfield a'], ['b', 'Subfield b'])} it "returns indicators as string" do expect(datafield.indicators_as_string).to eq '12' end it "returns subfields in array" do expect(datafield.subfields_as_arrays).to eq [['a', 'Subfield a'], ['b', 'Subfield b']] end it "does not contain any subfields" do datafield1 = MARC::DataField.new('100', '1', '2', ['a', 'Subfield a'], ['b', ' ']) expect(datafield1.subfields_as_arrays).to eq [['a', 'Subfield a']] end it "returns a json" do expect(datafield.to_fjson).to eq ['12', ['a', 'Subfield a'], ['b', 'Subfield b']] end end describe 'support functions' do it 'lists all tags of record' do expect(marc.tags).to match_array %w(001 005 100 101 200 210 215 606 701 712 801 911) end context 'controlfields' do let(:subject) { marc.controlfields } it 'is an Array' do expect(subject).to be_an Array end it 'contains only controlfields' do expect(subject.size).to eq 2 expect(subject[0].tag).to eq '001' expect(subject[1].tag).to eq '005' end end context 'datafields' do let(:subject) { marc.grouped_datafields } it 'is an Hash' do expect(subject).to be_an Hash end it 'is grouped by field tag' do expect(subject.keys).to match_array %w(100 101 200 210 215 606 701 712 801 911) expect(subject['701'].size).to eq 2 end end context 'djson' do context 'datafield' do it 'returns the right json' do k = { :count => 1, :fields => [ { ind: ' ', count: { 'a' => 1}, subfields: [{ 'a' => '19991022d |||y0Grey50 ba'}]}]} expect(marc.to_djson('100')).to eq k end end end end end
iBolom/TestPodFramework
TestPodFramework.podspec
Pod::Spec.new do |s| s.platform = :ios s.name = 'TestPodFramework' s.version = '1.0.1' s.summary = 'TestPodFramework' s.homepage = 'https://github.com/iBolom/TestPodFramework.git' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/iBolom/TestPodFramework.git', :tag => s.version.to_s } s.ios.deployment_target = '10.0' s.source_files = 'TestPodFramework/**/*{.h, .m}' s.static_framework = false s.frameworks = 'UIKit', 'Foundation' s.module_name = 'TestPodFramework' s.xcconfig = { "OTHER_LINK_FLAG" => '$(inherited) -ObjC'} end
ofri-switzerland/auto_complete
auto_complete.gemspec
<reponame>ofri-switzerland/auto_complete # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "auto_complete" s.version = "0.0.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["<NAME>"] s.date = "2012-01-30" s.description = "Rails' auto_complete plugin (for Prototype) as a gem" s.email = "<EMAIL>" s.extra_rdoc_files = [ "README" ] s.files = [ "Gemfile", "README", "Rakefile", "VERSION", "auto_complete.gemspec", "init.rb", "lib/auto_complete.rb", "lib/auto_complete_macros_helper.rb", "test/auto_complete_test.rb", "test/test_helper.rb" ] s.homepage = "https://github.com/Agiley/auto_complete" s.require_paths = ["lib"] s.rubygems_version = "1.8.10" s.summary = "Rails' auto_complete plugin (for Prototype) as a gem" if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<test-unit>, ["~> 2.4.5"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) else s.add_dependency(%q<test-unit>, ["~> 2.4.5"]) s.add_dependency(%q<jeweler>, [">= 0"]) end else s.add_dependency(%q<test-unit>, ["~> 2.4.5"]) s.add_dependency(%q<jeweler>, [">= 0"]) end end
ofri-switzerland/auto_complete
test/test_helper.rb
$LOAD_PATH << "." unless $LOAD_PATH.include?(".") begin require "rubygems" require "bundler" if Gem::Version.new(Bundler::VERSION) <= Gem::Version.new("0.9.5") raise RuntimeError, "Your bundler version is too old." + "Run `gem install bundler` to upgrade." end # Set up load paths for all bundled gems Bundler.setup rescue Bundler::GemNotFound raise RuntimeError, "Bundler couldn't find some gems." + "Did you run \`bundle install\`?" end Bundler.require require "rails" require "test/unit" require File.expand_path('../../lib/auto_complete', __FILE__)
ofri-switzerland/auto_complete
init.rb
require 'auto_complete' require 'auto_complete_macros_helper'
azanar/converge
test/unit/converge/db/table/merger_test.rb
<filename>test/unit/converge/db/table/merger_test.rb<gh_stars>0 require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/merger' class Converge::DB::Table::MergerTest < Test::Unit::TestCase setup do @connection = mock end test '#merger' do mock_date_range = mock mock_target_table = mock mock_staging_table = mock mock_conn_staging_table = mock mock_conn_target_table = mock mock_conn_target_table.expects(:update).with(mock_conn_staging_table) mock_conn_target_table.expects(:insert).with(mock_conn_staging_table) mock_conn_target_table.expects(:finalize) @connection.expects(:table).with(mock_staging_table).returns(mock_conn_staging_table) @connection.expects(:table).with(mock_target_table).returns(mock_conn_target_table) merger = Converge::DB::Table::Merger.new(mock_staging_table, @connection) merger.merge(mock_target_table) end end
azanar/converge
lib/converge.rb
require 'logger' require "hydrogen" require "converge/db" require "converge/model" require "converge/version" module Converge module_function def logger return @logger if @logger @logger = Logger.new(STDOUT) @logger.formatter = proc { |severity, datetime, progname, msg| "[#{datetime}, #{severity}] #{msg}\n" } @logger end def logger=(logger) @logger = logger end def env @_env ||= ActiveSupport::StringInquirer.new(ENV["QUASAR_ENV"] || ENV["RAILS_ENV"] || "development") end def env=(environment) @_env = ActiveSupport::StringInquirer.new(environment) end end
azanar/converge
lib/converge/db/table/partitioner/bookend.rb
<gh_stars>0 require 'converge/db/table/partitioner' module Converge module DB class Table module Partitioner class Bookend include Partitioner def initialize(source) @source = source end def matches? true end def partition_for(dest) @source end end end end end end
azanar/converge
lib/converge/db/table/loader.rb
<gh_stars>0 module Converge module DB class Table class Loader def initialize(table, conn) @table = table @conn = conn @truncated = false #assume we aren't truncated. end def load(object_collection) @table.truncate @table.copy(object_collection) @truncated = false end def finalize unless @truncated @table.truncate @truncated = true end end end end end end
azanar/converge
lib/converge/db/table.rb
require "converge/db/connection" require "converge/db/table/target" require "converge/db/table/staging"
azanar/converge
lib/converge/db/table/target.rb
require 'converge/db/table/base' module Converge module DB class Table class Target include Converge::DB::Table::Base def name @model.name end end end end end
azanar/converge
test/unit/converge/db/table/base_test.rb
<filename>test/unit/converge/db/table/base_test.rb require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/target' class Converge::DB::Table::BaseTest < Test::Unit::TestCase setup do @mock_model = mock @base = Class.new do include Converge::DB::Table::Base end @table = @base.new(@mock_model) end test '#name' do mock_columns = mock @mock_model.expects(:columns).returns(mock_columns) res = @table.columns assert_equal res, mock_columns end end
azanar/converge
lib/converge/db.rb
<gh_stars>0 require "converge/db/table" module Converge module DB end end
azanar/converge
test/unit/converge/db/table/target_test.rb
require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/target' class Converge::DB::Table::TargetTest < Test::Unit::TestCase setup do @mock_model = mock @target = Converge::DB::Table::Target.new(@mock_model) end end
azanar/converge
lib/converge/db/table/staging.rb
<reponame>azanar/converge require 'converge/db/table/base' require 'converge/db/table/loader' require 'converge/db/table/merger' module Converge module DB class Table class Staging include Converge::DB::Table::Base def name "#{@model.name}_staging" end def merger(connection) Merger.new(self, connection) end end end end end
azanar/converge
lib/converge/db/connection/table.rb
<filename>lib/converge/db/connection/table.rb module Converge module DB class Connection class Table def initialize(conn, table, opts = {}) @conn = conn @table = table @stale = false end def name @table.name end def columns @table.columns end def key @table.key end def update(table) conn_table.update(table) @stale = true end def insert(table) conn_table.insert(table) @stale = true end def copy(object_collection) conn_table.copy(object_collection) @stale = true end def truncate conn_table.truncate end def finalize if @stale conn_table.finalize @stale = false else Converge.logger.warn "Called finalize on a finalized table" end end private def conn_table @conn.table(self) end end end end end
azanar/converge
test/integration/mock/table.rb
module Converge module Mock class Table def initialize(conn, dest) @conn = conn @dest = dest end def copy(objects) @conn.run_command(cmd: "copy", objects: objects) end def update(table) @conn.run_command(cmd: "update", source: table.name, destination: @dest.name, columns: table.columns) end def insert(table) @conn.run_command(cmd: "insert", source: table.name, destination: @dest.name, columns: table.columns) end def finalize @conn.run_command(cmd: "finalize") end end end end
azanar/converge
lib/converge/db/table/merger.rb
module Converge module DB class Table class Merger def initialize(source, conn) @conn = conn @conn_source = @conn.table(source) end def merge(destination) conn_destination = @conn.table(destination) conn_destination.update(@conn_source) conn_destination.insert(@conn_source) conn_destination.finalize end end end end end
azanar/converge
test/unit/converge/db/table/loader_test.rb
<gh_stars>0 require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/loader' class Converge::DB::Table::LoaderTest < Test::Unit::TestCase setup do @test_host = "redshift-test.sjc.carrel.org" @test_table = "mock_table" @test_staging_table = "#{@test_table}_staging" @mock_connection = mock @mock_table = mock #@mock_table.expects(:name).at_least_once.returns(@test_table) #@mock_table.expects(:columns).at_least_once.returns(%w{id mock_col_1 mock_col_2}) @loader = Converge::DB::Table::Loader.new(@mock_table, @mock_connection) end test '#load' do mock_object_collection = mock @mock_table.expects(:truncate) @mock_table.expects(:copy).with(mock_object_collection) @loader.load(mock_object_collection) end test '#finalize once' do state = states('loader_state').starts_as('unclean') mock_object_collection = mock @mock_table.expects(:truncate). when(state.is('unclean')). then(state.is('clean')) @mock_table.expects(:copy). when(state.is('clean')). with(mock_object_collection). then(state.is('copied')) @mock_table.expects(:truncate). when(state.is('copied')). then(state.is('done')) @loader.load(mock_object_collection) @loader.finalize end test '#finalize twice should only run once' do state = states('loader_state').starts_as('unclean') mock_object_collection = mock @mock_table.expects(:truncate). when(state.is('unclean')). then(state.is('clean')) @mock_table.expects(:copy). when(state.is('clean')). with(mock_object_collection). then(state.is('copied')) @mock_table.expects(:truncate). when(state.is('copied')). then(state.is('done')) @loader.load(mock_object_collection) @loader.finalize @loader.finalize end test '#finalize should be allowed if the table has not be touched yet' do @mock_table.expects(:truncate) @loader.finalize end end
azanar/converge
test/unit/converge/db/table/staging_test.rb
require File.expand_path('../../../../test_helper', __FILE__) require 'converge/db/table/staging' class Converge::DB::Table::StagingTest < Test::Unit::TestCase end
azanar/converge
test/integration/mock_adapter.rb
<reponame>azanar/converge<filename>test/integration/mock_adapter.rb $LOAD_PATH.unshift(File.expand_path('../', __FILE__)) require 'mock/connection' require 'mock/table'
azanar/converge
lib/converge/db/connection.rb
require 'converge/db/connection/table' module Converge module DB class Connection def initialize(conn) @conn = conn end def table(table) Connection::Table.new(@conn, table) end end end end
azanar/converge
test/integration/converge_test.rb
<filename>test/integration/converge_test.rb require File.expand_path('../test_helper', __FILE__) require File.expand_path('../db_test_helper', __FILE__) require File.expand_path('../mock_adapter', __FILE__) require 'converge' require 'active_support' require 'active_support/core_ext/integer/time' require 'active_support/core_ext/date/calculations' require 'active_support/core_ext/time/calculations' class Converge::IntegrationTest < Test::Unit::TestCase include Converge::DBTestHelper setup do @columns= %w{id mock_col_1 mock_col_2} @target_name = "mock_models" @staging_name = "mock_models_staging" @mock_socket = mock @mock_db = Converge::Mock::Connection.new(@mock_socket) @connection = Converge::DB::Connection.new(@mock_db) @mock_config = mock @mock_config.expects(:columns).at_least_once.returns(@columns) @mock_model = mock @mock_model.expects(:table_name).at_least_once.returns(@target_name) @model = Converge::Model.new(@mock_config, @mock_model) @mock_table_object_collection = mock @concrete_staging_table = mock @concrete_target_table = mock end test 'standard table load' do progress = states('progress').starts_as('start') staging_table = Converge::DB::Table::Staging.new(@model) conn_staging = @connection.table(staging_table) target_table = Converge::DB::Table::Target.new(@model) @mock_socket .expects(:run_command) .when(progress.is('start')) .with( :cmd => "copy", :objects => @mock_table_object_collection ).then(progress.is('loaded')) @mock_socket.expects(:run_command) .when(progress.is('loaded')) .with( :cmd => "update", :source => @staging_name, :destination => @target_name, :columns => @columns ).then(progress.is('updated')) @mock_socket.expects(:run_command) .when(progress.is('updated')) .with( :cmd => "insert", :source => @staging_name, :destination => @target_name, :columns => @columns ).then(progress.is('inserted')) @mock_socket.expects(:run_command) .when(progress.is('inserted')) .with( :cmd => "finalize" ).then(progress.is('finalized')) conn_staging.copy(@mock_table_object_collection) merger = Converge::DB::Table::Merger.new(staging_table, @connection) merger.merge(target_table) assert progress.is('finalized') end end
azanar/converge
lib/converge/model.rb
<gh_stars>0 module Converge class Model def initialize(config, model) @config = config @model = model end def name @model.table_name end def columns @config.columns || @model.columns end def remove_quotes? @config.remove_quotes? end end end
azanar/converge
test/integration/mock/connection.rb
<gh_stars>0 module Converge module Mock class Connection def initialize(conn) @conn = conn end def run_command(cmd) @conn.run_command(cmd) end def table(name) Table.new(self, name) end attr_reader :conn end end end
azanar/converge
lib/converge/db/table/base.rb
<reponame>azanar/converge<gh_stars>0 module Converge module DB class Table module Base def initialize(model) @model = model @stale = false end def columns @model.columns end def key @model.key end def loader(connection) Loader.new(self, connection) end end end end end
MaximShirokov/amorail
lib/amorail/entities/task_type.rb
<filename>lib/amorail/entities/task_type.rb require 'amorail/entities/leadable' module Amorail class TaskType < Amorail::Entity amo_names 'task_types' amo_field :name, :code, :id validates :name, presence: true def self.remote_url(name = '') '/private/api/v2/json/accounts/current/task_types' end def self.body_response(response) response.body['response']['account'] end end end
MaximShirokov/amorail
lib/amorail/entities/lead_status.rb
require 'amorail/entities/leadable' module Amorail class LeadStatus < Amorail::Entity amo_names 'leads_statuses' amo_field :name, :pipeline_id, :id validates :name, presence: true def self.remote_url(name = '') '/private/api/v2/json/accounts/current/leads_statuses' end def self.body_response(response) response.body['response']['account'] end end end
MaximShirokov/amorail
lib/amorail/entities/contact.rb
require 'amorail/entities/leadable' module Amorail # AmoCRM contact entity class Contact < Amorail::Entity include Leadable amo_names 'contacts' amo_field :name, :company_name, :linked_company_id, :created_user_id amo_property :email, enum: 'WORK' amo_property :phone, enum: 'MOB' amo_property :position validates :name, presence: true # Clear company cache def reload @company = nil super end def company return if linked_company_id.nil? @company ||= Amorail::Company.find(linked_company_id) end end end
MaximShirokov/amorail
lib/amorail/entities/pipeline.rb
<reponame>MaximShirokov/amorail module Amorail class Pipeline < Amorail::Entity amo_names 'pipelines' amo_field :id, :label, :sort, :name validates :name, presence: true def merge_params(attrs) attrs.last.each do |k, v| action = "#{k}=" next unless respond_to?(action) send(action, v) end self end end end
MaximShirokov/amorail
spec/user_spec.rb
<reponame>MaximShirokov/amorail require "spec_helper" describe Amorail::User do before { mock_api } describe "validations" do it { should validate_presence_of(:name) } end describe ".attributes" do subject { described_class.attributes } it_behaves_like 'entity_class' specify do is_expected.to include( :name, :login, :last_name, :id ) end end describe "#params" do let(:user) do described_class.new( name: 'Mars', login: '<EMAIL>', last_name: '<NAME>', id: 123 ) end subject { user.params } specify { is_expected.to include(:last_modified) } specify { is_expected.to include(name: 'Mars') } specify { is_expected.to include(login: '<EMAIL>') } specify { is_expected.to include(last_name: '<NAME>') } specify { is_expected.to include(id: 123) } end end
drnic/errbit
app/models/notification_service.rb
class NotificationService include Mongoid::Document include Rails.application.routes.url_helpers default_url_options[:host] = ActionMailer::Base.default_url_options[:host] field :room_id, :type => String field :api_token, :type => String field :subdomain, :type => String embedded_in :app, :inverse_of => :notification_service validate :check_params # Subclasses are responsible for overwriting this method. def check_params; true; end def notification_description(problem) "[#{ problem.environment }][#{ problem.where }] #{problem.message.to_s.truncate(100)}" end # Allows us to set the issue tracker class from a single form. def type; self._type; end def type=(t); self._type=t; end # Retrieve tracker label from either class or instance. Label = '' def self.label; self::Label; end def label; self.class.label; end end
daniel-sim/common
db/migrate/20190122124356_common_change_plan_name_to_shopify_plan_on_shops.rb
class CommonChangePlanNameToShopifyPlanOnShops < ActiveRecord::Migration[5.0] def change rename_column :shops, :plan_name, :shopify_plan end end
daniel-sim/common
config/routes.rb
<reponame>daniel-sim/common<gh_stars>0 require 'sidekiq/web' Rails.application.routes.draw do devise_for :users, only: :none # see https://github.com/plataformatec/devise/issues/4580 devise_for :admins, class_name: "PR::Common::Models::Admin", controllers: { sessions: "admins/sessions" } mount Sidekiq::Web => '/sidekiq' resources :sessions, only: :create resources :signups, only: :create resources :forgotten_password_requests, only: :create resources :passwords, only: [:create, :update] namespace :promo_codes do get 'check/:promo_code', action: :check end namespace "admin" do resources :promo_codes end post 'shops/callback' post 'webhooks', to: 'webhooks#receive' post 'webhooks/:topic', to: 'webhooks#receive' resources :charges, only: [:create] do collection do get :callback end end end
daniel-sim/common
spec/lib/pr/common/models/admin_spec.rb
require "rails_helper" describe PR::Common::Models::Admin do it { is_expected.to have_many(:promo_codes).with_foreign_key(:created_by_id) } end
daniel-sim/common
config/initializers/assets.rb
Rails.application.config.assets.precompile += %w[admin/style.css] Rails.application.config.assets.precompile += %w[sessions/script.js]