aboutsummaryrefslogtreecommitdiffstats
path: root/yardstick/tests/unit/benchmark/contexts/test_heat.py
blob: fbc6fd26da0631dc5ea84fd3ed4f1bae44f27d9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
##############################################################################
# Copyright (c) 2015 Ericsson AB and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################

from collections import OrderedDict
import logging
import os

import mock
import unittest

from yardstick.benchmark.contexts import base
from yardstick.benchmark.contexts import heat
from yardstick.benchmark.contexts import model
from yardstick.common import constants as consts
from yardstick.common import exceptions as y_exc
from yardstick.common import openstack_utils
from yardstick.common import yaml_loader
from yardstick import ssh


LOG = logging.getLogger(__name__)


class HeatContextTestCase(unittest.TestCase):

    HEAT_POD_SAMPLE = {
        "nodes": [
            {
                "name": "node1",
                "role": "Controller",
                "ip": "10.229.47.137",
                "user": "root",
                "key_filename": "/root/.yardstick_key"
            },
            {
                "name": "node2",
                "role": "Compute",
                "ip": "10.229.47.139",
                "user": "root",
                "key_filename": "/root/.yardstick_key"
            }
        ]
    }

    def __init__(self, *args, **kwargs):

        super(HeatContextTestCase, self).__init__(*args, **kwargs)

    def setUp(self):
        self.test_context = heat.HeatContext()
        self.addCleanup(self._remove_contexts)
        self.mock_context = mock.Mock(spec=heat.HeatContext())

    def _remove_contexts(self):
        if self.test_context in self.test_context.list:
            self.test_context._delete_context()

    def test___init__(self):
        self.assertIsNone(self.test_context._name)
        self.assertIsNone(self.test_context._task_id)
        self.assertFalse(self.test_context._flags.no_setup)
        self.assertFalse(self.test_context._flags.no_teardown)
        self.assertIsNone(self.test_context.stack)
        self.assertEqual(self.test_context.networks, OrderedDict())
        self.assertEqual(self.test_context.servers, [])
        self.assertEqual(self.test_context.placement_groups, [])
        self.assertEqual(self.test_context.server_groups, [])
        self.assertIsNone(self.test_context.keypair_name)
        self.assertIsNone(self.test_context.secgroup_name)
        self.assertIsNone(self.test_context.security_group)
        self.assertEqual(self.test_context._server_map, {})
        self.assertIsNone(self.test_context._image)
        self.assertIsNone(self.test_context._flavor)
        self.assertIsNone(self.test_context._user)
        self.assertIsNone(self.test_context.template_file)
        self.assertIsNone(self.test_context.heat_parameters)
        self.assertIsNone(self.test_context.key_filename)
        self.assertTrue(self.test_context.yardstick_gen_key_file)

    @mock.patch.object(yaml_loader, 'read_yaml_file')
    @mock.patch('yardstick.benchmark.contexts.heat.PlacementGroup')
    @mock.patch('yardstick.benchmark.contexts.heat.ServerGroup')
    @mock.patch('yardstick.benchmark.contexts.heat.Network')
    @mock.patch('yardstick.benchmark.contexts.heat.Server')
    def test_init(self, mock_server, mock_network, mock_sg, mock_pg,
                  mock_read_yaml):

        mock_read_yaml.return_value = self.HEAT_POD_SAMPLE
        pgs = {'pgrp1': {'policy': 'availability'}}
        sgs = {'servergroup1': {'policy': 'affinity'}}
        networks = {'bar': {'cidr': '10.0.1.0/24'}}
        servers = {'baz': {'floating_ip': True, 'placement': 'pgrp1'}}
        attrs = {'name': 'foo',
                 'file': 'pod.yaml',
                 'task_id': '1234567890',
                 'placement_groups': pgs,
                 'server_groups': sgs,
                 'networks': networks,
                 'servers': servers}

        with mock.patch.object(openstack_utils, 'get_shade_client'), \
             mock.patch.object(openstack_utils, 'get_shade_operator_client'):
            self.test_context.init(attrs)

        self.assertFalse(self.test_context._flags.no_setup)
        self.assertFalse(self.test_context._flags.no_teardown)
        self.assertEqual(self.test_context._name, "foo")
        self.assertEqual(self.test_context._task_id, '1234567890')
        self.assertEqual(self.test_context.name, "foo-12345678")
        self.assertEqual(self.test_context.keypair_name, "foo-12345678-key")
        self.assertEqual(self.test_context.secgroup_name, "foo-12345678-secgroup")

        mock_pg.assert_called_with('pgrp1', self.test_context,
                                   pgs['pgrp1']['policy'])
        mock_sg.assert_called_with('servergroup1', self.test_context,
                                   sgs['servergroup1']['policy'])
        self.assertEqual(len(self.test_context.placement_groups), 1)
        self.assertEqual(len(self.test_context.server_groups), 1)

        mock_network.assert_called_with(
            'bar', self.test_context, networks['bar'])
        self.assertEqual(len(self.test_context.networks), 1)

        mock_server.assert_called_with('baz', self.test_context,
                                       servers['baz'])
        self.assertEqual(len(self.test_context.servers), 1)

    def test_init_no_name_or_task_id(self):
        attrs = {}
        self.assertRaises(KeyError, self.test_context.init, attrs)

    def test_name(self):
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.assertEqual(self.test_context.name, 'foo-12345678')
        self.assertEqual(self.test_context.assigned_name, 'foo')

    def test_name_flags(self):
        self.test_context._flags = base.Flags(
            **{"no_setup": True, "no_teardown": True})
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'

        self.assertEqual(self.test_context.name, 'foo')
        self.assertEqual(self.test_context.assigned_name, 'foo')

    def test_init_no_setup_no_teardown(self):

        attrs = {'name': 'foo',
                 'task_id': '1234567890',
                 'placement_groups': {},
                 'server_groups': {},
                 'networks': {},
                 'servers': {},
                 'file': "pod.yaml",
                 'flags': {
                     'no_setup': True,
                     'no_teardown': True,
                     },
                }

        with mock.patch.object(openstack_utils, 'get_shade_client'), \
             mock.patch.object(openstack_utils, 'get_shade_operator_client'):
            self.test_context.init(attrs)

        self.assertTrue(self.test_context._flags.no_setup)
        self.assertTrue(self.test_context._flags.no_teardown)

    def test_init_key_filename(self):
        attrs = {'name': 'foo',
                 'file': 'pod.yaml',
                 'task_id': '1234567890',
                 'server_groups': {},
                 'networks': {},
                 'servers': {},
                 'heat_template': "/root/clearwater.yaml",
                 'key_filename': '/etc/yardstick/yardstick.pem'}

        with mock.patch.object(openstack_utils, 'get_shade_client'), \
             mock.patch.object(openstack_utils, 'get_shade_operator_client'):
            self.test_context.init(attrs)

        self.assertIsNotNone(self.test_context.key_filename)
        self.assertFalse(self.test_context.yardstick_gen_key_file)

    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    def test__add_resources_to_template_no_servers(self, mock_template):
        self.test_context._name = 'ctx'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context.keypair_name = "ctx-key"
        self.test_context.secgroup_name = "ctx-secgroup"
        self.test_context.key_uuid = "2f2e4997-0a8e-4eb7-9fa4-f3f8fbbc393b"
        netattrs = {'cidr': '10.0.0.0/24', 'provider': None,
                    'external_network': 'ext_net'}

        self.test_context.networks = OrderedDict(
            {"mynet": model.Network("mynet", self.test_context,
                                           netattrs)})

        self.test_context._add_resources_to_template(mock_template)
        mock_template.add_keypair.assert_called_with(
            "ctx-key",
            "ctx-12345678")
        mock_template.add_security_group.assert_called_with("ctx-secgroup", None)
        mock_template.add_network.assert_called_with(
            "ctx-12345678-mynet", 'physnet1', None, None, None, None)
        mock_template.add_router.assert_called_with(
            "ctx-12345678-mynet-router",
            netattrs["external_network"],
            "ctx-12345678-mynet-subnet")
        mock_template.add_router_interface.assert_called_with(
            "ctx-12345678-mynet-router-if0",
            "ctx-12345678-mynet-router",
            "ctx-12345678-mynet-subnet")

    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    def test_attrs_get(self, *args):
        image, flavor, user = expected_tuple = 'foo1', 'foo2', 'foo3'
        self.assertNotEqual(self.test_context.image, image)
        self.assertNotEqual(self.test_context.flavor, flavor)
        self.assertNotEqual(self.test_context.user, user)
        self.test_context._image = image
        self.test_context._flavor = flavor
        self.test_context._user = user
        attr_tuple = self.test_context.image, self.test_context.flavor, self.test_context.user
        self.assertEqual(attr_tuple, expected_tuple)

    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    def test_attrs_set_negative(self, *args):
        with self.assertRaises(AttributeError):
            self.test_context.image = 'foo'

        with self.assertRaises(AttributeError):
            self.test_context.flavor = 'foo'

        with self.assertRaises(AttributeError):
            self.test_context.user = 'foo'

    def test__create_new_stack(self):
        template = mock.Mock()
        self.test_context._create_new_stack(template)
        template.create.assert_called_once()

    def test__create_new_stack_stack_create_failed(self):
        template = mock.Mock()
        template.create.side_effect = y_exc.HeatTemplateError

        self.assertRaises(y_exc.HeatTemplateError,
                          self.test_context._create_new_stack,
                          template)

    def test__create_new_stack_keyboard_interrupt(self):
        template = mock.Mock()
        template.create.side_effect = KeyboardInterrupt
        self.assertRaises(y_exc.StackCreationInterrupt,
                          self.test_context._create_new_stack,
                          template)

    @mock.patch.object(os.path, 'exists', return_value=True)
    @mock.patch.object(heat.HeatContext, '_add_resources_to_template')
    @mock.patch.object(heat.HeatContext, '_create_new_stack')
    def test_deploy_stack_creation_failed(self, mock_create,
            mock_resources_template, mock_path_exists):
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = 'foo-12345678'
        mock_create.side_effect = y_exc.HeatTemplateError
        self.assertRaises(y_exc.HeatTemplateError,
                          self.test_context.deploy)

        mock_path_exists.assert_called()
        mock_resources_template.assert_called_once()

    @mock.patch.object(os.path, 'exists', return_value=False)
    @mock.patch.object(ssh.SSH, 'gen_keys')
    @mock.patch.object(heat, 'HeatTemplate')
    def test_deploy(self, mock_template, mock_genkeys, mock_path_exists):
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context.template_file = '/bar/baz/some-heat-file'
        self.test_context.heat_parameters = {'image': 'cirros'}
        self.test_context.get_neutron_info = mock.MagicMock()
        self.test_context.deploy()

        mock_template.assert_called_with(
            'foo-12345678', template_file='/bar/baz/some-heat-file',
            heat_parameters={'image': 'cirros'},
            os_cloud_config=self.test_context._flags.os_cloud_config)
        self.assertIsNotNone(self.test_context.stack)
        key_filename = ''.join(
            [consts.YARDSTICK_ROOT_PATH,
             'yardstick/resources/files/yardstick_key-',
             self.test_context._name_task_id])
        mock_genkeys.assert_called_once_with(key_filename)
        mock_path_exists.assert_any_call(key_filename)

    @mock.patch.object(heat, 'HeatTemplate')
    @mock.patch.object(os.path, 'exists', return_value=False)
    @mock.patch.object(ssh.SSH, 'gen_keys')
    @mock.patch.object(heat.HeatContext, '_retrieve_existing_stack')
    @mock.patch.object(heat.HeatContext, '_create_new_stack')
    def test_deploy_no_setup(self, mock_create_new_stack,
            mock_retrieve_existing_stack, mock_genkeys, mock_path_exists,
            *args):
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context.template_file = '/bar/baz/some-heat-file'
        self.test_context.heat_parameters = {'image': 'cirros'}
        self.test_context.get_neutron_info = mock.MagicMock()
        self.test_context._flags.no_setup = True
        self.test_context.deploy()

        mock_create_new_stack.assert_not_called()
        mock_retrieve_existing_stack.assert_called_with(self.test_context.name)
        self.assertIsNotNone(self.test_context.stack)
        key_filename = ''.join(
            [consts.YARDSTICK_ROOT_PATH,
             'yardstick/resources/files/yardstick_key-',
             self.test_context._name])
        mock_genkeys.assert_called_once_with(key_filename)
        mock_path_exists.assert_any_call(key_filename)

    @mock.patch.object(heat, 'HeatTemplate')
    @mock.patch.object(os.path, 'exists', return_value=False)
    @mock.patch.object(ssh.SSH, 'gen_keys')
    @mock.patch.object(heat.HeatContext, '_create_new_stack')
    @mock.patch.object(heat.HeatContext, '_retrieve_existing_stack',
                       return_value=None)
    def test_deploy_try_retrieve_context_does_not_exist(self,
            mock_retrieve_stack, mock_create_new_stack, mock_genkeys,
            mock_path_exists, *args):
        self.test_context._name = 'demo'
        self.test_context._task_id = '1234567890'
        self.test_context._flags.no_setup = True
        self.test_context.template_file = '/bar/baz/some-heat-file'
        self.test_context.get_neutron_info = mock.MagicMock()
        self.test_context.deploy()

        mock_retrieve_stack.assert_called_once_with(self.test_context._name)
        mock_create_new_stack.assert_called()
        key_filename = ''.join(
            [consts.YARDSTICK_ROOT_PATH,
             'yardstick/resources/files/yardstick_key-',
             self.test_context._name])
        mock_genkeys.assert_called_once_with(key_filename)
        mock_path_exists.assert_any_call(key_filename)

    @mock.patch.object(heat, 'HeatTemplate', return_value='heat_template')
    @mock.patch.object(heat.HeatContext, '_add_resources_to_template')
    @mock.patch.object(os.path, 'exists', return_value=False)
    @mock.patch.object(ssh.SSH, 'gen_keys')
    def test_deploy_ssh_key_before_adding_resources(self, mock_genkeys,
            mock_path_exists, mock_add_resources, *args):
        mock_manager = mock.Mock()
        mock_manager.attach_mock(mock_add_resources,
                                 '_add_resources_to_template')
        mock_manager.attach_mock(mock_genkeys, 'gen_keys')
        mock_manager.reset_mock()
        self.test_context._name_task_id = 'demo-12345678'
        self.test_context.get_neutron_info = mock.Mock()
        with mock.patch.object(self.test_context, '_create_new_stack') as \
                mock_create_stack, \
                mock.patch.object(self.test_context, 'get_neutron_info') as \
                mock_neutron_info:
            self.test_context.deploy()

        mock_neutron_info.assert_called_once()
        mock_create_stack.assert_called_once()
        key_filename = ''.join(
            [consts.YARDSTICK_ROOT_PATH,
             'yardstick/resources/files/yardstick_key-',
             self.test_context._name_task_id])
        mock_genkeys.assert_called_once_with(key_filename)
        mock_path_exists.assert_any_call(key_filename)

        mock_call_gen_keys = mock.call.gen_keys(key_filename)
        mock_call_add_resources = (
            mock.call._add_resources_to_template('heat_template'))
        self.assertTrue(mock_manager.mock_calls.index(mock_call_gen_keys) <
                        mock_manager.mock_calls.index(mock_call_add_resources))

    @mock.patch.object(heat, 'HeatTemplate')
    @mock.patch.object(ssh.SSH, 'gen_keys')
    @mock.patch.object(heat.HeatContext, '_create_new_stack')
    def test_deploy_with_key_filename_provided(self, mock_create_new_stack,
                                               mock_gen_keys, *args):
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context.template_file = '/bar/baz/some-heat-file'
        self.test_context.heat_parameters = {'image': 'cirros'}
        self.test_context.yardstick_gen_key_file = False
        self.test_context.key_filename = '/etc/yardstick/yardstick.pem'
        self.test_context.get_neutron_info = mock.MagicMock()
        self.test_context.deploy()

        mock_create_new_stack.assert_called()
        mock_gen_keys.assert_not_called()

    def test_check_for_context(self):
        pass
        # check that the context exists

    def test_add_server_port(self):
        network1 = mock.MagicMock()
        network2 = mock.MagicMock()
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context.stack = mock.MagicMock()
        self.test_context.networks = {
            'a': network1,
            'c': network2,
        }
        self.test_context.stack.outputs = {
            u'b': u'10.20.30.45',
            u'b-subnet_id': 1,
            u'foo-12345678-a-subnet-cidr': u'10.20.0.0/15',
            u'foo-12345678-a-subnet-gateway_ip': u'10.20.30.1',
            u'b-mac_address': u'00:01',
            u'b-device_id': u'dev21',
            u'b-network_id': u'net789',
            u'd': u'40.30.20.15',
            u'd-subnet_id': 2,
            u'foo-12345678-c-subnet-cidr': u'40.30.0.0/18',
            u'foo-12345678-c-subnet-gateway_ip': u'40.30.20.254',
            u'd-mac_address': u'00:10',
            u'd-device_id': u'dev43',
            u'd-network_id': u'net987',
            u'e': u'40.30.20.15',
            u'e-subnet_id': 2,
            u'e-mac_address': u'00:10',
            u'e-device_id': u'dev43',
            u'e-network_id': u'net987',
        }
        server = mock.MagicMock()
        server.private_ip = None
        server.ports = OrderedDict([
            ('a', [{'stack_name': 'b', 'port': 'port_a'}]),
            ('c', [{'stack_name': 'd', 'port': 'port_c'},
                   {'stack_name': 'e', 'port': 'port_f'}]),
        ])

        expected = {
            "private_ip": '10.20.30.45',
            "subnet_id": 1,
            "subnet_cidr": '10.20.0.0/15',
            "network": '10.20.0.0',
            "netmask": '255.254.0.0',
            "name": "port_a",
            "gateway_ip": '10.20.30.1',
            "mac_address": '00:01',
            "device_id": 'dev21',
            "network_id": 'net789',
            "network_name": 'a',
            "local_mac": '00:01',
            "local_ip": '10.20.30.45',
        }
        self.test_context.add_server_port(server)
        self.assertEqual(server.private_ip, '10.20.30.45')
        self.assertEqual(len(server.interfaces), 3)
        self.assertDictEqual(server.interfaces['port_a'], expected)

    @mock.patch('yardstick.benchmark.contexts.heat.os')
    @mock.patch.object(heat.HeatContext, '_delete_key_file')
    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    def test_undeploy(self, mock_template, mock_delete_key, *args):
        self.test_context.stack = mock_template
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        # mock_os.path.exists.return_value = True
        self.test_context.key_filename = 'foo/bar/foobar'
        self.test_context.undeploy()
        mock_delete_key.assert_called()
        mock_template.delete.assert_called_once()

    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    def test_undeploy_no_teardown(self, mock_template):
        self.test_context.stack = mock_template
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._flags.no_teardown = True
        self.test_context.undeploy()

        mock_template.delete.assert_not_called()

    @mock.patch('yardstick.benchmark.contexts.heat.HeatTemplate')
    @mock.patch('yardstick.benchmark.contexts.heat.os')
    def test_undeploy_key_filename(self, mock_os, mock_template):
        self.test_context.stack = mock_template
        self.test_context._name = 'foo'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id)
        mock_os.path.exists.return_value = True
        self.test_context.key_filename = 'foo/bar/foobar'
        self.assertIsNone(self.test_context.undeploy())

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_found_dict(self, *args):
        """
        Use HeatContext._get_server to get a server that matches
        based on a dictionary input.
        """
        foo2_server = mock.Mock()
        foo2_server.key_filename = None
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.key_filename = None
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = '127.0.0.3'
        baz3_server.context.user = 'zab'

        self.test_context._name = 'bar'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context._user = 'bot'
        self.test_context.stack = mock.Mock()
        self.test_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.test_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
        }

        attr_name = {
            'name': 'foo.bar-12345678',
            'private_ip_attr': 'private_ip',
            'public_ip_attr': 'public_ip',
        }
        self.test_context.key_uuid = 'foo-42'
        result = self.test_context._get_server(attr_name)
        self.assertEqual(result['user'], 'bot')
        self.assertEqual(result['ip'], '127.0.0.1')
        self.assertEqual(result['private_ip'], '10.0.0.1')

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_found_dict_no_attrs(self, *args):
        """
        Use HeatContext._get_server to get a server that matches
        based on a dictionary input.
        """
        foo2_server = mock.Mock()
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = '127.0.0.3'
        baz3_server.context.user = 'zab'

        self.test_context._name = 'bar'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context._user = 'bot'
        self.test_context.stack = mock.Mock()
        self.test_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.test_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
        }

        attr_name = {
            'name': 'foo.bar-12345678',
        }

        self.test_context.key_uuid = 'foo-42'
        result = self.test_context._get_server(attr_name)
        self.assertEqual(result['user'], 'bot')
        # no private ip attr mapping in the map results in None value in the result
        self.assertIsNone(result['private_ip'])
        # no public ip attr mapping in the map results in no value in the result
        self.assertNotIn('ip', result)

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_found_not_dict(self, *args):
        """
        Use HeatContext._get_server to get a server that matches
        based on a non-dictionary input
        """
        foo2_server = mock.Mock()
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = None
        baz3_server.context.user = 'zab'

        self.test_context._name = 'bar1'
        self.test_context._task_id = '1234567890'
        self.test_context._name_task_id = 'bar1-12345678'
        self.test_context.stack = mock.Mock()
        self.test_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.test_context.generate_routing_table = mock.MagicMock(return_value=[])

        self.test_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
        }

        attr_name = 'baz3'
        result = self.test_context._get_server(attr_name)
        self.assertEqual(result['user'], 'zab')
        self.assertEqual(result['private_ip'], '10.0.0.3')
        # no public_ip on the server results in no value in the result
        self.assertNotIn('public_ip', result)

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_none_found_not_dict(self, *args):
        """
        Use HeatContext._get_server to not get a server due to
        None value associated with the match to a non-dictionary
        input
        """
        foo2_server = mock.Mock()
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = None
        baz3_server.context.user = 'zab'

        self.test_context._name = 'bar1'
        self.test_context.stack = mock.Mock()
        self.test_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.test_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
            'wow4': None,
        }

        self.test_context.key_uuid = 'foo-42'
        attr_name = 'wow4'
        result = self.test_context._get_server(attr_name)
        self.assertIsNone(result)

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_not_found_dict(self, *args):
        """
        Use HeatContext._get_server to not get a server for lack
        of a match to a dictionary input
        """
        foo2_server = mock.Mock()
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = None
        baz3_server.context.user = 'zab'

        self.test_context._name = 'bar1'
        self.test_context._task_id = '1235467890'
        self.test_context._name_task_id = '{}-{}'.format(
            self.test_context._name, self.test_context._task_id[:8])
        self.test_context.stack = mock.Mock()
        self.test_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.test_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
        }

        self.test_context.key_uuid = 'foo-42'
        attr_name = {
            'name': 'foo.wow4',
            'private_ip_attr': 'private_ip',
            'public_ip_attr': 'public_ip',
        }
        result = self.test_context._get_server(attr_name)
        self.assertIsNone(result)

    @mock.patch("yardstick.benchmark.contexts.heat.pkg_resources")
    def test__get_server_not_found_not_dict(self, *args):
        """
        Use HeatContext._get_server to not get a server for lack
        of a match to a non-dictionary input
        """
        foo2_server = mock.Mock()
        foo2_server.private_ip = '10.0.0.2'
        foo2_server.public_ip = '127.0.0.2'
        foo2_server.context.user = 'oof'

        baz3_server = mock.Mock()
        baz3_server.private_ip = '10.0.0.3'
        baz3_server.public_ip = None
        baz3_server.context.user = 'zab'

        self.mock_context._name = 'bar1'
        self.test_context.stack = mock.Mock()
        self.mock_context.stack.outputs = {
            'private_ip': '10.0.0.1',
            'public_ip': '127.0.0.1',
        }
        self.mock_context._server_map = {
            'baz3': baz3_server,
            'foo2': foo2_server,
        }

        self.test_context.key_uuid = 'foo-42'
        attr_name = 'foo.wow4'
        result = self.test_context._get_server(attr_name)
        self.assertIsNone(result)

    # TODO: Split this into more granular tests
    def test__get_network(self):
        network1 = mock.MagicMock()
        network1.name = 'net_1'
        network1.vld_id = 'vld111'
        network1.segmentation_id = 'seg54'
        network1.network_type = 'type_a'
        network1.physical_network = 'phys'

        network2 = mock.MagicMock()
        network2.name = 'net_2'
        network2.segmentation_id = 'seg45'
        network2.network_type = 'type_b'
        network2.physical_network = 'virt'

        self.test_context.networks = {
            'a': network1,
            'b': network2,
        }

        attr_name = None
        self.assertIsNone(self.test_context._get_network(attr_name))

        attr_name = {}
        self.assertIsNone(self.test_context._get_network(attr_name))

        attr_name = {'network_type': 'nosuch'}
        self.assertIsNone(self.test_context._get_network(attr_name))

        attr_name = 'vld777'
        self.assertIsNone(self.test_context._get_network(attr_name))

        attr_name = {'segmentation_id': 'seg45'}
        expected = {
            "name": 'net_2',
            "segmentation_id": 'seg45',
            "network_type": 'type_b',
            "physical_network": 'virt',
        }
        result = self.test_context._get_network(attr_name)
        self.assertDictEqual(result, expected)

        attr_name = 'a'
        expected = {
            "name": 'net_1',
            "segmentation_id": 'seg54',
            "network_type": 'type_a',
            "physical_network": 'phys',
        }
        result = self.test_context._get_network(attr_name)
        self.assertDictEqual(result, expected)

    def _get_file_abspath(self, filename):
        curr_path = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(curr_path, filename)
        return file_path

    def test__get_physical_nodes(self):
        self.test_context.nodes = {}
        nodes = self.test_context._get_physical_nodes()
        self.assertEquals(nodes, {})

    @mock.patch.object(yaml_loader, 'read_yaml_file')
    def test__get_physical_node_for_server(self, mock_read_yaml):
        attrs = {'name': 'foo',
                 'task_id': '12345678',
                 'file': "pod.yaml",
                 'servers': {'vnf': {}},
                 'networks': {'mgmt': {'cidr': '10.0.1.0/24'}}
                 }

        with mock.patch.object(openstack_utils, 'get_shade_client'), \
             mock.patch.object(openstack_utils, 'get_shade_operator_client'):
            mock_read_yaml.return_value = self.HEAT_POD_SAMPLE
            self.test_context.init(attrs)

        with mock.patch('yardstick.common.openstack_utils.get_server') as mock_get_server:
            mock_get_server.return_value = {'vnf': {}}

            # When server is not from this context
            result = self.test_context._get_physical_node_for_server('node1.foo-context')
            self.assertIsNone(result)

            # When node_name is not from this context
            result = self.test_context._get_physical_node_for_server('fake.foo-12345678')
            self.assertIsNone(result)

            mock_munch = mock.Mock()
            mock_munch.toDict = mock.Mock(return_value={
                'OS-EXT-SRV-ATTR:hypervisor_hostname': 'hypervisor_hostname'
            })
            mock_get_server.return_value = mock_munch

            hypervisor = mock.Mock()
            hypervisor.hypervisor_hostname = 'hypervisor_hostname'
            hypervisor.host_ip = '10.229.47.137'

            self.test_context.operator_client.list_hypervisors = mock.Mock(
                return_value=[hypervisor])

            mock_get_server.return_value = mock_munch

            result = self.test_context._get_physical_node_for_server('vnf.foo-12345678')
            self.assertEqual(result, 'node1.foo')