xref: /qemu/tests/functional/qemu_test/utils.py (revision cfcb4484fc78cbbd835e2880add561e1fbef6796)
1# Utilities for python-based QEMU tests
2#
3# Copyright 2024 Red Hat, Inc.
4#
5# Authors:
6#  Thomas Huth <thuth@redhat.com>
7#
8# This work is licensed under the terms of the GNU GPL, version 2 or
9# later.  See the COPYING file in the top-level directory.
10
11import gzip
12import lzma
13import os
14import shutil
15
16from .archive import tar_extract as archive_extract
17from .archive import cpio_extract
18
19"""
20Round up to next power of 2
21"""
22def pow2ceil(x):
23    return 1 if x == 0 else 2**(x - 1).bit_length()
24
25def file_truncate(path, size):
26    if size != os.path.getsize(path):
27        with open(path, 'ab+') as fd:
28            fd.truncate(size)
29
30"""
31Expand file size to next power of 2
32"""
33def image_pow2ceil_expand(path):
34        size = os.path.getsize(path)
35        size_aligned = pow2ceil(size)
36        if size != size_aligned:
37            with open(path, 'ab+') as fd:
38                fd.truncate(size_aligned)
39
40def gzip_uncompress(gz_path, output_path):
41    if os.path.exists(output_path):
42        return
43    with gzip.open(gz_path, 'rb') as gz_in:
44        try:
45            with open(output_path, 'wb') as raw_out:
46                shutil.copyfileobj(gz_in, raw_out)
47        except:
48            os.remove(output_path)
49            raise
50
51def lzma_uncompress(xz_path, output_path):
52    if os.path.exists(output_path):
53        return
54    with lzma.open(xz_path, 'rb') as lzma_in:
55        try:
56            with open(output_path, 'wb') as raw_out:
57                shutil.copyfileobj(lzma_in, raw_out)
58        except:
59            os.remove(output_path)
60            raise
61