371e4ef3662a40895f0b0e332638f8ce5bb311af
[yardstick.git] / yardstick / tests / unit / benchmark / contexts / standalone / test_model.py
1 # Copyright (c) 2016-2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import copy
16 import os
17 import uuid
18
19 import mock
20 import unittest
21 from xml.etree import ElementTree
22
23 from yardstick import ssh
24 from yardstick.benchmark.contexts.standalone import model
25 from yardstick.common import exceptions
26 from yardstick import constants
27 from yardstick.network_services import utils
28
29
30 XML_SAMPLE = """<?xml version="1.0"?>
31 <domain type="kvm">
32     <devices>
33     </devices>
34 </domain>
35 """
36
37 XML_SAMPLE_INTERFACE = """<?xml version="1.0"?>
38 <domain type="kvm">
39     <devices>
40         <interface>
41         </interface>
42     </devices>
43 </domain>
44 """
45
46
47 class ModelLibvirtTestCase(unittest.TestCase):
48
49     XML_STR = model.VM_TEMPLATE.format(
50         vm_name="vm_name",
51         random_uuid=uuid.uuid4(),
52         mac_addr="00:01:02:03:04:05",
53         memory=2048, vcpu=2, cpu=2,
54         numa_cpus=0 - 10,
55         socket=1, threads=1,
56         vm_image="/var/lib/libvirt/images/yardstick-nsb-image.img",
57         cpuset=2 - 10, cputune='')
58
59     def setUp(self):
60         self.pci_address_str = '0001:04:03.2'
61         self.pci_address = utils.PciAddress(self.pci_address_str)
62         self.mac = '00:00:00:00:00:01'
63         self._mock_ssh = mock.Mock()
64         self.mock_ssh = self._mock_ssh.start()
65         self.addCleanup(self._cleanup)
66
67     def _cleanup(self):
68         self._mock_ssh.stop()
69
70     # TODO: Remove mocking of yardstick.ssh.SSH (here and elsewhere)
71     # In this case, we are mocking a param to be passed into other methods
72     # It can be a generic Mock() with return values set for the right methods
73     def test_check_if_vm_exists_and_delete(self):
74         with mock.patch("yardstick.ssh.SSH") as ssh:
75             ssh_mock = mock.Mock(autospec=ssh.SSH)
76             ssh_mock.execute = mock.Mock(return_value=(0, "a", ""))
77             ssh.return_value = ssh_mock
78         # NOTE(ralonsoh): this test doesn't cover function execution.
79         model.Libvirt.check_if_vm_exists_and_delete('vm-0', ssh_mock)
80
81     def test_virsh_create_vm(self):
82         self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0))
83         model.Libvirt.virsh_create_vm(self.mock_ssh, 'vm-0')
84         self.mock_ssh.execute.assert_called_once_with('virsh create vm-0')
85
86     def test_virsh_create_vm_error(self):
87         self.mock_ssh.execute = mock.Mock(return_value=(1, 0, 'error_create'))
88         with self.assertRaises(exceptions.LibvirtCreateError) as exc:
89             model.Libvirt.virsh_create_vm(self.mock_ssh, 'vm-0')
90         self.assertEqual('Error creating the virtual machine. Error: '
91                          'error_create.', str(exc.exception))
92         self.mock_ssh.execute.assert_called_once_with('virsh create vm-0')
93
94     def test_virsh_destroy_vm(self):
95         self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0))
96         model.Libvirt.virsh_destroy_vm('vm-0', self.mock_ssh)
97         self.mock_ssh.execute.assert_called_once_with('virsh destroy vm-0')
98
99     @mock.patch.object(model, 'LOG')
100     def test_virsh_destroy_vm_error(self, mock_logger):
101         self.mock_ssh.execute = mock.Mock(return_value=(1, 0, 'error_destroy'))
102         mock_logger.warning = mock.Mock()
103         model.Libvirt.virsh_destroy_vm('vm-0', self.mock_ssh)
104         mock_logger.warning.assert_called_once_with(
105             'Error destroying VM %s. Error: %s', 'vm-0', 'error_destroy')
106         self.mock_ssh.execute.assert_called_once_with('virsh destroy vm-0')
107
108     def test_add_interface_address(self):
109         xml = ElementTree.ElementTree(
110             element=ElementTree.fromstring(XML_SAMPLE_INTERFACE))
111         interface = xml.find('devices').find('interface')
112         result = model.Libvirt._add_interface_address(interface, self.pci_address)
113         self.assertEqual('pci', result.get('type'))
114         self.assertEqual('0x{}'.format(self.pci_address.domain),
115                          result.get('domain'))
116         self.assertEqual('0x{}'.format(self.pci_address.bus),
117                          result.get('bus'))
118         self.assertEqual('0x{}'.format(self.pci_address.slot),
119                          result.get('slot'))
120         self.assertEqual('0x{}'.format(self.pci_address.function),
121                          result.get('function'))
122
123     def test_add_ovs_interfaces(self):
124         xml_input = copy.deepcopy(XML_SAMPLE)
125         xml_output = model.Libvirt.add_ovs_interface(
126             '/usr/local', 0, self.pci_address_str, self.mac, xml_input)
127
128         root = ElementTree.fromstring(xml_output)
129         et_out = ElementTree.ElementTree(element=root)
130         interface = et_out.find('devices').find('interface')
131         self.assertEqual('vhostuser', interface.get('type'))
132         mac = interface.find('mac')
133         self.assertEqual(self.mac, mac.get('address'))
134         source = interface.find('source')
135         self.assertEqual('unix', source.get('type'))
136         self.assertEqual('/usr/local/var/run/openvswitch/dpdkvhostuser0',
137                          source.get('path'))
138         self.assertEqual('client', source.get('mode'))
139         _model = interface.find('model')
140         self.assertEqual('virtio', _model.get('type'))
141         driver = interface.find('driver')
142         self.assertEqual('4', driver.get('queues'))
143         host = driver.find('host')
144         self.assertEqual('off', host.get('mrg_rxbuf'))
145         self.assertIsNotNone(interface.find('address'))
146
147     def test_add_sriov_interfaces(self):
148         xml_input = copy.deepcopy(XML_SAMPLE)
149         vm_pci = '0001:05:04.2'
150         xml_output = model.Libvirt.add_sriov_interfaces(
151             vm_pci, self.pci_address_str, self.mac, xml_input)
152         root = ElementTree.fromstring(xml_output)
153         et_out = ElementTree.ElementTree(element=root)
154         interface = et_out.find('devices').find('interface')
155         self.assertEqual('yes', interface.get('managed'))
156         self.assertEqual('hostdev', interface.get('type'))
157         mac = interface.find('mac')
158         self.assertEqual(self.mac, mac.get('address'))
159         source = interface.find('source')
160         source_address = source.find('address')
161         self.assertIsNotNone(source.find('address'))
162
163         self.assertEqual('pci', source_address.get('type'))
164         self.assertEqual('0x' + self.pci_address_str.split(':')[0],
165                          source_address.get('domain'))
166         self.assertEqual('0x' + self.pci_address_str.split(':')[1],
167                          source_address.get('bus'))
168         self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[0],
169                          source_address.get('slot'))
170         self.assertEqual('0x' + self.pci_address_str.split(':')[2].split('.')[1],
171                          source_address.get('function'))
172
173         interface_address = interface.find('address')
174         self.assertEqual('pci', interface_address.get('type'))
175         self.assertEqual('0x' + vm_pci.split(':')[0],
176                          interface_address.get('domain'))
177         self.assertEqual('0x' + vm_pci.split(':')[1],
178                          interface_address.get('bus'))
179         self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[0],
180                          interface_address.get('slot'))
181         self.assertEqual('0x' + vm_pci.split(':')[2].split('.')[1],
182                          interface_address.get('function'))
183
184     def test_add_cdrom(self):
185         xml_input = copy.deepcopy(XML_SAMPLE)
186         xml_output = model.Libvirt.add_cdrom('/var/lib/libvirt/images/data.img', xml_input)
187
188         root = ElementTree.fromstring(xml_output)
189         et_out = ElementTree.ElementTree(element=root)
190         disk = et_out.find('devices').find('disk')
191         self.assertEqual('file', disk.get('type'))
192         self.assertEqual('cdrom', disk.get('device'))
193         driver = disk.find('driver')
194         self.assertEqual('qemu', driver.get('name'))
195         self.assertEqual('raw', driver.get('type'))
196         source = disk.find('source')
197         self.assertEqual('/var/lib/libvirt/images/data.img', source.get('file'))
198         target = disk.find('target')
199         self.assertEqual('hdb', target.get('dev'))
200         self.assertIsNotNone(disk.find('readonly'))
201
202     def test_gen_cdrom_image(self):
203         self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0))
204         root = ElementTree.fromstring(self.XML_STR)
205         hostname = root.find('name').text
206         meta_data = "/tmp/meta-data"
207         user_data = "/tmp/user-data"
208         file_path = "/tmp/cdrom-0.img"
209         key_filename = "id_rsa"
210         pub_key_str = "KEY"
211         user = 'root'
212         user_config = ["    - name: {user_name}",
213                        "      ssh_authorized_keys:",
214                        "        - {pub_key_str}"]
215
216         user_conf = os.linesep.join(user_config).format(pub_key_str=pub_key_str, user_name=user)
217         with mock.patch('six.moves.builtins.open', mock.mock_open(read_data=pub_key_str),
218                         create=True) as mock_file:
219             with open(key_filename, "r") as h:
220                 result = h.read()
221             model.Libvirt.gen_cdrom_image(self.mock_ssh, file_path, hostname, user, key_filename)
222             mock_file.assert_called_with(".".join([key_filename, "pub"]), "r")
223         self.assertEqual(result, pub_key_str)
224
225         self.mock_ssh.execute.assert_has_calls([
226             mock.call("touch %s" % meta_data),
227             mock.call(model.USER_DATA_TEMPLATE.format(user_file=user_data, host=hostname,
228                                                       user_config=user_conf)),
229             mock.call("genisoimage -output {0} -volid cidata"
230                       " -joliet -r {1} {2}".format(file_path, meta_data, user_data)),
231             mock.call("rm {0} {1}".format(meta_data, user_data))
232         ])
233
234     def test_create_snapshot_qemu(self):
235         self.mock_ssh.execute = mock.Mock(return_value=(0, 0, 0))
236         index = 1
237         vm_image = '/var/lib/libvirt/images/%s.qcow2' % index
238         base_image = '/tmp/base_image'
239
240         model.Libvirt.create_snapshot_qemu(self.mock_ssh, index, base_image)
241         self.mock_ssh.execute.assert_has_calls([
242             mock.call('rm -- "%s"' % vm_image),
243             mock.call('test -r %s' % base_image),
244             mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' %
245                       (base_image, vm_image))
246         ])
247
248     @mock.patch.object(os.path, 'basename', return_value='base_image')
249     @mock.patch.object(os.path, 'normpath')
250     @mock.patch.object(os, 'access', return_value=True)
251     def test_create_snapshot_qemu_no_image_remote(self,
252             mock_os_access, mock_normpath, mock_basename):
253         self.mock_ssh.execute = mock.Mock(
254             side_effect=[(0, 0, 0), (1, 0, 0), (0, 0, 0), (0, 0, 0)])
255         index = 1
256         vm_image = '/var/lib/libvirt/images/%s.qcow2' % index
257         base_image = '/tmp/base_image'
258         mock_normpath.return_value = base_image
259
260         model.Libvirt.create_snapshot_qemu(self.mock_ssh, index, base_image)
261         self.mock_ssh.execute.assert_has_calls([
262             mock.call('rm -- "%s"' % vm_image),
263             mock.call('test -r %s' % base_image),
264             mock.call('mv -- "/tmp/%s" "%s"' % ('base_image', base_image)),
265             mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' %
266                       (base_image, vm_image))
267         ])
268         mock_os_access.assert_called_once_with(base_image, os.R_OK)
269         mock_normpath.assert_called_once_with(base_image)
270         mock_basename.assert_has_calls([mock.call(base_image)])
271         self.mock_ssh.put_file.assert_called_once_with(base_image,
272                                                        '/tmp/base_image')
273
274     @mock.patch.object(model.Libvirt, 'gen_cdrom_image')
275     def test_check_update_key(self, mock_gen_cdrom_image):
276         node = {'user': 'defuser', 'key_filename': '/home/ubuntu/id_rsa'}
277         cdrom_img = "/var/lib/libvirt/images/data.img"
278         id_name = 'fake_name'
279         key_filename = node.get('key_filename')
280         root = ElementTree.fromstring(self.XML_STR)
281         hostname = root.find('name').text
282         model.StandaloneContextHelper.check_update_key(self.mock_ssh, node, hostname, id_name,
283                                                        cdrom_img)
284         mock_gen_cdrom_image.assert_called_once_with(self.mock_ssh, cdrom_img, hostname,
285                                                      node.get('user'), key_filename)
286
287     @mock.patch.object(os, 'access', return_value=False)
288     def test_create_snapshot_qemu_no_image_local(self, mock_os_access):
289         self.mock_ssh.execute = mock.Mock(side_effect=[(0, 0, 0), (1, 0, 0)])
290         base_image = '/tmp/base_image'
291
292         with self.assertRaises(exceptions.LibvirtQemuImageBaseImageNotPresent):
293             model.Libvirt.create_snapshot_qemu(self.mock_ssh, 3, base_image)
294         mock_os_access.assert_called_once_with(base_image, os.R_OK)
295
296     def test_create_snapshot_qemu_error_qemuimg_command(self):
297         self.mock_ssh.execute = mock.Mock(
298             side_effect=[(0, 0, 0), (0, 0, 0), (1, 0, 0)])
299         index = 1
300         vm_image = '/var/lib/libvirt/images/%s.qcow2' % index
301         base_image = '/tmp/base_image'
302
303         with self.assertRaises(exceptions.LibvirtQemuImageCreateError):
304             model.Libvirt.create_snapshot_qemu(self.mock_ssh, index,
305                                                base_image)
306         self.mock_ssh.execute.assert_has_calls([
307             mock.call('rm -- "%s"' % vm_image),
308             mock.call('test -r %s' % base_image),
309             mock.call('qemu-img create -f qcow2 -o backing_file=%s %s' %
310                       (base_image, vm_image))
311         ])
312
313     @mock.patch.object(model.Libvirt, 'pin_vcpu_for_perf', return_value='4,5')
314     @mock.patch.object(model.Libvirt, 'create_snapshot_qemu',
315                        return_value='qemu_image')
316     def test_build_vm_xml(self, mock_create_snapshot_qemu,
317                           mock_pin_vcpu_for_perf):
318         extra_specs = {'hw:cpu_cores': '4',
319                        'hw:cpu_sockets': '3',
320                        'hw:cpu_threads': '2',
321                        'cputune': 'cool'}
322         flavor = {'ram': '1024',
323                   'extra_specs': extra_specs,
324                   'hw_socket': '1',
325                   'images': 'images'}
326         mac = model.StandaloneContextHelper.get_mac_address(0x00)
327         _uuid = uuid.uuid4()
328         connection = mock.Mock()
329         cdrom_img = '/tmp/cdrom-0.img'
330         with mock.patch.object(model.StandaloneContextHelper,
331                                'get_mac_address', return_value=mac) as \
332                 mock_get_mac_address, \
333                 mock.patch.object(uuid, 'uuid4', return_value=_uuid):
334             xml_out, mac = model.Libvirt.build_vm_xml(
335                 connection, flavor, 'vm_name', 100, cdrom_img)
336
337         xml_ref = model.VM_TEMPLATE.format(vm_name='vm_name',
338             random_uuid=_uuid, mac_addr=mac, memory='1024', vcpu='8', cpu='4',
339             numa_cpus='0-7', socket='3', threads='2',
340             vm_image='qemu_image', cpuset='4,5', cputune='cool')
341         xml_ref = model.Libvirt.add_cdrom(cdrom_img, xml_ref)
342         self.assertEqual(xml_out, xml_ref)
343         mock_get_mac_address.assert_called_once_with(0x00)
344         mock_create_snapshot_qemu.assert_called_once_with(
345             connection, 100, 'images')
346         mock_pin_vcpu_for_perf.assert_called_once_with(connection, '1')
347
348     # TODO: Edit this test to test state instead of output
349     # update_interrupts_hugepages_perf does not return anything
350     def test_update_interrupts_hugepages_perf(self):
351         with mock.patch("yardstick.ssh.SSH") as ssh:
352             ssh_mock = mock.Mock(autospec=ssh.SSH)
353             ssh_mock.execute = \
354                 mock.Mock(return_value=(0, "a", ""))
355             ssh.return_value = ssh_mock
356         # NOTE(ralonsoh): 'update_interrupts_hugepages_perf' always return
357         # None, this check is trivial.
358         #status = Libvirt.update_interrupts_hugepages_perf(ssh_mock)
359         #self.assertIsNone(status)
360         model.Libvirt.update_interrupts_hugepages_perf(ssh_mock)
361
362     @mock.patch.object(model, 'CpuSysCores')
363     @mock.patch.object(model.Libvirt, 'update_interrupts_hugepages_perf')
364     def test_pin_vcpu_for_perf(self, *args):
365         # NOTE(ralonsoh): test mocked methods/variables.
366         with mock.patch("yardstick.ssh.SSH") as ssh:
367             ssh_mock = mock.Mock(autospec=ssh.SSH)
368             ssh_mock.execute = \
369                 mock.Mock(return_value=(0, "a", ""))
370             ssh.return_value = ssh_mock
371         status = model.Libvirt.pin_vcpu_for_perf(ssh_mock, 4)
372         self.assertIsNotNone(status)
373
374
375 class StandaloneContextHelperTestCase(unittest.TestCase):
376
377     NODE_SAMPLE = "nodes_sample.yaml"
378     NODE_SRIOV_SAMPLE = "nodes_sriov_sample.yaml"
379
380     NETWORKS = {
381         'mgmt': {'cidr': '152.16.100.10/24'},
382         'private_0': {
383             'phy_port': "0000:05:00.0",
384             'vpci': "0000:00:07.0",
385             'cidr': '152.16.100.10/24',
386             'gateway_ip': '152.16.100.20'},
387         'public_0': {
388             'phy_port': "0000:05:00.1",
389             'vpci': "0000:00:08.0",
390             'cidr': '152.16.40.10/24',
391             'gateway_ip': '152.16.100.20'}
392     }
393
394     def setUp(self):
395         self.helper = model.StandaloneContextHelper()
396
397     def test___init__(self):
398         self.assertIsNone(self.helper.file_path)
399
400     def test_install_req_libs(self):
401         with mock.patch("yardstick.ssh.SSH") as ssh:
402             ssh_mock = mock.Mock(autospec=ssh.SSH)
403             ssh_mock.execute = \
404                 mock.Mock(return_value=(1, "a", ""))
405             ssh.return_value = ssh_mock
406         # NOTE(ralonsoh): this test doesn't cover function execution. This test
407         # should also check mocked function calls.
408         model.StandaloneContextHelper.install_req_libs(ssh_mock)
409
410     def test_get_kernel_module(self):
411         with mock.patch("yardstick.ssh.SSH") as ssh:
412             ssh_mock = mock.Mock(autospec=ssh.SSH)
413             ssh_mock.execute = \
414                 mock.Mock(return_value=(1, "i40e", ""))
415             ssh.return_value = ssh_mock
416         # NOTE(ralonsoh): this test doesn't cover function execution. This test
417         # should also check mocked function calls.
418         model.StandaloneContextHelper.get_kernel_module(
419             ssh_mock, "05:00.0", None)
420
421     @mock.patch.object(model.StandaloneContextHelper, 'get_kernel_module')
422     def test_get_nic_details(self, mock_get_kernel_module):
423         with mock.patch("yardstick.ssh.SSH") as ssh:
424             ssh_mock = mock.Mock(autospec=ssh.SSH)
425             ssh_mock.execute = mock.Mock(return_value=(1, "i40e ixgbe", ""))
426             ssh.return_value = ssh_mock
427         mock_get_kernel_module.return_value = "i40e"
428         # NOTE(ralonsoh): this test doesn't cover function execution. This test
429         # should also check mocked function calls.
430         model.StandaloneContextHelper.get_nic_details(
431             ssh_mock, self.NETWORKS, 'dpdk-devbind.py')
432
433     def test_get_virtual_devices(self):
434         pattern = "PCI_SLOT_NAME=0000:05:00.0"
435         with mock.patch("yardstick.ssh.SSH") as ssh:
436             ssh_mock = mock.Mock(autospec=ssh.SSH)
437             ssh_mock.execute = \
438                 mock.Mock(return_value=(1, pattern, ""))
439             ssh.return_value = ssh_mock
440         # NOTE(ralonsoh): this test doesn't cover function execution. This test
441         # should also check mocked function calls.
442         model.StandaloneContextHelper.get_virtual_devices(
443             ssh_mock, '0000:00:05.0')
444
445     def _get_file_abspath(self, filename):
446         curr_path = os.path.dirname(os.path.abspath(__file__))
447         file_path = os.path.join(curr_path, filename)
448         return file_path
449
450     def test_parse_pod_file(self):
451         self.helper.file_path = self._get_file_abspath("dummy")
452         self.assertRaises(IOError, self.helper.parse_pod_file,
453                           self.helper.file_path)
454
455         self.helper.file_path = self._get_file_abspath(self.NODE_SAMPLE)
456         self.assertRaises(TypeError, self.helper.parse_pod_file,
457                           self.helper.file_path)
458
459         self.helper.file_path = self._get_file_abspath(self.NODE_SRIOV_SAMPLE)
460         self.assertIsNotNone(self.helper.parse_pod_file(self.helper.file_path))
461
462     def test_get_mac_address(self):
463         status = model.StandaloneContextHelper.get_mac_address()
464         self.assertIsNotNone(status)
465
466     @mock.patch('yardstick.ssh.SSH')
467     def test_get_mgmt_ip(self, *args):
468         # NOTE(ralonsoh): test mocked methods/variables.
469         with mock.patch("yardstick.ssh.SSH") as ssh:
470             ssh_mock = mock.Mock(autospec=ssh.SSH)
471             ssh_mock.execute = mock.Mock(
472                 return_value=(1, "1.2.3.4 00:00:00:00:00:01", ""))
473             ssh.return_value = ssh_mock
474         # NOTE(ralonsoh): this test doesn't cover function execution. This test
475         # should also check mocked function calls.
476         status = model.StandaloneContextHelper.get_mgmt_ip(
477             ssh_mock, "00:00:00:00:00:01", "1.1.1.1/24", {})
478         self.assertIsNotNone(status)
479
480     @mock.patch('yardstick.ssh.SSH')
481     def test_get_mgmt_ip_no(self, *args):
482         # NOTE(ralonsoh): test mocked methods/variables.
483         with mock.patch("yardstick.ssh.SSH") as ssh:
484             ssh_mock = mock.Mock(autospec=ssh.SSH)
485             ssh_mock.execute = \
486                 mock.Mock(return_value=(1, "", ""))
487             ssh.return_value = ssh_mock
488         # NOTE(ralonsoh): this test doesn't cover function execution. This test
489         # should also check mocked function calls.
490         model.WAIT_FOR_BOOT = 0
491         status = model.StandaloneContextHelper.get_mgmt_ip(
492             ssh_mock, "99", "1.1.1.1/24", {})
493         self.assertIsNone(status)
494
495
496 class ServerTestCase(unittest.TestCase):
497
498     NETWORKS = {
499         'mgmt': {'cidr': '152.16.100.10/24'},
500         'private_0': {
501             'phy_port': "0000:05:00.0",
502             'vpci': "0000:00:07.0",
503             'driver': 'i40e',
504             'mac': '',
505             'cidr': '152.16.100.10/24',
506             'gateway_ip': '152.16.100.20'},
507         'public_0': {
508             'phy_port': "0000:05:00.1",
509             'vpci': "0000:00:08.0",
510             'driver': 'i40e',
511             'mac': '',
512             'cidr': '152.16.40.10/24',
513             'gateway_ip': '152.16.100.20'}
514     }
515
516     def setUp(self):
517         self.server = model.Server()
518
519     def test___init__(self):
520         self.assertIsNotNone(self.server)
521
522     def test_build_vnf_interfaces(self):
523         vnf = {
524             "network_ports": {
525                 'mgmt': {'cidr': '152.16.100.10/24'},
526                 'xe0': ['private_0'],
527                 'xe1': ['public_0'],
528             }
529         }
530         status = model.Server.build_vnf_interfaces(vnf, self.NETWORKS)
531         self.assertIsNotNone(status)
532
533     def test_generate_vnf_instance(self):
534         vnf = {
535             "network_ports": {
536                 'mgmt': {'cidr': '152.16.100.10/24'},
537                 'xe0': ['private_0'],
538                 'xe1': ['public_0'],
539             }
540         }
541         status = self.server.generate_vnf_instance(
542             {}, self.NETWORKS, '1.1.1.1/24', 'vm-0', vnf, '00:00:00:00:00:01')
543         self.assertIsNotNone(status)
544
545
546 class OvsDeployTestCase(unittest.TestCase):
547
548     OVS_DETAILS = {'version': {'ovs': 'ovs_version', 'dpdk': 'dpdk_version'}}
549
550     def setUp(self):
551         self._mock_ssh = mock.patch.object(ssh, 'SSH')
552         self.mock_ssh = self._mock_ssh.start()
553         self.ovs_deploy = model.OvsDeploy(self.mock_ssh,
554                                           '/tmp/dpdk-devbind.py',
555                                           self.OVS_DETAILS)
556         self._mock_path_isfile = mock.patch.object(os.path, 'isfile')
557         self._mock_path_join = mock.patch.object(os.path, 'join')
558         self.mock_path_isfile = self._mock_path_isfile.start()
559         self.mock_path_join = self._mock_path_join.start()
560
561         self.addCleanup(self._stop_mock)
562
563     def _stop_mock(self):
564         self._mock_ssh.stop()
565         self._mock_path_isfile.stop()
566         self._mock_path_join.stop()
567
568     @mock.patch.object(model.StandaloneContextHelper, 'install_req_libs')
569     def test_prerequisite(self, mock_install_req_libs):
570         pkgs = ["git", "build-essential", "pkg-config", "automake",
571                 "autotools-dev", "libltdl-dev", "cmake", "libnuma-dev",
572                 "libpcap-dev"]
573         self.ovs_deploy.prerequisite()
574         mock_install_req_libs.assert_called_once_with(
575             self.ovs_deploy.connection, pkgs)
576
577     def test_ovs_deploy_no_file(self):
578         self.mock_path_isfile.return_value = False
579         mock_file = mock.Mock()
580         self.mock_path_join.return_value = mock_file
581
582         self.ovs_deploy.ovs_deploy()
583         self.mock_path_isfile.assert_called_once_with(mock_file)
584         self.mock_path_join.assert_called_once_with(
585             constants.YARDSTICK_ROOT_PATH,
586             'yardstick/resources/scripts/install/',
587             self.ovs_deploy.OVS_DEPLOY_SCRIPT)
588
589     @mock.patch.object(os.environ, 'get', return_value='test_proxy')
590     def test_ovs_deploy(self, mock_env_get):
591         self.mock_path_isfile.return_value = True
592         mock_deploy_file = mock.Mock()
593         mock_remove_ovs_deploy = mock.Mock()
594         self.mock_path_join.side_effect = [mock_deploy_file,
595                                            mock_remove_ovs_deploy]
596         dpdk_version = self.OVS_DETAILS['version']['dpdk']
597         ovs_version = self.OVS_DETAILS['version']['ovs']
598
599         with mock.patch.object(self.ovs_deploy.connection, 'put') as \
600                 mock_put, \
601                 mock.patch.object(self.ovs_deploy.connection, 'execute') as \
602                 mock_execute, \
603                 mock.patch.object(self.ovs_deploy, 'prerequisite'):
604             mock_execute.return_value = (0, 0, 0)
605             self.ovs_deploy.ovs_deploy()
606
607             self.mock_path_isfile.assert_called_once_with(mock_deploy_file)
608             self.mock_path_join.assert_has_calls([
609                 mock.call(constants.YARDSTICK_ROOT_PATH,
610                           'yardstick/resources/scripts/install/',
611                           self.ovs_deploy.OVS_DEPLOY_SCRIPT),
612                 mock.call(self.ovs_deploy.bin_path,
613                           self.ovs_deploy.OVS_DEPLOY_SCRIPT)
614             ])
615             mock_put.assert_called_once_with(mock_deploy_file,
616                                              mock_remove_ovs_deploy)
617             cmd = ("sudo -E %(remote_ovs_deploy)s --ovs='%(ovs_version)s' "
618                    "--dpdk='%(dpdk_version)s' -p='%(proxy)s'" %
619                    {'remote_ovs_deploy': mock_remove_ovs_deploy,
620                     'ovs_version': ovs_version,
621                     'dpdk_version': dpdk_version,
622                     'proxy': 'test_proxy'})
623             mock_execute.assert_called_once_with(cmd)
624             mock_env_get.assert_has_calls([mock.call('http_proxy', '')])