Debian Codegraph @

ansible_collections/community/libvirt/tests/unit/module_utils/test_virt_install.py

raw
1 # -*- coding: utf-8 -*-
2 #
3 # (c) 2025, Joey Zhang <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import unittest
7 import tempfile
8 import shutil
9
10 from ansible_collections.community.libvirt.tests.unit.compat import mock
11 from ansible_collections.community.libvirt.plugins.module_utils.virt_install import (
12 _dict2options, _get_option_mapping, OPTION_BOOL_ONOFF, VirtInstallTool)
13
14
15 class TestDict2Options(unittest.TestCase):
16
17 def test_none_input(self):
18 """Test that None input returns empty string"""
19 result = _dict2options(None, None)
20 self.assertEqual(result, "")
21
22 def test_non_dict_input(self):
23 """Test that non-dict input returns string representation"""
24 self.assertEqual(_dict2options(42, None), "42")
25 self.assertEqual(_dict2options("test", None), "test")
26 self.assertEqual(_dict2options(True, None), "True")
27
28 def test_empty_dict(self):
29 """Test that empty dict returns 'none'"""
30 result = _dict2options({}, None)
31 self.assertEqual(result, "")
32
33 def test_simple_dict_no_mapping(self):
34 """Test simple dictionary without mapping"""
35 obj = {"memory": 2048, "vcpus": 4}
36 result = _dict2options(obj, None)
37 # Order might vary, so check both possibilities
38 self.assertIn(result, ["memory=2048,vcpus=4", "vcpus=4,memory=2048"])
39
40 def test_simple_dict_with_mapping(self):
41 """Test simple dictionary with mapping"""
42 obj = {"current_memory": 512}
43 mapping = {"current_memory": ("currentMemory", None)}
44 result = _dict2options(obj, mapping)
45 self.assertEqual(result, "currentMemory=512")
46
47 def test_mapping_with_none_name(self):
48 """Test mapping where name is None (should use original key)"""
49 obj = {"test_key": "value"}
50 mapping = {"test_key": (None, None)}
51 result = _dict2options(obj, mapping)
52 self.assertEqual(result, "test_key=value")
53
54 def test_bool_values_default(self):
55 """Test boolean values with default handling"""
56 obj = {"enabled": True, "disabled": False}
57 result = _dict2options(obj, None)
58 self.assertIn(result,
59 ["enabled=yes,disabled=no",
60 "disabled=no,enabled=yes"])
61
62 def test_bool_values_with_onoff_mapping(self):
63 """Test boolean values with OPTION_BOOL_ONOFF mapping"""
64 obj = {"enabled": True, "disabled": False}
65 mapping = {
66 "enabled": (None, OPTION_BOOL_ONOFF),
67 "disabled": (None, OPTION_BOOL_ONOFF)
68 }
69 result = _dict2options(obj, mapping)
70 self.assertIn(result,
71 ["enabled=on,disabled=off",
72 "disabled=off,enabled=on"])
73
74 def test_nested_dict(self):
75 """Test nested dictionary"""
76 obj = {"install": {"no_install": True}}
77 result = _dict2options(obj, None)
78 self.assertEqual(result, "install.no_install=yes")
79
80 def test_deeply_nested_dict_with_mapping(self):
81 """Test deeply nested dict with complex mapping"""
82 obj = {"suspend_to_disk": {"enabled": False}}
83 mapping = {
84 "suspend_to_disk": (None, {"enabled": (None, OPTION_BOOL_ONOFF)})
85 }
86 result = _dict2options(obj, mapping)
87 self.assertEqual(result, "suspend_to_disk.enabled=off")
88
89 def test_list_with_simple_values(self):
90 """Test list with simple values"""
91 obj = {"devices": ["dev1", "dev2", "dev3"]}
92 result = _dict2options(obj, None)
93 self.assertEqual(result, "devices0=dev1,devices1=dev2,devices2=dev3")
94
95 def test_list_with_boolean_values(self):
96 """Test list with boolean values (default handling)"""
97 obj = {"flags": [True, False, True]}
98 result = _dict2options(obj, None)
99 self.assertEqual(result, "flags0=yes,flags1=no,flags2=yes")
100
101 def test_list_with_boolean_values_onoff(self):
102 """Test list with boolean values (OPTION_BOOL_ONOFF handling)"""
103 obj = {"flags": [True, False]}
104 mapping = {"flags": (None, OPTION_BOOL_ONOFF)}
105 result = _dict2options(obj, mapping)
106 self.assertEqual(result, "flags0=on,flags1=off")
107
108 def test_list_with_dict_items(self):
109 """Test list containing dictionary items"""
110 obj = {"devices": [{"name": "dev1", "enabled": True}, {
111 "name": "dev2", "enabled": False}]}
112 result = _dict2options(obj, None)
113 expected_parts = [
114 "devices0.name=dev1",
115 "devices0.enabled=yes",
116 "devices1.name=dev2",
117 "devices1.enabled=no"]
118 for part in expected_parts:
119 self.assertIn(part, result)
120
121 def test_list_with_dict_items_and_mapping(self):
122 """Test list with dict items and mapping"""
123 obj = {"vcpu_specs": [{"id": 0, "enabled": True}]}
124 mapping = {
125 "vcpu_specs": (
126 "vcpus.vcpu", {
127 "enabled": (
128 None, OPTION_BOOL_ONOFF)})}
129 result = _dict2options(obj, mapping)
130 self.assertIn("vcpus.vcpu0.id=0", result)
131 self.assertIn("vcpus.vcpu0.enabled=on", result)
132
133 def test_complex_nested_structure(self):
134 """Test complex nested structure with multiple levels"""
135 obj = {
136 "cpu": {
137 "model": "host-passthrough",
138 "features": {
139 "vmx": {"policy": "require"},
140 "svm": {"policy": "disable"}
141 }
142 }
143 }
144 result = _dict2options(obj, None)
145 expected_parts = [
146 "cpu.model=host-passthrough",
147 "cpu.features.vmx.policy=require",
148 "cpu.features.svm.policy=disable"
149 ]
150 for part in expected_parts:
151 self.assertIn(part, result)
152
153 def test_mixed_types_in_dict(self):
154 """Test dictionary with mixed value types"""
155 obj = {
156 "name": "test-vm",
157 "memory": 2048,
158 "enabled": True,
159 "config": {"debug": False},
160 "devices": ["dev1", "dev2"]
161 }
162 result = _dict2options(obj, None)
163
164 expected_substrings = [
165 "name=test-vm",
166 "memory=2048",
167 "enabled=yes",
168 "config.debug=no",
169 "devices0=dev1",
170 "devices1=dev2"
171 ]
172
173 for substring in expected_substrings:
174 self.assertIn(substring, result)
175
176 def test_memory_options_example(self):
177 """Test example from virt-install memory options"""
178 obj = {
179 "memory": 2048,
180 "currentMemory": 1024,
181 "maxMemory": 4096,
182 "hugepages": True
183 }
184 mapping = {
185 "currentMemory": ("currentMemory", None),
186 "maxMemory": ("maxMemory", None),
187 "hugepages": (None, OPTION_BOOL_ONOFF)
188 }
189 result = _dict2options(obj, mapping)
190
191 expected_parts = [
192 "memory=2048",
193 "currentMemory=1024",
194 "maxMemory=4096",
195 "hugepages=on"
196 ]
197
198 for part in expected_parts:
199 self.assertIn(part, result)
200
201 def test_cpu_features_example(self):
202 """Test CPU features with policy mapping"""
203 obj = {
204 "features": {
205 "vmx": {"policy": "require"},
206 "lahf_lm": {"policy": "disable"}
207 }
208 }
209 result = _dict2options(obj, None)
210
211 expected_parts = [
212 "features.vmx.policy=require",
213 "features.lahf_lm.policy=disable"
214 ]
215
216 for part in expected_parts:
217 self.assertIn(part, result)
218
219 def test_pm_options_example(self):
220 """Test PM options from documentation example"""
221 obj = {
222 "suspend_to_mem": {"enabled": True},
223 "suspend_to_disk": {"enabled": False}
224 }
225 mapping = {
226 "suspend_to_mem": (None, {"enabled": (None, OPTION_BOOL_ONOFF)}),
227 "suspend_to_disk": (None, {"enabled": (None, OPTION_BOOL_ONOFF)})
228 }
229 result = _dict2options(obj, mapping)
230
231 expected_parts = [
232 "suspend_to_mem.enabled=on",
233 "suspend_to_disk.enabled=off"
234 ]
235
236 for part in expected_parts:
237 self.assertIn(part, result)
238
239 def test_get_option_mapping_helper(self):
240 """Test the _get_option_mapping helper function"""
241 # Test with None mapping
242 name, valmap = _get_option_mapping("test", None)
243 self.assertEqual(name, "test")
244 self.assertIsNone(valmap)
245
246 # Test with mapping but key not found
247 mapping = {"other_key": ("other", None)}
248 name, valmap = _get_option_mapping("test", mapping)
249 self.assertEqual(name, "test")
250 self.assertIsNone(valmap)
251
252 # Test with mapping and key found
253 mapping = {"test": ("mapped_name", "mapped_value")}
254 name, valmap = _get_option_mapping("test", mapping)
255 self.assertEqual(name, "mapped_name")
256 self.assertEqual(valmap, "mapped_value")
257
258 # Test with mapping where name is None
259 mapping = {"test": (None, "mapped_value")}
260 name, valmap = _get_option_mapping("test", mapping)
261 self.assertEqual(name, "test")
262 self.assertEqual(valmap, "mapped_value")
263
264 def test_prefix_handling(self):
265 """Test prefix handling in recursive calls"""
266 obj = {"level1": {"level2": {"value": "test"}}}
267 result = _dict2options(obj, None, prefix="root.")
268 self.assertEqual(result, "root.level1.level2=test")
269
270 def test_numeric_values(self):
271 """Test various numeric value types"""
272 obj = {
273 "int_val": 42,
274 "float_val": 3.14,
275 "zero": 0,
276 "negative": -5
277 }
278 result = _dict2options(obj, None)
279
280 expected_parts = [
281 "int_val=42",
282 "float_val=3.14",
283 "zero=0",
284 "negative=-5"
285 ]
286
287 for part in expected_parts:
288 self.assertIn(part, result)
289
290
291 class TestPrimaryValueFeature(unittest.TestCase):
292 """Test the primary value feature (value/_value attribute)"""
293
294 def test_value_at_root_level_only(self):
295 """Test primary value alone at root level"""
296 obj = {"value": "primary"}
297 result = _dict2options(obj, None)
298 self.assertEqual(result, "primary")
299
300 def test_value_at_root_level_with_other_properties(self):
301 """Test primary value with other properties at root level"""
302 obj = {"value": "primary", "prop1": "val1", "prop2": "val2"}
303 result = _dict2options(obj, None)
304 # Primary value should come first
305 self.assertTrue(result.startswith("primary,"))
306 self.assertIn("prop1=val1", result)
307 self.assertIn("prop2=val2", result)
308
309 def test_value_with_prefix_only(self):
310 """Test primary value with prefix, no other properties"""
311 obj = {"nested": {"value": "test"}}
312 result = _dict2options(obj, None)
313 self.assertEqual(result, "nested=test")
314
315 def test_value_with_prefix_and_properties(self):
316 """Test primary value with prefix and other properties"""
317 obj = {"nested": {"value": "primary", "prop1": "val1"}}
318 result = _dict2options(obj, None)
319 # Should be: nested=primary,nested.prop1=val1
320 self.assertIn("nested=primary", result)
321 self.assertIn("nested.prop1=val1", result)
322
323 def test_underscore_value_takes_precedence(self):
324 """Test that _value takes precedence over value"""
325 obj = {"_value": "underscore", "value": "regular", "prop": "test"}
326 result = _dict2options(obj, None)
327 # _value should be used as primary, not value
328 self.assertTrue(result.startswith("underscore,"))
329 self.assertIn("prop=test", result)
330 # When _value is present, "value" is treated as a regular property
331 self.assertIn("value=regular", result)
332
333 def test_only_underscore_value(self):
334 """Test _value alone"""
335 obj = {"_value": "underscore_primary"}
336 result = _dict2options(obj, None)
337 self.assertEqual(result, "underscore_primary")
338
339 def test_value_empty_string(self):
340 """Test empty string as primary value"""
341 obj = {"value": "", "prop": "test"}
342 result = _dict2options(obj, None)
343 # Empty string should still be treated as a primary value
344 self.assertTrue(result.startswith(","))
345 self.assertIn("prop=test", result)
346
347 def test_value_numeric(self):
348 """Test numeric value as primary"""
349 obj = {"value": 123, "prop": "test"}
350 result = _dict2options(obj, None)
351 self.assertTrue(result.startswith("123,"))
352 self.assertIn("prop=test", result)
353
354 def test_value_boolean_true(self):
355 """Test boolean True as primary value"""
356 obj = {"value": True, "prop": "test"}
357 result = _dict2options(obj, None)
358 self.assertTrue(result.startswith("True,"))
359 self.assertIn("prop=test", result)
360
361 def test_value_boolean_false(self):
362 """Test boolean False as primary value"""
363 obj = {"value": False, "prop": "test"}
364 result = _dict2options(obj, None)
365 self.assertTrue(result.startswith("False,"))
366 self.assertIn("prop=test", result)
367
368 def test_value_none_should_be_skipped(self):
369 """Test None as primary value - should be treated as no value"""
370 obj = {"value": None, "prop": "test"}
371 result = _dict2options(obj, None)
372 # None should result in empty primary value
373 self.assertEqual(result, "prop=test")
374
375 def test_value_with_nested_dict(self):
376 """Test primary value with nested dictionary"""
377 obj = {"value": "primary", "nested": {"key": "val"}}
378 result = _dict2options(obj, None)
379 self.assertTrue(result.startswith("primary,"))
380 self.assertIn("nested.key=val", result)
381
382 def test_value_in_deeply_nested_structure(self):
383 """Test primary value in deeply nested structure"""
384 obj = {
385 "level1": {
386 "level2": {
387 "value": "deep_primary",
388 "prop": "test"
389 }
390 }
391 }
392 result = _dict2options(obj, None)
393 self.assertIn("level1.level2=deep_primary", result)
394 self.assertIn("level1.level2.prop=test", result)
395
396 def test_multiple_nested_values(self):
397 """Test multiple nested dictionaries each with value"""
398 obj = {
399 "section1": {"value": "primary1", "prop1": "val1"},
400 "section2": {"value": "primary2", "prop2": "val2"}
401 }
402 result = _dict2options(obj, None)
403 self.assertIn("section1=primary1", result)
404 self.assertIn("section1.prop1=val1", result)
405 self.assertIn("section2=primary2", result)
406 self.assertIn("section2.prop2=val2", result)
407
408 def test_value_with_list_of_strings(self):
409 """Test primary value with list of strings"""
410 obj = {"value": "primary", "items": ["a", "b", "c"]}
411 result = _dict2options(obj, None)
412 self.assertTrue(result.startswith("primary,"))
413 self.assertIn("items0=a", result)
414 self.assertIn("items1=b", result)
415 self.assertIn("items2=c", result)
416
417 def test_value_with_list_of_dicts(self):
418 """Test primary value with list of dictionaries"""
419 obj = {
420 "value": "primary",
421 "items": [
422 {"name": "item1", "enabled": True},
423 {"name": "item2", "enabled": False}
424 ]
425 }
426 result = _dict2options(obj, None)
427 self.assertTrue(result.startswith("primary,"))
428 self.assertIn("items0.name=item1", result)
429 self.assertIn("items0.enabled=yes", result)
430 self.assertIn("items1.name=item2", result)
431 self.assertIn("items1.enabled=no", result)
432
433 def test_list_items_with_value_attribute(self):
434 """Test list where items themselves have value attribute"""
435 obj = {
436 "items": [
437 {"value": "primary1", "prop": "val1"},
438 {"value": "primary2", "prop": "val2"}
439 ]
440 }
441 result = _dict2options(obj, None)
442 # Each list item's primary value should be formatted correctly
443 self.assertIn("items0=primary1", result)
444 self.assertIn("items0.prop=val1", result)
445 self.assertIn("items1=primary2", result)
446 self.assertIn("items1.prop=val2", result)
447
448 def test_value_with_boolean_default_mapping(self):
449 """Test primary value with boolean using default yes/no mapping"""
450 obj = {"value": "primary", "enabled": True, "disabled": False}
451 result = _dict2options(obj, None)
452 self.assertTrue(result.startswith("primary,"))
453 self.assertIn("enabled=yes", result)
454 self.assertIn("disabled=no", result)
455
456 def test_value_with_boolean_onoff_mapping(self):
457 """Test primary value with boolean using on/off mapping"""
458 obj = {"value": "primary", "enabled": True, "disabled": False}
459 mapping = {
460 "enabled": (None, OPTION_BOOL_ONOFF),
461 "disabled": (None, OPTION_BOOL_ONOFF)
462 }
463 result = _dict2options(obj, mapping)
464 self.assertTrue(result.startswith("primary,"))
465 self.assertIn("enabled=on", result)
466 self.assertIn("disabled=off", result)
467
468 def test_value_with_explicit_prefix(self):
469 """Test primary value with explicit prefix parameter"""
470 obj = {"value": "test", "prop": "val"}
471 result = _dict2options(obj, None, prefix="root.")
472 self.assertIn("root=test", result)
473 self.assertIn("root.prop=val", result)
474
475 def test_nested_value_with_explicit_prefix(self):
476 """Test nested value with explicit prefix"""
477 obj = {"level1": {"value": "test", "prop": "val"}}
478 result = _dict2options(obj, None, prefix="root.")
479 self.assertIn("root.level1=test", result)
480 self.assertIn("root.level1.prop=val", result)
481
482 def test_value_with_name_mapping(self):
483 """Test that value attribute is not affected by mapping"""
484 obj = {"value": "primary", "old_name": "test"}
485 mapping = {"old_name": ("new_name", None)}
486 result = _dict2options(obj, mapping)
487 self.assertTrue(result.startswith("primary,"))
488 self.assertIn("new_name=test", result)
489
490 def test_value_with_special_characters(self):
491 """Test primary value with special characters"""
492 obj = {"value": "test=value,with=special", "prop": "test"}
493 result = _dict2options(obj, None)
494 self.assertIn("test=value,with=special", result)
495
496 def test_value_with_spaces(self):
497 """Test primary value with spaces"""
498 obj = {"value": "value with spaces", "prop": "test"}
499 result = _dict2options(obj, None)
500 self.assertIn("value with spaces", result)
501
502 def test_value_with_all_none_properties(self):
503 """Test primary value with all other properties being None"""
504 obj = {"value": "primary", "prop1": None, "prop2": None}
505 result = _dict2options(obj, None)
506 # Should only return the primary value
507 self.assertEqual(result, "primary")
508
509 def test_deeply_nested_underscore_value(self):
510 """Test _value in deeply nested structure"""
511 obj = {
512 "level1": {
513 "level2": {
514 "level3": {
515 "_value": "deep",
516 "prop": "test"
517 }
518 }
519 }
520 }
521 result = _dict2options(obj, None)
522 self.assertIn("level1.level2.level3=deep", result)
523 self.assertIn("level1.level2.level3.prop=test", result)
524
525 def test_value_precedence_over_regular_key(self):
526 """Test that value attribute doesn't conflict with regular keys"""
527 obj = {
528 "value": "primary",
529 "other_value": "regular",
530 "prop": "test"
531 }
532 result = _dict2options(obj, None)
533 # Primary value should be first
534 self.assertTrue(result.startswith("primary,"))
535 # Regular key should be included
536 self.assertIn("other_value=regular", result)
537 self.assertIn("prop=test", result)
538
539 def test_dict_without_value_unchanged(self):
540 """Test that dicts without value attribute work as before"""
541 obj = {"prop1": "val1", "prop2": "val2"}
542 result = _dict2options(obj, None)
543 self.assertIn("prop1=val1", result)
544 self.assertIn("prop2=val2", result)
545
546 def test_nested_dict_without_value_unchanged(self):
547 """Test nested structures without value attribute"""
548 obj = {
549 "nested": {
550 "prop1": "val1",
551 "prop2": "val2"
552 }
553 }
554 result = _dict2options(obj, None)
555 self.assertIn("nested.prop1=val1", result)
556 self.assertIn("nested.prop2=val2", result)
557
558 def test_list_without_value_unchanged(self):
559 """Test lists without value attribute"""
560 obj = {
561 "items": [
562 {"name": "item1"},
563 {"name": "item2"}
564 ]
565 }
566 result = _dict2options(obj, None)
567 self.assertIn("items0.name=item1", result)
568 self.assertIn("items1.name=item2", result)
569
570
571 class TestAddParameter(unittest.TestCase):
572
573 def setUp(self):
574 """Set up test fixtures"""
575 self.mock_module = mock.Mock()
576 self.virt_install = VirtInstallTool(self.mock_module)
577
578 def test_add_memory_parameter(self):
579 dict_value = {
580 "current_memory": 1024,
581 "max_memory": 4096,
582 "max_memory_opts": {
583 "slots": 2
584 }
585 }
586 mapping = {
587 'current_memory': ('currentMemory', None),
588 'max_memory': ('maxMemory', None),
589 'max_memory_opts': ('maxMemory', None),
590 }
591
592 self.virt_install._add_parameter(
593 '--memory', 2048, dict_value=dict_value, dict_mapping=mapping)
594 self.assertEqual(self.virt_install.command_argv[-2], "--memory")
595 memory_cmdline = self.virt_install.command_argv[-1]
596 self.assertTrue(memory_cmdline.startswith("2048,"))
597 self.assertIn("currentMemory=1024", memory_cmdline)
598 self.assertIn("maxMemory=4096", memory_cmdline)
599 self.assertIn("maxMemory.slots=2", memory_cmdline)
600
601 def test_add_parameter_no_values(self):
602 """Test adding a parameter with no values"""
603 self.virt_install._add_parameter('--test')
604 self.assertEqual(self.virt_install.command_argv[-1], "--test")
605
606 def test_add_parameter_primary_only(self):
607 """Test adding a parameter with only primary value"""
608 self.virt_install._add_parameter('--vcpus', 4)
609 self.assertEqual(self.virt_install.command_argv[-2:], ["--vcpus", "4"])
610
611 def test_add_parameter_dict_only(self):
612 """Test adding a parameter with only dict value"""
613 dict_value = {
614 "hugepages": True,
615 "nosharepages": False
616 }
617 self.virt_install._add_parameter(
618 '--memorybacking', dict_value=dict_value)
619 self.assertEqual(self.virt_install.command_argv[-2], "--memorybacking")
620 memorybacking_cmdline = self.virt_install.command_argv[-1]
621 self.assertIn("hugepages=yes", memorybacking_cmdline)
622 self.assertIn("nosharepages=no", memorybacking_cmdline)
623
624 def test_add_parameter_with_bool_onoff_mapping(self):
625 """Test adding a parameter with OPTION_BOOL_ONOFF mapping"""
626 dict_value = {
627 "enabled": True,
628 "disabled": False
629 }
630 mapping = {
631 'enabled': (None, OPTION_BOOL_ONOFF),
632 'disabled': (None, OPTION_BOOL_ONOFF)
633 }
634 self.virt_install._add_parameter(
635 '--test', dict_value=dict_value, dict_mapping=mapping)
636 test_arg = self.virt_install.command_argv[-1]
637 self.assertIn("enabled=on", test_arg)
638 self.assertIn("disabled=off", test_arg)
639
640 def test_add_parameter_with_nested_dict(self):
641 """Test adding a parameter with nested dictionary"""
642 dict_value = {
643 "cpu": {
644 "model": "host-passthrough",
645 "features": {
646 "vmx": {"policy": "require"}
647 }
648 }
649 }
650 self.virt_install._add_parameter('--test', dict_value=dict_value)
651 test_arg = self.virt_install.command_argv[-1]
652 self.assertIn("cpu.model=host-passthrough", test_arg)
653 self.assertIn("cpu.features.vmx.policy=require", test_arg)
654
655 def test_add_parameter_with_list_values(self):
656 """Test adding a parameter with list values"""
657 dict_value = {
658 "devices": ["dev1", "dev2", "dev3"]
659 }
660 self.virt_install._add_parameter('--test', dict_value=dict_value)
661 test_arg = self.virt_install.command_argv[-1]
662 self.assertIn("devices0=dev1", test_arg)
663 self.assertIn("devices1=dev2", test_arg)
664 self.assertIn("devices2=dev3", test_arg)
665
666 def test_add_parameter_with_list_of_dicts(self):
667 """Test adding a parameter with list of dictionaries"""
668 dict_value = {
669 "vcpu_specs": [
670 {"id": 0, "enabled": True},
671 {"id": 1, "enabled": False}
672 ]
673 }
674 mapping = {
675 "vcpu_specs": (
676 "vcpus.vcpu", {
677 "enabled": (
678 None, OPTION_BOOL_ONOFF)})}
679 self.virt_install._add_parameter(
680 '--test', dict_value=dict_value, dict_mapping=mapping)
681 test_arg = self.virt_install.command_argv[-1]
682 self.assertIn("vcpus.vcpu0.id=0", test_arg)
683 self.assertIn("vcpus.vcpu0.enabled=on", test_arg)
684 self.assertIn("vcpus.vcpu1.id=1", test_arg)
685 self.assertIn("vcpus.vcpu1.enabled=off", test_arg)
686
687 def test_add_parameter_with_no_log_masks_display_only(self):
688 """Test no_log masks only the display command value"""
689 self.virt_install._add_parameter('--secret', 'super-secret', no_log=True)
690 self.assertEqual(self.virt_install.command_argv[-2:], ["--secret", "super-secret"])
691 self.assertEqual(self.virt_install._display_argv[-2:], ["--secret", "***"])
692
693 def test_add_parameter_uses_sanitized_dict_value_for_display(self):
694 """Test sanitized_dict_value is used only for display output"""
695 dict_value = {
696 "product_key": "AAAAA-BBBBB-CCCCC-DDDDD-EEEEE",
697 "profile": "desktop"
698 }
699 sanitized_dict_value = {
700 "product_key": "***",
701 "profile": "desktop"
702 }
703 mapping = {
704 "product_key": ("product-key", None),
705 "profile": ("profile", None)
706 }
707
708 self.virt_install._add_parameter(
709 '--unattended',
710 dict_value=dict_value,
711 dict_mapping=mapping,
712 sanitized_dict_value=sanitized_dict_value)
713
714 self.assertIn('product-key=AAAAA-BBBBB-CCCCC-DDDDD-EEEEE', self.virt_install.command_argv[-1])
715 self.assertIn('product-key=***', self.virt_install._display_argv[-1])
716 self.assertIn('profile=desktop', self.virt_install._display_argv[-1])
717
718 def test_add_flag_parameter_true(self):
719 """Test adding a flag parameter"""
720 self.virt_install._add_flag_parameter('--test', True)
721 self.assertEqual(self.virt_install.command_argv[-1], "--test")
722
723 def test_add_flag_parameter_false(self):
724 """Test adding a flag parameter"""
725 self.virt_install._add_flag_parameter('--test', False)
726 self.assertNotIn("--test", self.virt_install.command_argv[-1])
727
728
729 class TestGetParamCombinedItems(unittest.TestCase):
730
731 def setUp(self):
732 """Set up test environment"""
733 self.module = mock.Mock()
734 self.tool = VirtInstallTool(self.module)
735
736 def test_both_params_none(self):
737 """Test when both singular and plural parameters are None"""
738 self.tool.params = {}
739 result = self.tool._get_param_combined_items('input', 'input_devices')
740 self.assertEqual(result, [])
741
742 def test_only_singular_param(self):
743 """Test when only singular parameter exists"""
744 self.tool.params = {'input': {'type': 'keyboard'}}
745 result = self.tool._get_param_combined_items('input', 'input_devices')
746 self.assertEqual(result, [{'type': 'keyboard'}])
747
748 def test_only_plural_param(self):
749 """Test when only plural parameter exists"""
750 self.tool.params = {
751 'input_devices': [
752 {'type': 'keyboard'},
753 {'type': 'mouse'}
754 ]
755 }
756 result = self.tool._get_param_combined_items('input', 'input_devices')
757 self.assertEqual(result, [
758 {'type': 'keyboard'},
759 {'type': 'mouse'}
760 ])
761
762 def test_both_params_exist(self):
763 """Test when both singular and plural parameters exist"""
764 self.tool.params = {
765 'input': {'type': 'keyboard'},
766 'input_devices': [
767 {'type': 'mouse'},
768 {'type': 'tablet'}
769 ]
770 }
771 result = self.tool._get_param_combined_items('input', 'input_devices')
772 self.assertEqual(result, [
773 {'type': 'keyboard'},
774 {'type': 'mouse'},
775 {'type': 'tablet'}
776 ])
777
778 def test_empty_plural_param(self):
779 """Test when plural parameter is an empty list"""
780 self.tool.params = {
781 'input': {'type': 'keyboard'},
782 'input_devices': []
783 }
784 result = self.tool._get_param_combined_items('input', 'input_devices')
785 self.assertEqual(result, [{'type': 'keyboard'}])
786
787 def test_none_values_in_params(self):
788 """Test when parameters have None values"""
789 self.tool.params = {
790 'input': None,
791 'input_devices': None
792 }
793 result = self.tool._get_param_combined_items('input', 'input_devices')
794 self.assertEqual(result, [])
795
796 def test_complex_nested_structures(self):
797 """Test with complex nested data structures"""
798 self.tool.params = {
799 'controller': {
800 'type': 'usb',
801 'model': 'qemu-xhci'
802 },
803 'controller_devices': [
804 {
805 'type': 'scsi',
806 'model': 'virtio-scsi',
807 'driver': {'iommu': 'on'}
808 },
809 {
810 'type': 'pci',
811 'model': 'pcie-root'
812 }
813 ]
814 }
815 result = self.tool._get_param_combined_items(
816 'controller', 'controller_devices')
817 self.assertEqual(result, [
818 {
819 'type': 'usb',
820 'model': 'qemu-xhci'
821 },
822 {
823 'type': 'scsi',
824 'model': 'virtio-scsi',
825 'driver': {'iommu': 'on'}
826 },
827 {
828 'type': 'pci',
829 'model': 'pcie-root'
830 }
831 ])
832
833
834 class TestBuildCommand(unittest.TestCase):
835 """Test the _build_command method of VirtInstallTool"""
836
837 def setUp(self):
838 """Set up test fixtures"""
839 self.mock_module = mock.Mock()
840 self.mock_module.tmpdir = tempfile.mkdtemp()
841 self.mock_module.params = {}
842 self.virt_install = VirtInstallTool(self.mock_module)
843
844 def tearDown(self):
845 shutil.rmtree(self.mock_module.tmpdir)
846
847 def test_basic_command_structure(self):
848 """Test basic command structure with minimal required parameters"""
849 self.mock_module.params = {
850 'name': 'test-vm',
851 'memory': 2048
852 }
853 self.virt_install = VirtInstallTool(self.mock_module)
854 self.virt_install._build_command()
855
856 # Check base command
857 self.assertEqual(self.virt_install.command_argv[0], 'virt-install')
858 # Check --noautoconsole is always added
859 cmdline = ' '.join(self.virt_install.command_argv)
860 self.assertIn('--noautoconsole', cmdline)
861 # Check name and memory are added
862 self.assertIn('--name test-vm', cmdline)
863 self.assertIn('--memory 2048', cmdline)
864
865 def test_memory_with_options(self):
866 """Test memory parameter with additional options"""
867 self.mock_module.params = {
868 'name': 'test-vm',
869 'memory': 4096,
870 'memory_opts': {
871 'current_memory': 2048,
872 'max_memory': 8192,
873 'max_memory_opts': {
874 'slots': 4
875 }
876 }
877 }
878 self.virt_install = VirtInstallTool(self.mock_module)
879 self.virt_install._build_command()
880
881 memory_args = []
882 for i, arg in enumerate(self.virt_install.command_argv):
883 if arg == '--memory' and i + \
884 1 < len(self.virt_install.command_argv):
885 memory_args.append(self.virt_install.command_argv[i + 1])
886
887 self.assertEqual(len(memory_args), 1)
888 self.assertIn('4096', memory_args[0])
889 self.assertIn('currentMemory=2048', memory_args[0])
890 self.assertIn('maxMemory=8192', memory_args[0])
891 self.assertIn('maxMemory.slots=4', memory_args[0])
892
893 def test_memorybacking_options(self):
894 """Test memorybacking parameter"""
895 self.mock_module.params = {
896 'name': 'test-vm',
897 'memory': 2048,
898 'memorybacking': {
899 'hugepages': True,
900 'nosharepages': False,
901 'locked': True,
902 'hugepage_specs': [
903 {'page_size': 2048, 'nodeset': '0-1'},
904 {'page_size': 1048576, 'nodeset': '2-3'}
905 ]
906 }
907 }
908 self.virt_install = VirtInstallTool(self.mock_module)
909 self.virt_install._build_command()
910
911 try:
912 idx = self.virt_install.command_argv.index('--memorybacking')
913 memorybacking_cmdline = self.virt_install.command_argv[idx + 1]
914 except (ValueError, IndexError):
915 memorybacking_cmdline = None
916
917 self.assertIsNotNone(memorybacking_cmdline)
918 self.assertIn('hugepages=yes', memorybacking_cmdline)
919 self.assertIn('nosharepages=no', memorybacking_cmdline)
920 self.assertIn('locked=yes', memorybacking_cmdline)
921 self.assertIn('hugepages.page0.size=2048', memorybacking_cmdline)
922 self.assertIn('hugepages.page0.nodeset=0-1', memorybacking_cmdline)
923
924 def test_memorybacking_with_memfd_source(self):
925 """Test memorybacking parameter with memfd source"""
926 self.mock_module.params = {
927 'name': 'test-vm',
928 'memory': 4096,
929 'memorybacking': {
930 'source': {
931 'type': 'memfd'
932 },
933 'access': {
934 'mode': 'shared'
935 }
936 }
937 }
938 self.virt_install = VirtInstallTool(self.mock_module)
939 self.virt_install._build_command()
940
941 try:
942 idx = self.virt_install.command_argv.index('--memorybacking')
943 memorybacking_cmdline = self.virt_install.command_argv[idx + 1]
944 except (ValueError, IndexError):
945 memorybacking_cmdline = None
946
947 self.assertIsNotNone(memorybacking_cmdline)
948 self.assertIn('source.type=memfd', memorybacking_cmdline)
949 self.assertIn('access.mode=shared', memorybacking_cmdline)
950
951 def test_vcpus_configuration(self):
952 """Test vcpus parameter with options"""
953 self.mock_module.params = {
954 'name': 'test-vm',
955 'memory': 2048,
956 'vcpus': 4,
957 'vcpus_opts': {
958 'maxvcpus': 8,
959 'sockets': 2,
960 'cores': 2,
961 'threads': 1,
962 'current': 2,
963 'cpuset': '0-3',
964 'placement': 'static'
965 }
966 }
967 self.virt_install = VirtInstallTool(self.mock_module)
968 self.virt_install._build_command()
969
970 try:
971 idx = self.virt_install.command_argv.index('--vcpus')
972 vcpus_cmdline = self.virt_install.command_argv[idx + 1]
973 except (ValueError, IndexError):
974 vcpus_cmdline = None
975
976 self.assertIsNotNone(vcpus_cmdline)
977 self.assertTrue(vcpus_cmdline.startswith('4'))
978 self.assertIn('maxvcpus=8', vcpus_cmdline)
979 self.assertIn('sockets=2', vcpus_cmdline)
980 self.assertIn('cores=2', vcpus_cmdline)
981 self.assertIn('threads=1', vcpus_cmdline)
982 self.assertIn('vcpu.current=2', vcpus_cmdline)
983 self.assertIn('cpuset=0-3', vcpus_cmdline)
984 self.assertIn('vcpu.placement=static', vcpus_cmdline)
985
986 def test_cpu_configuration(self):
987 """Test CPU configuration with complex options"""
988 self.mock_module.params = {
989 'name': 'test-vm',
990 'memory': 2048,
991 'cpu': {
992 'model': 'host-passthrough',
993 'match': 'exact',
994 'migratable': True,
995 'features': {
996 'vmx': 'require',
997 'svm': 'disable',
998 'lahf_lm': 'optional'
999 },
1000 'cache': {
1001 'mode': 'passthrough',
1002 'level': 3
1003 }
1004 }
1005 }
1006 self.virt_install = VirtInstallTool(self.mock_module)
1007 self.virt_install._build_command()
1008
1009 try:
1010 idx = self.virt_install.command_argv.index('--cpu')
1011 cpu_cmdline = self.virt_install.command_argv[idx + 1]
1012 except (ValueError, IndexError):
1013 cpu_cmdline = None
1014
1015 self.assertIsNotNone(cpu_cmdline)
1016 # Features should be processed as primary value
1017 self.assertTrue(cpu_cmdline.startswith('host-passthrough'))
1018 self.assertIn('require=vmx', cpu_cmdline)
1019 self.assertIn('disable=svm', cpu_cmdline)
1020 self.assertIn('optional=lahf_lm', cpu_cmdline)
1021 # Other options should be in dict format
1022 self.assertIn('match=exact', cpu_cmdline)
1023 self.assertIn('migratable=yes', cpu_cmdline)
1024 self.assertIn('cache.mode=passthrough', cpu_cmdline)
1025 self.assertIn('cache.level=3', cpu_cmdline)
1026
1027 def test_storage_configuration(self):
1028 """Test disk storage configuration"""
1029 self.mock_module.params = {
1030 'name': 'test-vm',
1031 'memory': 2048,
1032 'disks': [
1033 {
1034 'size': 20,
1035 'format': 'qcow2',
1036 'bus': 'virtio',
1037 'cache': 'writeback',
1038 'sparse': True
1039 },
1040 {
1041 'path': '/var/lib/libvirt/images/test-vm-data.qcow2',
1042 'size': 100,
1043 'format': 'qcow2',
1044 'bus': 'virtio',
1045 'readonly': False,
1046 'shareable': True
1047 }
1048 ]
1049 }
1050 self.virt_install = VirtInstallTool(self.mock_module)
1051 self.virt_install._build_command()
1052
1053 disk_args = []
1054 for i, arg in enumerate(self.virt_install.command_argv):
1055 if arg == '--disk' and i + 1 < len(self.virt_install.command_argv):
1056 disk_args.append(self.virt_install.command_argv[i + 1])
1057
1058 self.assertEqual(len(disk_args), 2)
1059 # Check first disk
1060 self.assertIn('size=20', disk_args[0])
1061 self.assertIn('format=qcow2', disk_args[0])
1062 self.assertIn('bus=virtio', disk_args[0])
1063 self.assertIn('cache=writeback', disk_args[0])
1064 self.assertIn('sparse=yes', disk_args[0])
1065
1066 # Check second disk
1067 self.assertIn(
1068 'path=/var/lib/libvirt/images/test-vm-data.qcow2',
1069 disk_args[1])
1070 self.assertIn('size=100', disk_args[1])
1071 self.assertIn('readonly=no', disk_args[1])
1072 self.assertIn('shareable=yes', disk_args[1])
1073
1074 def test_network_configuration(self):
1075 """Test network configuration"""
1076 self.mock_module.params = {
1077 'name': 'test-vm',
1078 'memory': 2048,
1079 'networks': [
1080 {
1081 'network': 'default',
1082 'model': {'type': 'virtio'},
1083 'mac': {'address': '52:54:00:12:34:56'}
1084 },
1085 {
1086 'bridge': 'br0',
1087 'model': {'type': 'e1000'},
1088 'trust_guest_rx_filters': True
1089 }
1090 ]
1091 }
1092 self.virt_install = VirtInstallTool(self.mock_module)
1093 self.virt_install._build_command()
1094
1095 # Find network arguments
1096 network_args = []
1097 for i, arg in enumerate(self.virt_install.command_argv):
1098 if arg == '--network' and i + \
1099 1 < len(self.virt_install.command_argv):
1100 network_args.append(self.virt_install.command_argv[i + 1])
1101
1102 self.assertEqual(len(network_args), 2)
1103
1104 # Check first network
1105 self.assertIn('network=default', network_args[0])
1106 self.assertIn('model.type=virtio', network_args[0])
1107 self.assertIn('mac.address=52:54:00:12:34:56', network_args[0])
1108
1109 # Check second network
1110 self.assertIn('bridge=br0', network_args[1])
1111 self.assertIn('model.type=e1000', network_args[1])
1112 self.assertIn('trustGuestRxFilters=yes', network_args[1])
1113
1114 def test_empty_networks_list(self):
1115 """Test empty networks list results in no network"""
1116 self.mock_module.params = {
1117 'name': 'test-vm',
1118 'memory': 2048,
1119 'networks': []
1120 }
1121 self.virt_install = VirtInstallTool(self.mock_module)
1122 self.virt_install._build_command()
1123
1124 # Find network arguments
1125 network_args = []
1126 for i, arg in enumerate(self.virt_install.command_argv):
1127 if arg == '--network' and i + \
1128 1 < len(self.virt_install.command_argv):
1129 network_args.append(self.virt_install.command_argv[i + 1])
1130
1131 self.assertEqual(len(network_args), 1)
1132 self.assertEqual(network_args[0], 'none')
1133
1134 def test_graphics_configuration(self):
1135 """Test graphics configuration"""
1136 self.mock_module.params = {
1137 'name': 'test-vm',
1138 'memory': 2048,
1139 'graphics': {
1140 'type': 'vnc',
1141 'listen': '0.0.0.0',
1142 'port': 5901,
1143 'password': 'secret'
1144 }
1145 }
1146 self.virt_install = VirtInstallTool(self.mock_module)
1147 self.virt_install._build_command()
1148
1149 graphics_args = []
1150 for i, arg in enumerate(self.virt_install.command_argv):
1151 if arg == '--graphics' and i + \
1152 1 < len(self.virt_install.command_argv):
1153 graphics_args.append(self.virt_install.command_argv[i + 1])
1154
1155 self.assertEqual(len(graphics_args), 1)
1156 self.assertTrue(graphics_args[0].startswith('vnc,'))
1157 self.assertIn('listen=0.0.0.0', graphics_args[0])
1158 self.assertIn('port=5901', graphics_args[0])
1159 self.assertIn('password=secret', graphics_args[0])
1160
1161 def test_graphics_devices_list(self):
1162 """Test multiple graphics devices"""
1163 self.mock_module.params = {
1164 'name': 'test-vm',
1165 'memory': 2048,
1166 'graphics_devices': [
1167 {'type': 'vnc', 'port': 5901},
1168 {'type': 'spice', 'port': 5902}
1169 ]
1170 }
1171 self.virt_install = VirtInstallTool(self.mock_module)
1172 self.virt_install._build_command()
1173
1174 graphics_args = []
1175 for i, arg in enumerate(self.virt_install.command_argv):
1176 if arg == '--graphics' and i + \
1177 1 < len(self.virt_install.command_argv):
1178 graphics_args.append(self.virt_install.command_argv[i + 1])
1179
1180 self.assertEqual(len(graphics_args), 2)
1181 self.assertTrue(graphics_args[0].startswith('vnc,'))
1182 self.assertIn('port=5901', graphics_args[0])
1183 self.assertTrue(graphics_args[1].startswith('spice,'))
1184 self.assertIn('port=5902', graphics_args[1])
1185
1186 def test_no_graphics_configuration(self):
1187 """Test no graphics configuration results in none"""
1188 self.mock_module.params = {
1189 'name': 'test-vm',
1190 'memory': 2048
1191 }
1192 self.virt_install = VirtInstallTool(self.mock_module)
1193 self.virt_install._build_command()
1194
1195 # Find graphics arguments
1196 graphics_args = []
1197 for i, arg in enumerate(self.virt_install.command_argv):
1198 if arg == '--graphics' and i + \
1199 1 < len(self.virt_install.command_argv):
1200 graphics_args.append(self.virt_install.command_argv[i + 1])
1201
1202 self.assertEqual(len(graphics_args), 1)
1203 self.assertEqual(graphics_args[0], 'none')
1204
1205 def test_installation_options(self):
1206 """Test installation options"""
1207 self.mock_module.params = {
1208 'name': 'test-vm',
1209 'memory': 2048,
1210 'location': 'http://mirror.centos.org/centos-7/7/os/x86_64/',
1211 'location_opts': {
1212 'kernel': 'images/pxeboot/vmlinuz',
1213 'initrd': 'images/pxeboot/initrd.img'
1214 },
1215 'extra_args': 'console=ttyS0,115200n8 serial',
1216 'osinfo': {
1217 'name': 'centos7.0',
1218 'detect': True,
1219 'require': False
1220 }
1221 }
1222 self.virt_install = VirtInstallTool(self.mock_module)
1223 self.virt_install._build_command()
1224
1225 location_args = []
1226 for i, arg in enumerate(self.virt_install.command_argv):
1227 if arg == '--location' and i + \
1228 1 < len(self.virt_install.command_argv):
1229 location_args.append(self.virt_install.command_argv[i + 1])
1230 self.assertEqual(len(location_args), 1)
1231 self.assertIn(
1232 'http://mirror.centos.org/centos-7/7/os/x86_64/',
1233 location_args[0])
1234 self.assertIn('kernel=images/pxeboot/vmlinuz', location_args[0])
1235 self.assertIn('initrd=images/pxeboot/initrd.img', location_args[0])
1236
1237 extra_args_args = []
1238 for i, arg in enumerate(self.virt_install.command_argv):
1239 if arg == '--extra-args' and i + \
1240 1 < len(self.virt_install.command_argv):
1241 extra_args_args.append(self.virt_install.command_argv[i + 1])
1242 self.assertEqual(len(extra_args_args), 1)
1243 self.assertEqual('console=ttyS0,115200n8 serial', extra_args_args[0])
1244
1245 osinfo_args = []
1246 for i, arg in enumerate(self.virt_install.command_argv):
1247 if arg == '--osinfo' and i + \
1248 1 < len(self.virt_install.command_argv):
1249 osinfo_args.append(self.virt_install.command_argv[i + 1])
1250 self.assertEqual(len(osinfo_args), 1)
1251 self.assertIn('name=centos7.0', osinfo_args[0])
1252 self.assertIn('detect=on', osinfo_args[0])
1253 self.assertIn('require=off', osinfo_args[0])
1254
1255 def test_flag_parameters(self):
1256 """Test flag parameters (pxe, import, etc.)"""
1257 self.mock_module.params = {
1258 'name': 'test-vm',
1259 'memory': 2048,
1260 'pxe': True,
1261 'autostart': True,
1262 'transient': False,
1263 'noreboot': True
1264 }
1265 self.virt_install = VirtInstallTool(self.mock_module)
1266 self.virt_install._build_command()
1267
1268 # Check that true flags are present
1269 self.assertIn('--pxe', self.virt_install.command_argv)
1270 self.assertIn('--autostart', self.virt_install.command_argv)
1271 self.assertIn('--noreboot', self.virt_install.command_argv)
1272
1273 # Check that false flags are not present
1274 self.assertNotIn('--transient', self.virt_install.command_argv)
1275
1276 def test_import_flag(self):
1277 """Test the import flag (Python keyword)"""
1278 self.mock_module.params = {
1279 'name': 'test-vm',
1280 'memory': 2048,
1281 'import': True
1282 }
1283 self.virt_install = VirtInstallTool(self.mock_module)
1284 self.virt_install._build_command()
1285
1286 self.assertIn('--import', self.virt_install.command_argv)
1287
1288 def test_device_configurations(self):
1289 """Test various device configurations"""
1290 self.mock_module.params = {
1291 'name': 'test-vm',
1292 'memory': 2048,
1293 'controller_devices': [
1294 {'type': 'usb', 'model': 'none'},
1295 {'type': 'scsi', 'model': 'virtio-scsi'}
1296 ],
1297 'input_devices': [
1298 {'type': 'tablet', 'bus': 'usb'},
1299 {'type': 'keyboard', 'bus': 'usb'}
1300 ],
1301 'sound_devices': [
1302 {'model': 'ich9'}
1303 ],
1304 'video_devices': [
1305 {'model': 'qxl', 'vram': 65536}
1306 ]
1307 }
1308 self.virt_install = VirtInstallTool(self.mock_module)
1309 self.virt_install._build_command()
1310
1311 # Check controller devices
1312 controller_args = []
1313 for i, arg in enumerate(self.virt_install.command_argv):
1314 if arg == '--controller' and i + \
1315 1 < len(self.virt_install.command_argv):
1316 controller_args.append(self.virt_install.command_argv[i + 1])
1317 self.assertEqual(len(controller_args), 2)
1318 self.assertIn('type=usb', controller_args[0])
1319 self.assertIn('model=none', controller_args[0])
1320 self.assertIn('type=scsi', controller_args[1])
1321 self.assertIn('model=virtio-scsi', controller_args[1])
1322
1323 # Check input devices
1324 input_args = []
1325 for i, arg in enumerate(self.virt_install.command_argv):
1326 if arg == '--input' and i + \
1327 1 < len(self.virt_install.command_argv):
1328 input_args.append(self.virt_install.command_argv[i + 1])
1329 self.assertEqual(len(input_args), 2)
1330
1331 # Check sound devices
1332 sound_args = []
1333 for i, arg in enumerate(self.virt_install.command_argv):
1334 if arg == '--sound' and i + \
1335 1 < len(self.virt_install.command_argv):
1336 sound_args.append(self.virt_install.command_argv[i + 1])
1337 self.assertEqual(len(sound_args), 1)
1338 self.assertIn('model=ich9', sound_args[0])
1339
1340 # Check video devices
1341 video_args = []
1342 for i, arg in enumerate(self.virt_install.command_argv):
1343 if arg == '--video' and i + \
1344 1 < len(self.virt_install.command_argv):
1345 video_args.append(self.virt_install.command_argv[i + 1])
1346 self.assertEqual(len(video_args), 1)
1347 self.assertIn('model=qxl', video_args[0])
1348 self.assertIn('vram=65536', video_args[0])
1349
1350 def test_combined_singular_plural_devices(self):
1351 """Test combining singular and plural device parameters"""
1352 self.mock_module.params = {
1353 'name': 'test-vm',
1354 'memory': 2048,
1355 'controller': {'type': 'usb', 'model': 'qemu-xhci'},
1356 'controller_devices': [
1357 {'type': 'scsi', 'model': 'virtio-scsi'},
1358 {'type': 'pci', 'model': 'pcie-root'}
1359 ]
1360 }
1361 self.virt_install = VirtInstallTool(self.mock_module)
1362 self.virt_install._build_command()
1363
1364 # Should have 3 controller arguments (1 singular + 2 plural)
1365
1366 controller_args = []
1367 for i, arg in enumerate(self.virt_install.command_argv):
1368 if arg == '--controller' and i + \
1369 1 < len(self.virt_install.command_argv):
1370 controller_args.append(self.virt_install.command_argv[i + 1])
1371
1372 self.assertEqual(len(controller_args), 3)
1373 # Check that singular is included first
1374 self.assertIn('type=usb', controller_args[0])
1375 self.assertIn('model=qemu-xhci', controller_args[0])
1376 self.assertIn('type=scsi', controller_args[1])
1377 self.assertIn('model=virtio-scsi', controller_args[1])
1378 self.assertIn('type=pci', controller_args[2])
1379 self.assertIn('model=pcie-root', controller_args[2])
1380
1381 def test_cloud_init_configuration(self):
1382 """Test cloud-init configuration"""
1383 self.mock_module.params = {
1384 'name': 'test-vm',
1385 'memory': 2048,
1386 'cloud_init': {
1387 'root_password_generate': True,
1388 'disable': False,
1389 'root_ssh_key': '/path/to/key.pub',
1390 'clouduser_ssh_key': '/path/to/user_key.pub',
1391 'meta_data': r'{"instance-id": "test-vm"}',
1392 'user_data': r'{"users": [{"name": "testuser", "sudo": "ALL=(ALL) NOPASSWD:ALL"}]}'
1393 }
1394 }
1395 self.virt_install = VirtInstallTool(self.mock_module)
1396 self.virt_install._build_command()
1397
1398 cloud_init_args = []
1399 for i, arg in enumerate(self.virt_install.command_argv):
1400 if arg == '--cloud-init' and i + \
1401 1 < len(self.virt_install.command_argv):
1402 cloud_init_args.append(self.virt_install.command_argv[i + 1])
1403
1404 self.assertEqual(len(cloud_init_args), 1)
1405 self.assertIn('root-password-generate=on', cloud_init_args[0])
1406 self.assertIn('disable=off', cloud_init_args[0])
1407 self.assertIn('root-ssh-key=/path/to/key.pub', cloud_init_args[0])
1408 self.assertIn(
1409 'clouduser-ssh-key=/path/to/user_key.pub',
1410 cloud_init_args[0])
1411
1412 def test_launch_security_configuration(self):
1413 """Test launch security (SEV) configuration"""
1414 self.mock_module.params = {
1415 'name': 'test-vm',
1416 'memory': 2048,
1417 'launch_security': {
1418 'type': 'sev',
1419 'policy': '0x01',
1420 'cbitpos': 47,
1421 'reduced_phys_bits': 1
1422 }
1423 }
1424 self.virt_install = VirtInstallTool(self.mock_module)
1425 self.virt_install._build_command()
1426
1427 launch_security_args = []
1428 for i, arg in enumerate(self.virt_install.command_argv):
1429 if arg == '--launchSecurity' and i + \
1430 1 < len(self.virt_install.command_argv):
1431 launch_security_args.append(
1432 self.virt_install.command_argv[i + 1])
1433
1434 self.assertEqual(len(launch_security_args), 1)
1435 self.assertIn('type=sev', launch_security_args[0])
1436 self.assertIn('policy=0x01', launch_security_args[0])
1437 self.assertIn('cbitpos=47', launch_security_args[0])
1438 self.assertIn('reducedPhysBits=1', launch_security_args[0])
1439
1440 def test_validate_params_error(self):
1441 """Test parameter validation errors"""
1442 # Test case where memory_opts is provided without memory
1443 self.mock_module.params = {
1444 'name': 'test-vm',
1445 'memory_opts': {'current_memory': 1024}
1446 }
1447 self.mock_module.fail_json = mock.Mock()
1448 self.virt_install = VirtInstallTool(self.mock_module)
1449
1450 self.virt_install._build_command()
1451
1452 # Should call fail_json with validation error
1453 self.mock_module.fail_json.assert_called_once()
1454 args, kwargs = self.mock_module.fail_json.call_args
1455 self.assertIn('memory_opts requires memory', kwargs['msg'])
1456
1457 def test_complete_vm_configuration(self):
1458 """Test a complete VM configuration with many options"""
1459 self.mock_module.params = {
1460 'name': 'production-vm',
1461 'memory': 8192,
1462 'memory_opts': {
1463 'current_memory': 4096,
1464 'max_memory': 16384
1465 },
1466 'vcpus': 4,
1467 'vcpus_opts': {
1468 'maxvcpus': 8,
1469 'sockets': 2,
1470 'cores': 2
1471 },
1472 'cpu': {
1473 'model': 'host-passthrough',
1474 'features': {
1475 'vmx': 'require'
1476 }
1477 },
1478 'disks': [
1479 {
1480 'size': 40,
1481 'format': 'qcow2',
1482 'bus': 'virtio',
1483 'cache': 'writeback'
1484 }
1485 ],
1486 'networks': [
1487 {
1488 'network': 'default',
1489 'model': {'type': 'virtio'}
1490 }
1491 ],
1492 'graphics': {
1493 'type': 'spice',
1494 'listen': '127.0.0.1'
1495 },
1496 'osinfo': {
1497 'name': 'fedora39'
1498 },
1499 'location': (
1500 'https://download.fedoraproject.org/pub/fedora/linux/'
1501 'releases/39/Server/x86_64/'),
1502 'autostart': True,
1503 'noreboot': True
1504 }
1505 self.virt_install = VirtInstallTool(self.mock_module)
1506 self.virt_install._build_command()
1507
1508 # Verify the command structure
1509 self.assertEqual(self.virt_install.command_argv[0], 'virt-install')
1510 self.assertIn('--noautoconsole', self.virt_install.command_argv)
1511
1512 # Verify major components are present
1513 arg_prefixes = [
1514 '--name',
1515 '--memory',
1516 '--vcpus',
1517 '--cpu',
1518 '--disk',
1519 '--network',
1520 '--graphics',
1521 '--osinfo',
1522 '--location',
1523 '--autostart',
1524 '--noreboot']
1525 for prefix in arg_prefixes:
1526 found = any(arg.startswith(prefix)
1527 for arg in self.virt_install.command_argv)
1528 self.assertTrue(
1529 found, f"Expected argument with prefix '{prefix}' not found in command")
1530
1531 def test_additional_validation_errors(self):
1532 """Test additional parameter validation errors"""
1533 # Test case where vcpus_opts is provided without vcpus
1534 self.mock_module.params = {
1535 'name': 'test-vm',
1536 'memory': 2048,
1537 'vcpus_opts': {'maxvcpus': 8}
1538 }
1539 self.mock_module.fail_json = mock.Mock()
1540 self.virt_install = VirtInstallTool(self.mock_module)
1541
1542 self.virt_install._build_command()
1543
1544 # Should call fail_json with validation error
1545 self.mock_module.fail_json.assert_called_once()
1546 args, kwargs = self.mock_module.fail_json.call_args
1547 self.assertIn('vcpus_opts requires vcpus', kwargs['msg'])
1548
1549 def test_filesystem_configuration(self):
1550 """Test filesystem configuration"""
1551 self.mock_module.params = {
1552 'name': 'test-vm',
1553 'memory': 2048,
1554 'filesystems': [
1555 {
1556 'type': 'mount',
1557 'accessmode': 'passthrough',
1558 'source': {'dir': '/host/share'},
1559 'target': {'dir': '/guest/share'},
1560 'readonly': False
1561 },
1562 {
1563 'type': 'mount',
1564 'accessmode': 'mapped',
1565 'source': {'dir': '/host/data'},
1566 'target': {'dir': '/guest/data'},
1567 'fmode': '0644',
1568 'dmode': '0755'
1569 }
1570 ]
1571 }
1572 self.virt_install = VirtInstallTool(self.mock_module)
1573 self.virt_install._build_command()
1574
1575 # Find filesystem arguments
1576 fs_args = []
1577 for i, arg in enumerate(self.virt_install.command_argv):
1578 if arg == '--filesystem' and i + \
1579 1 < len(self.virt_install.command_argv):
1580 fs_args.append(self.virt_install.command_argv[i + 1])
1581
1582 self.assertEqual(len(fs_args), 2)
1583
1584 # Check first filesystem
1585 self.assertIn('type=mount', fs_args[0])
1586 self.assertIn('accessmode=passthrough', fs_args[0])
1587 self.assertIn('source.dir=/host/share', fs_args[0])
1588 self.assertIn('target.dir=/guest/share', fs_args[0])
1589 self.assertIn('readonly=no', fs_args[0])
1590
1591 # Check second filesystem
1592 self.assertIn('type=mount', fs_args[1])
1593 self.assertIn('accessmode=mapped', fs_args[1])
1594 self.assertIn('fmode=0644', fs_args[1])
1595 self.assertIn('dmode=0755', fs_args[1])
1596
1597 def test_complex_boolean_mappings(self):
1598 """Test complex boolean mappings with OPTION_BOOL_ONOFF"""
1599 self.mock_module.params = {
1600 'name': 'test-vm',
1601 'memory': 2048,
1602 'memballoon_devices': [
1603 {
1604 'model': 'virtio',
1605 'freePageReporting': True,
1606 'autodeflate': False
1607 }
1608 ],
1609 'tpm_devices': [
1610 {
1611 'model': 'tpm-tis',
1612 'backend': {
1613 'type': 'emulator',
1614 'version': '2.0',
1615 'persistent_state': True
1616 },
1617 'active_pcr_banks': {
1618 'sha1': True,
1619 'sha256': False
1620 }
1621 }
1622 ]
1623 }
1624 self.virt_install = VirtInstallTool(self.mock_module)
1625 self.virt_install._build_command()
1626
1627 # Find memballoon arguments
1628 memballoon_args = []
1629 for i, arg in enumerate(self.virt_install.command_argv):
1630 if arg == '--memballoon' and i + \
1631 1 < len(self.virt_install.command_argv):
1632 memballoon_args.append(self.virt_install.command_argv[i + 1])
1633 self.assertEqual(len(memballoon_args), 1)
1634 self.assertIn('freePageReporting=on', memballoon_args[0])
1635 self.assertIn('autodeflate=off', memballoon_args[0])
1636
1637 # Find TPM arguments
1638 tpm_args = []
1639 for i, arg in enumerate(self.virt_install.command_argv):
1640 if arg == '--tpm' and i + 1 < len(self.virt_install.command_argv):
1641 tpm_args.append(self.virt_install.command_argv[i + 1])
1642 self.assertEqual(len(tpm_args), 1)
1643 self.assertIn('backend.persistent_state=on', tpm_args[0])
1644 self.assertIn('active_pcr_banks.sha1=on', tpm_args[0])
1645 self.assertIn('active_pcr_banks.sha256=off', tpm_args[0])
1646
1647 def test_installation_medium_combinations(self):
1648 """Test different installation medium combinations"""
1649 # Test CDROM installation
1650 self.mock_module.params = {
1651 'name': 'test-vm',
1652 'memory': 2048,
1653 'cdrom': '/path/to/installer.iso'
1654 }
1655 self.virt_install = VirtInstallTool(self.mock_module)
1656 self.virt_install._build_command()
1657
1658 cmdline = ' '.join(self.virt_install.command_argv)
1659 self.assertIn(
1660 '--cdrom /path/to/installer.iso',
1661 cmdline)
1662
1663 def test_unattended_installation(self):
1664 """Test unattended installation configuration"""
1665 self.mock_module.params = {
1666 'name': 'test-vm',
1667 'memory': 2048,
1668 'unattended': {
1669 'profile': 'desktop',
1670 'admin_password_file': '/tmp/admin_pass',
1671 'user_login': 'testuser',
1672 'user_password_file': '/tmp/user_pass',
1673 'product_key': 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX'
1674 }
1675 }
1676 self.virt_install = VirtInstallTool(self.mock_module)
1677 self.virt_install._build_command()
1678
1679 # Find unattended argument
1680 unattended_arg = None
1681 for i, arg in enumerate(self.virt_install.command_argv):
1682 if arg == '--unattended' and i + \
1683 1 < len(self.virt_install.command_argv):
1684 unattended_arg = self.virt_install.command_argv[i + 1]
1685 break
1686
1687 self.assertIsNotNone(unattended_arg)
1688 self.assertIn('profile=desktop', unattended_arg)
1689 self.assertIn('admin-password-file=/tmp/admin_pass', unattended_arg)
1690 self.assertIn('user-login=testuser', unattended_arg)
1691 self.assertIn('user-password-file=/tmp/user_pass', unattended_arg)
1692 self.assertIn(
1693 'product-key=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX',
1694 unattended_arg)
1695
1696 def test_unattended_masks_product_key_in_display_command(self):
1697 """Test unattended product key is masked in display argv"""
1698 product_key = 'XXXXX-XXXXX-XXXXX-XXXXX-XXXXX'
1699 self.mock_module.params = {
1700 'name': 'test-vm',
1701 'memory': 2048,
1702 'unattended': {
1703 'profile': 'desktop',
1704 'product_key': product_key
1705 }
1706 }
1707 self.virt_install = VirtInstallTool(self.mock_module)
1708 self.virt_install._build_command()
1709
1710 real_arg = None
1711 display_arg = None
1712 for i, arg in enumerate(self.virt_install.command_argv):
1713 if arg == '--unattended' and i + 1 < len(self.virt_install.command_argv):
1714 real_arg = self.virt_install.command_argv[i + 1]
1715 break
1716 for i, arg in enumerate(self.virt_install._display_argv):
1717 if arg == '--unattended' and i + 1 < len(self.virt_install._display_argv):
1718 display_arg = self.virt_install._display_argv[i + 1]
1719 break
1720
1721 self.assertIsNotNone(real_arg)
1722 self.assertIsNotNone(display_arg)
1723 self.assertIn('product-key={}'.format(product_key), real_arg)
1724 self.assertIn('product-key=***', display_arg)
1725 self.assertNotIn('product-key={}'.format(product_key), display_arg)
1726
1727 def test_cloud_init_masks_sensitive_keys_in_display_command(self):
1728 """Test cloud-init SSH keys are masked in display argv"""
1729 self.mock_module.params = {
1730 'name': 'test-vm',
1731 'memory': 2048,
1732 'cloud_init': {
1733 'root_password_generate': True,
1734 'root_ssh_key': '/path/to/root.pub',
1735 'clouduser_ssh_key': '/path/to/clouduser.pub'
1736 }
1737 }
1738 self.virt_install = VirtInstallTool(self.mock_module)
1739 self.virt_install._build_command()
1740
1741 real_arg = None
1742 display_arg = None
1743 for i, arg in enumerate(self.virt_install.command_argv):
1744 if arg == '--cloud-init' and i + 1 < len(self.virt_install.command_argv):
1745 real_arg = self.virt_install.command_argv[i + 1]
1746 break
1747 for i, arg in enumerate(self.virt_install._display_argv):
1748 if arg == '--cloud-init' and i + 1 < len(self.virt_install._display_argv):
1749 display_arg = self.virt_install._display_argv[i + 1]
1750 break
1751
1752 self.assertIsNotNone(real_arg)
1753 self.assertIsNotNone(display_arg)
1754 self.assertIn('root-ssh-key=/path/to/root.pub', real_arg)
1755 self.assertIn('clouduser-ssh-key=/path/to/clouduser.pub', real_arg)
1756 self.assertIn('root-ssh-key=***', display_arg)
1757 self.assertIn('clouduser-ssh-key=***', display_arg)
1758 self.assertNotIn('/path/to/root.pub', display_arg)
1759 self.assertNotIn('/path/to/clouduser.pub', display_arg)
1760
1761 def test_virtualization_options(self):
1762 """Test virtualization-specific options"""
1763 self.mock_module.params = {
1764 'name': 'test-vm',
1765 'memory': 2048,
1766 'virt_type': 'kvm',
1767 'hvm': True,
1768 'paravirt': False,
1769 'container': False,
1770 }
1771 self.virt_install = VirtInstallTool(self.mock_module)
1772 self.virt_install._build_command()
1773
1774 self.assertIn('--hvm', self.virt_install.command_argv)
1775 self.assertNotIn('--paravirt', self.virt_install.command_argv)
1776 self.assertNotIn('--container', self.virt_install.command_argv)
1777
1778 def test_complex_numa_configuration(self):
1779 """Test complex NUMA configuration"""
1780 self.mock_module.params = {
1781 'name': 'test-vm',
1782 'memory': 2048,
1783 'numatune': {
1784 'memory': {
1785 'mode': 'strict',
1786 'nodeset': '0-1',
1787 'placement': 'static'
1788 },
1789 'memnode_specs': [
1790 {
1791 'cellid': 0,
1792 'mode': 'strict',
1793 'nodeset': '0'
1794 },
1795 {
1796 'cellid': 1,
1797 'mode': 'interleave',
1798 'nodeset': '1'
1799 }
1800 ]
1801 }
1802 }
1803 self.virt_install = VirtInstallTool(self.mock_module)
1804 self.virt_install._build_command()
1805
1806 numatune_args = []
1807 for i, arg in enumerate(self.virt_install.command_argv):
1808 if arg == '--numatune' and i + \
1809 1 < len(self.virt_install.command_argv):
1810 numatune_args.append(self.virt_install.command_argv[i + 1])
1811
1812 self.assertEqual(len(numatune_args), 1)
1813 self.assertIn('memory.mode=strict', numatune_args[0])
1814 self.assertIn('memory.nodeset=0-1', numatune_args[0])
1815 self.assertIn('memory.placement=static', numatune_args[0])
1816 self.assertIn('memnode0.cellid=0', numatune_args[0])
1817 self.assertIn('memnode0.mode=strict', numatune_args[0])
1818 self.assertIn('memnode1.cellid=1', numatune_args[0])
1819 self.assertIn('memnode1.mode=interleave', numatune_args[0])
1820
1821 def test_empty_command_argv_initialization(self):
1822 """Test that command_argv is properly initialized"""
1823 self.mock_module.params = {
1824 'name': 'test-vm',
1825 'memory': 2048
1826 }
1827 self.virt_install = VirtInstallTool(self.mock_module)
1828
1829 # Before _build_command, should only have base command
1830 self.assertEqual(len(self.virt_install.command_argv), 1)
1831 self.assertEqual(self.virt_install.command_argv[0], 'virt-install')
1832
1833 self.virt_install._build_command()
1834
1835 # After _build_command, should have more arguments
1836 self.assertGreater(len(self.virt_install.command_argv), 1)
1837 self.assertEqual('--noautoconsole', self.virt_install.command_argv[-1])
1838
1839 def test_metadata_configuration(self):
1840 """Test metadata parameter configuration"""
1841 self.mock_module.params = {
1842 'name': 'test-vm',
1843 'memory': 2048,
1844 'metadata': {
1845 'title': 'Test Virtual Machine',
1846 'description': 'A test VM for unit testing',
1847 'name': 'test-vm-metadata',
1848 'uuid': '12345678-1234-5678-9012-123456789abc'
1849 }
1850 }
1851 self.virt_install = VirtInstallTool(self.mock_module)
1852 self.virt_install._build_command()
1853
1854 # Find metadata arguments
1855 metadata_args = []
1856 for i, arg in enumerate(self.virt_install.command_argv):
1857 if arg == '--metadata' and i + 1 < len(self.virt_install.command_argv):
1858 metadata_args.append(self.virt_install.command_argv[i + 1])
1859
1860 self.assertEqual(len(metadata_args), 1)
1861 self.assertIn('title=Test Virtual Machine', metadata_args[0])
1862 self.assertIn('description=A test VM for unit testing', metadata_args[0])
1863 self.assertIn('name=test-vm-metadata', metadata_args[0])
1864 self.assertIn('uuid=12345678-1234-5678-9012-123456789abc', metadata_args[0])
1865
1866 def test_resource_configuration(self):
1867 """Test resource parameter configuration"""
1868 self.mock_module.params = {
1869 'name': 'test-vm',
1870 'memory': 2048,
1871 'resource': {
1872 'partition': '/machine/test',
1873 'fibrechannel': {
1874 'appid': 'test-app',
1875 'wwnn': '5001a4a93526d0a1',
1876 'wwpn': '5001a4a93526d0a2'
1877 }
1878 }
1879 }
1880 self.virt_install = VirtInstallTool(self.mock_module)
1881 self.virt_install._build_command()
1882
1883 # Find resource arguments
1884 resource_args = []
1885 for i, arg in enumerate(self.virt_install.command_argv):
1886 if arg == '--resource' and i + 1 < len(self.virt_install.command_argv):
1887 resource_args.append(self.virt_install.command_argv[i + 1])
1888
1889 self.assertEqual(len(resource_args), 1)
1890 self.assertIn('partition=/machine/test', resource_args[0])
1891 self.assertIn('fibrechannel.appid=test-app', resource_args[0])
1892 self.assertIn('fibrechannel.wwnn=5001a4a93526d0a1', resource_args[0])
1893 self.assertIn('fibrechannel.wwpn=5001a4a93526d0a2', resource_args[0])
1894
1895 def test_sysinfo_configuration(self):
1896 """Test sysinfo parameter configuration"""
1897 self.mock_module.params = {
1898 'name': 'test-vm',
1899 'memory': 2048,
1900 'sysinfo': {
1901 'type': 'smbios',
1902 'bios': {
1903 'vendor': 'Test BIOS Vendor',
1904 'version': '1.0.0',
1905 'date': '01/01/2024'
1906 },
1907 'system': {
1908 'manufacturer': 'Test System Manufacturer',
1909 'product': 'Test Product',
1910 'version': '1.0',
1911 'serial': 'TEST123456',
1912 'uuid': 'abcdef12-3456-7890-abcd-ef1234567890',
1913 'sku': 'TEST-SKU-001',
1914 'family': 'Test Family'
1915 },
1916 'baseBoard': {
1917 'manufacturer': 'Test Board Manufacturer',
1918 'product': 'Test Board Product',
1919 'version': '1.0',
1920 'serial': 'BOARD123456'
1921 }
1922 }
1923 }
1924 self.virt_install = VirtInstallTool(self.mock_module)
1925 self.virt_install._build_command()
1926
1927 # Find sysinfo arguments
1928 sysinfo_args = []
1929 for i, arg in enumerate(self.virt_install.command_argv):
1930 if arg == '--sysinfo' and i + 1 < len(self.virt_install.command_argv):
1931 sysinfo_args.append(self.virt_install.command_argv[i + 1])
1932
1933 self.assertEqual(len(sysinfo_args), 1)
1934 # Check type
1935 self.assertIn('type=smbios', sysinfo_args[0])
1936 # Check BIOS information
1937 self.assertIn('bios.vendor=Test BIOS Vendor', sysinfo_args[0])
1938 self.assertIn('bios.version=1.0.0', sysinfo_args[0])
1939 self.assertIn('bios.date=01/01/2024', sysinfo_args[0])
1940 # Check system information
1941 self.assertIn('system.manufacturer=Test System Manufacturer', sysinfo_args[0])
1942 self.assertIn('system.product=Test Product', sysinfo_args[0])
1943 self.assertIn('system.version=1.0', sysinfo_args[0])
1944 self.assertIn('system.serial=TEST123456', sysinfo_args[0])
1945 self.assertIn('system.uuid=abcdef12-3456-7890-abcd-ef1234567890', sysinfo_args[0])
1946 self.assertIn('system.sku=TEST-SKU-001', sysinfo_args[0])
1947 self.assertIn('system.family=Test Family', sysinfo_args[0])
1948 # Check baseBoard information
1949 self.assertIn('baseBoard.manufacturer=Test Board Manufacturer', sysinfo_args[0])
1950 self.assertIn('baseBoard.product=Test Board Product', sysinfo_args[0])
1951 self.assertIn('baseBoard.version=1.0', sysinfo_args[0])
1952 self.assertIn('baseBoard.serial=BOARD123456', sysinfo_args[0])
1953
1954 def test_cloud_init_dict_network_config(self):
1955 """Test cloud-init configuration with dictionary network_config"""
1956 self.mock_module.params = {
1957 'name': 'test-vm',
1958 'memory': 2048,
1959 'cloud_init': {
1960 'network_config': {
1961 'version': 2,
1962 'ethernets': {
1963 'eth0': {
1964 'dhcp4': True,
1965 'dhcp6': False
1966 }
1967 }
1968 }
1969 }
1970 }
1971 self.virt_install = VirtInstallTool(self.mock_module)
1972 self.virt_install._build_command()
1973
1974 # Verify that the command was built successfully
1975 self.assertIn('--cloud-init', self.virt_install.command_argv)
1976
1977 # Find the cloud-init argument value
1978 cloud_init_idx = self.virt_install.command_argv.index('--cloud-init')
1979 self.assertLess(cloud_init_idx + 1, len(self.virt_install.command_argv))
1980
1981 # The network-config should be a file path, not the raw content
1982 cloud_init_value = self.virt_install.command_argv[cloud_init_idx + 1]
1983 self.assertIn('network-config=', cloud_init_value)
1984
1985 # Extract the file path and verify its contents
1986 network_config_path = cloud_init_value.split('network-config=')[1].split(',')[0]
1987 self.assertTrue(network_config_path.startswith(self.mock_module.tmpdir))
1988
1989 # Read and verify the YAML file contents
1990 with open(network_config_path, 'r') as f:
1991 yaml_content = f.read()
1992
1993 # Verify the YAML contains expected content
1994 self.assertIn('version: 2', yaml_content)
1995 self.assertIn('ethernets:', yaml_content)
1996 self.assertIn('eth0:', yaml_content)
1997 self.assertIn('dhcp4: true', yaml_content)
1998 self.assertIn('dhcp6: false', yaml_content)
1999
2000 def test_cloud_init_dict_meta_data(self):
2001 """Test cloud-init configuration with dictionary meta_data"""
2002 self.mock_module.params = {
2003 'name': 'test-vm',
2004 'memory': 2048,
2005 'cloud_init': {
2006 'meta_data': {
2007 'instance-id': 'test-vm-001',
2008 'local-hostname': 'testhost.local',
2009 'availability-zone': 'us-east-1a'
2010 }
2011 }
2012 }
2013 self.virt_install = VirtInstallTool(self.mock_module)
2014 self.virt_install._build_command()
2015
2016 # Verify that the command was built successfully
2017 self.assertIn('--cloud-init', self.virt_install.command_argv)
2018
2019 # Find the cloud-init argument value
2020 cloud_init_idx = self.virt_install.command_argv.index('--cloud-init')
2021 self.assertLess(cloud_init_idx + 1, len(self.virt_install.command_argv))
2022
2023 # The meta-data should be a file path, not the raw content
2024 cloud_init_value = self.virt_install.command_argv[cloud_init_idx + 1]
2025 self.assertIn('meta-data=', cloud_init_value)
2026
2027 # Extract the file path and verify its contents
2028 meta_data_path = cloud_init_value.split('meta-data=')[1].split(',')[0]
2029 self.assertTrue(meta_data_path.startswith(self.mock_module.tmpdir))
2030
2031 # Read and verify the YAML file contents
2032 with open(meta_data_path, 'r') as f:
2033 yaml_content = f.read()
2034
2035 # Verify the YAML contains expected content
2036 self.assertIn('instance-id: test-vm-001', yaml_content)
2037 self.assertIn('local-hostname: testhost.local', yaml_content)
2038 self.assertIn('availability-zone: us-east-1a', yaml_content)
2039
2040 def test_cloud_init_dict_user_data(self):
2041 """Test cloud-init configuration with dictionary user_data"""
2042 self.mock_module.params = {
2043 'name': 'test-vm',
2044 'memory': 2048,
2045 'cloud_init': {
2046 'user_data': {
2047 'users': [
2048 {
2049 'name': 'admin',
2050 'sudo': 'ALL=(ALL) NOPASSWD:ALL',
2051 'ssh_authorized_keys': ['ssh-rsa AAAAB3NzaC1yc2E...']
2052 }
2053 ],
2054 'packages': ['nginx', 'htop'],
2055 'runcmd': [
2056 'systemctl enable nginx',
2057 'systemctl start nginx'
2058 ]
2059 }
2060 }
2061 }
2062 self.virt_install = VirtInstallTool(self.mock_module)
2063 self.virt_install._build_command()
2064
2065 # Verify that the command was built successfully
2066 self.assertIn('--cloud-init', self.virt_install.command_argv)
2067
2068 # Find the cloud-init argument value
2069 cloud_init_idx = self.virt_install.command_argv.index('--cloud-init')
2070 self.assertLess(cloud_init_idx + 1, len(self.virt_install.command_argv))
2071
2072 # The user-data should be a file path, not the raw content
2073 cloud_init_value = self.virt_install.command_argv[cloud_init_idx + 1]
2074 self.assertIn('user-data=', cloud_init_value)
2075
2076 # Extract the file path and verify its contents
2077 user_data_path = cloud_init_value.split('user-data=')[1].split(',')[0]
2078 self.assertTrue(user_data_path.startswith(self.mock_module.tmpdir))
2079
2080 # Read and verify the YAML file contents
2081 with open(user_data_path, 'r') as f:
2082 yaml_content = f.read()
2083
2084 # Verify the YAML contains expected content
2085 self.assertIn('users:', yaml_content)
2086 self.assertIn('name: admin', yaml_content)
2087 self.assertIn('sudo: ALL=(ALL) NOPASSWD:ALL', yaml_content)
2088 self.assertIn('ssh_authorized_keys:', yaml_content)
2089 self.assertIn('- ssh-rsa AAAAB3NzaC1yc2E...', yaml_content)
2090 self.assertIn('packages:', yaml_content)
2091 self.assertIn('- nginx', yaml_content)
2092 self.assertIn('- htop', yaml_content)
2093 self.assertIn('runcmd:', yaml_content)
2094 self.assertIn('- systemctl enable nginx', yaml_content)
2095 self.assertIn('- systemctl start nginx', yaml_content)
2096
2097 def test_cloud_init_mixed_dict_and_string(self):
2098 """Test cloud-init configuration with mixed dictionary and string inputs"""
2099 self.mock_module.params = {
2100 'name': 'test-vm',
2101 'memory': 2048,
2102 'cloud_init': {
2103 'network_config': {
2104 'version': 2,
2105 'ethernets': {'eth0': {'dhcp4': True}}
2106 },
2107 'meta_data': '{"instance-id": "test-vm", "local-hostname": "testhost"}',
2108 'user_data': {
2109 'users': [{'name': 'admin', 'sudo': 'ALL=(ALL) NOPASSWD:ALL'}],
2110 'packages': ['nginx']
2111 }
2112 }
2113 }
2114 self.virt_install = VirtInstallTool(self.mock_module)
2115 self.virt_install._build_command()
2116
2117 # Verify that the command was built successfully
2118 self.assertIn('--cloud-init', self.virt_install.command_argv)
2119
2120 # Find the cloud-init argument value
2121 cloud_init_idx = self.virt_install.command_argv.index('--cloud-init')
2122 self.assertLess(cloud_init_idx + 1, len(self.virt_install.command_argv))
2123
2124 cloud_init_value = self.virt_install.command_argv[cloud_init_idx + 1]
2125 # All three should be present as file paths
2126 self.assertIn('network-config=', cloud_init_value)
2127 self.assertIn('meta-data=', cloud_init_value)
2128 self.assertIn('user-data=', cloud_init_value)
2129
2130 # Extract file paths and verify contents for each parameter
2131 # 1. Verify network_config (dict input -> YAML conversion)
2132 network_config_path = cloud_init_value.split('network-config=')[1].split(',')[0]
2133 self.assertTrue(network_config_path.startswith(self.mock_module.tmpdir))
2134
2135 with open(network_config_path, 'r') as f:
2136 network_yaml = f.read()
2137 self.assertIn('version: 2', network_yaml)
2138 self.assertIn('ethernets:', network_yaml)
2139 self.assertIn('eth0:', network_yaml)
2140 self.assertIn('dhcp4: true', network_yaml)
2141
2142 # 2. Verify meta_data (string input -> no conversion)
2143 meta_data_path = cloud_init_value.split('meta-data=')[1].split(',')[0]
2144 self.assertTrue(meta_data_path.startswith(self.mock_module.tmpdir))
2145
2146 with open(meta_data_path, 'r') as f:
2147 meta_data_content = f.read()
2148 self.assertEqual(meta_data_content, '{"instance-id": "test-vm", "local-hostname": "testhost"}')
2149
2150 # 3. Verify user_data (dict input -> YAML conversion)
2151 user_data_path = cloud_init_value.split('user-data=')[1].split(',')[0]
2152 self.assertTrue(user_data_path.startswith(self.mock_module.tmpdir))
2153
2154 with open(user_data_path, 'r') as f:
2155 user_data_yaml = f.read()
2156 self.assertIn('users:', user_data_yaml)
2157 self.assertIn('name: admin', user_data_yaml)
2158 self.assertIn('sudo: ALL=(ALL) NOPASSWD:ALL', user_data_yaml)
2159 self.assertIn('packages:', user_data_yaml)
2160 self.assertIn('- nginx', user_data_yaml)
2161
2162 def test_cloud_init_yaml_conversion_accuracy(self):
2163 """Test that YAML conversion accurately represents the input dictionary structure"""
2164 self.mock_module.params = {
2165 'name': 'test-vm',
2166 'memory': 2048,
2167 'cloud_init': {
2168 'network_config': {
2169 'version': 2,
2170 'ethernets': {
2171 'eth0': {
2172 'dhcp4': True,
2173 'dhcp6': False,
2174 'mtu': 1500,
2175 'nameservers': {
2176 'addresses': ['8.8.8.8', '1.1.1.1']
2177 }
2178 }
2179 }
2180 },
2181 'user_data': {
2182 'ssh_pwauth': False,
2183 'disable_root': True,
2184 'users': [
2185 {
2186 'name': 'admin',
2187 'groups': ['sudo', 'docker'],
2188 'shell': '/bin/bash',
2189 'sudo': 'ALL=(ALL) NOPASSWD:ALL',
2190 'ssh_authorized_keys': [
2191 'ssh-rsa AAAAB3NzaC1yc2E...',
2192 'ssh-rsa BBBBC3NzaC1yc2E...'
2193 ]
2194 }
2195 ],
2196 'packages': ['nginx', 'htop', 'vim'],
2197 'runcmd': [
2198 'systemctl enable nginx',
2199 'systemctl start nginx',
2200 'echo "Server configured successfully"'
2201 ]
2202 }
2203 }
2204 }
2205 self.virt_install = VirtInstallTool(self.mock_module)
2206 self.virt_install._build_command()
2207
2208 # Verify command structure
2209 self.assertIn('--cloud-init', self.virt_install.command_argv)
2210 cloud_init_idx = self.virt_install.command_argv.index('--cloud-init')
2211 cloud_init_value = self.virt_install.command_argv[cloud_init_idx + 1]
2212
2213 # Verify network_config YAML conversion
2214 network_config_path = cloud_init_value.split('network-config=')[1].split(',')[0]
2215 with open(network_config_path, 'r') as f:
2216 network_yaml = f.read()
2217
2218 # Check network configuration structure
2219 self.assertIn('version: 2', network_yaml)
2220 self.assertIn('ethernets:', network_yaml)
2221 self.assertIn('eth0:', network_yaml)
2222 self.assertIn('dhcp4: true', network_yaml)
2223 self.assertIn('dhcp6: false', network_yaml)
2224 self.assertIn('mtu: 1500', network_yaml)
2225 self.assertIn('nameservers:', network_yaml)
2226 self.assertIn('addresses:', network_yaml)
2227 self.assertIn('- 8.8.8.8', network_yaml)
2228 self.assertIn('- 1.1.1.1', network_yaml)
2229
2230 # Verify user_data YAML conversion
2231 user_data_path = cloud_init_value.split('user-data=')[1].split(',')[0]
2232 with open(user_data_path, 'r') as f:
2233 user_data_yaml = f.read()
2234
2235 # Check user data structure
2236 self.assertIn('ssh_pwauth: false', user_data_yaml)
2237 self.assertIn('disable_root: true', user_data_yaml)
2238 self.assertIn('users:', user_data_yaml)
2239 self.assertIn('name: admin', user_data_yaml)
2240 self.assertIn('groups:', user_data_yaml)
2241 self.assertIn('- sudo', user_data_yaml)
2242 self.assertIn('- docker', user_data_yaml)
2243 self.assertIn('shell: /bin/bash', user_data_yaml)
2244 self.assertIn('sudo: ALL=(ALL) NOPASSWD:ALL', user_data_yaml)
2245 self.assertIn('ssh_authorized_keys:', user_data_yaml)
2246 self.assertIn('- ssh-rsa AAAAB3NzaC1yc2E...', user_data_yaml)
2247 self.assertIn('- ssh-rsa BBBBC3NzaC1yc2E...', user_data_yaml)
2248 self.assertIn('packages:', user_data_yaml)
2249 self.assertIn('- nginx', user_data_yaml)
2250 self.assertIn('- htop', user_data_yaml)
2251 self.assertIn('- vim', user_data_yaml)
2252 self.assertIn('runcmd:', user_data_yaml)
2253 self.assertIn('- systemctl enable nginx', user_data_yaml)
2254 self.assertIn('- systemctl start nginx', user_data_yaml)
2255 self.assertIn('- echo "Server configured successfully"', user_data_yaml)
2256
2257
2258 class TestVirtInstallToolExecute(unittest.TestCase):
2259 """Test cases for VirtInstallTool.execute() method"""
2260
2261 def setUp(self):
2262 """Set up test fixtures"""
2263 self.mock_module = mock.Mock()
2264 self.mock_module.params = {
2265 'name': 'test-vm',
2266 'memory': 2048,
2267 'vcpus': 2,
2268 'disks': [{'size': 20}],
2269 'networks': [{'network': 'default'}],
2270 'osinfo': {'name': 'fedora39'},
2271 'graphics': {'type': 'spice'}
2272 }
2273
2274 def test_execute_success(self):
2275 """Test successful execution"""
2276 # Mock successful command execution
2277 self.mock_module.run_command.return_value = (
2278 0, "Domain installation proceeding...", "")
2279
2280 self.virt_install = VirtInstallTool(self.mock_module)
2281 changed, rc, result = self.virt_install.execute()
2282
2283 # Assert successful execution
2284 self.assertTrue(changed)
2285 self.assertEqual(rc, 0) # VIRT_SUCCESS
2286 self.assertIn("msg", result)
2287 self.assertIn(
2288 "virtual machine 'test-vm' created successfully",
2289 result["msg"])
2290
2291 # Verify run_command was called
2292 self.mock_module.run_command.assert_called_once()
2293
2294 # Verify command contains expected elements
2295 called_args = self.mock_module.run_command.call_args[0][0]
2296 self.assertIn('virt-install', called_args)
2297 self.assertIn('--noautoconsole', called_args)
2298
2299 def test_execute_failure(self):
2300 """Test failed execution"""
2301 error_message = "ERROR: Unable to connect to libvirt"
2302 self.mock_module.run_command.return_value = (1, "", error_message)
2303
2304 self.virt_install = VirtInstallTool(self.mock_module)
2305 changed, rc, result = self.virt_install.execute()
2306
2307 # Assert failed execution
2308 self.assertFalse(changed)
2309 self.assertEqual(rc, 1)
2310 self.assertIn("msg", result)
2311 self.assertIn(
2312 "failed to create virtual machine 'test-vm'",
2313 result["msg"])
2314 self.assertIn(error_message, result["msg"])
2315
2316 def test_execute_failure_with_stdout_error(self):
2317 """Test failed execution where error info is in stdout"""
2318 error_message = "ERROR: Domain already exists"
2319 self.mock_module.run_command.return_value = (2, error_message, "")
2320
2321 self.virt_install = VirtInstallTool(self.mock_module)
2322 changed, rc, result = self.virt_install.execute()
2323
2324 # Assert failed execution
2325 self.assertFalse(changed)
2326 self.assertEqual(rc, 2)
2327 self.assertIn("msg", result)
2328 self.assertIn(
2329 "failed to create virtual machine 'test-vm'",
2330 result["msg"])
2331 self.assertIn(error_message, result["msg"])
2332
2333 def test_execute_dryrun_success(self):
2334 """Test dry run execution"""
2335 self.mock_module.run_command.return_value = (
2336 0, "Would create domain test-vm", "")
2337
2338 self.virt_install = VirtInstallTool(self.mock_module)
2339 changed, rc, result = self.virt_install.execute(dryrun=True)
2340
2341 # Assert successful dry run
2342 self.assertTrue(changed)
2343 self.assertEqual(rc, 0)
2344 self.assertIn("msg", result)
2345 self.assertIn(
2346 "virtual machine 'test-vm' created successfully",
2347 result["msg"])
2348
2349 # Verify --dry-run was added to command
2350 called_args = self.mock_module.run_command.call_args[0][0]
2351 self.assertIn('--dry-run', called_args)
2352
2353 def test_execute_dryrun_failure(self):
2354 """Test dry run execution with failure"""
2355 error_message = "ERROR: Missing required option --cdrom"
2356 self.mock_module.run_command.return_value = (3, "", error_message)
2357
2358 self.virt_install = VirtInstallTool(self.mock_module)
2359 changed, rc, result = self.virt_install.execute(dryrun=True)
2360
2361 # Assert failed dry run
2362 self.assertFalse(changed)
2363 self.assertEqual(rc, 3)
2364 self.assertIn("msg", result)
2365 self.assertIn(
2366 "failed to create virtual machine 'test-vm'",
2367 result["msg"])
2368 self.assertIn(error_message, result["msg"])
2369
2370 def test_execute_with_complex_configuration(self):
2371 """Test execution with complex VM configuration"""
2372 # Set up complex configuration
2373 self.mock_module.params.update({
2374 'memory_opts': {
2375 'current_memory': 1024,
2376 'max_memory': 4096
2377 },
2378 'vcpus_opts': {
2379 'maxvcpus': 8,
2380 'sockets': 2,
2381 'cores': 2,
2382 'threads': 2
2383 },
2384 'cpu': {
2385 'model': 'host-passthrough',
2386 'features': {
2387 'vmx': 'require',
2388 }
2389 },
2390 'clock': {
2391 'offset': 'utc',
2392 'timers': [
2393 {'name': 'rtc', 'tickpolicy': 'catchup'}
2394 ]
2395 }
2396 })
2397
2398 self.mock_module.run_command.return_value = (
2399 0, "Installation starting...", "")
2400
2401 self.virt_install = VirtInstallTool(self.mock_module)
2402 changed, rc, result = self.virt_install.execute()
2403
2404 # Assert successful execution
2405 self.assertTrue(changed)
2406 self.assertEqual(rc, 0)
2407
2408 # Verify complex options were included in command
2409 called_args = self.mock_module.run_command.call_args[0][0]
2410 self.assertIn('virt-install', called_args)
2411
2412 # Validate memory configuration with memory_opts
2413 memory_args = []
2414 for i, arg in enumerate(called_args):
2415 if arg == '--memory' and i + 1 < len(called_args):
2416 memory_args.append(called_args[i + 1])
2417 self.assertEqual(len(memory_args), 1)
2418 memory_arg = memory_args[0]
2419 self.assertIn('2048,', memory_arg) # Base memory value
2420 self.assertIn('currentMemory=1024', memory_arg)
2421 self.assertIn('maxMemory=4096', memory_arg)
2422
2423 # Validate vCPU configuration with vcpus_opts
2424 vcpus_args = []
2425 for i, arg in enumerate(called_args):
2426 if arg == '--vcpus' and i + 1 < len(called_args):
2427 vcpus_args.append(called_args[i + 1])
2428 self.assertEqual(len(vcpus_args), 1)
2429 vcpus_arg = vcpus_args[0]
2430 self.assertIn('2,', vcpus_arg) # Base vcpus value
2431 self.assertIn('maxvcpus=8', vcpus_arg)
2432 self.assertIn('sockets=2', vcpus_arg)
2433 self.assertIn('cores=2', vcpus_arg)
2434 self.assertIn('threads=2', vcpus_arg)
2435
2436 # Validate CPU configuration with model and features
2437 cpu_args = []
2438 for i, arg in enumerate(called_args):
2439 if arg == '--cpu' and i + 1 < len(called_args):
2440 cpu_args.append(called_args[i + 1])
2441 self.assertEqual(len(cpu_args), 1)
2442 cpu_arg = cpu_args[0]
2443 # Features should be converted to primary value format
2444 self.assertIn('require=vmx', cpu_arg)
2445 # Model should be in dict format
2446 self.assertIn('host-passthrough', cpu_arg)
2447
2448 # Validate clock configuration
2449 clock_args = []
2450 for i, arg in enumerate(called_args):
2451 if arg == '--clock' and i + 1 < len(called_args):
2452 clock_args.append(called_args[i + 1])
2453 self.assertEqual(len(clock_args), 1)
2454 clock_arg = clock_args[0]
2455 self.assertIn('offset=utc', clock_arg)
2456 self.assertIn('timer0.name=rtc', clock_arg)
2457 self.assertIn('timer0.tickpolicy=catchup', clock_arg)
2458
2459 # Validate basic VM parameters are still present
2460 name_args = []
2461 for i, arg in enumerate(called_args):
2462 if arg == '--name' and i + 1 < len(called_args):
2463 name_args.append(called_args[i + 1])
2464 self.assertEqual(len(name_args), 1)
2465 self.assertIn('test-vm', name_args[0])
2466
2467 # Validate disk configuration from base params
2468 disk_args = []
2469 for i, arg in enumerate(called_args):
2470 if arg == '--disk' and i + 1 < len(called_args):
2471 disk_args.append(called_args[i + 1])
2472 self.assertEqual(len(disk_args), 1)
2473 self.assertIn('size=20', disk_args[0])
2474
2475 # Validate network configuration from base params
2476 network_args = []
2477 for i, arg in enumerate(called_args):
2478 if arg == '--network' and i + 1 < len(called_args):
2479 network_args.append(called_args[i + 1])
2480 self.assertEqual(len(network_args), 1)
2481 self.assertIn('network=default', network_args[0])
2482
2483 # Validate OS info configuration from base params
2484 osinfo_args = []
2485 for i, arg in enumerate(called_args):
2486 if arg == '--osinfo' and i + 1 < len(called_args):
2487 osinfo_args.append(called_args[i + 1])
2488 self.assertEqual(len(osinfo_args), 1)
2489 self.assertIn('name=fedora39', osinfo_args[0])
2490
2491 # Validate graphics configuration from base params
2492 graphics_args = []
2493 for i, arg in enumerate(called_args):
2494 if arg == '--graphics' and i + 1 < len(called_args):
2495 graphics_args.append(called_args[i + 1])
2496 self.assertEqual(len(graphics_args), 1)
2497 self.assertEqual('spice', graphics_args[0])
2498
2499 # Verify --noautoconsole is always present
2500 self.assertIn('--noautoconsole', called_args)
2501
2502 def test_execute_command_building_error(self):
2503 """Test execution when command building encounters validation error"""
2504 # Set up invalid configuration that should trigger validation error
2505 self.mock_module.params['memory_opts'] = {'current_memory': 1024}
2506 # Remove required 'memory' parameter to trigger validation error
2507 del self.mock_module.params['memory']
2508 self.virt_install = VirtInstallTool(self.mock_module)
2509
2510 # Should raise an exception during _validate_params
2511 with self.assertRaises(Exception):
2512 self.virt_install.execute()
2513
2514 def test_execute_preserves_command_structure(self):
2515 """Test that execute() preserves the command structure"""
2516 self.mock_module.run_command.return_value = (0, "Success", "")
2517 self.virt_install = VirtInstallTool(self.mock_module)
2518
2519 # Store original command_argv
2520 original_argv = self.virt_install.command_argv[:]
2521
2522 self.virt_install.execute()
2523
2524 # Verify command was built (should be different from original)
2525 self.assertNotEqual(original_argv, self.virt_install.command_argv)
2526
2527 # Verify basic structure
2528 self.assertEqual('virt-install', self.virt_install.command_argv[0])
2529 self.assertEqual('--noautoconsole', self.virt_install.command_argv[-1])
2530
2531 @mock.patch('ansible_collections.community.libvirt.plugins.module_utils.virt_install.VirtInstallTool._build_command')
2532 def test_execute_calls_build_command(self, mock_build_command):
2533 """Test that execute() calls _build_command()"""
2534 self.mock_module.run_command.return_value = (0, "Success", "")
2535
2536 self.virt_install = VirtInstallTool(self.mock_module)
2537 self.virt_install.execute()
2538
2539 # Verify _build_command was called
2540 mock_build_command.assert_called_once()
2541
2542 def test_execute_different_return_codes(self):
2543 """Test execution with various return codes"""
2544 self.virt_install = VirtInstallTool(self.mock_module)
2545 test_cases = [
2546 (0, "Success", "", True, 0), # Success case
2547 (1, "", "Generic error", False, 1), # Generic failure
2548 (2, "Validation error", "", False, 2), # Validation failure
2549 (255, "", "Command not found", False, 255), # Command not found
2550 ]
2551
2552 for rc_input, stdout, stderr, expected_changed, expected_rc in test_cases:
2553 with self.subTest(rc=rc_input):
2554 self.mock_module.run_command.return_value = (
2555 rc_input, stdout, stderr)
2556
2557 changed, rc, result = self.virt_install.execute()
2558
2559 self.assertEqual(changed, expected_changed)
2560 self.assertEqual(rc, expected_rc)
2561 self.assertIn("msg", result)
2562
2563 def test_execute_empty_stderr_stdout(self):
2564 """Test execution when both stderr and stdout are empty"""
2565 self.mock_module.run_command.return_value = (1, "", "")
2566
2567 self.virt_install = VirtInstallTool(self.mock_module)
2568 changed, rc, result = self.virt_install.execute()
2569
2570 # Assert failed execution
2571 self.assertFalse(changed)
2572 self.assertEqual(rc, 1)
2573 self.assertIn("msg", result)
2574 self.assertIn(
2575 "failed to create virtual machine 'test-vm'",
2576 result["msg"])
2577
2578 def test_execute_with_whitespace_in_output(self):
2579 """Test execution with whitespace in output"""
2580 self.mock_module.run_command.return_value = (
2581 1, " \n ", " Error with spaces \n")
2582
2583 self.virt_install = VirtInstallTool(self.mock_module)
2584 changed, rc, result = self.virt_install.execute()
2585
2586 # Assert error message is properly stripped
2587 self.assertFalse(changed)
2588 self.assertEqual(rc, 1)
2589 self.assertIn("Error with spaces", result["msg"])
2590 self.assertNotIn("\n", result["msg"])
2591
2592 def test_execute_command_check_rc_false(self):
2593 """Test that execute() calls run_command with check_rc=False"""
2594 self.mock_module.run_command.return_value = (0, "Success", "")
2595
2596 self.virt_install = VirtInstallTool(self.mock_module)
2597 self.virt_install.execute()
2598
2599 # Verify run_command was called with check_rc=False
2600 call_args, call_kwargs = self.mock_module.run_command.call_args
2601 self.assertEqual(call_kwargs.get('check_rc'), False)
2602
2603 def test_execute_vm_name_in_messages(self):
2604 """Test that VM name is correctly included in success/failure messages"""
2605 # Test with different VM names
2606 self.virt_install = VirtInstallTool(self.mock_module)
2607 test_names = ['test-vm', 'my_vm_123', 'vm-with-dashes', 'CamelCaseVM']
2608
2609 for vm_name in test_names:
2610 with self.subTest(name=vm_name):
2611 self.virt_install._vm_name = vm_name
2612
2613 # Test success case
2614 self.mock_module.run_command.return_value = (0, "Success", "")
2615 changed, rc, result = self.virt_install.execute()
2616 self.assertIn(vm_name, result["msg"])
2617
2618 # Test failure case
2619 self.mock_module.run_command.return_value = (1, "", "Error")
2620 changed, rc, result = self.virt_install.execute()
2621 self.assertIn(vm_name, result["msg"])
2622
2623 def test_execute_result_structure(self):
2624 """Test that execute() returns properly structured results"""
2625 self.mock_module.run_command.return_value = (0, "Success", "")
2626
2627 self.virt_install = VirtInstallTool(self.mock_module)
2628 changed, rc, result = self.virt_install.execute()
2629
2630 # Verify result structure
2631 self.assertIsInstance(result, dict)
2632 self.assertIn("msg", result)
2633 self.assertIsInstance(result["msg"], str)
2634 self.assertTrue(len(result["msg"]) > 0)
2635
2636 # Verify return types
2637 self.assertIsInstance(changed, bool)
2638 self.assertIsInstance(rc, int)
2639
2640 def test_execute_records_sanitized_command(self):
2641 """Test get_commands() returns sanitized command string"""
2642 product_key = 'AAAAA-BBBBB-CCCCC-DDDDD-EEEEE'
2643 self.mock_module.params.update({
2644 'unattended': {
2645 'profile': 'desktop',
2646 'product_key': product_key
2647 }
2648 })
2649 self.mock_module.run_command.return_value = (0, "Success", "")
2650 self.virt_install = VirtInstallTool(self.mock_module)
2651
2652 self.virt_install.execute()
2653
2654 executed_commands = self.virt_install.get_commands()
2655 self.assertEqual(len(executed_commands), 1)
2656 self.assertIn('product-key=***', executed_commands[0])
2657 self.assertNotIn(product_key, executed_commands[0])
2658
2659
2660 if __name__ == '__main__':
2661 unittest.main(verbosity=2)