test_gce.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # -*- coding: utf-8 -*-
  2. """
  3. :codeauthor: `Anthony Shaw <anthonyshaw@apache.org>`
  4. tests.unit.cloud.clouds.gce_test
  5. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  6. """
  7. # Import Python libs
  8. from __future__ import absolute_import, print_function, unicode_literals
  9. import collections
  10. # Import Salt Libs
  11. from salt.cloud.clouds import gce
  12. from salt.exceptions import SaltCloudSystemExit
  13. from salt.utils.versions import LooseVersion
  14. # Import Salt Testing Libs
  15. from tests.support.mixins import LoaderModuleMockMixin
  16. from tests.support.mock import MagicMock
  17. from tests.support.mock import __version__ as mock_version
  18. from tests.support.mock import patch
  19. from tests.support.unit import TestCase
  20. try:
  21. import libcloud.security
  22. HAS_LIBCLOUD = True
  23. except ImportError:
  24. HAS_LIBCLOUD = False
  25. VM_NAME = "kings_landing"
  26. DUMMY_TOKEN = {
  27. "refresh_token": None,
  28. "client_id": "dany123",
  29. "client_secret": "lalalalalalala",
  30. "grant_type": "refresh_token",
  31. }
  32. # Use certifi if installed
  33. try:
  34. if HAS_LIBCLOUD:
  35. # This work-around for Issue #32743 is no longer needed for libcloud >=
  36. # 1.4.0. However, older versions of libcloud must still be supported
  37. # with this work-around. This work-around can be removed when the
  38. # required minimum version of libcloud is 2.0.0 (See PR #40837 - which
  39. # is implemented in Salt 2018.3.0).
  40. if LooseVersion(libcloud.__version__) < LooseVersion("1.4.0"):
  41. import certifi
  42. libcloud.security.CA_CERTS_PATH.append(certifi.where())
  43. except ImportError:
  44. pass
  45. class DummyGCEConn(object):
  46. def __init__(self):
  47. self.create_node = MagicMock()
  48. def __getattr__(self, attr):
  49. if attr != "create_node":
  50. # Return back the first thing passed in (i.e. don't call out to get
  51. # the override value).
  52. return lambda *args, **kwargs: args[0]
  53. class GCETestCase(TestCase, LoaderModuleMockMixin):
  54. """
  55. Unit TestCase for salt.cloud.clouds.gce module.
  56. """
  57. def setup_loader_modules(self):
  58. return {
  59. gce: {
  60. "__active_provider_name__": "",
  61. "__utils__": {
  62. "cloud.fire_event": MagicMock(),
  63. "cloud.filter_event": MagicMock(),
  64. },
  65. "__opts__": {
  66. "sock_dir": True,
  67. "transport": True,
  68. "providers": {
  69. "my-google-cloud": {
  70. "gce": {
  71. "project": "daenerys-cloud",
  72. "service_account_email_address": "dany@targaryen.westeros.cloud",
  73. "service_account_private_key": "/home/dany/PRIVKEY.pem",
  74. "driver": "gce",
  75. "ssh_interface": "public_ips",
  76. }
  77. }
  78. },
  79. },
  80. }
  81. }
  82. def setUp(self):
  83. self.location = collections.namedtuple("Location", "name")("chicago")
  84. self.vm_ = {
  85. "name": "new",
  86. "driver": "gce",
  87. "profile": None,
  88. "size": 1234,
  89. "image": "myimage",
  90. "location": self.location,
  91. "ex_network": "mynetwork",
  92. "ex_subnetwork": "mysubnetwork",
  93. "ex_tags": "mytags",
  94. "ex_metadata": "metadata",
  95. }
  96. self.conn = DummyGCEConn()
  97. def tearDown(self):
  98. del self.vm_
  99. del self.conn
  100. def test_destroy_call(self):
  101. """
  102. Tests that a SaltCloudSystemExit is raised when trying to call destroy
  103. with --function or -f.
  104. """
  105. self.assertRaises(
  106. SaltCloudSystemExit, gce.destroy, vm_name=VM_NAME, call="function"
  107. )
  108. def test_fail_virtual_missing_deps(self):
  109. # Missing deps
  110. with patch("salt.config.check_driver_dependencies", return_value=False):
  111. v = gce.__virtual__()
  112. self.assertEqual(v, False)
  113. def test_fail_virtual_deps_missing_config(self):
  114. with patch("salt.config.check_driver_dependencies", return_value=True):
  115. with patch("salt.config.is_provider_configured", return_value=False):
  116. v = gce.__virtual__()
  117. self.assertEqual(v, False)
  118. def test_import(self):
  119. """
  120. Test that the module picks up installed deps
  121. """
  122. with patch("salt.config.check_driver_dependencies", return_value=True) as p:
  123. get_deps = gce.get_dependencies()
  124. self.assertEqual(get_deps, True)
  125. if LooseVersion(mock_version) >= LooseVersion("2.0.0"):
  126. self.assert_called_once(p)
  127. def test_provider_matches(self):
  128. """
  129. Test that the first configured instance of a gce driver is matched
  130. """
  131. p = gce.get_configured_provider()
  132. self.assertNotEqual(p, None)
  133. def test_request_instance_with_accelerator(self):
  134. """
  135. Test requesting an instance with GCE accelerators
  136. """
  137. self.vm_.update({"ex_accelerator_type": "foo", "ex_accelerator_count": 42})
  138. call_kwargs = {
  139. "ex_disk_type": "pd-standard",
  140. "ex_metadata": {"items": [{"value": None, "key": "salt-cloud-profile"}]},
  141. "ex_accelerator_count": 42,
  142. "name": "new",
  143. "ex_service_accounts": None,
  144. "external_ip": "ephemeral",
  145. "ex_accelerator_type": "foo",
  146. "ex_tags": None,
  147. "ex_disk_auto_delete": True,
  148. "ex_network": "default",
  149. "ex_disks_gce_struct": None,
  150. "ex_preemptible": False,
  151. "ex_can_ip_forward": False,
  152. "ex_on_host_maintenance": "TERMINATE",
  153. "location": self.location,
  154. "ex_subnetwork": None,
  155. "image": "myimage",
  156. "size": 1234,
  157. }
  158. with patch(
  159. "salt.cloud.clouds.gce.get_conn", MagicMock(return_value=self.conn)
  160. ), patch("salt.cloud.clouds.gce.show_instance", MagicMock()), patch(
  161. "salt.cloud.clouds.gce.LIBCLOUD_VERSION_INFO", (2, 3, 0)
  162. ):
  163. gce.request_instance(self.vm_)
  164. self.conn.create_node.assert_called_once_with(**call_kwargs)