virtualbox.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # -*- coding: utf-8 -*-
  2. # Import Python libs
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import logging
  5. import os
  6. # Import Salt Testing libs
  7. import tests.integration.cloud.helpers
  8. from tests.support.case import ShellCase
  9. from tests.support.unit import TestCase, skipIf
  10. from tests.support.paths import FILES
  11. # Import Salt libs
  12. from salt.ext import six
  13. import salt.utils.json
  14. import salt.utils.virtualbox
  15. # Create the cloud instance name to be used throughout the tests
  16. INSTANCE_NAME = tests.integration.cloud.helpers.random_name()
  17. PROVIDER_NAME = "virtualbox"
  18. CONFIG_NAME = PROVIDER_NAME + "-config"
  19. PROFILE_NAME = PROVIDER_NAME + "-test"
  20. DEPLOY_PROFILE_NAME = PROVIDER_NAME + "-deploy-test"
  21. DRIVER_NAME = "virtualbox"
  22. BASE_BOX_NAME = "__temp_test_vm__"
  23. BOOTABLE_BASE_BOX_NAME = "SaltMiniBuntuTest"
  24. # Setup logging
  25. log = logging.getLogger(__name__)
  26. @skipIf(salt.utils.virtualbox.HAS_LIBS is False, 'virtualbox has to be installed')
  27. class VirtualboxTestCase(TestCase):
  28. def setUp(self):
  29. self.vbox = salt.utils.virtualbox.vb_get_box()
  30. def assertMachineExists(self, name, msg=None):
  31. try:
  32. self.vbox.findMachine(name)
  33. except Exception as e:
  34. if msg:
  35. self.fail(msg)
  36. else:
  37. self.fail(e.message)
  38. def assertMachineDoesNotExist(self, name):
  39. self.assertRaisesRegex(Exception, "Could not find a registered machine", self.vbox.findMachine, name)
  40. @skipIf(salt.utils.virtualbox.HAS_LIBS is False, 'salt-cloud requires virtualbox to be installed')
  41. class VirtualboxCloudTestCase(ShellCase):
  42. def run_cloud(self, arg_str, catch_stderr=False, timeout=None):
  43. """
  44. Execute salt-cloud with json output and try to interpret it
  45. @return:
  46. @rtype: dict
  47. """
  48. config_path = os.path.join(FILES, 'conf')
  49. arg_str = '--out=json -c {0} {1}'.format(config_path, arg_str)
  50. # arg_str = "{0} --log-level=error".format(arg_str)
  51. log.debug("running salt-cloud with %s", arg_str)
  52. output = self.run_script('salt-cloud', arg_str, catch_stderr, timeout=timeout)
  53. # Sometimes tuples are returned???
  54. if isinstance(output, tuple) and len(output) == 2:
  55. output = output[0]
  56. # Attempt to clean json output before fix of https://github.com/saltstack/salt/issues/27629
  57. valid_initial_chars = ['{', '[', '"']
  58. for line in output[:]:
  59. if len(line) == 0 or (line[0] not in valid_initial_chars):
  60. output.pop(0)
  61. else:
  62. break
  63. if len(output) is 0:
  64. return dict()
  65. else:
  66. return salt.utils.json.loads(''.join(output))
  67. def run_cloud_function(self, function, kw_function_args=None, **kwargs):
  68. """
  69. A helper to call `salt-cloud -f function provider`
  70. @param function:
  71. @type function:
  72. @param kw_function_args: Keyword arguments for the argument string in the commandline
  73. @type dict:
  74. @param kwargs: For the `run_cloud` function
  75. @type kwargs:
  76. @return:
  77. @rtype: dict
  78. """
  79. args = []
  80. # Args converted in the form of key1='value1' ... keyN='valueN'
  81. if kw_function_args:
  82. args = [
  83. "{0}='{1}'".format(key, value)
  84. for key, value in six.iteritems(kw_function_args)
  85. ]
  86. output = self.run_cloud("-f {0} {1} {2}".format(function, CONFIG_NAME, " ".join(args)), **kwargs)
  87. return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {})
  88. def run_cloud_action(self, action, instance_name, **kwargs):
  89. """
  90. A helper to call `salt-cloud -a action instance_name`
  91. @param action:
  92. @type action: str
  93. @param instance_name:
  94. @type instance_name: str
  95. @return:
  96. @rtype: dict
  97. """
  98. output = self.run_cloud("-a {0} {1} --assume-yes".format(action, instance_name), **kwargs)
  99. return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {})