provide unit tests

This commit is contained in:
vernoncole 2017-09-18 21:21:07 -06:00
parent fb634b986d
commit c8a78c7ceb
2 changed files with 99 additions and 83 deletions

View File

@ -16,7 +16,7 @@ from collections import defaultdict
import salt.cache
import salt.utils
import salt.utils.stringutils
from salt.exceptions import CommandExecutionError, SaltCacheError
from salt.exceptions import CommandExecutionError, SaltCacheError, SaltInvocationError
import salt.ext.six as six
if six.PY3:
import ipaddress
@ -37,14 +37,12 @@ def __virtual__():
return __virtualname__
def _update_cache(name, vm_, opts=None):
def _update_cache(name, vm_):
vm_cache = salt.cache.Cache(__opts__, expire=13140000) # keep data for ten years
vm_cache.store('vagrant', name, vm_)
if opts:
vm_cache.store('vagrant_opts', name, opts)
def _get_cached_vm(name):
def get_vm_info(name):
vm_cache = salt.cache.Cache(__opts__)
try:
vm_ = vm_cache.fetch('vagrant', name)
@ -54,20 +52,10 @@ def _get_cached_vm(name):
try:
_ = vm_['machine']
except KeyError:
raise ValueError, 'No Vagrant machine defined for Salt-id {}'.format(name)
raise SaltInvocationError, 'No Vagrant machine defined for Salt-id {}'.format(name)
return vm_
def _get_cached_opts(name):
vm_cache = salt.cache.Cache(__opts__)
try:
opts = vm_cache.fetch('vagrant_opts', name)
except SaltCacheError:
log.warn('Trouble reading Salt opts cache for vagrant[%s]', name)
return None
return opts
def _erase_cache(name):
vm_cache = salt.cache.Cache(__opts__)
try:
@ -252,12 +240,12 @@ def vm_state(name='', cwd=None):
def init(name, # Salt_id for created VM
cwd, # path to find Vagrantfile
cwd=None, # path to find Vagrantfile
machine='', # name of machine in Vagrantfile
runas=None, # username who owns Vagrant box
start=True, # start the machine when initialized
start=False, # start the machine when initialized
deploy=None, # load Salt onto the virtual machine, default=True
vagrant_provider='', # vagrant provider engine name
vagrant_provider='', # vagrant provider (default=virtualbox)
vm={}, # a dictionary of VM configuration settings
):
'''
@ -272,8 +260,10 @@ def init(name, # Salt_id for created VM
'''
vm_ = vm.copy() # passed configuration data
vm_['name'] = name
vm_['cwd'] = cwd
# passed-in keyword arguments overwrite vm dictionary values
vm_['cwd'] = cwd or vm_.get('cwd')
if not vm_['cwd']:
raise SaltInvocationError('Path to Vagrantfile must be defined by \'cwd\' argument')
vm_['machine'] = machine or vm_.get('machine', machine)
vm_['runas'] = runas or vm_.get('runas', runas)
vm_['deploy'] = deploy if deploy is not None else vm_.get('deploy', True)
@ -318,7 +308,7 @@ def start(name, vm_={}):
def _start(name, vm_): # internal call name, because "start" is a keyword argument to vagrant.init
if not vm_:
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
try:
machine = vm_['machine']
@ -364,7 +354,7 @@ def stop(name):
salt <host> vagrant.stop <salt_id>
'''
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
machine = vm_['machine']
cmd = _runas_sudo(vm_, 'vagrant halt {}'.format(machine))
@ -387,7 +377,7 @@ def pause(name):
salt <host> vagrant.pause <salt_id>
'''
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
machine = vm_['machine']
cmd = _runas_sudo(vm_, 'vagrant suspend {}'.format(machine))
@ -410,7 +400,7 @@ def reboot(name):
salt <host> vagrant.reboot <salt_id>
'''
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
machine = vm_['machine']
cmd = _runas_sudo(vm_, 'vagrant reload {}'.format(machine))
@ -433,7 +423,7 @@ def destroy(name):
salt <host> vagrant.destroy <salt_id>
'''
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
machine = vm_['machine']
cmd = _runas_sudo(vm_, 'vagrant destroy -f {}'.format(machine))
@ -480,7 +470,7 @@ def get_ssh_config(name, network_mask='', get_private_key=False):
It will send an `ifconfig` command to the VM (using ssh to `ssh_host`:`ssh_port`) and scan the
result, returning the IP address of the first interface it can find which matches your mask.
'''
vm_ = _get_cached_vm(name)
vm_ = get_vm_info(name)
ssh_config = _vagrant_ssh_config(vm_)

View File

@ -2,21 +2,18 @@
# Import python libs
from __future__ import absolute_import
import re
# Import Salt Testing libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import skipIf, TestCase
from tests.support.mock import NO_MOCK, NO_MOCK_REASON, MagicMock, patch
from tests.support.mock import NO_MOCK, NO_MOCK_REASON
# Import salt libs
import salt.modules.vagrant as vagrant
import salt.modules.config as config
from salt._compat import ElementTree as ET
import salt.utils
import salt.exceptions
# Import third party libs
import yaml
from salt.ext import six
@ -25,65 +22,94 @@ class VagrantTestCase(TestCase, LoaderModuleMockMixin):
'''
Unit TestCase for the salt.modules.vagrant module.
'''
# def setup_loader_modules(self):
# return {vsphere: {'__virtual__': MagicMock(return_value='vsphere')}}
def setup_loader_modules(self):
loader_globals = {
'__salt__': {
'config.get': config.get,
'config.option': config.option,
vagrant_globals = {
'__opts__': {
'extension_modules': '',
'cachedir': '/tmp/salt-tests-tmpdir/cache',
'cache': 'localfs'
}
}
return {vagrant: loader_globals, config: loader_globals}
return {vagrant: vagrant_globals}
def test_boot_default_dev(self):
diskp = vagrant._disk_profile('default', 'kvm')
nicp = vagrant._nic_profile('default', 'kvm')
xml_data = vagrant._gen_xml(
'hello',
1,
512,
diskp,
nicp,
'kvm'
def test_vagrant_get_vm_info(self):
with self.assertRaises(salt.exceptions.SaltInvocationError):
vagrant.get_vm_info('thisNameDoesNotExist')
def test_vagrant_init_positional(self):
resp = vagrant.init(
'test1',
'/tmp/nowhere',
'onetest',
'nobody',
False,
True,
'french',
{'different': 'very'}
)
root = ET.fromstring(xml_data)
self.assertEqual(root.find('os/boot').attrib['dev'], 'hd')
def test_gen_xml_for_telnet_console(self):
diskp = vagrant._disk_profile('default', 'kvm')
nicp = vagrant._nic_profile('default', 'kvm')
xml_data = vagrant._gen_xml(
'hello',
1,
512,
diskp,
nicp,
'kvm',
serial_type='tcp',
console=True,
telnet_port=22223
self.assertIsInstance(resp, six.string_types)
resp = vagrant.get_vm_info('test1')
expected = dict(name='test1',
cwd='/tmp/nowhere',
machine='onetest',
runas='nobody',
deploy=True,
vagrant_provider='french',
different= 'very'
)
root = ET.fromstring(xml_data)
self.assertEqual(root.find('devices/serial').attrib['type'], 'tcp')
self.assertEqual(root.find('devices/console').attrib['type'], 'tcp')
self.assertEqual(root.find('devices/console/source').attrib['service'], '22223')
self.assertEqual(resp, expected)
def test_controller_for_kvm(self):
diskp = vagrant._disk_profile('default', 'kvm')
nicp = vagrant._nic_profile('default', 'kvm')
xml_data = vagrant._gen_xml(
'hello',
1,
512,
diskp,
nicp,
'kvm'
)
root = ET.fromstring(xml_data)
controllers = root.findall('.//devices/controller')
# There should be no controller
self.assertTrue(len(controllers) == 0)
def test_vagrant_init_dict(self):
testdict = dict(cwd='/tmp/anywhere',
machine='twotest',
runas='somebody',
deploy=True,
vagrant_provider='english')
vagrant.init('test2', vm=testdict)
resp = vagrant.get_vm_info('test2')
testdict['name'] = 'test2'
self.assertEqual(resp, testdict)
def test_vagrant_get_ssh_config_fails(self):
testdict = dict(cwd='/tmp/there',
machine='treetest',
runas='anybody',
deploy=False,
vagrant_provider='spansh')
vagrant.init('test3',
cwd='/tmp',
machine='threetest',
runas='him',
deploy=True,
vagrant_provider='polish',
vm=testdict)
resp = vagrant.get_vm_info('test3')
expected = dict(name='test3',
cwd='/tmp',
machine='threetest',
runas='him',
deploy=True,
vagrant_provider='polish')
self.assertEqual(resp, expected)
def test_vagrant_get_ssh_config_fails(self):
vagrant.init('test3', cwd='/tmp')
with self.assertRaises(salt.exceptions.CommandExecutionError):
vagrant.get_ssh_config('test3') # has not been started
def test_vagrant_destroy_removes_cached_entry(self):
vagrant.init('test3', cwd='/tmp')
# VM has a stored value
self.assertEqual(vagrant.get_vm_info('test3')['name'], 'test3')
# clean up (an error is expected -- machine never started)
self.assertFalse(vagrant.destroy('test3'))
# VM no longer exists
with self.assertRaises(salt.exceptions.SaltInvocationError):
vagrant.get_ssh_config('test3')