conftest.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import pytest
  2. import salt.modules.config as config
  3. import salt.modules.virt as virt
  4. from salt._compat import ElementTree as ET
  5. from tests.support.mock import MagicMock
  6. class LibvirtMock(MagicMock): # pylint: disable=too-many-ancestors
  7. """
  8. Libvirt library mock
  9. """
  10. class virDomain(MagicMock):
  11. """
  12. virDomain mock
  13. """
  14. class libvirtError(Exception):
  15. """
  16. libvirtError mock
  17. """
  18. def __init__(self, msg):
  19. super().__init__(msg)
  20. self.msg = msg
  21. def get_error_message(self):
  22. return self.msg
  23. class MappedResultMock(MagicMock):
  24. """
  25. Mock class consistently return the same mock object based on the first argument.
  26. """
  27. _instances = {}
  28. def __init__(self):
  29. def mapped_results(*args, **kwargs):
  30. if args[0] not in self._instances.keys():
  31. raise virt.libvirt.libvirtError("Not found: {}".format(args[0]))
  32. return self._instances[args[0]]
  33. super().__init__(side_effect=mapped_results)
  34. def add(self, name):
  35. self._instances[name] = MagicMock()
  36. @pytest.fixture(autouse=True)
  37. def setup_loader():
  38. # Create libvirt mock and connection mock
  39. mock_libvirt = LibvirtMock()
  40. mock_conn = MagicMock()
  41. mock_conn.getStoragePoolCapabilities.return_value = "<storagepoolCapabilities/>"
  42. mock_libvirt.openAuth.return_value = mock_conn
  43. setup_loader_modules = {
  44. virt: {
  45. "libvirt": mock_libvirt,
  46. "__salt__": {"config.get": config.get, "config.option": config.option},
  47. },
  48. config: {},
  49. }
  50. with pytest.helpers.loader_mock(setup_loader_modules) as loader_mock:
  51. yield loader_mock
  52. @pytest.fixture
  53. def make_mock_vm():
  54. def _make_mock_vm(xml_def):
  55. mocked_conn = virt.libvirt.openAuth.return_value
  56. doc = ET.fromstring(xml_def)
  57. name = doc.find("name").text
  58. os_type = "hvm"
  59. os_type_node = doc.find("os/type")
  60. if os_type_node is not None:
  61. os_type = os_type_node.text
  62. mocked_conn.listDefinedDomains.return_value = [name]
  63. # Configure the mocked domain
  64. domain_mock = virt.libvirt.virDomain()
  65. if not isinstance(mocked_conn.lookupByName, MappedResultMock):
  66. mocked_conn.lookupByName = MappedResultMock()
  67. mocked_conn.lookupByName.add(name)
  68. domain_mock = mocked_conn.lookupByName(name)
  69. domain_mock.XMLDesc.return_value = xml_def
  70. domain_mock.OSType.return_value = os_type
  71. # Return state as shutdown
  72. domain_mock.info.return_value = [
  73. 4,
  74. 2048 * 1024,
  75. 1024 * 1024,
  76. 2,
  77. 1234,
  78. ]
  79. domain_mock.ID.return_value = 1
  80. domain_mock.name.return_value = name
  81. domain_mock.attachDevice.return_value = 0
  82. domain_mock.detachDevice.return_value = 0
  83. return domain_mock
  84. return _make_mock_vm
  85. @pytest.fixture
  86. def make_mock_storage_pool():
  87. def _make_mock_storage_pool(name, type, volumes):
  88. mocked_conn = virt.libvirt.openAuth.return_value
  89. # Append the pool name to the list of known mocked pools
  90. all_pools = mocked_conn.listStoragePools.return_value
  91. if not isinstance(all_pools, list):
  92. all_pools = []
  93. all_pools.append(name)
  94. mocked_conn.listStoragePools.return_value = all_pools
  95. # Ensure we have mapped results for the pools
  96. if not isinstance(mocked_conn.storagePoolLookupByName, MappedResultMock):
  97. mocked_conn.storagePoolLookupByName = MappedResultMock()
  98. # Configure the pool
  99. mocked_conn.storagePoolLookupByName.add(name)
  100. mocked_pool = mocked_conn.storagePoolLookupByName(name)
  101. source = ""
  102. if type == "disk":
  103. source = "<device path='/dev/{}'/>".format(name)
  104. pool_path = "/path/to/{}".format(name)
  105. mocked_pool.XMLDesc.return_value = """
  106. <pool type='{}'>
  107. <source>
  108. {}
  109. </source>
  110. <target>
  111. <path>{}</path>
  112. </target>
  113. </pool>
  114. """.format(
  115. type, source, pool_path
  116. )
  117. mocked_pool.name.return_value = name
  118. mocked_pool.info.return_value = [
  119. virt.libvirt.VIR_STORAGE_POOL_RUNNING,
  120. ]
  121. # Append the pool to the listAllStoragePools list
  122. all_pools_obj = mocked_conn.listAllStoragePools.return_value
  123. if not isinstance(all_pools_obj, list):
  124. all_pools_obj = []
  125. all_pools_obj.append(mocked_pool)
  126. mocked_conn.listAllStoragePools.return_value = all_pools_obj
  127. # Configure the volumes
  128. if not isinstance(mocked_pool.storageVolLookupByName, MappedResultMock):
  129. mocked_pool.storageVolLookupByName = MappedResultMock()
  130. mocked_pool.listVolumes.return_value = volumes
  131. all_volumes = []
  132. for volume in volumes:
  133. mocked_pool.storageVolLookupByName.add(volume)
  134. mocked_vol = mocked_pool.storageVolLookupByName(volume)
  135. vol_path = "{}/{}".format(pool_path, volume)
  136. mocked_vol.XMLDesc.return_value = """
  137. <volume>
  138. <target>
  139. <path>{}</path>
  140. </target>
  141. </volume>
  142. """.format(
  143. vol_path,
  144. )
  145. mocked_vol.path.return_value = vol_path
  146. mocked_vol.name.return_value = volume
  147. mocked_vol.info.return_value = [
  148. 0,
  149. 1234567,
  150. 12345,
  151. ]
  152. all_volumes.append(mocked_vol)
  153. # Set the listAllVolumes return_value
  154. mocked_pool.listAllVolumes.return_value = all_volumes
  155. return mocked_pool
  156. return _make_mock_storage_pool
  157. @pytest.fixture
  158. def make_capabilities():
  159. def _make_capabilities():
  160. mocked_conn = virt.libvirt.openAuth.return_value
  161. mocked_conn.getCapabilities.return_value = """
  162. <capabilities>
  163. <host>
  164. <uuid>44454c4c-3400-105a-8033-b3c04f4b344a</uuid>
  165. <cpu>
  166. <arch>x86_64</arch>
  167. <model>Nehalem</model>
  168. <vendor>Intel</vendor>
  169. <microcode version='25'/>
  170. <topology sockets='1' cores='4' threads='2'/>
  171. <feature name='vme'/>
  172. <feature name='ds'/>
  173. <feature name='acpi'/>
  174. <pages unit='KiB' size='4'/>
  175. <pages unit='KiB' size='2048'/>
  176. </cpu>
  177. <power_management>
  178. <suspend_mem/>
  179. <suspend_disk/>
  180. <suspend_hybrid/>
  181. </power_management>
  182. <migration_features>
  183. <live/>
  184. <uri_transports>
  185. <uri_transport>tcp</uri_transport>
  186. <uri_transport>rdma</uri_transport>
  187. </uri_transports>
  188. </migration_features>
  189. <topology>
  190. <cells num='1'>
  191. <cell id='0'>
  192. <memory unit='KiB'>12367120</memory>
  193. <pages unit='KiB' size='4'>3091780</pages>
  194. <pages unit='KiB' size='2048'>0</pages>
  195. <distances>
  196. <sibling id='0' value='10'/>
  197. </distances>
  198. <cpus num='8'>
  199. <cpu id='0' socket_id='0' core_id='0' siblings='0,4'/>
  200. <cpu id='1' socket_id='0' core_id='1' siblings='1,5'/>
  201. <cpu id='2' socket_id='0' core_id='2' siblings='2,6'/>
  202. <cpu id='3' socket_id='0' core_id='3' siblings='3,7'/>
  203. <cpu id='4' socket_id='0' core_id='0' siblings='0,4'/>
  204. <cpu id='5' socket_id='0' core_id='1' siblings='1,5'/>
  205. <cpu id='6' socket_id='0' core_id='2' siblings='2,6'/>
  206. <cpu id='7' socket_id='0' core_id='3' siblings='3,7'/>
  207. </cpus>
  208. </cell>
  209. </cells>
  210. </topology>
  211. <cache>
  212. <bank id='0' level='3' type='both' size='8' unit='MiB' cpus='0-7'/>
  213. </cache>
  214. <secmodel>
  215. <model>apparmor</model>
  216. <doi>0</doi>
  217. </secmodel>
  218. <secmodel>
  219. <model>dac</model>
  220. <doi>0</doi>
  221. <baselabel type='kvm'>+487:+486</baselabel>
  222. <baselabel type='qemu'>+487:+486</baselabel>
  223. </secmodel>
  224. </host>
  225. <guest>
  226. <os_type>hvm</os_type>
  227. <arch name='i686'>
  228. <wordsize>32</wordsize>
  229. <emulator>/usr/bin/qemu-system-i386</emulator>
  230. <machine maxCpus='255'>pc-i440fx-2.6</machine>
  231. <machine canonical='pc-i440fx-2.6' maxCpus='255'>pc</machine>
  232. <machine maxCpus='255'>pc-0.12</machine>
  233. <domain type='qemu'/>
  234. <domain type='kvm'>
  235. <emulator>/usr/bin/qemu-kvm</emulator>
  236. <machine maxCpus='255'>pc-i440fx-2.6</machine>
  237. <machine canonical='pc-i440fx-2.6' maxCpus='255'>pc</machine>
  238. <machine maxCpus='255'>pc-0.12</machine>
  239. </domain>
  240. </arch>
  241. <features>
  242. <cpuselection/>
  243. <deviceboot/>
  244. <disksnapshot default='on' toggle='no'/>
  245. <acpi default='on' toggle='yes'/>
  246. <apic default='on' toggle='no'/>
  247. <pae/>
  248. <nonpae/>
  249. </features>
  250. </guest>
  251. <guest>
  252. <os_type>hvm</os_type>
  253. <arch name='x86_64'>
  254. <wordsize>64</wordsize>
  255. <emulator>/usr/bin/qemu-system-x86_64</emulator>
  256. <machine maxCpus='255'>pc-i440fx-2.6</machine>
  257. <machine canonical='pc-i440fx-2.6' maxCpus='255'>pc</machine>
  258. <machine maxCpus='255'>pc-0.12</machine>
  259. <domain type='qemu'/>
  260. <domain type='kvm'>
  261. <emulator>/usr/bin/qemu-kvm</emulator>
  262. <machine maxCpus='255'>pc-i440fx-2.6</machine>
  263. <machine canonical='pc-i440fx-2.6' maxCpus='255'>pc</machine>
  264. <machine maxCpus='255'>pc-0.12</machine>
  265. </domain>
  266. </arch>
  267. <features>
  268. <cpuselection/>
  269. <deviceboot/>
  270. <disksnapshot default='on' toggle='no'/>
  271. <acpi default='on' toggle='yes'/>
  272. <apic default='on' toggle='no'/>
  273. </features>
  274. </guest>
  275. </capabilities>"""
  276. return _make_capabilities