1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
|
# Copyright (C) 2019-2022 Benjamin Drung <bdrung@posteo.de>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Test configuration handling of bdebstrap."""
import contextlib
import io
import logging
import os
import tempfile
import typing
import unittest
import unittest.mock
from bdebstrap import HOOKS_DIR, Config, dict_merge, parse_args
EXAMPLE_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "..", "examples")
TEST_CONFIG_DIR = os.path.join(os.path.dirname(__file__), "configs")
def get_subset(dict_: typing.Any, keys: set[str]) -> dict[str, typing.Any]:
"""Return a dictionary that only contains the items for the given keys."""
return {key: value for key, value in dict_.items() if key in keys}
class TestArguments(unittest.TestCase):
"""
This unittest class tests the argument parsing.
"""
maxDiff = None
def test_debug(self) -> None:
"""Test --debug argument parsing."""
args = parse_args(["--debug"])
self.assertEqual(args.log_level, logging.DEBUG)
def test_empty_args(self) -> None:
"""Test setting arguments to empty strings."""
args = parse_args(
[
"--aptopt=",
"--architectures=",
"--cleanup-hook=",
"--components=",
"--config=",
"--customize-hook=",
"--dpkgopt=",
"--essential-hook=",
"--extract-hook=",
"--hook-dir=",
"--keyring=",
"--skip=",
"--mirrors=",
"--packages=",
"--setup-hook=",
]
)
self.assertEqual(
get_subset(
args.__dict__,
{
"aptopt",
"architectures",
"cleanup_hook",
"components",
"config",
"customize_hook",
"dpkgopt",
"essential_hook",
"extract_hook",
"hook_dir",
"keyring",
"mirrors",
"packages",
"setup_hook",
"skip",
},
),
{
"aptopt": [],
"architectures": [],
"cleanup_hook": [],
"components": [],
"config": [],
"customize_hook": [],
"dpkgopt": [],
"essential_hook": [],
"extract_hook": [],
"hook_dir": [],
"keyring": [],
"mirrors": [],
"packages": [],
"setup_hook": [],
"skip": [],
},
)
def test_no_args(self) -> None:
"""Test calling bdebstrap without arguments."""
args = parse_args([])
self.assertEqual(
args.__dict__,
{
"aptopt": None,
"architectures": None,
"cleanup_hook": None,
"components": None,
"config": [],
"customize_hook": None,
"dpkgopt": None,
"env": {},
"essential_hook": None,
"extract_hook": None,
"force": False,
"format": None,
"hook_dir": None,
"hostname": None,
"install_recommends": False,
"keyring": None,
"log_level": logging.WARNING,
"mirrors": [],
"mode": None,
"name": None,
"output_base_dir": ".",
"output": None,
"packages": None,
"setup_hook": None,
"simulate": False,
"skip": None,
"suite": None,
"target": None,
"tmpdir": None,
"variant": None,
},
)
def test_parse_env(self) -> None:
"""Test parsing --env parameters."""
args = parse_args(["-e", "KEY=VALUE", "--env", "FOO=bar"])
self.assertEqual(args.env, {"FOO": "bar", "KEY": "VALUE"})
def test_malformed_env(self) -> None:
"""Test malformed --env parameter (missing equal sign)."""
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit):
parse_args(["--env", "invalid"])
self.assertIn("Failed to parse --env 'invalid'.", stderr.getvalue())
def test_mirrors_with_spaces(self) -> None:
"""Test --mirrors with leading/trailing spaces."""
args = parse_args(
[
"--mirrors",
" deb http://deb.debian.org/debian unstable main\t , \t, "
"deb http://deb.debian.org/debian unstable non-free\t",
"--mirrors",
"\tdeb http://deb.debian.org/debian unstable contrib ",
]
)
self.assertEqual(
args.mirrors,
[
"deb http://deb.debian.org/debian unstable main",
"deb http://deb.debian.org/debian unstable non-free",
"deb http://deb.debian.org/debian unstable contrib",
],
)
def test_optional_args(self) -> None:
"""Test optional arguments (which also have positional ones)."""
args = parse_args(
[
"--suite",
"unstable",
"--target",
"unstable.tar",
"--mirrors",
"deb http://deb.debian.org/debian unstable main,"
"deb http://deb.debian.org/debian unstable non-free",
"--mirrors",
"deb http://deb.debian.org/debian unstable contrib",
]
)
self.assertEqual(
get_subset(args.__dict__, {"mirrors", "suite", "target"}),
{
"mirrors": [
"deb http://deb.debian.org/debian unstable main",
"deb http://deb.debian.org/debian unstable non-free",
"deb http://deb.debian.org/debian unstable contrib",
],
"suite": "unstable",
"target": "unstable.tar",
},
)
def test_positional_args(self) -> None:
"""Test positional arguments (overwriting optional ones)."""
args = parse_args(
[
"--suite",
"bullseye",
"--target",
"bullseye.tar",
"--mirrors",
"deb http://deb.debian.org/debian unstable main,"
"deb http://deb.debian.org/debian unstable non-free",
"unstable",
"unstable.tar",
"deb http://deb.debian.org/debian unstable contrib",
]
)
self.assertEqual(
get_subset(args.__dict__, {"mirrors", "suite", "target"}),
{
"mirrors": [
"deb http://deb.debian.org/debian unstable main",
"deb http://deb.debian.org/debian unstable non-free",
"deb http://deb.debian.org/debian unstable contrib",
],
"suite": "unstable",
"target": "unstable.tar",
},
)
def test_split(self) -> None:
"""Test splitting comma and space separated values."""
args = parse_args(
[
"--packages",
"distro-info ionit,netconsole",
"--include",
"openssh-server,restricted-ssh-commands",
"--components",
"main,non-free contrib",
"--architectures",
"amd64,i386",
]
)
self.assertEqual(
get_subset(args.__dict__, {"architectures", "components", "packages"}),
{
"architectures": ["amd64", "i386"],
"components": ["main", "non-free", "contrib"],
"packages": [
"distro-info",
"ionit",
"netconsole",
"openssh-server",
"restricted-ssh-commands",
],
},
)
class TestConfig(unittest.TestCase):
"""
This unittest class tests the Config object.
"""
maxDiff = None
def test_add_command_line_arguments(self) -> None:
"""Test Config.add_command_line_arguments()."""
args = parse_args(
[
"-c",
os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml"),
"--name",
"Debian-unstable",
]
)
config = Config()
config.add_command_line_arguments(args)
self.assertEqual(
config,
{
"mmdebstrap": {
"keyrings": ["/usr/share/keyrings/debian-archive-keyring.gpg"],
"mode": "unshare",
"suite": "unstable",
"target": "root.tar.xz",
"variant": "minbase",
},
"name": "Debian-unstable",
},
)
def test_config_and_arguments(self) -> None:
"""Test Config.add_command_line_arguments() with config file and arguments."""
args = parse_args(
[
"-c",
os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml"),
"--name",
"Debian-unstable",
"--variant",
"standard",
"--mode",
"root",
"--format",
"tar",
"--aptopt",
'Apt::Install-Recommends "0"',
"--keyring",
"/usr/share/keyrings",
"--dpkgopt",
"force-confdef",
"--dpkgopt",
"force-confold",
"--include",
"ionit,netconsole",
"--components",
"main,non-free",
"--architectures",
"i386",
"--mirrors",
"http://deb.debian.org/debian",
"unstable",
"unstable.tar",
]
)
config = Config()
config.add_command_line_arguments(args)
self.assertDictEqual(
config,
{
"mmdebstrap": {
"aptopts": ['Apt::Install-Recommends "0"'],
"architectures": ["i386"],
"components": ["main", "non-free"],
"dpkgopts": ["force-confdef", "force-confold"],
"format": "tar",
"keyrings": [
"/usr/share/keyrings/debian-archive-keyring.gpg",
"/usr/share/keyrings",
],
"mirrors": ["http://deb.debian.org/debian"],
"mode": "root",
"packages": ["ionit", "netconsole"],
"suite": "unstable",
"target": "unstable.tar",
"variant": "standard",
},
"name": "Debian-unstable",
},
)
def test_add_command_line_arguments_no_config(self) -> None:
"""Test Config.add_command_line_arguments() with no config file."""
args = parse_args(
[
"--cleanup-hook",
'cp /dev/null "$1/etc/hostname"',
"--customize-hook",
'chroot "$1" apt-get update',
"--env",
"KEY=VALUE",
"--essential-hook",
"copy-in /etc/bash.bashrc /etc",
"--extract-hook",
'find "$1" -xtype l',
"--hostname",
"cobb",
"--install-recommends",
"--skip=check/signed-by",
"--hook-dir=/usr/share/mmdebstrap/hooks/eatmydata",
"--name",
"ubuntu-24.04",
"--setup-hook",
'echo root:x:0:0:root:/root:/bin/sh > "$1/etc/passwd"',
]
)
config = Config()
config.add_command_line_arguments(args)
self.assertEqual(
config,
{
"env": {"KEY": "VALUE"},
"mmdebstrap": {
"cleanup-hooks": ['cp /dev/null "$1/etc/hostname"'],
"customize-hooks": ['chroot "$1" apt-get update'],
"essential-hooks": ["copy-in /etc/bash.bashrc /etc"],
"extract-hooks": ['find "$1" -xtype l'],
"hook-dirs": ["/usr/share/mmdebstrap/hooks/eatmydata"],
"hostname": "cobb",
"install-recommends": True,
"setup-hooks": ['echo root:x:0:0:root:/root:/bin/sh > "$1/etc/passwd"'],
"skip": ["check/signed-by"],
},
"name": "ubuntu-24.04",
},
)
@staticmethod
def test_check_example() -> None:
"""Test example unstable.yaml file."""
config = Config()
config.load(os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml"))
config["name"] = "Debian-unstable"
config.check()
@staticmethod
def test_commented_packages() -> None:
"""Test commented-packages.yaml file."""
config = Config()
config.load(os.path.join(TEST_CONFIG_DIR, "commented-packages.yaml"))
config.sanitize_packages()
config.check()
def test_env_items(self) -> None:
"""Test environment variables for example unstable.yaml."""
config = Config()
config.load(os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml"))
config["name"] = "Debian-unstable"
self.assertEqual(
config.env_items(),
[
("BDEBSTRAP_HOOKS", HOOKS_DIR),
("BDEBSTRAP_NAME", "Debian-unstable"),
("BDEBSTRAP_OUTPUT_DIR", "/tmp/bdebstrap-output"),
],
)
def test_loading(self) -> None:
"""Test loading a YAML configuration file."""
config = Config()
config.load(os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml"))
self.assertEqual(
config,
{
"mmdebstrap": {
"keyrings": ["/usr/share/keyrings/debian-archive-keyring.gpg"],
"mode": "unshare",
"suite": "unstable",
"target": "root.tar.xz",
"variant": "minbase",
}
},
)
def test_sanitize_packages_debs(self) -> None:
"""Test sanitize_packages method: multiple local .debs"""
config = Config()
config["mmdebstrap"] = {"packages": ["/home/user/foo.deb", "/home/user/bar.deb"]}
config.sanitize_packages()
self.assertEqual(
config["mmdebstrap"]["packages"], ["/home/user/foo.deb", "/home/user/bar.deb"]
)
def test_sanitize_packages_duplicate_debs(self) -> None:
"""Test sanitize_packages method: remove duplicate local .debs."""
config = Config()
config["mmdebstrap"] = {
"packages": ["./bdebstrap_0.5_all.deb", "../bdebstrap_0.4_all.deb"]
}
config.sanitize_packages()
self.assertEqual(config["mmdebstrap"]["packages"], ["../bdebstrap_0.4_all.deb"])
def test_sanitize_packages_duplicates(self) -> None:
"""Test sanitize_packages method: remove duplicates."""
config = Config()
config["mmdebstrap"] = {"packages": ["less/jammy-updates", "more", "less=590-1build1"]}
config.sanitize_packages()
self.assertEqual(config["mmdebstrap"]["packages"], ["less=590-1build1", "more"])
def test_sanitize_packages_pattern(self) -> None:
"""Test sanitize_packages method: APT pattern"""
config = Config()
config["mmdebstrap"] = {"packages": ["?priority(required)", "?priority(important)"]}
config.sanitize_packages()
self.assertEqual(
config["mmdebstrap"]["packages"], ["?priority(required)", "?priority(important)"]
)
def test_yaml_rendering(self) -> None:
"""Test that config.yaml is a syntactically valid yaml file."""
config = Config()
config_filename = os.path.join(EXAMPLE_CONFIG_DIR, "Debian-unstable.yaml")
config.load(config_filename)
with tempfile.NamedTemporaryFile() as temp_file:
config.save(temp_file.name)
with open(temp_file.name, encoding="utf-8") as config_file:
output_config = config_file.read()
with open(config_filename, encoding="utf-8") as config_file:
input_config = config_file.read()
self.assertEqual(output_config, input_config)
def test_yaml_flow_style(self) -> None:
"""Test that config.yaml follows the correct flow style."""
config = Config()
config["mmdebstrap"] = {"packages": ["1", "2", "3", "4", "5"]}
with tempfile.NamedTemporaryFile() as temp_file:
config.save(temp_file.name)
with open(temp_file.name, encoding="utf-8") as config_file:
lines = len(config_file.readlines())
self.assertEqual(lines, 8)
def test_source_date_epoch(self) -> None:
"""Test getting and setting SOURCE_DATE_EPOCH."""
config = Config()
self.assertIsNone(config.source_date_epoch)
with unittest.mock.patch("time.time", return_value=1581694618.0388665):
config.set_source_date_epoch()
self.assertEqual(config.source_date_epoch, 1581694618)
def test_wrong_element_type(self) -> None:
"""Test error message for wrong list element type."""
config = Config()
config.load(os.path.join(TEST_CONFIG_DIR, "wrong-element-type.yaml"))
with self.assertRaisesRegex(ValueError, "'customize-hooks' has type 'CommentedMap'"):
config.check()
class TestDictMerge(unittest.TestCase):
"""Unittests for dict_merge function."""
def test_merge_lists(self) -> None:
"""Test merging nested dicts."""
items = {"A": ["A1", "A2", "A3"], "C": 4}
dict_merge(items, {"A": ["A4", "A5"]})
self.assertEqual(items, {"A": ["A1", "A2", "A3", "A4", "A5"], "C": 4})
def test_merge_nested_dicts(self) -> None:
"""Test merging nested dicts."""
items = {"A": {"A1": 0, "A4": 4}, "C": 4}
dict_merge(items, {"A": {"A1": 1, "A5": 5}})
self.assertEqual(items, {"A": {"A1": 1, "A4": 4, "A5": 5}, "C": 4})
|