Debian Codegraph @

ansible_collections/community/libvirt/tests/unit/module_utils/test_qemu.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 json
8
9 from ansible_collections.community.libvirt.tests.unit.compat import mock
10 from ansible_collections.community.libvirt.plugins.module_utils.qemu import QemuImgTool
11
12
13 class TestQemuImgToolInit(unittest.TestCase):
14 """Test QemuImgTool initialization"""
15
16 def setUp(self):
17 """Set up test fixtures"""
18 self.mock_module = mock.Mock()
19 self.mock_module.check_mode = False
20
21 def test_init_default_command(self):
22 """Test initialization with default qemu-img command"""
23 tool = QemuImgTool(self.mock_module)
24
25 self.assertEqual(tool.module, self.mock_module)
26 self.assertEqual(tool.warnings, [])
27 self.assertEqual(tool.command_argv, ['qemu-img'])
28
29 def test_init_custom_command(self):
30 """Test initialization with custom command"""
31 custom_cmd = '/usr/local/bin/qemu-img'
32 tool = QemuImgTool(self.mock_module, qemu_img_path=custom_cmd)
33
34 self.assertEqual(tool.module, self.mock_module)
35 self.assertEqual(tool.warnings, [])
36 self.assertEqual(tool.command_argv, [custom_cmd])
37
38 def test_init_none_command(self):
39 """Test initialization with None command (should use default)"""
40 tool = QemuImgTool(self.mock_module, qemu_img_path=None)
41
42 self.assertEqual(tool.command_argv, ['qemu-img'])
43
44
45 class TestQemuImgToolHelperMethods(unittest.TestCase):
46 """Test QemuImgTool helper methods"""
47
48 def setUp(self):
49 """Set up test fixtures"""
50 self.mock_module = mock.Mock()
51 self.mock_module.check_mode = False
52 self.tool = QemuImgTool(self.mock_module)
53
54 def test_add_flag(self):
55 """Test adding a flag to command line"""
56 self.tool._add_flag('--verbose')
57 self.assertEqual(self.tool.command_argv, ['qemu-img', '--verbose'])
58
59 def test_add_option_with_value(self):
60 """Test adding an option with value"""
61 self.tool._add_option('-f', 'qcow2')
62 self.assertEqual(self.tool.command_argv, ['qemu-img', '-f', 'qcow2'])
63
64 def test_add_option_with_none_value(self):
65 """Test adding an option with None value (should be ignored)"""
66 self.tool._add_option('-f', None)
67 self.assertEqual(self.tool.command_argv, ['qemu-img'])
68
69 def test_add_option_with_numeric_value(self):
70 """Test adding an option with numeric value"""
71 self.tool._add_option('-m', 4)
72 self.assertEqual(self.tool.command_argv, ['qemu-img', '-m', '4'])
73
74 def test_add_option_list_empty(self):
75 """Test adding option list with empty list"""
76 self.tool._add_option_list('-o', [])
77 self.assertEqual(self.tool.command_argv, ['qemu-img'])
78
79 def test_add_option_list_with_values(self):
80 """Test adding option list with values"""
81 self.tool._add_option_list(
82 '-o', ['preallocation=metadata', 'lazy_refcounts=on'])
83 expected = ['qemu-img', '-o', 'preallocation=metadata',
84 '-o', 'lazy_refcounts=on']
85 self.assertEqual(self.tool.command_argv, expected)
86
87 def test_add_option_list_with_none_values(self):
88 """Test adding option list with some None values"""
89 self.tool._add_option_list(
90 '-o', ['preallocation=metadata', None, 'lazy_refcounts=on'])
91 expected = ['qemu-img', '-o', 'preallocation=metadata',
92 '-o', 'lazy_refcounts=on']
93 self.assertEqual(self.tool.command_argv, expected)
94
95
96 class TestQemuImgToolConvert(unittest.TestCase):
97 """Test QemuImgTool convert method"""
98
99 def setUp(self):
100 """Set up test fixtures"""
101 self.mock_module = mock.Mock()
102 self.mock_module.check_mode = False
103 self.tool = QemuImgTool(self.mock_module)
104
105 def test_convert_basic(self):
106 """Test basic convert operation"""
107 self.mock_module.run_command.return_value = (0, '', '')
108
109 rc, stdout, stderr = self.tool.convert('input.qcow2', 'output.qcow2')
110
111 expected_cmd = ['qemu-img', 'convert', 'input.qcow2', 'output.qcow2']
112 self.assertEqual(rc, 0)
113 self.mock_module.run_command.assert_called_once_with(
114 expected_cmd, check_rc=False)
115
116 def test_convert_with_formats(self):
117 """Test convert with source and output formats"""
118 self.mock_module.run_command.return_value = (0, '', '')
119
120 rc, stdout, stderr = self.tool.convert(
121 'input.img', 'output.qcow2',
122 source_format='raw', output_format='qcow2'
123 )
124
125 expected_cmd = ['qemu-img', 'convert', '-f', 'raw',
126 '-O', 'qcow2', 'input.img', 'output.qcow2']
127 self.assertEqual(rc, 0)
128 self.mock_module.run_command.assert_called_once_with(
129 expected_cmd, check_rc=False)
130
131 def test_convert_with_compression(self):
132 """Test convert with compression enabled"""
133 self.mock_module.run_command.return_value = (0, '', '')
134
135 rc, stdout, stderr = self.tool.convert(
136 'input.qcow2', 'output.qcow2',
137 compressed=True
138 )
139
140 expected_cmd = ['qemu-img', 'convert',
141 '-c', 'input.qcow2', 'output.qcow2']
142 self.assertEqual(rc, 0)
143 self.mock_module.run_command.assert_called_once_with(
144 expected_cmd, check_rc=False)
145
146 def test_convert_with_sparse_size(self):
147 """Test convert with sparse size option"""
148 self.mock_module.run_command.return_value = (0, '', '')
149
150 rc, stdout, stderr = self.tool.convert(
151 'input.qcow2', 'output.qcow2',
152 sparse_size='4k'
153 )
154
155 expected_cmd = ['qemu-img', 'convert', '-S',
156 '4k', 'input.qcow2', 'output.qcow2']
157 self.assertEqual(rc, 0)
158 self.mock_module.run_command.assert_called_once_with(
159 expected_cmd, check_rc=False)
160
161 def test_convert_with_num_coroutines(self):
162 """Test convert with number of coroutines"""
163 self.mock_module.run_command.return_value = (0, '', '')
164
165 rc, stdout, stderr = self.tool.convert(
166 'input.qcow2', 'output.qcow2',
167 num_coroutines=4
168 )
169
170 expected_cmd = ['qemu-img', 'convert', '-m',
171 '4', 'input.qcow2', 'output.qcow2']
172 self.assertEqual(rc, 0)
173 self.mock_module.run_command.assert_called_once_with(
174 expected_cmd, check_rc=False)
175
176 def test_convert_with_all_options(self):
177 """Test convert with all options enabled"""
178 self.mock_module.run_command.return_value = (0, '', '')
179
180 rc, stdout, stderr = self.tool.convert(
181 'input.raw', 'output.qcow2',
182 source_format='raw',
183 output_format='qcow2',
184 compressed=True,
185 sparse_size='64k',
186 num_coroutines=8
187 )
188
189 expected_cmd = [
190 'qemu-img', 'convert',
191 '-f', 'raw',
192 '-O', 'qcow2',
193 '-c',
194 '-S', '64k',
195 '-m', '8',
196 'input.raw', 'output.qcow2'
197 ]
198 self.assertEqual(rc, 0)
199 self.mock_module.run_command.assert_called_once_with(
200 expected_cmd, check_rc=False)
201
202 def test_convert_failure(self):
203 """Test convert operation failure"""
204 self.mock_module.run_command.return_value = (
205 1, '', 'qemu-img: error: Could not open input file')
206
207 rc, stdout, stderr = self.tool.convert(
208 'nonexistent.qcow2', 'output.qcow2')
209
210 self.assertEqual(rc, 1)
211 self.assertEqual(stderr, 'qemu-img: error: Could not open input file')
212
213 def test_convert_with_spaces_in_filenames(self):
214 """Test convert with filenames containing spaces"""
215 self.mock_module.run_command.return_value = (0, '', '')
216
217 rc, stdout, stderr = self.tool.convert(
218 'input file.qcow2', 'output file.qcow2')
219
220 expected_cmd = ['qemu-img', 'convert',
221 'input file.qcow2', 'output file.qcow2']
222 self.mock_module.run_command.assert_called_once_with(
223 expected_cmd, check_rc=False)
224
225
226 class TestQemuImgToolInfo(unittest.TestCase):
227 """Test QemuImgTool info method"""
228
229 def setUp(self):
230 """Set up test fixtures"""
231 self.mock_module = mock.Mock()
232 self.mock_module.check_mode = False
233 self.tool = QemuImgTool(self.mock_module)
234
235 def test_info_basic(self):
236 """Test basic info operation"""
237 info_output = {
238 "virtual-size": 1073741824,
239 "filename": "test.qcow2",
240 "cluster-size": 65536,
241 "format": "qcow2",
242 "actual-size": 262144,
243 "format-specific": {
244 "type": "qcow2",
245 "data": {
246 "compat": "1.1",
247 "lazy-refcounts": False,
248 "refcount-bits": 16,
249 "corrupt": False
250 }
251 }
252 }
253 self.mock_module.run_command.return_value = (
254 0, json.dumps(info_output), '')
255
256 rc, parsed_output, stderr = self.tool.info('test.qcow2')
257
258 expected_cmd = ['qemu-img', 'info', '--output', 'json', 'test.qcow2']
259 self.assertEqual(rc, 0)
260 self.assertEqual(parsed_output, info_output)
261 self.mock_module.run_command.assert_called_once_with(
262 expected_cmd, check_rc=False)
263
264 def test_info_with_source_format(self):
265 """Test info with source format specified"""
266 self.mock_module.run_command.return_value = (0, '{}', '')
267
268 rc, parsed_output, stderr = self.tool.info(
269 'test.img', source_format='raw')
270
271 expected_cmd = ['qemu-img', 'info', '-f',
272 'raw', '--output', 'json', 'test.img']
273 self.assertEqual(rc, 0)
274 self.mock_module.run_command.assert_called_once_with(
275 expected_cmd, check_rc=False)
276
277 def test_info_with_backing_chain(self):
278 """Test info with backing chain option"""
279 self.mock_module.run_command.return_value = (0, '{}', '')
280
281 rc, parsed_output, stderr = self.tool.info(
282 'test.qcow2', backing_chain=True)
283
284 expected_cmd = ['qemu-img', 'info', '--backing-chain',
285 '--output', 'json', 'test.qcow2']
286 self.assertEqual(rc, 0)
287 self.mock_module.run_command.assert_called_once_with(
288 expected_cmd, check_rc=False)
289
290 def test_info_with_all_options(self):
291 """Test info with all options"""
292 self.mock_module.run_command.return_value = (0, '{}', '')
293
294 rc, parsed_output, stderr = self.tool.info(
295 'test.qcow2',
296 source_format='qcow2',
297 backing_chain=True
298 )
299
300 expected_cmd = [
301 'qemu-img', 'info',
302 '-f', 'qcow2',
303 '--backing-chain',
304 '--output', 'json',
305 'test.qcow2'
306 ]
307 self.assertEqual(rc, 0)
308 self.mock_module.run_command.assert_called_once_with(
309 expected_cmd, check_rc=False)
310
311 def test_info_json_parse_failure(self):
312 """Test info with invalid JSON output"""
313 self.mock_module.run_command.return_value = (0, 'invalid json', '')
314
315 rc, parsed_output, stderr = self.tool.info('test.qcow2')
316
317 self.assertEqual(rc, 0)
318 self.assertEqual(parsed_output, {})
319 self.assertEqual(len(self.tool.warnings), 1)
320 self.assertIn('Failed to parse JSON output', self.tool.warnings[0])
321
322 def test_info_empty_output(self):
323 """Test info with empty output"""
324 self.mock_module.run_command.return_value = (0, '', '')
325
326 rc, parsed_output, stderr = self.tool.info('test.qcow2')
327
328 self.assertEqual(rc, 0)
329 self.assertEqual(parsed_output, {})
330 self.assertEqual(len(self.tool.warnings), 0)
331
332 def test_info_whitespace_output(self):
333 """Test info with whitespace-only output"""
334 self.mock_module.run_command.return_value = (0, ' \n \t ', '')
335
336 rc, parsed_output, stderr = self.tool.info('test.qcow2')
337
338 self.assertEqual(rc, 0)
339 self.assertEqual(parsed_output, {})
340
341 def test_info_failure(self):
342 """Test info operation failure"""
343 self.mock_module.run_command.return_value = (
344 1, '', 'qemu-img: Could not open file')
345
346 rc, parsed_output, stderr = self.tool.info('nonexistent.qcow2')
347
348 self.assertEqual(rc, 1)
349 self.assertEqual(parsed_output, {})
350 self.assertEqual(stderr, 'qemu-img: Could not open file')
351
352 def test_info_complex_json(self):
353 """Test info with complex JSON output including backing files"""
354 complex_info = {
355 "virtual-size": 2147483648,
356 "filename": "overlay.qcow2",
357 "cluster-size": 65536,
358 "format": "qcow2",
359 "actual-size": 1048576,
360 "backing-filename": "base.qcow2",
361 "backing-filename-format": "qcow2",
362 "format-specific": {
363 "type": "qcow2",
364 "data": {
365 "compat": "1.1",
366 "lazy-refcounts": True,
367 "refcount-bits": 16,
368 "corrupt": False,
369 "extended-l2": False
370 }
371 }
372 }
373 self.mock_module.run_command.return_value = (
374 0, json.dumps(complex_info), '')
375
376 rc, parsed_output, stderr = self.tool.info('overlay.qcow2')
377
378 self.assertEqual(rc, 0)
379 self.assertEqual(parsed_output, complex_info)
380 self.assertIn('backing-filename', parsed_output)
381 self.assertEqual(parsed_output['backing-filename'], 'base.qcow2')
382
383
384 class TestQemuImgToolResize(unittest.TestCase):
385 """Test QemuImgTool resize method"""
386
387 def setUp(self):
388 """Set up test fixtures"""
389 self.mock_module = mock.Mock()
390 self.mock_module.check_mode = False
391 self.tool = QemuImgTool(self.mock_module)
392
393 def test_resize_basic(self):
394 """Test basic resize operation"""
395 self.mock_module.run_command.return_value = (0, '', '')
396
397 rc, stdout, stderr = self.tool.resize('test.qcow2', '20G')
398
399 expected_cmd = ['qemu-img', 'resize', 'test.qcow2', '20G']
400 self.assertEqual(rc, 0)
401 self.mock_module.run_command.assert_called_once_with(
402 expected_cmd, check_rc=False)
403
404 def test_resize_with_format(self):
405 """Test resize with source format"""
406 self.mock_module.run_command.return_value = (0, '', '')
407
408 rc, stdout, stderr = self.tool.resize(
409 'test.img', '10G', source_format='raw')
410
411 expected_cmd = ['qemu-img', 'resize', '-f', 'raw', 'test.img', '10G']
412 self.assertEqual(rc, 0)
413 self.mock_module.run_command.assert_called_once_with(
414 expected_cmd, check_rc=False)
415
416 def test_resize_with_preallocation(self):
417 """Test resize with preallocation mode"""
418 self.mock_module.run_command.return_value = (0, '', '')
419
420 rc, stdout, stderr = self.tool.resize(
421 'test.qcow2', '30G',
422 preallocation='metadata'
423 )
424
425 expected_cmd = ['qemu-img', 'resize',
426 '--preallocation', 'metadata', 'test.qcow2', '30G']
427 self.assertEqual(rc, 0)
428 self.mock_module.run_command.assert_called_once_with(
429 expected_cmd, check_rc=False)
430
431 def test_resize_with_shrink(self):
432 """Test resize with shrink option"""
433 self.mock_module.run_command.return_value = (0, '', '')
434
435 rc, stdout, stderr = self.tool.resize(
436 'test.qcow2', '5G',
437 shrink=True
438 )
439
440 expected_cmd = ['qemu-img', 'resize', '--shrink', 'test.qcow2', '5G']
441 self.assertEqual(rc, 0)
442 self.mock_module.run_command.assert_called_once_with(
443 expected_cmd, check_rc=False)
444
445 def test_resize_with_all_options(self):
446 """Test resize with all options"""
447 self.mock_module.run_command.return_value = (0, '', '')
448
449 rc, stdout, stderr = self.tool.resize(
450 'test.qcow2', '15G',
451 source_format='qcow2',
452 preallocation='full',
453 shrink=True
454 )
455
456 expected_cmd = [
457 'qemu-img', 'resize',
458 '-f', 'qcow2',
459 '--preallocation', 'full',
460 '--shrink',
461 'test.qcow2', '15G'
462 ]
463 self.assertEqual(rc, 0)
464 self.mock_module.run_command.assert_called_once_with(
465 expected_cmd, check_rc=False)
466
467 def test_resize_increase_size(self):
468 """Test resize with size increase (+prefix)"""
469 self.mock_module.run_command.return_value = (0, '', '')
470
471 rc, stdout, stderr = self.tool.resize('test.qcow2', '+5G')
472
473 expected_cmd = ['qemu-img', 'resize', 'test.qcow2', '+5G']
474 self.assertEqual(rc, 0)
475 self.mock_module.run_command.assert_called_once_with(
476 expected_cmd, check_rc=False)
477
478 def test_resize_decrease_size(self):
479 """Test resize with size decrease (-prefix)"""
480 self.mock_module.run_command.return_value = (0, '', '')
481
482 rc, stdout, stderr = self.tool.resize(
483 'test.qcow2', '-500M', shrink=True)
484
485 expected_cmd = ['qemu-img', 'resize',
486 '--shrink', 'test.qcow2', '-500M']
487 self.assertEqual(rc, 0)
488 self.mock_module.run_command.assert_called_once_with(
489 expected_cmd, check_rc=False)
490
491 def test_resize_different_size_units(self):
492 """Test resize with different size units"""
493 size_units = ['1024', '2k', '3M', '4G', '5T']
494
495 for size in size_units:
496 with self.subTest(size=size):
497 # Reset the tool for each test
498 self.tool = QemuImgTool(self.mock_module)
499 self.mock_module.run_command.return_value = (0, '', '')
500
501 rc, stdout, stderr = self.tool.resize('test.qcow2', size)
502
503 expected_cmd = ['qemu-img', 'resize', 'test.qcow2', size]
504 self.assertEqual(rc, 0)
505 self.mock_module.run_command.assert_called_with(
506 expected_cmd, check_rc=False)
507
508 def test_resize_failure(self):
509 """Test resize operation failure"""
510 self.mock_module.run_command.return_value = (
511 1, '', 'qemu-img: Could not resize image')
512
513 rc, stdout, stderr = self.tool.resize('test.qcow2', '10G')
514
515 self.assertEqual(rc, 1)
516 self.assertEqual(stderr, 'qemu-img: Could not resize image')
517
518 def test_resize_shrink_without_flag_failure(self):
519 """Test resize shrink without shrink flag (should fail)"""
520 error_msg = 'qemu-img: Use the --shrink option to perform a shrink operation.'
521 self.mock_module.run_command.return_value = (1, '', error_msg)
522
523 rc, stdout, stderr = self.tool.resize(
524 'test.qcow2', '5G') # No shrink=True
525
526 self.assertEqual(rc, 1)
527 self.assertEqual(stderr, error_msg)
528
529 def test_resize_numeric_size(self):
530 """Test resize with numeric size (should be converted to string)"""
531 self.mock_module.run_command.return_value = (0, '', '')
532
533 rc, stdout, stderr = self.tool.resize(
534 'test.qcow2', 21474836480) # 20G in bytes
535
536 expected_cmd = ['qemu-img', 'resize', 'test.qcow2', '21474836480']
537 self.assertEqual(rc, 0)
538 self.mock_module.run_command.assert_called_once_with(
539 expected_cmd, check_rc=False)
540
541 def test_resize_preallocation_modes(self):
542 """Test resize with different preallocation modes"""
543 prealloc_modes = ['off', 'metadata', 'falloc', 'full']
544
545 for mode in prealloc_modes:
546 with self.subTest(mode=mode):
547 # Reset the tool for each test
548 self.tool = QemuImgTool(self.mock_module)
549 self.mock_module.run_command.return_value = (0, '', '')
550
551 rc, stdout, stderr = self.tool.resize(
552 'test.qcow2', '20G',
553 preallocation=mode
554 )
555
556 expected_cmd = ['qemu-img', 'resize',
557 '--preallocation', mode, 'test.qcow2', '20G']
558 self.assertEqual(rc, 0)
559 self.mock_module.run_command.assert_called_with(
560 expected_cmd, check_rc=False)
561
562
563 class TestQemuImgToolIntegration(unittest.TestCase):
564 """Integration tests for QemuImgTool"""
565
566 def setUp(self):
567 """Set up test fixtures"""
568 self.mock_module = mock.Mock()
569 self.mock_module.check_mode = False
570
571 def test_automatic_command_reset(self):
572 """Test that command_argv is automatically reset for each operation"""
573 tool = QemuImgTool(self.mock_module)
574 self.mock_module.run_command.return_value = (
575 0, '{"format": "qcow2"}', '')
576
577 # Verify initial state
578 self.assertEqual(tool.command_argv, ['qemu-img'])
579 self.assertEqual(tool._base_command, 'qemu-img')
580
581 # First operation: info
582 tool.info('test.qcow2')
583 first_call = self.mock_module.run_command.call_args[0][0]
584 expected_first = ['qemu-img', 'info', '--output', 'json', 'test.qcow2']
585 self.assertEqual(first_call, expected_first)
586
587 # Second operation: convert (should start fresh)
588 tool.convert('input.qcow2', 'output.qcow2', compressed=True)
589 second_call = self.mock_module.run_command.call_args[0][0]
590 expected_second = ['qemu-img', 'convert',
591 '-c', 'input.qcow2', 'output.qcow2']
592 self.assertEqual(second_call, expected_second)
593
594 # Third operation: resize (should start fresh)
595 tool.resize('test.qcow2', '20G', shrink=True)
596 third_call = self.mock_module.run_command.call_args[0][0]
597 expected_third = ['qemu-img', 'resize',
598 '--shrink', 'test.qcow2', '20G']
599 self.assertEqual(third_call, expected_third)
600
601 def test_automatic_command_reset_custom_tool(self):
602 """Test automatic reset works with custom tool command"""
603 custom_cmd = '/opt/qemu/bin/qemu-img'
604 tool = QemuImgTool(self.mock_module, qemu_img_path=custom_cmd)
605 self.mock_module.run_command.return_value = (0, '', '')
606
607 # Verify initial state with custom command
608 self.assertEqual(tool.command_argv, [custom_cmd])
609 self.assertEqual(tool._base_command, custom_cmd)
610
611 # First operation
612 tool.info('test.qcow2')
613 first_call = self.mock_module.run_command.call_args[0][0]
614 self.assertEqual(first_call[0], custom_cmd)
615
616 # Second operation should reset to custom command
617 tool.convert('input.qcow2', 'output.qcow2')
618 second_call = self.mock_module.run_command.call_args[0][0]
619 self.assertEqual(second_call[0], custom_cmd)
620 self.assertEqual(second_call[1], 'convert')
621
622 def test_multiple_operations_same_instance(self):
623 """Test performing multiple operations with the same instance"""
624 tool = QemuImgTool(self.mock_module)
625
626 # First operation: info
627 self.mock_module.run_command.return_value = (
628 0, '{"format": "qcow2"}', '')
629 rc1, output1, stderr1 = tool.info('test.qcow2')
630
631 # Second operation: resize (should automatically reset command_argv)
632 self.mock_module.run_command.return_value = (0, '', '')
633 rc2, output2, stderr2 = tool.resize('test.qcow2', '20G')
634
635 # Third operation: convert (should automatically reset command_argv)
636 self.mock_module.run_command.return_value = (0, '', '')
637 rc3, output3, stderr3 = tool.convert('test.qcow2', 'output.qcow2')
638
639 # Verify all operations succeeded
640 self.assertEqual(rc1, 0)
641 self.assertEqual(rc2, 0)
642 self.assertEqual(rc3, 0)
643 self.assertEqual(output1, {"format": "qcow2"})
644
645 def test_command_argv_isolation(self):
646 """Test that command_argv is properly isolated between operations"""
647 tool = QemuImgTool(self.mock_module)
648 self.mock_module.run_command.return_value = (0, '', '')
649
650 # First operation should not affect subsequent operations
651 tool.convert('input.qcow2', 'output1.qcow2', compressed=True)
652 first_call_args = self.mock_module.run_command.call_args[0][0]
653
654 # Second operation (should automatically reset command_argv)
655 tool.convert('input.qcow2', 'output2.qcow2') # No compression
656 second_call_args = self.mock_module.run_command.call_args[0][0]
657
658 # First call should have compression flag, second should not
659 self.assertIn('-c', first_call_args)
660 self.assertNotIn('-c', second_call_args)
661
662 def test_warnings_accumulation(self):
663 """Test that warnings accumulate across operations"""
664 tool = QemuImgTool(self.mock_module)
665
666 # First operation with invalid JSON
667 self.mock_module.run_command.return_value = (0, 'invalid json 1', '')
668 tool.info('test1.qcow2')
669
670 # Second operation with invalid JSON
671 self.mock_module.run_command.return_value = (0, 'invalid json 2', '')
672 tool.info('test2.qcow2')
673
674 # Should have two warnings
675 self.assertEqual(len(tool.warnings), 2)
676 self.assertIn('Failed to parse JSON output', tool.warnings[0])
677 self.assertIn('Failed to parse JSON output', tool.warnings[1])
678
679 def test_custom_command_path(self):
680 """Test using custom qemu-img command path"""
681 custom_path = '/opt/qemu/bin/qemu-img'
682 tool = QemuImgTool(self.mock_module, qemu_img_path=custom_path)
683 self.mock_module.run_command.return_value = (0, '', '')
684
685 tool.info('test.qcow2')
686
687 called_cmd = self.mock_module.run_command.call_args[0][0]
688 self.assertEqual(called_cmd[0], custom_path)
689
690 def test_error_handling_consistency(self):
691 """Test consistent error handling across all methods"""
692 tool = QemuImgTool(self.mock_module)
693 error_rc = 2
694 error_message = 'Generic qemu-img error'
695 self.mock_module.run_command.return_value = (
696 error_rc, '', error_message)
697
698 # Test all methods return the same error code and message
699 rc1, stdout1, stderr1 = tool.convert('input.qcow2', 'output.qcow2')
700 rc2, stdout2, stderr2 = tool.info('test.qcow2')
701 rc3, stdout3, stderr3 = tool.resize('test.qcow2', '10G')
702
703 self.assertEqual(rc1, error_rc)
704 self.assertEqual(rc2, error_rc)
705 self.assertEqual(rc3, error_rc)
706 self.assertEqual(stderr1, error_message)
707 self.assertEqual(stderr2, error_message)
708 self.assertEqual(stderr3, error_message)
709
710 def test_check_mode_convert(self):
711 """Test that convert respects check_mode"""
712 tool = QemuImgTool(self.mock_module)
713 self.mock_module.check_mode = True
714
715 # In check mode, command should not be executed
716 rc, stdout, stderr = tool.convert(
717 'input.qcow2', 'output.qcow2', compressed=True)
718
719 # Should return success with descriptive message
720 self.assertEqual(rc, 0)
721 self.assertIn(
722 'Would convert image from input.qcow2 to output.qcow2', stdout)
723 self.assertEqual(stderr, '')
724
725 # run_command should not have been called
726 self.mock_module.run_command.assert_not_called()
727
728 def test_check_mode_resize(self):
729 """Test that resize respects check_mode"""
730 tool = QemuImgTool(self.mock_module)
731 self.mock_module.check_mode = True
732
733 # In check mode, command should not be executed
734 rc, stdout, stderr = tool.resize('test.qcow2', '20G', shrink=True)
735
736 # Should return success with descriptive message
737 self.assertEqual(rc, 0)
738 self.assertIn('Would resize image test.qcow2 to 20G', stdout)
739 self.assertEqual(stderr, '')
740
741 # run_command should not have been called
742 self.mock_module.run_command.assert_not_called()
743
744 def test_check_mode_info_not_affected(self):
745 """Test that info command is not affected by check_mode"""
746 tool = QemuImgTool(self.mock_module)
747 self.mock_module.check_mode = True
748 self.mock_module.run_command.return_value = (
749 0, '{"format": "qcow2"}', '')
750
751 # Info should still execute even in check mode (read-only operation)
752 rc, output, stderr = tool.info('test.qcow2')
753
754 # Should execute normally and return parsed output
755 self.assertEqual(rc, 0)
756 self.assertEqual(output, {"format": "qcow2"})
757 self.assertEqual(stderr, '')
758
759 # run_command should have been called for info (read-only)
760 self.mock_module.run_command.assert_called_once()
761
762 def test_check_mode_false_normal_execution(self):
763 """Test that operations execute normally when check_mode is False"""
764 tool = QemuImgTool(self.mock_module)
765 self.mock_module.check_mode = False
766 self.mock_module.run_command.return_value = (0, '', '')
767
768 # All operations should execute normally
769 rc1, stdout1, stderr1 = tool.convert('input.qcow2', 'output.qcow2')
770 rc2, stdout2, stderr2 = tool.resize('test.qcow2', '20G')
771
772 # Should return normal command output, not check_mode messages
773 self.assertEqual(rc1, 0)
774 self.assertEqual(rc2, 0)
775 self.assertNotIn('Would convert', stdout1)
776 self.assertNotIn('Would resize', stdout2)
777
778 # run_command should have been called twice
779 self.assertEqual(self.mock_module.run_command.call_count, 2)
780
781
782 if __name__ == '__main__':
783 unittest.main(verbosity=2)