Skip to content

Commit 51ec16a

Browse files
committed
move test code into a module
Signed-off-by: Zen <[email protected]>
1 parent b65d1b1 commit 51ec16a

File tree

10 files changed

+136
-96
lines changed

10 files changed

+136
-96
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "ugrd"
7-
version = "1.16.0"
7+
version = "1.17.0"
88
authors = [
99
{ name="Desultory", email="[email protected]" },
1010
]

src/ugrd/base/test.py

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
__version__ = "0.2.0"
2+
3+
4+
COPY_CONFIG = ['mounts', 'test_image_size', 'test_flag', 'out_dir', 'clean']
5+
6+
7+
def init_test_vars(self):
8+
if not self.get("test_kernel"):
9+
raise ValueError("test_kernel not set")
10+
if not self['test_kernel'].exists():
11+
raise FileNotFoundError("Test kernel not found: %s" % self['test_kernel'])
12+
13+
14+
def get_qemu_cmd_args(self):
15+
""" Gets the qemu command from the configuration """
16+
qemu_args = {'-m': self['test_memory'],
17+
'-cpu': self['test_cpu'],
18+
'-kernel': self['test_kernel'],
19+
'-initrd': self['_archive_out_path'],
20+
'-serial': 'mon:stdio',
21+
'-append': self['test_cmdline'],
22+
'-drive': 'file=%s,format=raw' % self['_test_rootfs']['_archive_out_path']}
23+
24+
qemu_bools = [f'-{item}' for item in self['qemu_bool_args']]
25+
26+
arglist = [f"qemu-system-{self['test_arch']}"] + qemu_bools
27+
for key, value in qemu_args.items():
28+
arglist.append(key)
29+
arglist.append(value)
30+
31+
self['_qemu_cmd'] = ' '.join(str(arg) for arg in arglist)
32+
33+
return arglist
34+
35+
36+
def make_test_image(self):
37+
""" Creates a new initramfs generator to creaate the test image """
38+
from ugrd.initramfs_generator import InitramfsGenerator
39+
40+
kwargs = {'logger': self.logger,
41+
'validate': False,
42+
'NO_BASE': True,
43+
'config': None,
44+
'modules': 'ugrd.fs.test_image',
45+
'out_file': self['test_rootfs_name'],
46+
'build_dir': self['test_rootfs_build_dir'],
47+
**{key: self[key] for key in COPY_CONFIG}}
48+
49+
target_fs = InitramfsGenerator(**kwargs)
50+
target_fs.build()
51+
self['_test_rootfs'] = target_fs
52+
53+
54+
def test_image(self):
55+
qemu_cmd = get_qemu_cmd_args(self)
56+
self.logger.info("Testing initramfs image: %s", self['_archive_out_path'])
57+
self.logger.info("Test kernel: %s", self['test_kernel'])
58+
self.logger.info("Test rootfs: %s", self['_test_rootfs']['_archive_out_path'])
59+
self.logger.info("QEMU command: %s", self['_qemu_cmd'])
60+
61+
try:
62+
results = self._run(qemu_cmd, timeout=self['test_timeout'])
63+
except RuntimeError as e:
64+
self.logger.error("Test failed: %s", e)
65+
return False
66+
67+
stdout = results.stdout.decode('utf-8').split('\r\n')
68+
self.logger.debug("QEMU output: %s", stdout)
69+
70+
if self['test_flag'] in stdout:
71+
self.logger.info("Test passed")
72+
else:
73+
self.logger.error("Test failed")
74+
self.logger.error("QEMU stdout:\n%s", stdout)
75+
76+

src/ugrd/base/test.toml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
test_rootfs_name = 'ugrd-test-rootfs'
2+
test_rootfs_build_dir = '/tmp/initramfs_test_rootfs'
3+
test_image_size = 16
4+
test_flag = "UGRD TEST SUCCESSFUL"
5+
6+
test_memory = '256M'
7+
test_cpu = 'host'
8+
test_arch = 'x86_64'
9+
test_timeout = 15
10+
test_cmdline = 'console=ttyS0,115200 panic=1'
11+
qemu_bool_args = ['nographic', 'no-reboot', 'enable-kvm']
12+
13+
[imports.tests]
14+
"ugrd.base.test" = ["init_test_vars", "make_test_image", "test_image"]
15+
16+
[custom_parameters]
17+
test_kernel = "Path" # Define the kernel to use for the test
18+
test_memory = "str" # Define the amount of memory to use for the test image (passed to qemu)
19+
test_cpu = "str" # Define the CPU to use for the test image (passed to qemu)
20+
test_arch = "str" # Define the qemu arch (added to the qemu-system- command)
21+
test_cmdline = "str" # Define the kernel command line for the test image
22+
test_timeout = "int" # Define the timeout for the test
23+
test_image_size = "int" # Define the size of the test image, in MB
24+
test_flag = "str" # Define the success flag for the test
25+
test_rootfs_name = "str" # Define the name of the rootfs image
26+
test_rootfs_build_dir = "Path" # Define the build directory for the rootfs image
27+
qemu_bool_args = "NoDupFlatList" # Define the qemu boolean arguments
28+
_test_rootfs = "InitramfsGenerator" # Define the target rootfs generator
29+
_qemu_cmd = "str" # Define the qemu command to use for the test

src/ugrd/fs/test_image.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
11
__version__ = "0.3.0"
22

33

4-
def init_test_vars(self):
5-
if not self.get('test_kernel'):
6-
raise ValueError("No test kernel specified")
7-
elif not self['test_kernel'].exists():
8-
raise FileNotFoundError("Test kernel not found: %s" % self['test_kernel'])
9-
4+
def init_banner(self):
105
self['banner'] = f"echo {self['test_flag']}"
116

127

src/ugrd/fs/test_image.toml

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,23 @@
11
modules = ['ugrd.fs.cpio']
22
paths = ['dev', 'sys', 'proc']
33

4-
5-
binaries = ['halt', 'shutdown', 'ls', 'top', 'ps']
6-
shebang = "#!/bin/bash"
7-
8-
qemu_arch = 'x86_64'
94
test_image_size = 16
10-
test_memory = '256M'
11-
test_cpu = 'host'
12-
test_cmdline = 'console=ttyS0,115200 panic=1'
135
test_flag = "UGRD TEST SUCCESSFUL"
14-
test_timeout = 15
6+
shebang = "#!/bin/bash"
7+
158

169
[masks]
1710
pack = "make_cpio"
1811

1912
[imports.build_pre]
20-
"ugrd.fs.test_image" = ["init_test_vars"]
13+
"ugrd.fs.test_image" = ["init_banner"]
2114

2215
[imports.pack]
2316
"ugrd.fs.test_image" = ["make_test_image"]
2417

2518
[custom_parameters]
26-
shebang = "str" # Add the shebang property, because the test mode disables the base module
27-
test_kernel = "Path" # Define the kernel to use for the test image
28-
test_cmdline = "str" # Define the kernel command line for the test image
29-
test_image_size = "int" # Define the size of the test image in MiB
30-
test_memory = "str" # Define the amount of memory to use for the test image (passed to qemu)
31-
test_cpu = "str" # Define the CPU to use for the test image (passed to qemu)
32-
qemu_arch = "str" # Define the qemu arch (added to the qemu-system- command)
19+
shebang = "str" # Add the shebang property, because the test mode disables the base moduleo
3320
mounts = "dict" # We only need the mounts dict, not the whole module
21+
test_image_size = "int" # Define the size of the test image in MiB
3422
test_flag = "str" # Define the success flag used to determine if the test was successful
35-
test_timeout = "int" # Define the timeout for the test
3623

src/ugrd/initramfs_dict.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ def handle_parameter(self, key: str, value) -> None:
7474
for d in (self.builtin_parameters, self['custom_parameters']):
7575
expected_type = d.get(key)
7676
if expected_type:
77+
if expected_type.__name__ == "InitramfsGenerator":
78+
return super().__setitem__(key, value)
7779
break
7880
else:
7981
raise KeyError("Parameter not registered: %s" % key)
@@ -125,6 +127,8 @@ def _process_custom_parameters(self, parameter_name: str, parameter_type: type)
125127
If the parameter is in the processing queue, process the queued values.
126128
"""
127129
from pycpio import PyCPIO
130+
from .initramfs_generator import InitramfsGenerator
131+
128132
self['custom_parameters'][parameter_name] = eval(parameter_type)
129133
self.logger.debug("Registered custom parameter '%s' with type: %s" % (parameter_name, parameter_type))
130134

@@ -139,12 +143,12 @@ def _process_custom_parameters(self, parameter_name: str, parameter_type: type)
139143
super().__setitem__(parameter_name, 0)
140144
case "float":
141145
super().__setitem__(parameter_name, 0.0)
142-
case "PyCPIO":
143-
super().__setitem__(parameter_name, PyCPIO(logger=self.logger, _log_init=False, _log_bump=10))
144146
case "str":
145147
super().__setitem__(parameter_name, "")
146148
case "Path":
147149
super().__setitem__(parameter_name, Path())
150+
case "PyCPIO":
151+
super().__setitem__(parameter_name, PyCPIO(logger=self.logger, _log_init=False, _log_bump=10))
148152
case _: # For strings and things, don't init them so they are None
149153
self.logger.warning("Leaving '%s' as None" % parameter_name)
150154
super().__setitem__(parameter_name, None)

src/ugrd/initramfs_generator.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ def build(self) -> None:
7676
self.generate_init()
7777
self.run_hook('build_final')
7878
self.pack_build()
79+
self.run_tests()
7980

8081
def run_func(self, function, force_include=False) -> list[str]:
8182
""" Runs a function, If force_include is set, forces the function to be included in the bash source file. """
@@ -206,3 +207,14 @@ def pack_build(self) -> None:
206207
else:
207208
self.logger.warning("No pack functions specified, the final build is present in: %s" % self.build_dir)
208209

210+
def run_tests(self) -> None:
211+
""" Runs tests if defined in self['imports']['tests']. """
212+
if test_output := self.run_hook('tests'):
213+
self.logger.info("Completed tests:\n%s", test_output)
214+
else:
215+
self.logger.debug("No tests executed.")
216+
217+
218+
219+
220+

src/ugrd/initramfs_tester.py

Lines changed: 0 additions & 63 deletions
This file was deleted.

src/ugrd/main.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python
22

33
from ugrd.initramfs_generator import InitramfsGenerator
4-
from ugrd.initramfs_tester import InitramfsTester
54
from zenlib.util import get_kwargs_from_args, get_args_n_logger
65

76

@@ -47,12 +46,12 @@ def main():
4746
kwargs.pop('print_config', None) # This is not a valid kwarg for InitramfsGenerator
4847
kwargs.pop('print_init', None) # This is not a valid kwarg for InitramfsGenerator
4948
test = kwargs.pop('test', False)
50-
test_kernel = kwargs.pop('test_kernel', None)
5149

5250
if test:
5351
logger.warning("TEST MODE ENABLED")
5452
logger.info("Disabling DM autodetection")
5553
kwargs['autodetect_root_dm'] = False
54+
kwargs['modules'] = 'ugrd.base.test'
5655

5756
logger.debug(f"Using the following kwargs: {kwargs}")
5857
generator = InitramfsGenerator(**kwargs)
@@ -76,10 +75,6 @@ def main():
7675
for func in generator.imports[runlevel]:
7776
print(f" {func.__name__}")
7877

79-
if test:
80-
tester = InitramfsTester(generator, test_kernel=test_kernel, logger=logger, _log_init=False)
81-
tester.test()
82-
8378

8479
if __name__ == '__main__':
8580
main()

tests/fullauto.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# NOP
22

33
modules = [
4+
"ugrd.base.test",
45
"ugrd.kmod.standard_mask",
56
]
67

@@ -9,6 +10,10 @@ out_dir = "/tmp/initramfs_test"
910

1011
kernel_version = "6.6.35-gentoo-dist"
1112
test_kernel = "/boot/vmlinuz-6.6.35-gentoo-dist"
13+
cpio_compression = false
14+
15+
autodetect_root_dm = false
16+
1217

1318
# Optionally supply a kernel version, uses the current kernel version if not specified
1419
#kernel_version = "6.1.53-gentoo-dist"

0 commit comments

Comments
 (0)