This file is indexed.

/usr/lib/python2.7/dist-packages/os_xenapi/tests/plugins/test_xenhost.py is in python-os-xenapi 0.3.1-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
# Copyright (c) 2017 Citrix Systems, Inc
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

try:
    import json
except ImportError:
    import simplejson as json
import mock
from mock import call
from os_xenapi.tests.plugins import plugin_test
import time


class FakeXenAPIException(Exception):
    pass


class XenHostRunCmdTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(XenHostRunCmdTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")

    def test_run_command(self):
        self.mock_patch_object(self.host.utils,
                               'run_command',
                               'fake_run_cmd_return')
        cmd_result = self.host._run_command('fake_command')

        self.assertEqual(cmd_result, 'fake_run_cmd_return')
        self.host.utils.run_command.assert_called_with(
            'fake_command', cmd_input=None)

    def test_run_command_exception(self):
        side_effect = [self.host.utils.SubprocessException(
                       'fake_cmdline', 0,
                       'fake_out', 'fake_err')]
        self.mock_patch_object(self.host.utils,
                               'run_command',
                               'fake_run_cmd_return')
        self.host.utils.run_command.side_effect = side_effect

        self.assertRaises(self.pluginlib.PluginError,
                          self.host._run_command,
                          'fake_command')
        self.host.utils.run_command.assert_called_with(
            'fake_command', cmd_input=None)


class VMOperationTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(VMOperationTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")
        self.mock_patch_object(self.host,
                               '_run_command',
                               'fake_run_cmd_return')

    @mock.patch.object(time, 'sleep')
    def test_resume_compute(self, mock_sleep):
        self.mock_patch_object(self.session.xenapi.VM,
                               'start')
        self.host._resume_compute(self.session,
                                  'fake_compute_ref',
                                  'fake_compute_uuid')

        self.session.xenapi.VM.start.assert_called_with(
            'fake_compute_ref', False, True)
        mock_sleep.time.assert_not_called()

    @mock.patch.object(time, 'sleep')
    def test_resume_compute_exception_compute_VM_restart(self, mock_sleep):
        side_effect_xenapi_failure = FakeXenAPIException
        self.mock_patch_object(self.session.xenapi.VM,
                               'start')
        self.host.XenAPI.Failure = FakeXenAPIException
        self.session.xenapi.VM.start.side_effect = \
            side_effect_xenapi_failure

        self.host._resume_compute(self.session,
                                  'fake_compute_ref',
                                  'fake_compute_uuid')
        self.session.xenapi.VM.start.assert_called_with(
            'fake_compute_ref', False, True)
        self.host._run_command.assert_called_with(
            ["xe", "vm-start", "uuid=%s" % 'fake_compute_uuid']
        )
        mock_sleep.assert_not_called()

    @mock.patch.object(time, 'sleep')
    def test_resume_compute_exception_wait_slave_available(self, mock_sleep):
        side_effect_xenapi_failure = FakeXenAPIException
        side_effect_plugin_error = [self.pluginlib.PluginError(
                                    "Wait for the slave to become available"),
                                    None]
        self.mock_patch_object(self.session.xenapi.VM,
                               'start')
        self.session.xenapi.VM.start.side_effect = \
            side_effect_xenapi_failure
        self.host._run_command.side_effect = side_effect_plugin_error
        self.host.XenAPI.Failure = FakeXenAPIException
        expected = [call(["xe", "vm-start", "uuid=%s" % 'fake_compute_uuid']),
                    call(["xe", "vm-start", "uuid=%s" % 'fake_compute_uuid'])]

        self.host._resume_compute(self.session,
                                  'fake_compute_ref',
                                  'fake_compute_uuid')
        self.session.xenapi.VM.start.assert_called_with(
            'fake_compute_ref', False, True)
        self.assertEqual(expected, self.host._run_command.call_args_list)
        mock_sleep.assert_called_once()

    @mock.patch.object(time, 'sleep')
    def test_resume_compute_exception_unrecoverable(self, mock_sleep):
        fake_compute_ref = -1
        side_effect_xenapi_failure = FakeXenAPIException
        side_effect_plugin_error = (
            [self.pluginlib.PluginError]
            * self.host.DEFAULT_TRIES)
        self.mock_patch_object(self.session.xenapi.VM,
                               'start')
        self.session.xenapi.VM.start.side_effect = \
            side_effect_xenapi_failure
        self.host.XenAPI.Failure = FakeXenAPIException
        self.host._run_command.side_effect = side_effect_plugin_error

        self.assertRaises(self.pluginlib.PluginError,
                          self.host._resume_compute,
                          self.session,
                          fake_compute_ref,
                          'fake_compute_uuid')
        self.session.xenapi.VM.start.assert_called_with(
            -1, False, True)
        self.host._run_command.assert_called_with(
            ["xe", "vm-start", "uuid=%s" % 'fake_compute_uuid']
        )
        mock_sleep.assert_called()

    def test_set_host_enabled_no_enabled_key_in_arg_dict(self):
        temp_dict = {}
        self.assertRaises(self.pluginlib.PluginError,
                          self.host.set_host_enabled,
                          self.host, temp_dict)

    def test_set_host_enabled_unexpected_enabled_key(self):
        temp_dict = {}
        temp_dict.update({'enabled': 'unexpected_status'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        self.assertRaises(self.pluginlib.PluginError,
                          self.host.set_host_enabled,
                          self.host, temp_dict)

    def test_set_host_enabled_host_enable_disable_cmd_return_not_empty(self):
        temp_dict = {}
        temp_dict.update({'enabled': 'true'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        fake_run_command_return = 'not empty'
        self.host._run_command.return_value = fake_run_command_return
        self.assertRaises(self.pluginlib.PluginError,
                          self.host.set_host_enabled,
                          self.host, temp_dict)
        self.host._run_command.assert_called_once

    def test_set_host_enabled_request_host_enabled(self):
        temp_dict = {}
        side_effects = ['', 'any_value']
        temp_dict.update({'enabled': 'true'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        expected = [call(['xe', 'host-enable', 'uuid=fake_host_uuid']),
                    call(['xe', 'host-param-get', 'uuid=fake_host_uuid',
                         'param-name=enabled'])]
        self.host._run_command.side_effect = side_effects
        self.host.set_host_enabled(self.host, temp_dict)
        self.assertEqual(self.host._run_command.call_args_list, expected)

    def test_set_host_enabled_request_cmd_host_disable(self):
        temp_dict = {}
        side_effects = ['', 'any_value']
        temp_dict.update({'enabled': 'false'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        expected = [call(["xe", "host-disable", "uuid=%s" %
                         temp_dict['host_uuid']],),
                    call(["xe", "host-param-get", "uuid=%s"
                         % temp_dict['host_uuid'],
                         "param-name=enabled"],)]
        self.host._run_command.side_effect = side_effects
        self.host.set_host_enabled(self.host, temp_dict)
        self.assertEqual(self.host._run_command.call_args_list, expected)

    def test_set_host_enabled_confirm_host_enabled(self):
        temp_dict = {}
        side_effects = ['', 'true']
        temp_dict.update({'enabled': 'true'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        self.host._run_command.side_effect = side_effects
        result_status = self.host.set_host_enabled(self.host, temp_dict)
        self.assertEqual(result_status, '{"status": "enabled"}')

    def test_set_host_enabled_confirm_host_disabled(self):
        temp_dict = {}
        side_effects = ['', 'any_value']
        temp_dict.update({'enabled': 'false'})
        temp_dict.update({'host_uuid': 'fake_host_uuid'})
        self.host._run_command.side_effect = side_effects
        result_status = self.host.set_host_enabled(self.host, temp_dict)
        self.assertEqual(result_status, '{"status": "disabled"}')


class HostOptTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(HostOptTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")
        self.mock_patch_object(self.host,
                               '_run_command',
                               'fake_run_cmd_return')

    # may be removed because the operation would be deprecate
    def test_power_action_disable_cmd_result_not_empty(self):
        temp_arg_dict = {'host_uuid': 'fake_host_uuid'}
        self.host._run_command.return_value = 'not_empty'
        expected_cmd_arg = ["xe", "host-disable", "uuid=%s" %
                            'fake_host_uuid']

        self.assertRaises(self.pluginlib.PluginError,
                          self.host._power_action,
                          'fake_action', temp_arg_dict)
        self.host._run_command.assert_called_with(expected_cmd_arg)

    # may be removed because the operation would be deprecate
    def test_power_action_shutdown_cmd_result_not_empty(self):
        side_effects = [None, 'not_empty']
        temp_arg_dict = {'host_uuid': 'fake_host_uuid'}
        self.host._run_command.side_effect = side_effects
        expected_cmd_arg_list = [call(["xe", "host-disable", "uuid=%s"
                                      % 'fake_host_uuid']),
                                 call(["xe", "vm-shutdown", "--multiple",
                                      "resident-on=%s" % 'fake_host_uuid'])]

        self.assertRaises(self.pluginlib.PluginError,
                          self.host._power_action,
                          'fake_action', temp_arg_dict)
        self.assertEqual(self.host._run_command.call_args_list,
                         expected_cmd_arg_list)

    # may be removed because the operation would be deprecate
    def test_power_action_input_cmd_result_not_empty(self):
        side_effects = [None, None, 'not_empty']
        temp_arg_dict = {'host_uuid': 'fake_host_uuid'}
        self.host._run_command.side_effect = side_effects
        cmds = {"reboot": "host-reboot",
                "startup": "host-power-on",
                "shutdown": "host-shutdown"}
        fake_action = 'reboot'  # 'statup' and 'shutdown' should be same
        expected_cmd_arg_list = [call(["xe", "host-disable", "uuid=%s"
                                      % 'fake_host_uuid']),
                                 call(["xe", "vm-shutdown", "--multiple",
                                      "resident-on=%s" % 'fake_host_uuid']),
                                 call(["xe", cmds[fake_action], "uuid=%s" %
                                      'fake_host_uuid'])]

        self.assertRaises(self.pluginlib.PluginError,
                          self.host._power_action,
                          fake_action, temp_arg_dict)
        self.assertEqual(self.host._run_command.call_args_list,
                         expected_cmd_arg_list)

    def test_power_action(self):
        temp_arg_dict = {'host_uuid': 'fake_host_uuid'}
        self.host._run_command.return_value = None
        cmds = {"reboot": "host-reboot",
                "startup": "host-power-on",
                "shutdown": "host-shutdown"}
        fake_action = 'reboot'  # 'statup' and 'shutdown' should be same
        expected_cmd_arg_list = [call(["xe", "host-disable", "uuid=%s"
                                      % 'fake_host_uuid']),
                                 call(["xe", "vm-shutdown", "--multiple",
                                      "resident-on=%s" % 'fake_host_uuid']),
                                 call(["xe", cmds[fake_action], "uuid=%s" %
                                      'fake_host_uuid'])]
        expected_result = {"power_action": fake_action}

        action_result = self.host._power_action(fake_action, temp_arg_dict)
        self.assertEqual(self.host._run_command.call_args_list,
                         expected_cmd_arg_list)
        self.assertEqual(action_result, expected_result)

    def test_host_reboot(self):
        fake_action = 'reboot'
        self.mock_patch_object(self.host,
                               '_power_action',
                               'fake_action_result')
        self.host.host_reboot(self.host, 'fake_arg_dict')

        self.host._power_action.assert_called_with(fake_action,
                                                   'fake_arg_dict')

    def test_host_shutdown(self):
        fake_action = 'shutdown'
        self.mock_patch_object(self.host,
                               '_power_action',
                               'fake_action_result')
        self.host.host_shutdown(self.host, 'fake_arg_dict')

        self.host._power_action.assert_called_with(fake_action,
                                                   'fake_arg_dict')

    def test_host_start(self):
        fake_action = 'startup'
        self.mock_patch_object(self.host,
                               '_power_action',
                               'fake_action_result')
        self.host.host_start(self.host, 'fake_arg_dict')

        self.host._power_action.assert_called_with(fake_action,
                                                   'fake_arg_dict')

    def test_host_join(self):
        temp_arg_dict = {'url': 'fake_url',
                         'user': 'fake_user',
                         'password': 'fake_password',
                         'master_addr': 'fake_master_addr',
                         'master_user': 'fake_master_user',
                         'master_pass': 'fake_master_pass',
                         'compute_uuid': 'fake_compute_uuid'}
        self.mock_patch_object(self.host, '_resume_compute')
        self.host.XenAPI = mock.Mock()
        self.host.XenAPI.Session = mock.Mock()

        self.host.host_join(self.host, temp_arg_dict)
        self.host.XenAPI.Session().login_with_password.assert_called_once()
        self.host.XenAPI.Session().xenapi.pool.join.assert_called_with(
            'fake_master_addr',
            'fake_master_user',
            'fake_master_pass')
        self.host._resume_compute.assert_called_with(
            self.host.XenAPI.Session(),
            self.host.XenAPI.Session().xenapi.VM.get_by_uuid(
                'fake_compute_uuid'),
            'fake_compute_uuid')

    def test_host_join_force_join(self):
        temp_arg_dict = {'force': 'true',
                         'master_addr': 'fake_master_addr',
                         'master_user': 'fake_master_user',
                         'master_pass': 'fake_master_pass',
                         'compute_uuid': 'fake_compute_uuid'}
        self.mock_patch_object(self.host, '_resume_compute')
        self.host.XenAPI = mock.Mock()
        self.host.XenAPI.Session = mock.Mock()

        self.host.host_join(self.host, temp_arg_dict)
        self.host.XenAPI.Session().login_with_password.assert_called_once()
        self.host.XenAPI.Session().xenapi.pool.join_force.assert_called_with(
            'fake_master_addr',
            'fake_master_user',
            'fake_master_pass')
        self.host._resume_compute.assert_called_with(
            self.host.XenAPI.Session(),
            self.host.XenAPI.Session().xenapi.VM.get_by_uuid(
                'fake_compute_uuid'),
            'fake_compute_uuid')

    def test_host_data(self):
        temp_arg_dict = {'host_uuid': 'fake_host_uuid'}
        fake_dict_after_cleanup = {'new_key': 'new_value'}
        fake_config_setting = {'config': 'fake_config_setting'}
        self.host._run_command.return_value = 'fake_resp'
        self.mock_patch_object(self.host,
                               'parse_response',
                               'fake_parsed_data')
        self.mock_patch_object(self.host,
                               'cleanup',
                               fake_dict_after_cleanup)
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               fake_config_setting)
        expected_ret_dict = fake_dict_after_cleanup
        expected_ret_dict.update(fake_config_setting)

        return_host_data = self.host.host_data(self.host,
                                               temp_arg_dict)
        self.host._run_command.assert_called_with(
            ["xe", "host-param-list", "uuid=%s" % temp_arg_dict['host_uuid']]
        )
        self.host.parse_response.assert_called_with('fake_resp')
        self.host.cleanup('fake_parsed_data')
        self.host._get_config_dict.assert_called_once()
        self.assertEqual(expected_ret_dict, json.loads(return_host_data))

    def test_parse_response(self):
        fake_resp = 'fake_name ( fake_flag): fake_value'
        expected_parsed_resp = {'fake_name': 'fake_value'}
        result_data = self.host.parse_response(fake_resp)
        self.assertEqual(result_data, expected_parsed_resp)

    def test_parse_response_one_invalid_line(self):
        fake_resp = "(exeception line)\n \
                     fake_name ( fake_flag): fake_value"
        expected_parsed_resp = {'fake_name': 'fake_value'}

        result_data = self.host.parse_response(fake_resp)
        self.assertEqual(result_data, expected_parsed_resp)

    def test_host_uptime(self):
        self.host._run_command.return_value = 'fake_uptime'
        uptime_return = self.host.host_uptime(self.host, 'fake_arg_dict')

        self.assertEqual(uptime_return, '{"uptime": "fake_uptime"}')


class ConfigOptTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(ConfigOptTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")
        self.mock_patch_object(self.host,
                               '_run_command',
                               'fake_run_cmd_return')

    def test_get_config_no_config_key(self):
        temp_dict = {'params': '{"key": "fake_key"}'}
        fake_conf_dict = {}
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               fake_conf_dict)

        config_return = self.host.get_config(self.host, temp_dict)
        self.assertEqual(json.loads(config_return), "None")
        self.host._get_config_dict.assert_called_once()

    def test_get_config_json(self):
        temp_dict = {'params': '{"key": "fake_key"}'}
        fake_conf_dict = {'fake_key': 'fake_conf_key'}
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               fake_conf_dict)
        config_return = self.host.get_config(self.host, temp_dict)
        self.assertEqual(json.loads(config_return), 'fake_conf_key')
        self.host._get_config_dict.assert_called_once()

    def test_get_config_dict(self):
        temp_dict = {'params': {"key": "fake_key"}}
        fake_conf_dict = {'fake_key': 'fake_conf_key'}
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               fake_conf_dict)
        config_return = self.host.get_config(self.host, temp_dict)
        self.assertEqual(json.loads(config_return), 'fake_conf_key')
        self.host._get_config_dict.assert_called_once()

    def test_set_config_remove_none_key(self):
        temp_arg_dict = {'params': {"key": "fake_key", "value": None}}
        temp_conf = {'fake_key': 'fake_value'}
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               temp_conf)
        self.mock_patch_object(self.host,
                               '_write_config_dict')

        self.host.set_config(self.host, temp_arg_dict)
        self.assertTrue("fake_key" not in temp_conf)
        self.host._get_config_dict.assert_called_once()
        self.host._write_config_dict.assert_called_with(temp_conf)

    def test_set_config_overwrite_key_value(self):
        temp_arg_dict = {'params': {"key": "fake_key", "value": "new_value"}}
        temp_conf = {'fake_key': 'fake_value'}
        self.mock_patch_object(self.host,
                               '_get_config_dict',
                               temp_conf)
        self.mock_patch_object(self.host,
                               '_write_config_dict')

        self.host.set_config(self.host, temp_arg_dict)
        self.assertTrue('fake_key' in temp_conf)
        self.host._get_config_dict.assert_called_once()
        temp_conf.update({'fake_key': 'new_value'})
        self.host._write_config_dict.assert_called_with(temp_conf)


class NetworkTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(NetworkTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")
        self.mock_patch_object(self.host,
                               '_run_command',
                               'fake_run_cmd_return')

    def test_ovs_add_patch_port(self):
        brige_name = 'fake_brige_name'
        port_name = 'fake_port_name'
        peer_port_name = 'fake_peer_port_name'
        side_effects = [brige_name, port_name, peer_port_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ovs-vsctl', '--', '--if-exists', 'del-port',
                             port_name, '--', 'add-port', brige_name,
                             'fake_port_name', '--', 'set', 'interface',
                             'fake_port_name', 'type=patch',
                             'options:peer=%s' % peer_port_name]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'port_name'),
                                       call('fake_args', 'peer_port_name')]

        self.host._ovs_add_patch_port('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ovs_del_port(self):
        bridge_name = 'fake_brige_name'
        port_name = 'fake_port_name'
        side_effects = [bridge_name, port_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ovs-vsctl', '--', '--if-exists', 'del-port',
                             bridge_name, port_name]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'port_name')]

        self.host._ovs_del_port('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ovs_del_br(self):
        bridge_name = 'fake_brige_name'
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               bridge_name)
        expected_cmd_args = ['ovs-vsctl', '--', '--if-exists',
                             'del-br', bridge_name]

        self.host._ovs_del_br('fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'bridge_name')
        self.host._run_command.assert_called_with(expected_cmd_args)

    def test_ovs_set_if_external_id(self):
        interface = 'fake_interface'
        extneral_id = 'fake_extneral_id'
        value = 'fake_value'
        side_effects = [interface, extneral_id, value]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ovs-vsctl', 'set', 'Interface', interface,
                             'external-ids:%s=%s' % (extneral_id, value)]
        expected_pluginlib_arg_list = [call('fake_args', 'interface'),
                                       call('fake_args', 'extneral_id'),
                                       call('fake_args', 'value')]

        self.host._ovs_set_if_external_id('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ovs_add_port(self):
        bridge_name = 'fake_brige_name'
        port_name = 'fake_port_name'
        side_effects = [bridge_name, port_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ovs-vsctl', '--', '--if-exists', 'del-port',
                             port_name, '--', 'add-port', bridge_name,
                             port_name]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'port_name')]

        self.host._ovs_add_port('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ovs_create_port(self):
        bridge_name = 'fake_brige_name'
        port_name = 'fake_port_name'
        iface_id = 'fake_iface_id'
        mac = 'fake_mac'
        status = 'fake_status'
        side_effects = [bridge_name, port_name, iface_id, mac, status]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ovs-vsctl', '--', '--if-exists', 'del-port',
                             port_name, '--', 'add-port', bridge_name,
                             port_name, '--', 'set', 'Interface', port_name,
                             'external_ids:iface-id=%s' % iface_id,
                             'external_ids:iface-status=%s' % status,
                             'external_ids:attached-mac=%s' % mac,
                             'external_ids:xs-vif-uuid=%s' % iface_id]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge'),
                                       call('fake_args', 'port'),
                                       call('fake_args', 'iface-id'),
                                       call('fake_args', 'mac'),
                                       call('fake_args', 'status')]

        self.host._ovs_create_port('fake_args')
        self.pluginlib.exists.assert_called()
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ip_link_get_dev(self):
        device_name = 'fake_device_name'
        expected_cmd_args = ['ip', 'link', 'show', device_name]
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               device_name)

        self.host._ip_link_get_dev('fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'device_name')
        self.host._run_command.assert_called_with(expected_cmd_args)

    def test_ip_link_del_dev(self):
        device_name = 'fake_device_name'
        expected_cmd_args = ['ip', 'link', 'delete', device_name]
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               'fake_device_name')

        self.host._ip_link_del_dev('fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'device_name')
        self.host._run_command.assert_called_with(expected_cmd_args)

    def test_ip_link_add_veth_pair(self):
        dev1_name = 'fake_brige_name'
        dev2_name = 'fake_port_name'
        side_effects = [dev1_name, dev2_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ip', 'link', 'add', dev1_name, 'type',
                             'veth', 'peer', 'name', dev2_name]
        expected_pluginlib_arg_list = [call('fake_args', 'dev1_name'),
                                       call('fake_args', 'dev2_name')]

        self.host._ip_link_add_veth_pair('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ip_link_set_dev(self):
        device_name = 'fake_device_name'
        option = 'fake_option'
        side_effects = [device_name, option]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ip', 'link', 'set', device_name, option]
        expected_pluginlib_arg_list = [call('fake_args', 'device_name'),
                                       call('fake_args', 'option')]

        self.host._ip_link_set_dev('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_ip_link_set_promisc(self):
        device_name = 'fake_device_name'
        option = 'fake_option'
        side_effects = [device_name, option]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['ip', 'link', 'set', device_name, 'promisc',
                             option]
        expected_pluginlib_arg_list = [call('fake_args', 'device_name'),
                                       call('fake_args', 'option')]

        self.host._ip_link_set_promisc('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_brctl_add_br(self):
        bridge_name = 'fake_bridge_name'
        cmd_args = 'fake_option'
        side_effects = [bridge_name, cmd_args]
        self.pluginlib.exists.side_effect = side_effects
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               bridge_name)
        expected_cmd_args = ['brctl', 'addbr', bridge_name]

        self.host._brctl_add_br('fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'bridge_name')
        self.host._run_command.assert_called_with(expected_cmd_args)

    def test_brctl_del_br(self):
        bridge_name = 'fake_bridge_name'
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               bridge_name)
        expected_cmd_args = ['brctl', 'delbr', bridge_name]

        self.host._brctl_del_br('fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'bridge_name')
        self.host._run_command.assert_called_with(expected_cmd_args)

    def test_brctl_set_fd(self):
        bridge_name = 'fake_device_name'
        fd = 'fake_fd'
        side_effects = [bridge_name, fd]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['brctl', 'setfd', bridge_name, fd]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'fd')]

        self.host._brctl_set_fd('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_brctl_set_stp(self):
        bridge_name = 'fake_device_name'
        option = 'fake_option'
        side_effects = [bridge_name, option]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['brctl', 'stp', bridge_name, option]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'option')]

        self.host._brctl_set_stp('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_brctl_add_if(self):
        bridge_name = 'fake_device_name'
        if_name = 'fake_if_name'
        side_effects = [bridge_name, if_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['brctl', 'addif', bridge_name, if_name]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'interface_name')]

        self.host._brctl_add_if('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    def test_brctl_del_if(self):
        bridge_name = 'fake_device_name'
        if_name = 'fake_if_name'
        side_effects = [bridge_name, if_name]
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        expected_cmd_args = ['brctl', 'delif', bridge_name, if_name]
        expected_pluginlib_arg_list = [call('fake_args', 'bridge_name'),
                                       call('fake_args', 'interface_name')]

        self.host._brctl_del_if('fake_args')
        self.host._run_command.assert_called_with(expected_cmd_args)
        self.assertEqual(self.pluginlib.exists.call_args_list,
                         expected_pluginlib_arg_list)

    @mock.patch.object(json, 'loads')
    def test_iptables_config(self, mock_json_loads):
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               'fake_cmd_args')
        self.mock_patch_object(self.pluginlib,
                               'optional',
                               'fake_cmd_pro_input')
        self.host._run_command.return_value = 'fake_run_cmd_resule'
        mock_json_loads.return_value = ['iptables-save']
        expected = json.dumps(dict(out='fake_run_cmd_resule', err=''))

        ret_str = self.host.iptables_config('fake_session', 'fake_args')
        self.pluginlib.exists.assert_called_once()
        self.pluginlib.optional.assert_called_once()
        mock_json_loads.assert_called_with('fake_cmd_args')
        self.assertEqual(ret_str, expected)
        self.host._run_command.assert_called_with(
            map(str, ['iptables-save']), 'fake_cmd_pro_input')

    @mock.patch.object(json, 'loads')
    def test_iptables_config_plugin_error(self, mock_json_loads):
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.mock_patch_object(self.pluginlib,
                               'optional')

        self.assertRaises(self.pluginlib.PluginError,
                          self.host.iptables_config,
                          'fake_session', 'fake_args')
        self.pluginlib.exists.assert_called_once()
        self.pluginlib.optional.assert_called_once()
        mock_json_loads.assert_called_with(None)

    def test_network_config_invalid_cmd(self):
        fake_invalid_cmd = 0
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               fake_invalid_cmd)

        self.assertRaises(self.pluginlib.PluginError,
                          self.host.network_config,
                          'fake_session', 'fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'cmd')

    def test_network_config_unexpected_cmd(self):
        fake_unexpected_cmd = 'fake_unknow_cmd'
        self.mock_patch_object(self.pluginlib,
                               'exists',
                               fake_unexpected_cmd)

        self.assertRaises(self.pluginlib.PluginError,
                          self.host.network_config,
                          'fake_session', 'fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'cmd')

    def test_network_config(self):
        fake_valid_cmd = 'ovs_add_patch_port'
        side_effects = [fake_valid_cmd, 'fake_cmd_args']
        self.mock_patch_object(self.pluginlib,
                               'exists')
        self.pluginlib.exists.side_effect = side_effects
        mock_func = self.mock_patch_object(self.host,
                                           '_ovs_add_patch_port')
        self.host.ALLOWED_NETWORK_CMDS['ovs_add_patch_port'] = mock_func

        self.host.network_config('fake_session', 'fake_args')
        self.pluginlib.exists.assert_called_with('fake_args', 'args')
        self.host._ovs_add_patch_port.assert_called_with('fake_cmd_args')


class XenHostTestCase(plugin_test.PluginTestBase):
    def setUp(self):
        super(XenHostTestCase, self).setUp()
        self.host = self.load_plugin("xenhost.py")
        self.pluginlib = self.load_plugin("dom0_pluginlib.py")
        self.mock_patch_object(self.host,
                               '_run_command',
                               'fake_run_cmd_return')

    def test_clean_up(self):
        fake_arg_dict = {
            'enabled': 'enabled',
            'memory-total': '0',
            'memory-overhead': '1',
            'memory-free': '2',
            'memory-free-computed': '3',
            'uuid': 'fake_uuid',
            'name-label': 'fake_name-label',
            'name-description': 'fake_name-description',
            'hostname': 'fake_hostname',
            'address': 'fake_address',
            'other-config': 'config:fake_other-config_1; \
             config:fake_other-config_2',
            'capabilities': 'fake_cap_1; fake_cap_2',
            'cpu_info': 'cpu_count:1; family:101; unknow:1'
        }
        expected_out = {
            'enabled': 'enabled',
            'host_memory': {'total': 0,
                            'overhead': 1,
                            'free': 2,
                            'free-computed': 3},
            'host_uuid': 'fake_uuid',
            'host_name-label': 'fake_name-label',
            'host_name-description': 'fake_name-description',
            'host_hostname': 'fake_hostname',
            'host_ip_address': 'fake_address',
            'host_other-config': {'config': 'fake_other-config_1',
                                  'config': 'fake_other-config_2'},
            'host_capabilities': ['fake_cap_1', 'fake_cap_2'],
            'host_cpu_info': {'cpu_count': 1, 'family': 101,
                              'unknow': '1'}
        }

        out = self.host.cleanup(fake_arg_dict)
        self.assertEqual(out, expected_out)

    def test_clean_up_exception_invalid_memory_value(self):
        fake_arg_dict = {
            'enabled': 'enabled',
            'memory-total': 'invalid',
            'memory-overhead': 'invalid',
            'memory-free': 'invalid',
            'memory-free-computed': 'invalid',
            'uuid': 'fake_uuid',
            'name-label': 'fake_name-label',
            'name-description': 'fake_name-description',
            'hostname': 'fake_hostname',
            'address': 'fake_address',
            'other-config': 'config:fake_other-config_1; \
             config:fake_other-config_2',
            'capabilities': 'fake_cap_1; fake_cap_2',
            'cpu_info': 'cpu_count:1; family:101; unknow:1'
        }
        expected_out = {
            'enabled': 'enabled',
            'host_memory': {'total': None,
                            'overhead': None,
                            'free': None,
                            'free-computed': None},
            'host_uuid': 'fake_uuid',
            'host_name-label': 'fake_name-label',
            'host_name-description': 'fake_name-description',
            'host_hostname': 'fake_hostname',
            'host_ip_address': 'fake_address',
            'host_other-config': {'config': 'fake_other-config_1',
                                  'config': 'fake_other-config_2'},
            'host_capabilities': ['fake_cap_1', 'fake_cap_2'],
            'host_cpu_info': {'cpu_count': 1, 'family': 101,
                              'unknow': '1'}
        }

        out = self.host.cleanup(fake_arg_dict)
        self.assertEqual(out, expected_out)

    def test_query_gc_running(self):
        fake_cmd_result = "Currently running: True"
        self.host._run_command.return_value = fake_cmd_result
        query_gc_result = self.host.query_gc('fake_session',
                                             'fake_sr_uuid',
                                             'fake_vdi_uuid')
        self.assertTrue(query_gc_result)
        self.host._run_command.assert_called_with(
            ["/opt/xensource/sm/cleanup.py",
             "-q", "-u", 'fake_sr_uuid'])

    def test_query_gc_not_running(self):
        fake_cmd_result = "Currently running: False"
        self.host._run_command.return_value = fake_cmd_result
        query_gc_result = self.host.query_gc('fake_session',
                                             'fake_sr_uuid',
                                             'fake_vdi_uuid')
        self.assertFalse(query_gc_result)
        self.host._run_command.assert_called_with(
            ["/opt/xensource/sm/cleanup.py",
             "-q", "-u", 'fake_sr_uuid'])

    def test_get_pci_device_details(self):
        self.host.get_pci_device_details('fake_session')
        self.host._run_command.assert_called_with(
            ["lspci", "-vmmnk"])

    def test_get_pci_type_no_domain(self):
        fake_pci_device = '00:00.0'
        self.host._run_command.return_value = ['fake_pci_type', ]

        self.host.get_pci_type('fake_session', fake_pci_device)
        self.host._run_command.assert_called_with(
            ["ls", "/sys/bus/pci/devices/" + '0000:'
             + fake_pci_device + "/"])

    def test_get_pci_type_physfn(self):
        fake_pci_device = '0000:00:00.0'
        self.host._run_command.return_value = ['physfn', ]

        output = self.host.get_pci_type('fake_session', fake_pci_device)
        self.host._run_command.assert_called_with(
            ["ls", "/sys/bus/pci/devices/" + fake_pci_device + "/"])
        self.assertEqual(output, 'type-VF')

    def test_get_pci_type_virtfn(self):
        fake_pci_device = '0000:00:00.0'
        self.host._run_command.return_value = ['virtfn', ]

        output = self.host.get_pci_type('fake_session', fake_pci_device)
        self.host._run_command.assert_called_with(
            ["ls", "/sys/bus/pci/devices/" + fake_pci_device + "/"])
        self.assertEqual(output, 'type-PF')

    def test_get_pci_type_PCI(self):
        fake_pci_device = '0000:00:00.0'
        self.host._run_command.return_value = ['other', ]

        output = self.host.get_pci_type('fake_session', fake_pci_device)
        self.host._run_command.assert_called_with(
            ["ls", "/sys/bus/pci/devices/" + fake_pci_device + "/"])
        self.assertEqual(output, 'type-PCI')