id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11,900
|
main.py
|
andreafrancia_trash-cli/trashcli/restore/main.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
import os
import sys
import trashcli.trash
from .file_system import RealRestoreReadFileSystem, \
RealRestoreWriteFileSystem, RealReadCwd, RealFileReader, \
RealListingFileSystem
from .info_dir_searcher import InfoDirSearcher
from .info_files import InfoFiles
from .real_restore_logger import RealRestoreLogger
from .restore_cmd import RestoreCmd
from .trash_directories import TrashDirectoriesImpl
from .trashed_files import TrashedFiles
from ..fstab.volumes import RealVolumes
from ..lib.logger import my_logger
from ..lib.my_input import RealInput
def main():
info_files = InfoFiles(RealListingFileSystem())
volumes = RealVolumes()
trash_directories = TrashDirectoriesImpl(volumes,
os.getuid(),
os.environ)
searcher = InfoDirSearcher(trash_directories, info_files)
trashed_files = TrashedFiles(RealRestoreLogger(my_logger),
RealFileReader(),
searcher)
RestoreCmd.make(
stdout=sys.stdout,
stderr=sys.stderr,
exit=sys.exit,
input=RealInput(),
version=trashcli.trash.version,
trashed_files=trashed_files,
read_fs=RealRestoreReadFileSystem(),
write_fs=RealRestoreWriteFileSystem(),
read_cwd=RealReadCwd()
).run(sys.argv)
| 1,447
|
Python
|
.py
| 37
| 30.891892
| 62
| 0.686567
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,901
|
restore_logger.py
|
andreafrancia_trash-cli/trashcli/restore/restore_logger.py
|
from trashcli.compat import Protocol
class RestoreLogger(Protocol):
def warning(self, message):
raise NotImplementedError
| 136
|
Python
|
.py
| 4
| 29.5
| 36
| 0.792308
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,902
|
file_system.py
|
andreafrancia_trash-cli/trashcli/restore/file_system.py
|
import os
from abc import ABCMeta, abstractmethod
from trashcli.compat import Protocol
import six
from trashcli import fs
from trashcli.fs import FsMethods, RealListFilesInDir, ListFilesInDir, \
RealContentsOf
class FileReader(Protocol):
@abstractmethod
def contents_of(self, path):
raise NotImplementedError()
class RealFileReader(RealContentsOf, FileReader):
pass
class FakeFileReader(FileReader):
def __init__(self, contents=None):
self.contents = contents
def set_content(self, contents):
self.contents = contents
def contents_of(self, path):
return self.contents
@six.add_metaclass(ABCMeta)
class RestoreReadFileSystem:
@abstractmethod
def path_exists(self, path): # type: (str) -> bool
raise NotImplementedError()
class RealRestoreReadFileSystem(RestoreReadFileSystem):
def path_exists(self, path):
return os.path.exists(path)
@six.add_metaclass(ABCMeta)
class RestoreWriteFileSystem:
@abstractmethod
def mkdirs(self, path): # type: (str) -> None
raise NotImplementedError()
@abstractmethod
def move(self, path, dest): # type: (str, str) -> None
raise NotImplementedError()
@abstractmethod
def remove_file(self, path): # type: (str) -> None
raise NotImplementedError()
class RealRestoreWriteFileSystem(RestoreWriteFileSystem):
def mkdirs(self, path):
return fs.mkdirs(path)
def move(self, path, dest):
return fs.move(path, dest)
def remove_file(self, path):
return fs.remove_file(path)
@six.add_metaclass(ABCMeta)
class ReadCwd:
@abstractmethod
def getcwd_as_realpath(self): # type: () -> str
raise NotImplementedError()
class RealReadCwd(ReadCwd):
def getcwd_as_realpath(self):
return os.path.realpath(os.curdir)
class FakeReadCwd(ReadCwd):
def __init__(self, default_cur_dir=None):
self.default_cur_dir = default_cur_dir
def chdir(self, path):
self.default_cur_dir = path
def getcwd_as_realpath(self):
return self.default_cur_dir
class ListingFileSystem(ListFilesInDir, Protocol):
pass
class RealListingFileSystem(ListingFileSystem, RealListFilesInDir):
pass
| 2,250
|
Python
|
.py
| 65
| 29.338462
| 72
| 0.722455
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,903
|
handler.py
|
andreafrancia_trash-cli/trashcli/restore/handler.py
|
from __future__ import print_function
from __future__ import unicode_literals
from typing import List
from trashcli.lib.my_input import Input
from trashcli.restore.file_system import ReadCwd
from trashcli.restore.output import Output
from trashcli.restore.output_recorder import OutputRecorder
from trashcli.restore.restore_asking_the_user import RestoreAskingTheUser
from trashcli.restore.restorer import Restorer
from trashcli.restore.run_restore_action import Handler
from trashcli.restore.trashed_file import TrashedFile
class HandlerImpl(Handler):
def __init__(self,
input, # type: Input
cwd, # type: ReadCwd
restorer, # type: Restorer
output, # type: Output
):
self.input = input
self.cwd = cwd
self.restorer = restorer
self.output = output
def handle_trashed_files(self,
trashed_files, # type: List[TrashedFile]
overwrite, # type: bool
):
if not trashed_files:
self.report_no_files_found(self.cwd.getcwd_as_realpath())
else:
for i, trashed_file in enumerate(trashed_files):
self.output.println("%4d %s %s" % (i,
trashed_file.deletion_date,
trashed_file.original_location))
self.restore_asking_the_user(trashed_files, overwrite)
def restore_asking_the_user(self, trashed_files, overwrite=False):
my_output = OutputRecorder()
restore_asking_the_user = RestoreAskingTheUser(self.input,
self.restorer,
my_output)
restore_asking_the_user.restore_asking_the_user(trashed_files,
overwrite)
my_output.apply_to(self.output)
def report_no_files_found(self, directory): # type: (str) -> None
self.output.println(
"No files trashed from current dir ('%s')" % directory)
| 2,187
|
Python
|
.py
| 45
| 33.933333
| 83
| 0.575176
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,904
|
user_info.py
|
andreafrancia_trash-cli/trashcli/lib/user_info.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
import pwd
from typing import Union
from trashcli.lib.trash_dirs import (
home_trash_dir_path_from_env,
home_trash_dir_path_from_home)
class UserInfo:
def __init__(self, home_trash_dir_paths, uid):
self.home_trash_dir_paths = home_trash_dir_paths
self.uid = uid
class SingleUserInfoProvider:
@staticmethod
def get_user_info(environ, uid):
return [UserInfo(home_trash_dir_path_from_env(environ), uid)]
class AllUsersInfoProvider:
@staticmethod
def get_user_info(_environ, _uid):
for user in pwd.getpwall():
yield UserInfo([home_trash_dir_path_from_home(user.pw_dir)],
user.pw_uid)
UserInfoProvider = Union[SingleUserInfoProvider, AllUsersInfoProvider]
| 860
|
Python
|
.py
| 22
| 33.136364
| 72
| 0.706522
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,905
|
dir_checker.py
|
andreafrancia_trash-cli/trashcli/lib/dir_checker.py
|
from __future__ import absolute_import
import os
class DirChecker:
@staticmethod
def is_dir(path):
return os.path.isdir(path)
| 145
|
Python
|
.py
| 6
| 20
| 38
| 0.720588
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,906
|
my_input.py
|
andreafrancia_trash-cli/trashcli/lib/my_input.py
|
from abc import abstractmethod, ABCMeta
import six
from six.moves import input as _my_input
@six.add_metaclass(ABCMeta)
class Input:
@abstractmethod
def read_input(self, prompt): # type: (str) -> str
raise NotImplementedError
class RealInput(Input):
def read_input(self, prompt): # type: (str) -> str
return _my_input(prompt)
class HardCodedInput(Input):
def __init__(self, reply=None):
self.reply, self.exception = self._reply(reply)
def set_reply(self, reply):
self.reply, self.exception = self._reply(reply)
def _reply(self, reply):
if reply is None:
return None, ValueError("No reply set")
else:
return reply, None
def raise_exception(self, exception):
self.exception = exception
def read_input(self, prompt): # type: (str) -> str
self.used_prompt = prompt
if self.exception:
raise self.exception
return self.reply
def last_prompt(self):
return self.used_prompt
| 1,040
|
Python
|
.py
| 30
| 27.966667
| 55
| 0.651652
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,907
|
trash_dir_reader.py
|
andreafrancia_trash-cli/trashcli/lib/trash_dir_reader.py
|
from __future__ import absolute_import
import os
from trashcli.lib.dir_reader import DirReader
class TrashDirReader:
def __init__(self,
dir_reader, # type: DirReader
):
self.dir_reader = dir_reader
def list_orphans(self, path):
info_dir = os.path.join(path, 'info')
files_dir = os.path.join(path, 'files')
for entry in self.dir_reader.entries_if_dir_exists(files_dir):
trashinfo_path = os.path.join(info_dir, entry + '.trashinfo')
file_path = os.path.join(files_dir, entry)
if not self.dir_reader.exists(trashinfo_path):
yield file_path
def list_trashinfo(self, path):
info_dir = os.path.join(path, 'info')
for entry in self.dir_reader.entries_if_dir_exists(info_dir):
if entry.endswith('.trashinfo'):
yield os.path.join(info_dir, entry)
| 919
|
Python
|
.py
| 21
| 34.142857
| 73
| 0.613917
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,908
|
print_version.py
|
andreafrancia_trash-cli/trashcli/lib/print_version.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
from __future__ import print_function
import os
import six
from typing import NamedTuple
class PrintVersionArgs(
NamedTuple('PrintVersionArgs', [
('argv0', str),
])):
def program_name(self):
return os.path.basename(self.argv0)
class PrintVersionAction(object):
def __init__(self, out, version):
self.out = out
self.version = version
def run_action(self,
args, # type: PrintVersionArgs
):
print_version(self.out, args.program_name(), self.version)
def print_version(out, program_name, version):
print("%s %s" % (program_name, six.text_type(version)), file=out)
| 774
|
Python
|
.py
| 22
| 29.045455
| 69
| 0.665317
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,909
|
trash_dirs.py
|
andreafrancia_trash-cli/trashcli/lib/trash_dirs.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
import os
from trashcli.fstab.volume_of import VolumeOf
def home_trash_dir_path_from_env(environ):
if 'XDG_DATA_HOME' in environ:
return ['%(XDG_DATA_HOME)s/Trash' % environ]
elif 'HOME' in environ:
return ['%(HOME)s/.local/share/Trash' % environ]
return []
def home_trash_dir_path_from_home(home_dir):
return '%s/.local/share/Trash' % home_dir
def home_trash_dir(environ,
volume_of, # type: VolumeOf
):
paths = home_trash_dir_path_from_env(environ)
for path in paths:
yield path, volume_of.volume_of(path)
def volume_trash_dir1(volume, uid):
path = os.path.join(volume, '.Trash/%s' % uid)
yield path, volume
def volume_trash_dir2(volume, uid):
path = os.path.join(volume, ".Trash-%s" % uid)
yield path, volume
| 926
|
Python
|
.py
| 24
| 32.833333
| 60
| 0.662921
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,910
|
exit_codes.py
|
andreafrancia_trash-cli/trashcli/lib/exit_codes.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
import os
# Error codes (from os on *nix, hard coded for Windows):
EX_OK = getattr(os, 'EX_OK', 0)
EX_USAGE = getattr(os, 'EX_USAGE', 64)
EX_IOERR = getattr(os, 'EX_IOERR', 74)
| 279
|
Python
|
.py
| 7
| 38.571429
| 60
| 0.714815
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,911
|
environ.py
|
andreafrancia_trash-cli/trashcli/lib/environ.py
|
import os
from typing import Dict
Environ = Dict[str, str]
def cast_environ(env,
): # type: (...) -> Environ
if env == os.environ:
return env
else:
raise ValueError("env must be os.environ")
| 237
|
Python
|
.py
| 9
| 20.333333
| 50
| 0.59375
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,912
|
logger.py
|
andreafrancia_trash-cli/trashcli/lib/logger.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
import logging
my_logger = logging.getLogger('trashcli.trash')
my_logger.setLevel(logging.WARNING)
my_logger.addHandler(logging.StreamHandler())
| 207
|
Python
|
.py
| 5
| 40.2
| 60
| 0.820896
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,913
|
path_of_backup_copy.py
|
andreafrancia_trash-cli/trashcli/lib/path_of_backup_copy.py
|
from __future__ import absolute_import
import os
def path_of_backup_copy(trashinfo_path):
trash_dir = os.path.dirname(os.path.dirname(trashinfo_path))
basename = os.path.basename(trashinfo_path)[:-len('.trashinfo')]
return os.path.join(trash_dir, 'files', basename)
| 281
|
Python
|
.py
| 6
| 43.333333
| 68
| 0.738971
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,914
|
enum_repr.py
|
andreafrancia_trash-cli/trashcli/lib/enum_repr.py
|
from enum import Enum
def repr_for_enum(enum): # type: (Enum) -> str
return "%s.%s" % (type(enum).__name__, enum.name)
| 126
|
Python
|
.py
| 3
| 39
| 53
| 0.619835
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,915
|
my_permission_error.py
|
andreafrancia_trash-cli/trashcli/lib/my_permission_error.py
|
from typing import Type
def get_permission_error_class(): # type: () -> Type[Exception]
try:
return PermissionError
except NameError:
return OSError
MyPermissionError = get_permission_error_class()
| 227
|
Python
|
.py
| 7
| 27.428571
| 64
| 0.717593
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,916
|
dir_reader.py
|
andreafrancia_trash-cli/trashcli/lib/dir_reader.py
|
from __future__ import absolute_import
from trashcli.compat import Protocol
from trashcli.fs import EntriesIfDirExists, PathExists, RealEntriesIfDirExists, \
RealExists
class DirReader(
EntriesIfDirExists,
PathExists,
Protocol,
):
pass
class RealDirReader(RealEntriesIfDirExists, RealExists):
pass
| 328
|
Python
|
.py
| 12
| 23.833333
| 81
| 0.806452
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,917
|
file_remover.py
|
andreafrancia_trash-cli/trashcli/rm/file_remover.py
|
from trashcli.fs import FsMethods
class FileRemover:
remove_file2 = FsMethods().remove_file2
remove_file_if_exists = FsMethods().remove_file_if_exists
| 161
|
Python
|
.py
| 4
| 36.75
| 61
| 0.780645
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,918
|
filter.py
|
andreafrancia_trash-cli/trashcli/rm/filter.py
|
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy
import fnmatch
import os
class Filter:
def __init__(self, pattern):
self.pattern = pattern
def matches(self, original_location):
basename = os.path.basename(original_location)
subject = original_location if self.pattern[0] == '/' else basename
return fnmatch.fnmatchcase(subject, self.pattern)
| 399
|
Python
|
.py
| 10
| 34.6
| 75
| 0.712435
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,919
|
cleanable_trashcan.py
|
andreafrancia_trash-cli/trashcli/rm/cleanable_trashcan.py
|
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy
from trashcli.rm.file_remover import FileRemover
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
class CleanableTrashcan:
def __init__(self,
file_remover, # type: FileRemover
):
self._file_remover = file_remover
def delete_trash_info_and_backup_copy(self, trash_info_path):
backup_copy = path_of_backup_copy(trash_info_path)
self._file_remover.remove_file_if_exists(backup_copy)
self._file_remover.remove_file2(trash_info_path)
| 584
|
Python
|
.py
| 12
| 41.25
| 65
| 0.697715
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,920
|
rm_cmd.py
|
andreafrancia_trash-cli/trashcli/rm/rm_cmd.py
|
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy
from trashcli.compat import Protocol
from trashcli.fs import ContentsOf
from trashcli.lib.dir_checker import DirChecker
from trashcli.lib.dir_reader import DirReader
from trashcli.lib.user_info import SingleUserInfoProvider
from trashcli.rm.cleanable_trashcan import CleanableTrashcan
from trashcli.rm.file_remover import FileRemover
from trashcli.rm.filter import Filter
from trashcli.rm.list_trashinfo import ListTrashinfos
from trashcli.trash_dirs_scanner import TrashDirsScanner, TopTrashDirRules, \
trash_dir_found
class RmFileSystemReader(ContentsOf,
DirReader,
TopTrashDirRules.Reader,
Protocol):
pass
class RmCmd:
def __init__(self,
environ,
getuid,
volumes_listing,
stderr,
file_reader, # type: RmFileSystemReader
):
self.environ = environ
self.getuid = getuid
self.volumes_listing = volumes_listing
self.stderr = stderr
self.file_reader = file_reader
def run(self, argv, uid):
args = argv[1:]
self.exit_code = 0
if not args:
self.print_err('Usage:\n'
' trash-rm PATTERN\n'
'\n'
'Please specify PATTERN.\n'
'trash-rm uses fnmatch.fnmatchcase to match patterns, see https://docs.python.org/3/library/fnmatch.html for more details.')
self.exit_code = 8
return
trashcan = CleanableTrashcan(FileRemover())
cmd = Filter(args[0])
listing = ListTrashinfos.make(self.file_reader, self.file_reader)
user_info_provider = SingleUserInfoProvider()
scanner = TrashDirsScanner(user_info_provider,
self.volumes_listing,
TopTrashDirRules(self.file_reader),
DirChecker())
for event, args in scanner.scan_trash_dirs(self.environ, uid):
if event == trash_dir_found:
path, volume = args
for type, arg in listing.list_from_volume_trashdir(path,
volume):
if type == 'unable_to_parse_path':
self.unable_to_parse_path(arg)
elif type == 'trashed_file':
original_location, info_file = arg
if cmd.matches(original_location):
trashcan.delete_trash_info_and_backup_copy(
info_file)
def unable_to_parse_path(self, trashinfo):
self.report_error('{}: unable to parse \'Path\''.format(trashinfo))
def report_error(self, error_msg):
self.print_err('trash-rm: {}'.format(error_msg))
def print_err(self, msg):
self.stderr.write(msg + '\n')
| 3,066
|
Python
|
.py
| 67
| 31.522388
| 151
| 0.567839
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,921
|
list_trashinfo.py
|
andreafrancia_trash-cli/trashcli/rm/list_trashinfo.py
|
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy
import os
from abc import abstractmethod
from trashcli.compat import Protocol
from trashcli.fs import ContentsOf
from trashcli.lib.dir_reader import DirReader
from trashcli.lib.trash_dir_reader import TrashDirReader
from trashcli.parse_trashinfo.parse_path import parse_path
from trashcli.parse_trashinfo.parser_error import ParseError
class FileContentReader(Protocol):
@abstractmethod
def contents_of(self, path):
raise NotImplementedError()
class ListTrashinfos:
def __init__(self,
file_content_reader, # type: ContentsOf
trash_dir_reader, # type: TrashDirReader
):
self.trash_dir_reader = trash_dir_reader
self.file_content_reader = file_content_reader
def list_from_volume_trashdir(self, trashdir_path, volume):
for trashinfo_path in self.trash_dir_reader.list_trashinfo(
trashdir_path):
trashinfo = self.file_content_reader.contents_of(trashinfo_path)
try:
path = parse_path(trashinfo)
except ParseError:
yield 'unable_to_parse_path', trashinfo_path
else:
complete_path = os.path.join(volume, path)
yield 'trashed_file', (complete_path, trashinfo_path)
@staticmethod
def make(file_content_reader, # type: ContentsOf
dir_reader, # type: DirReader
):
trash_dir_reader = TrashDirReader(dir_reader)
return ListTrashinfos(file_content_reader, trash_dir_reader)
| 1,612
|
Python
|
.py
| 37
| 34.891892
| 76
| 0.677296
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,922
|
main.py
|
andreafrancia_trash-cli/trashcli/rm/main.py
|
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy
import os
import sys
from trashcli.fs import RealExists, RealIsStickyDir, RealIsSymLink, \
RealContentsOf, RealEntriesIfDirExists
from trashcli.fstab.volume_listing import RealVolumesListing
from trashcli.rm.rm_cmd import RmCmd, RmFileSystemReader
def main():
volumes_listing = RealVolumesListing()
cmd = RmCmd(environ=os.environ,
getuid=os.getuid,
volumes_listing=volumes_listing,
stderr=sys.stderr,
file_reader=RealRmFileSystemReader())
cmd.run(sys.argv, os.getuid())
return cmd.exit_code
class RealRmFileSystemReader(RmFileSystemReader,
RealExists,
RealIsStickyDir,
RealIsSymLink,
RealContentsOf,
RealEntriesIfDirExists,
):
pass
| 963
|
Python
|
.py
| 24
| 27.916667
| 69
| 0.61588
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,923
|
parse_trashinfo.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/parse_trashinfo.py
|
from __future__ import absolute_import
import datetime
from six.moves.urllib.parse import unquote
def do_nothing(*argv, **argvk): pass
class ParseTrashInfo:
def __init__(self,
on_deletion_date=do_nothing,
on_invalid_date=do_nothing,
on_path=do_nothing):
self.found_deletion_date = on_deletion_date
self.found_invalid_date = on_invalid_date
self.found_path = on_path
def parse_trashinfo(self, contents):
found_deletion_date = False
for line in contents.split('\n'):
if not found_deletion_date and line.startswith('DeletionDate='):
found_deletion_date = True
try:
date = datetime.datetime.strptime(
line, "DeletionDate=%Y-%m-%dT%H:%M:%S")
except ValueError:
self.found_invalid_date()
else:
self.found_deletion_date(date)
if line.startswith('Path='):
path = unquote(line[len('Path='):])
self.found_path(path)
| 1,116
|
Python
|
.py
| 27
| 28.851852
| 76
| 0.560074
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,924
|
maybe_parse_deletion_date.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/maybe_parse_deletion_date.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import absolute_import
from trashcli.parse_trashinfo.basket import Basket
from trashcli.parse_trashinfo.parse_trashinfo import ParseTrashInfo
def maybe_parse_deletion_date(contents):
result = Basket(unknown_date)
parser = ParseTrashInfo(
on_deletion_date=lambda date: result.collect(date),
on_invalid_date=lambda: result.collect(unknown_date)
)
parser.parse_trashinfo(contents)
return result.collected
unknown_date = '????-??-?? ??:??:??'
| 557
|
Python
|
.py
| 13
| 38.692308
| 67
| 0.74397
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,925
|
parse_original_location.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/parse_original_location.py
|
from __future__ import absolute_import
import os
from trashcli.parse_trashinfo.parse_path import parse_path
def parse_original_location(contents, volume_path):
path = parse_path(contents)
return os.path.join(volume_path, path)
| 239
|
Python
|
.py
| 6
| 36.833333
| 58
| 0.790393
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,926
|
parse_deletion_date.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/parse_deletion_date.py
|
from __future__ import absolute_import
from trashcli.parse_trashinfo.parse_trashinfo import ParseTrashInfo
from trashcli.parse_trashinfo.basket import Basket
def parse_deletion_date(contents):
result = Basket()
parser = ParseTrashInfo(on_deletion_date=result.collect)
parser.parse_trashinfo(contents)
return result.collected
| 344
|
Python
|
.py
| 8
| 39.625
| 67
| 0.810811
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,927
|
parse_path.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/parse_path.py
|
from __future__ import absolute_import
from six.moves.urllib.parse import unquote
from trashcli.parse_trashinfo.parser_error import ParseError
def parse_path(contents):
for line in contents.split('\n'):
if line.startswith('Path='):
return unquote(line[len('Path='):])
raise ParseError('Unable to parse Path')
| 341
|
Python
|
.py
| 8
| 37.625
| 60
| 0.723404
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,928
|
basket.py
|
andreafrancia_trash-cli/trashcli/parse_trashinfo/basket.py
|
from __future__ import absolute_import
class Basket:
def __init__(self, initial_value=None):
self.collected = initial_value
def collect(self, value):
self.collected = value
| 200
|
Python
|
.py
| 6
| 27.833333
| 43
| 0.680628
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,929
|
prepare_output_message.py
|
andreafrancia_trash-cli/trashcli/empty/prepare_output_message.py
|
from trashcli.trash_dirs_scanner import trash_dir_found
def prepare_output_message(trash_dirs):
result = []
if trash_dirs:
result.append("Would empty the following trash directories:")
for event, args in trash_dirs:
if event == trash_dir_found:
trash_dir, volume = args
result.append(" - %s" % trash_dir)
result.append("Proceed? (y/N) ")
return "\n".join(result)
else:
return 'No trash directories to empty.\n'
| 512
|
Python
|
.py
| 13
| 30.846154
| 69
| 0.607646
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,930
|
description.py
|
andreafrancia_trash-cli/trashcli/empty/description.py
|
def description(program_name, printer):
printer.usage('Usage: %s [days]' % program_name)
printer.summary('Purge trashed files.')
printer.options(
" --version show program's version number and exit",
" -h, --help show this help message and exit")
printer.bug_reporting()
| 307
|
Python
|
.py
| 7
| 38.285714
| 63
| 0.663333
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,931
|
errors.py
|
andreafrancia_trash-cli/trashcli/empty/errors.py
|
class Errors:
def __init__(self, program_name, err):
self.program_name = program_name
self.err = err
def print_error(self, msg):
self.err.write(format_error_msg(self.program_name, msg))
def format_error_msg(program_name, msg):
return "%s: %s\n" % (program_name, msg)
| 306
|
Python
|
.py
| 8
| 32.375
| 64
| 0.644068
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,932
|
user.py
|
andreafrancia_trash-cli/trashcli/empty/user.py
|
from trashcli.lib.my_input import Input
class User:
def __init__(self,
prepare_output_message,
input, # type: Input
parse_reply):
self.prepare_output_message = prepare_output_message
self.input = input
self.parse_reply = parse_reply
def do_you_wanna_empty_trash_dirs(self, trash_dirs):
reply = self.input.read_input(self.prepare_output_message(trash_dirs))
return self.parse_reply(reply)
| 490
|
Python
|
.py
| 12
| 31.333333
| 78
| 0.631579
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,933
|
print_time_action.py
|
andreafrancia_trash-cli/trashcli/empty/print_time_action.py
|
# Copyright (C) 2007-2023 Andrea Francia Trivolzio(PV) Italy
from __future__ import print_function
from typing import NamedTuple
from trashcli.lib.environ import Environ
class PrintTimeArgs(
NamedTuple('PrintTimeArgs', [
('environ', Environ),
])):
pass
class PrintTimeAction:
def __init__(self, out, clock):
self.out = out
self.clock = clock
def run_action(self,
args, # type: PrintTimeArgs
):
now_value = self.clock.get_now_value(args.environ)
print(now_value.replace(microsecond=0).isoformat(), file=self.out)
| 618
|
Python
|
.py
| 18
| 27.5
| 74
| 0.652614
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,934
|
delete_according_date.py
|
andreafrancia_trash-cli/trashcli/empty/delete_according_date.py
|
from trashcli.empty.clock import Clock
from trashcli.empty.older_than import older_than
from trashcli.fs import ContentsOf
from trashcli.parse_trashinfo.parse_deletion_date import parse_deletion_date
class DeleteAccordingDate:
def __init__(self,
reader, # type: ContentsOf
clock, # type: Clock
):
self.reader = reader
self.clock = clock
def ok_to_delete(self, trashinfo_path, environ,
parsed_days): # type: (str, dict, int) -> bool
if parsed_days is None:
return True
else:
contents = self.reader.contents_of(trashinfo_path)
now_value = self.clock.get_now_value(environ)
deletion_date = parse_deletion_date(contents)
if deletion_date is not None:
if older_than(parsed_days, now_value, deletion_date):
return True
return False
| 952
|
Python
|
.py
| 23
| 30.695652
| 76
| 0.609071
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,935
|
emptier.py
|
andreafrancia_trash-cli/trashcli/empty/emptier.py
|
# Copyright (C) 2022 Andrea Francia Bereguardo(PV) Italy
from typing import Iterable
from trashcli.empty.console import Console
from trashcli.empty.delete_according_date import DeleteAccordingDate
from trashcli.empty.existing_file_remover import ExistingFileRemover
from trashcli.lib.path_of_backup_copy import path_of_backup_copy
from trashcli.lib.trash_dir_reader import TrashDirReader
from trashcli.trash_dirs_scanner import TrashDir, only_found
class Emptier:
def __init__(self, delete_mode, trash_dir_reader, file_remover, console
): # type: (DeleteAccordingDate, TrashDirReader, ExistingFileRemover, Console) -> None
self.console = console
self.file_remover = file_remover
self.delete_mode = delete_mode
self.trash_dir_reader = trash_dir_reader
def do_empty(self,
trash_dirs, # type: Iterable[TrashDir]
environ, # type: dict
parsed_days, # type: int
dry_run, # type: bool
verbose, # type: int
): # type: (...) -> None
for path in self.files_to_delete(trash_dirs, environ, parsed_days):
if dry_run:
self.console.print_dry_run(path)
else:
if verbose:
self.console.print_removing(path)
try:
self.file_remover.remove_file_if_exists(path)
except OSError:
self.console.print_cannot_remove_error(path)
def files_to_delete(self,
trash_dirs, # type: Iterable[TrashDir]
environ, # type: dict
parsed_days, # type: int
): # type: (...) -> Iterable[str]
for trash_dir in only_found(trash_dirs): # type: TrashDir
for trash_info_path in self.trash_dir_reader.list_trashinfo(
trash_dir.path):
if self.delete_mode.ok_to_delete(trash_info_path, environ,
parsed_days):
yield (path_of_backup_copy(trash_info_path))
yield trash_info_path
for orphan in self.trash_dir_reader.list_orphans(
trash_dir.path):
yield orphan
| 2,328
|
Python
|
.py
| 47
| 35.489362
| 104
| 0.576011
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,936
|
clock.py
|
andreafrancia_trash-cli/trashcli/empty/clock.py
|
from __future__ import absolute_import
import datetime
class Clock:
def __init__(self, real_now, errors):
self.real_now = real_now
self.errors = errors
def get_now_value(self, environ):
if 'TRASH_DATE' in environ:
try:
return datetime.datetime.strptime(environ['TRASH_DATE'],
"%Y-%m-%dT%H:%M:%S")
except ValueError:
self.errors.print_error('invalid TRASH_DATE: %s' %
environ['TRASH_DATE'])
return self.real_now()
return self.real_now()
| 642
|
Python
|
.py
| 16
| 26.25
| 72
| 0.508039
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,937
|
console.py
|
andreafrancia_trash-cli/trashcli/empty/console.py
|
from typing import TextIO
from trashcli.empty.errors import format_error_msg
class Console:
def __init__(self, program_name, out,
err): # type: (str, TextIO, TextIO) -> None
self.program_name = program_name
self.out = out
self.err = err
def print_cannot_remove_error(self, path):
self.print_error("cannot remove %s" % path)
def print_error(self, msg):
self.err.write(format_error_msg(self.program_name, msg))
def print_dry_run(self, path):
self.out.write("would remove %s\n" % path)
def print_removing(self, path):
self.out.write("removing %s\n" % path)
| 655
|
Python
|
.py
| 16
| 33.6875
| 64
| 0.637658
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,938
|
older_than.py
|
andreafrancia_trash-cli/trashcli/empty/older_than.py
|
def older_than(days_ago, now_value, deletion_date):
from datetime import timedelta
limit_date = now_value - timedelta(days=days_ago)
return deletion_date < limit_date
| 179
|
Python
|
.py
| 4
| 40.75
| 53
| 0.742857
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,939
|
file_system_dir_reader.py
|
andreafrancia_trash-cli/trashcli/empty/file_system_dir_reader.py
|
from trashcli.fs import RealExists, RealEntriesIfDirExists
from trashcli.lib.dir_reader import DirReader
class FileSystemDirReader(DirReader,
RealEntriesIfDirExists,
RealExists,
):
pass
| 270
|
Python
|
.py
| 7
| 25.571429
| 58
| 0.613027
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,940
|
empty_cmd.py
|
andreafrancia_trash-cli/trashcli/empty/empty_cmd.py
|
import os
from datetime import datetime
from typing import TextIO, Callable
from trashcli.empty.clock import Clock
from trashcli.empty.console import Console
from trashcli.empty.empty_action import EmptyAction, EmptyActionArgs
from trashcli.empty.errors import Errors
from trashcli.empty.existing_file_remover import ExistingFileRemover
from trashcli.empty.is_input_interactive import is_input_interactive
from trashcli.empty.parser import Parser
from trashcli.empty.print_time_action import PrintTimeAction, PrintTimeArgs
from trashcli.fs import ContentsOf
from trashcli.fstab.volume_listing import VolumesListing
from trashcli.fstab.volume_of import VolumeOf
from trashcli.lib.dir_reader import DirReader
from trashcli.lib.exit_codes import EX_OK
from trashcli.lib.print_version import PrintVersionAction, PrintVersionArgs
from trashcli.trash_dirs_scanner import TopTrashDirRules
class EmptyCmd:
def __init__(self,
argv0, # type: str
out, # type: TextIO
err, # type: TextIO
volumes_listing, # type: VolumesListing
now, # type: Callable[[], datetime]
file_reader, # type: TopTrashDirRules.Reader
dir_reader, # type: DirReader
content_reader, # type: ContentsOf
file_remover, # type: ExistingFileRemover
version, # type: str
volumes, # type: VolumeOf
):
self.volumes = volumes
self.file_remover = file_remover
self.dir_reader = dir_reader
self.file_reader = file_reader
self.volumes_listing = volumes_listing
self.argv0 = argv0
self.out = out
self.err = err
self.version = version
self.now = now
self.content_reader = content_reader
self.parser = Parser()
self.program_name = os.path.basename(argv0)
errors = Errors(self.program_name, self.err)
clock = Clock(self.now, errors)
console = Console(self.program_name, self.out, self.err)
self.empty_action = EmptyAction(clock,
self.file_remover,
self.volumes_listing,
self.file_reader,
self.volumes,
self.dir_reader,
self.content_reader,
console)
self.print_version_action = PrintVersionAction(self.out,
self.version)
self.print_time_action = PrintTimeAction(self.out, clock)
def run_cmd(self, args, environ, uid):
args = self.parser.parse(
default_is_interactive=is_input_interactive(),
args=args,
argv0=self.argv0,
environ=environ,
uid=uid)
if type(args) is PrintVersionArgs:
return self.print_version_action.run_action(args)
elif type(args) is EmptyActionArgs:
return self.empty_action.run_action(args)
elif type(args) is PrintTimeArgs:
return self.print_time_action.run_action(args)
return EX_OK
| 3,298
|
Python
|
.py
| 73
| 32.657534
| 75
| 0.607331
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,941
|
empty_action.py
|
andreafrancia_trash-cli/trashcli/empty/empty_action.py
|
from typing import NamedTuple, List
from trashcli.empty.clock import Clock
from trashcli.empty.console import Console
from trashcli.empty.delete_according_date import (
DeleteAccordingDate,
)
from trashcli.empty.emptier import Emptier
from trashcli.empty.existing_file_remover import ExistingFileRemover
from trashcli.empty.guard import Guard
from trashcli.empty.parse_reply import parse_reply
from trashcli.empty.prepare_output_message import prepare_output_message
from trashcli.empty.user import User
from trashcli.fs import ContentsOf
from trashcli.fstab.volume_listing import VolumesListing
from trashcli.fstab.volume_of import VolumeOf
from trashcli.lib.dir_reader import DirReader
from trashcli.lib.environ import Environ
from trashcli.lib.my_input import RealInput
from trashcli.lib.trash_dir_reader import TrashDirReader
from trashcli.list.trash_dir_selector import TrashDirsSelector
from trashcli.trash_dirs_scanner import TopTrashDirRules
class EmptyActionArgs(
NamedTuple('EmptyActionArgs', [
('user_specified_trash_dirs', List[str]),
('all_users', bool),
('interactive', bool),
('days', int),
('dry_run', bool),
('verbose', int),
('environ', Environ),
('uid', int),
])):
pass
class EmptyAction:
def __init__(self,
clock, # type: Clock
file_remover, # type: ExistingFileRemover
volumes_listing, # type: VolumesListing
file_reader, # type: TopTrashDirRules.Reader
volumes, # type: VolumeOf
dir_reader, # type: DirReader
content_reader, # type: ContentsOf
console, # type: Console
): # type: (...) -> None
self.selector = TrashDirsSelector.make(volumes_listing,
file_reader,
volumes)
trash_dir_reader = TrashDirReader(dir_reader)
delete_mode = DeleteAccordingDate(content_reader,
clock)
user = User(prepare_output_message, RealInput(), parse_reply)
self.emptier = Emptier(delete_mode, trash_dir_reader, file_remover,
console)
self.guard = Guard(user)
def run_action(self,
args, # type: EmptyActionArgs
): # type: (...) -> None
trash_dirs = self.selector.select(args.all_users,
args.user_specified_trash_dirs,
args.environ,
args.uid)
delete_pass = self.guard.ask_the_user(args.interactive,
trash_dirs)
if delete_pass.ok_to_empty:
self.emptier.do_empty(delete_pass.trash_dirs, args.environ,
args.days, args.dry_run, args.verbose)
| 2,991
|
Python
|
.py
| 66
| 33.075758
| 75
| 0.601576
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,942
|
parser.py
|
andreafrancia_trash-cli/trashcli/empty/parser.py
|
import argparse
from typing import List
from trashcli.empty.empty_action import EmptyActionArgs
from trashcli.empty.print_time_action import PrintTimeArgs
from trashcli.lib.environ import Environ
from trashcli.lib.print_version import PrintVersionArgs
from trashcli.shell_completion import TRASH_DIRS, add_argument_to
class Parser:
def parse(self,
default_is_interactive, # type: bool
environ, # type: Environ
args, # type: List[str]
uid, # type: int
argv0, # type: str
):
parser = self.make_parser(default_is_interactive)
namespace = parser.parse_args(args)
if namespace.version:
return PrintVersionArgs(
argv0=argv0,
)
elif namespace.print_time:
return PrintTimeArgs(environ=environ)
else:
return EmptyActionArgs(
user_specified_trash_dirs=namespace.user_specified_trash_dirs,
all_users=namespace.all_users,
interactive=namespace.interactive,
days=namespace.days,
dry_run=namespace.dry_run,
verbose=namespace.verbose,
environ=environ,
uid=uid,
)
@staticmethod
def make_parser(default_is_interactive):
parser = argparse.ArgumentParser(
description='Purge trashed files.',
epilog='Report bugs to https://github.com/andreafrancia/trash-cli/issues')
add_argument_to(parser)
parser.add_argument('--version', action='store_true', default=False,
help="show program's version number and exit")
parser.add_argument("-v",
"--verbose",
default=0,
action="count",
dest="verbose",
help="list files that will be deleted",
)
parser.add_argument('--trash-dir', action='append', default=[],
metavar='TRASH_DIR',
dest='user_specified_trash_dirs',
help='specify the trash directory to use'
).complete = TRASH_DIRS
parser.add_argument('--print-time', action='store_true',
dest='print_time',
help=argparse.SUPPRESS)
parser.add_argument('--all-users', action='store_true',
dest='all_users',
help='empty all trashcan of all the users')
parser.add_argument('-i',
'--interactive',
action='store_true',
dest='interactive',
help='ask before emptying trash directories',
default=default_is_interactive)
parser.add_argument('-f',
action='store_false',
help='don\'t ask before emptying trash directories',
dest='interactive')
parser.add_argument('--dry-run',
action='store_true',
help='show which files would have been removed',
dest='dry_run')
parser.add_argument('days', action='store', default=None, type=int,
nargs='?')
return parser
| 3,538
|
Python
|
.py
| 77
| 29.064935
| 86
| 0.514765
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,943
|
main.py
|
andreafrancia_trash-cli/trashcli/empty/main.py
|
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy
import os
import sys
from datetime import datetime
from trashcli.compat import Protocol
from trashcli import trash
from trashcli.empty.empty_cmd import EmptyCmd
from trashcli.fs import RealContentsOf, ContentsOf
from .existing_file_remover import ExistingFileRemover
from .file_system_dir_reader import FileSystemDirReader
from .top_trash_dir_rules_file_system_reader import \
RealTopTrashDirRulesReader
from ..fstab.volume_listing import RealVolumesListing
from ..fstab.real_volume_of import RealVolumeOf
class ContentReader(ContentsOf, Protocol):
pass
def main():
empty_cmd = EmptyCmd(argv0=sys.argv[0],
out=sys.stdout,
err=sys.stderr,
volumes_listing=RealVolumesListing(),
now=datetime.now,
file_reader=RealTopTrashDirRulesReader(),
file_remover=ExistingFileRemover(),
content_reader=FileSystemContentReader(),
dir_reader=FileSystemDirReader(),
version=trash.version,
volumes=RealVolumeOf())
return empty_cmd.run_cmd(sys.argv[1:], os.environ, os.getuid())
class FileSystemContentReader(ContentReader, RealContentsOf):
pass
| 1,366
|
Python
|
.py
| 31
| 34.096774
| 67
| 0.675207
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,944
|
guard.py
|
andreafrancia_trash-cli/trashcli/empty/guard.py
|
from typing import Iterable, NamedTuple
from trashcli.empty.user import User
from trashcli.trash_dirs_scanner import TrashDir
UserIntention = NamedTuple('UserIntention',
[('ok_to_empty', bool),
('trash_dirs', Iterable[TrashDir])])
class Guard:
def __init__(self, user): # type: (User) -> None
self.user = user
def ask_the_user(self,
parsed_interactive, # type: bool
trash_dirs, # type: Iterable[TrashDir]
): # type: (...) -> UserIntention
if parsed_interactive:
return self._interactive(trash_dirs)
else:
return self.non_interactive(trash_dirs)
def _interactive(self, trash_dirs, # type: Iterable[TrashDir]
): # type: (...) -> UserIntention
trash_dirs_list = list(trash_dirs) # type: Iterable[TrashDir]
ok_to_empty = \
self.user.do_you_wanna_empty_trash_dirs(trash_dirs_list)
list_result = trash_dirs_list if ok_to_empty else []
return UserIntention(ok_to_empty=ok_to_empty,
trash_dirs=list_result)
def non_interactive(self,
trash_dirs, # type: Iterable[TrashDir]
):
trash_dirs_list = trash_dirs # type: Iterable[TrashDir]
return UserIntention(ok_to_empty=True,
trash_dirs=trash_dirs_list)
| 1,477
|
Python
|
.py
| 31
| 34.483871
| 70
| 0.561892
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,945
|
top_trash_dir_rules_file_system_reader.py
|
andreafrancia_trash-cli/trashcli/empty/top_trash_dir_rules_file_system_reader.py
|
from trashcli.fs import RealExists, RealIsStickyDir, RealIsSymLink
from trashcli.trash_dirs_scanner import TopTrashDirRules
class RealTopTrashDirRulesReader(
TopTrashDirRules.Reader,
RealExists,
RealIsStickyDir,
RealIsSymLink,
):
pass
| 257
|
Python
|
.py
| 9
| 25.111111
| 66
| 0.825203
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,946
|
mount_points_listing.py
|
andreafrancia_trash-cli/trashcli/fstab/mount_points_listing.py
|
# Copyright (C) 2009-2020 Andrea Francia Trivolzio(PV) Italy
import os
from abc import ABCMeta, abstractmethod
import six
@six.add_metaclass(ABCMeta)
class MountPointsListing:
@abstractmethod
def list_mount_points(self):
raise NotImplementedError()
class RealMountPointsListing(MountPointsListing):
def list_mount_points(self):
return os_mount_points()
class FakeMountPointsListing(MountPointsListing):
def __init__(self, mount_points):
self.mount_points = mount_points
def set_mount_points(self, mount_points):
self.mount_points = mount_points
def list_mount_points(self):
return self.mount_points
def os_mount_points():
import psutil
# List of accepted non-physical fstypes
fstypes = [
'nfs',
'nfs4',
'p9', # file system used in WSL 2 (Windows Subsystem for Linux)
'btrfs',
'fuse', # https://github.com/andreafrancia/trash-cli/issues/250
'fuse.glusterfs',
# https://github.com/andreafrancia/trash-cli/issues/255
'fuse.mergerfs',
'fuse.gocryptfs',
]
# Append fstypes of physical devices to list
fstypes += set([p.fstype for p in psutil.disk_partitions()])
partitions = Partitions(fstypes)
for p in psutil.disk_partitions(all=True):
if os.path.isdir(p.mountpoint) and \
partitions.should_used_by_trashcli(p):
yield p.mountpoint
class Partitions:
def __init__(self, physical_fstypes):
self.physical_fstypes = physical_fstypes
def should_used_by_trashcli(self, partition):
if ((partition.device, partition.mountpoint,
partition.fstype) ==
('tmpfs', '/tmp', 'tmpfs')):
return True
return partition.fstype in self.physical_fstypes
| 1,823
|
Python
|
.py
| 49
| 30.204082
| 72
| 0.670461
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,947
|
volume_listing.py
|
andreafrancia_trash-cli/trashcli/fstab/volume_listing.py
|
import os
from abc import ABCMeta, abstractmethod
import six
from trashcli.fstab.mount_points_listing import MountPointsListing, \
RealMountPointsListing
@six.add_metaclass(ABCMeta)
class VolumesListing:
@abstractmethod
def list_volumes(self, environ): # type (dict) -> Iterable[str]
raise NotImplementedError()
class FixedVolumesListing(VolumesListing):
def __init__(self, volumes):
self.volumes = volumes
def list_volumes(self, _environ):
return self.volumes
class RealVolumesListing(VolumesListing):
def list_volumes(self, environ):
return VolumesListingImpl(RealMountPointsListing()).list_volumes(
environ)
class VolumesListingImpl:
def __init__(self,
mount_points_listing, # type: MountPointsListing
):
self.mount_points_listing = mount_points_listing
def list_volumes(self, environ):
if 'TRASH_VOLUMES' in environ and environ['TRASH_VOLUMES']:
return [vol
for vol in environ['TRASH_VOLUMES'].split(':')
if vol != '']
return self.mount_points_listing.list_mount_points()
class NoVolumesListing(VolumesListing):
def list_volumes(self, environ):
return []
class RealIsMount:
def is_mount(self, path):
return os.path.ismount(path)
| 1,361
|
Python
|
.py
| 36
| 30.527778
| 73
| 0.6822
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,948
|
volume_of_impl.py
|
andreafrancia_trash-cli/trashcli/fstab/volume_of_impl.py
|
import os
from trashcli.fstab.volume_of import VolumeOf
class VolumeOfImpl(VolumeOf):
def __init__(self, ismount, abspath):
self.ismount = ismount
self.abspath = abspath
def volume_of(self, path):
path = self.abspath(path)
while path != os.path.dirname(path):
if self.ismount.is_mount(path):
break
path = os.path.dirname(path)
return path
| 431
|
Python
|
.py
| 13
| 25.076923
| 45
| 0.620773
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,949
|
volume_of.py
|
andreafrancia_trash-cli/trashcli/fstab/volume_of.py
|
from abc import abstractmethod
from trashcli.compat import Protocol
class VolumeOf(Protocol):
@abstractmethod
def volume_of(self, path):
raise NotImplementedError()
| 184
|
Python
|
.py
| 6
| 26.5
| 36
| 0.782857
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,950
|
volumes.py
|
andreafrancia_trash-cli/trashcli/fstab/volumes.py
|
from abc import ABCMeta
import six
import os
from trashcli.fstab.mount_points_listing import MountPointsListing, \
RealMountPointsListing
from trashcli.fstab.volume_of import VolumeOf
from trashcli.fstab.real_volume_of import RealVolumeOf
@six.add_metaclass(ABCMeta)
class Volumes(VolumeOf, MountPointsListing):
pass
class RealVolumes(Volumes):
def volume_of(self, path):
return RealVolumeOf().volume_of(path)
def list_mount_points(self):
return RealMountPointsListing().list_mount_points()
class VolumesImpl(Volumes):
def __init__(self,
volumes, # type: VolumeOf
mount_point_listing, # type: MountPointsListing
):
self.volumes = volumes
self.mount_point_listing = mount_point_listing
def volume_of(self, path):
return self.volumes.volume_of(path)
def list_mount_points(self):
return self.mount_point_listing.list_mount_points()
class FakeVolumes(Volumes):
def __init__(self,
mount_points, # type Iterable[str]
):
self.mount_points = mount_points
def list_mount_points(self):
return self.mount_points
def volume_of(self, path):
while path != os.path.dirname(path):
if self.is_a_mount_point(path):
break
path = os.path.dirname(path)
return path
def is_a_mount_point(self, path):
return path in self.mount_points
def add_volume(self, path):
self.mount_points.append(path)
class FakeVolumes2(Volumes):
def __init__(self, volume_of_string, volumes_list):
self.volume_of_string = volume_of_string
self.volumes_list = volumes_list
def volume_of(self, path):
return self.volume_of_string % path
def set_volumes(self, volumes_list):
self.volumes_list = volumes_list
def list_mount_points(self):
return self.volumes_list
| 1,961
|
Python
|
.py
| 53
| 29.471698
| 69
| 0.665607
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,951
|
real_volume_of.py
|
andreafrancia_trash-cli/trashcli/fstab/real_volume_of.py
|
import os
from trashcli.fstab.volume_listing import RealIsMount
from trashcli.fstab.volume_of import VolumeOf
from trashcli.fstab.volume_of_impl import VolumeOfImpl
class RealVolumeOf(VolumeOf):
def __init__(self):
self.impl = VolumeOfImpl(RealIsMount(), os.path.abspath)
def volume_of(self, path):
return self.impl.volume_of(path)
| 360
|
Python
|
.py
| 9
| 35.888889
| 64
| 0.766571
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,952
|
check-python-dep
|
andreafrancia_trash-cli/scripts/lib/check-python-dep
|
#!/bin/bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
COMMAND="$1"
test -x "$VIRTUAL_ENV/bin/$COMMAND" || {
>&2 echo "$COMMAND not installed
Please run:
pip install -r requirements.txt -r requirements-dev.txt
"
}
| 282
|
Python
|
.pyt
| 10
| 26
| 80
| 0.63806
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,953
|
print_python_executable.py
|
andreafrancia_trash-cli/trashcli/list/minor_actions/print_python_executable.py
|
class PrintPythonExecutableArgs:
pass
class PrintPythonExecutable:
def run_action(self,
_args, # type: PrintPythonExecutableArgs
):
import sys
print(sys.executable)
| 230
|
Python
|
.pyt
| 8
| 19.75
| 60
| 0.618182
|
andreafrancia/trash-cli
| 3,580
| 179
| 62
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,954
|
setup.py
|
cobbler_cobbler/setup.py
|
#!/usr/bin/env python3
"""
Setup module for Cobbler
"""
import codecs
import glob as _glob
import os
import pwd
import shutil
import subprocess
import sys
import time
from configparser import ConfigParser
from distutils.command.build import build as _build
from typing import Any, Dict, List
from setuptools import Command
from setuptools import Distribution as _Distribution
from setuptools import find_packages, setup
from setuptools.command.build_py import build_py as _build_py
from setuptools.command.install import install as _install
try:
# Setuptools compatibility 70+
# https://github.com/cobbler/cobbler/issues/3692
from setuptools import modified
except ImportError:
from setuptools import dep_util as modified # type: ignore
VERSION = "3.4.0"
OUTPUT_DIR = "config"
# # Configurable installation roots for various data files.
datadir = os.environ.get("DATAPATH", "/usr/share/cobbler")
docpath = os.environ.get("DOCPATH", "share/man")
etcpath = os.environ.get("ETCPATH", "/etc/cobbler")
libpath = os.environ.get("LIBPATH", "/var/lib/cobbler")
logpath = os.environ.get("LOG_PATH", "/var/log")
completion_path = os.environ.get(
"COMPLETION_PATH", "/usr/share/bash-completion/completions"
)
statepath = os.environ.get("STATEPATH", "/tmp/cobbler_settings/devinstall")
http_user = os.environ.get("HTTP_USER", "wwwrun")
httpd_service = os.environ.get("HTTPD_SERVICE", "apache2.service")
webconfig = os.environ.get("WEBCONFIG", "/etc/apache2/vhosts.d")
webroot = os.environ.get("WEBROOT", "/srv/www")
tftproot = os.environ.get("TFTPROOT", "/srv/tftpboot")
bind_zonefiles = os.environ.get("ZONEFILES", "/var/lib/named/")
shim_folder = os.environ.get("SHIM_FOLDER", "/usr/share/efi/*/")
shim_file = os.environ.get("SHIM_FILE", r"shim\.efi")
secure_boot_folder = os.environ.get("SECURE_BOOT_FOLDER", "/usr/share/efi/*/")
secure_boot_file = os.environ.get("SECURE_BOOT_FILE", r"grub\.efi")
ipxe_folder = os.environ.get("IPXE_FOLDER", "/usr/share/ipxe/")
memdisk_folder = os.environ.get("MEMDISK_FOLDER", "/usr/share/syslinux")
pxelinux_folder = os.environ.get("PXELINUX_FOLDER", "/usr/share/syslinux")
syslinux_dir = os.environ.get("SYSLINUX_DIR", "/usr/share/syslinux")
grub_mod_folder = os.environ.get("GRUB_MOD_FOLDER", "/usr/share/grub2")
#####################################################################
# # Helper Functions #################################################
#####################################################################
def glob(*args: str, **kwargs: Any) -> List[str]:
recursive = kwargs.get("recursive", False)
results: List[str] = []
for arg in args:
for elem in _glob.glob(arg):
# Now check if we should handle/check those results.
if os.path.isdir(elem):
if os.path.islink(elem):
# We skip symlinks
pass
else:
# We only handle directories if recursive was specified
if recursive:
results.extend(
# Add the basename of arg (the pattern) to elem and continue
glob(
os.path.join(elem, os.path.basename(arg)),
recursive=True,
)
)
else:
# Always append normal files
results.append(elem)
return results
def read_readme_file() -> str:
"""
read the contents of your README file
"""
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
return f.read()
#####################################################################
#####################################################################
def gen_build_version():
buildepoch = int(os.environ.get("SOURCE_DATE_EPOCH", time.time()))
builddate = time.asctime(time.gmtime(buildepoch))
gitloc = "/usr/bin/git"
gitdate = "?"
gitstamp = "?"
if not os.path.isfile(gitloc):
print("warning: " + gitloc + " not found")
else:
cmd = subprocess.Popen(
[gitloc, "log", "--format=%h%n%ad", "-1"], stdout=subprocess.PIPE
)
data = cmd.communicate()[0].strip()
if cmd.returncode == 0:
gitstamp, gitdate = data.decode("utf8").split("\n")
with open(
os.path.join(OUTPUT_DIR, "version"), "w", encoding="UTF-8"
) as version_file:
config = ConfigParser()
config.add_section("cobbler")
config.set("cobbler", "gitdate", str(gitdate))
config.set("cobbler", "gitstamp", str(gitstamp))
config.set("cobbler", "builddate", builddate)
config.set("cobbler", "version", VERSION)
config.set(
"cobbler", "version_tuple", str([int(x) for x in VERSION.split(".")])
)
config.write(version_file)
#####################################################################
# # Custom Distribution Class ########################################
#####################################################################
class Distribution(_Distribution):
def __init__(self, *args: Any, **kwargs: Any):
self.configure_files = []
self.configure_values = {}
self.man_pages = []
_Distribution.__init__(self, *args, **kwargs)
#####################################################################
# # Modify Build Stage ##############################################
#####################################################################
class BuildPy(_build_py):
"""Specialized Python source builder."""
def run(self):
gen_build_version()
_build_py.run(self)
#####################################################################
# # Modify Build Stage ##############################################
#####################################################################
class Build(_build):
"""Specialized Python source builder."""
def run(self):
_build.run(self)
#####################################################################
# # Configure files ##################################################
#####################################################################
class BuildCfg(Command):
"""
TODO
"""
description = "configure files (copy and substitute options)"
user_options = [
("install-base=", None, "base installation directory"),
(
"install-platbase=",
None,
"base installation directory for platform-specific files ",
),
(
"install-purelib=",
None,
"installation directory for pure Python module distributions",
),
(
"install-platlib=",
None,
"installation directory for non-pure module distributions",
),
(
"install-lib=",
None,
"installation directory for all module distributions "
+ "(overrides --install-purelib and --install-platlib)",
),
("install-headers=", None, "installation directory for C/C++ headers"),
("install-scripts=", None, "installation directory for Python scripts"),
("install-data=", None, "installation directory for data files"),
("force", "f", "forcibly build everything (ignore file timestamps"),
]
boolean_options = ["force"]
def initialize_options(self):
"""
TODO
"""
self.build_dir = None
self.force = None
self.install_base = None
self.install_platbase = None
self.install_scripts = None
self.install_data = None
self.install_purelib = None
self.install_platlib = None
self.install_lib = None
self.install_headers = None
self.root = None
def finalize_options(self):
"""
TODO
"""
self.set_undefined_options(
"build", ("build_base", "build_dir"), ("force", "force")
)
self.set_undefined_options(
"install",
("install_base", "install_base"),
("install_platbase", "install_platbase"),
("install_scripts", "install_scripts"),
("install_data", "install_data"),
("install_purelib", "install_purelib"),
("install_platlib", "install_platlib"),
("install_lib", "install_lib"),
("install_headers", "install_headers"),
("root", "root"),
)
if self.root:
# We need the unrooted versions of this values
for name in ("lib", "purelib", "platlib", "scripts", "data", "headers"):
attr = "install_" + name
setattr(
self, attr, "/" + os.path.relpath(getattr(self, attr), self.root)
)
# Check if we are running under a virtualenv
if hasattr(sys, "real_prefix"):
virtualenv = sys.prefix
else:
virtualenv = ""
# The values to expand.
self.configure_values = { # type: ignore
"python_executable": sys.executable,
"virtualenv": virtualenv,
"install_base": os.path.normpath(self.install_base), # type: ignore
"install_platbase": os.path.normpath(self.install_platbase), # type: ignore
"install_scripts": os.path.normpath(self.install_scripts), # type: ignore
"install_data": os.path.normpath(self.install_data), # type: ignore
"install_purelib": os.path.normpath(self.install_purelib), # type: ignore
"install_platlib": os.path.normpath(self.install_platlib), # type: ignore
"install_lib": os.path.normpath(self.install_lib), # type: ignore
"install_headers": os.path.normpath(self.install_headers), # type: ignore
}
self.configure_values.update(self.distribution.configure_values) # type: ignore
def run(self):
"""
TODO
"""
# On dry-run ignore missing source files.
if self.dry_run: # type: ignore
mode = "newer"
else:
mode = "error"
# Work on all files
for infile in self.distribution.configure_files: # type: ignore
# We copy the files to build/
outfile = os.path.join(self.build_dir, infile) # type: ignore
# check if the file is out of date
if self.force or modified.newer_group([infile, "setup.py"], outfile, mode): # type: ignore
# It is. Configure it
self.configure_one_file(infile, outfile) # type: ignore
def configure_one_file(self, infile: str, outfile: str):
"""
TODO
"""
self.announce("configuring %s" % infile, 3)
if not self.dry_run: # type: ignore
# Read the file
with codecs.open(infile, "r", "utf-8") as fh:
before = fh.read()
# Substitute the variables
# Create the output directory if necessary
outdir = os.path.dirname(outfile)
if not os.path.exists(outdir):
os.makedirs(outdir)
# Write it into build/
with codecs.open(outfile, "w", "utf-8") as fh:
fh.write(self.substitute_values(before, self.configure_values)) # type: ignore
# The last step is to copy the permission bits
shutil.copymode(infile, outfile)
def substitute_values(self, string: str, values: Dict[str, Any]) -> str:
"""
TODO
"""
for name, val in list(values.items()):
# print("replacing @@%s@@ with %s" % (name, val))
string = string.replace(f"@@{name}@@", val)
return string
def has_configure_files(build: Build):
"""Check if the distribution has configuration files to work on."""
return bool(build.distribution.configure_files) # type: ignore
Build.sub_commands.extend((("build_cfg", has_configure_files),))
#####################################################################
# # Modify Install Stage ############################################
#####################################################################
class Install(_install):
"""Specialised python package installer.
It does some required chown calls in addition to the usual stuff.
"""
def __init__(self, *args: Any):
_install.__init__(self, *args)
def change_owner(self, path: str, owner: str):
"""
TODO
"""
user = pwd.getpwnam(owner)
try:
self.announce("changing mode of %s" % path, 3)
if not self.dry_run: # type: ignore
# os.walk does not include the toplevel directory
os.lchown(path, user.pw_uid, -1)
# Now walk the directory and change them all
for root, dirs, files in os.walk(path):
for dirname in dirs:
os.lchown(os.path.join(root, dirname), user.pw_uid, -1)
for filename in files:
os.lchown(os.path.join(root, filename), user.pw_uid, -1)
except OSError as os_error:
# We only check for errno = 1 (EPERM) here because its kinda
# expected when installing as a non root user.
if os_error.errno == 1:
self.warn("Could not change owner: You have insufficient permissions.")
else:
raise os_error
def run(self):
"""
TODO
"""
# Run the usual stuff.
_install.run(self) # type: ignore
# If --root wasn't specified default to /usr/local
if self.root is None:
self.root = "/usr/local"
#####################################################################
# # Test Command #####################################################
#####################################################################
class TestCommand(Command):
"""
TODO
"""
user_options = []
def initialize_options(self):
"""
TODO
"""
def finalize_options(self):
"""
TODO
"""
def run(self):
"""
TODO
"""
import pytest
from coverage import Coverage # type: ignore
cov = Coverage()
cov.erase()
cov.start()
result = pytest.main()
cov.stop()
cov.save()
cov.html_report(directory="covhtml") # type: ignore
sys.exit(int(bool(len(result.failures) > 0 or len(result.errors) > 0))) # type: ignore
#####################################################################
# # state command base class #########################################
#####################################################################
class Statebase(Command):
"""
TODO
"""
user_options = [
("statepath=", None, "directory to backup configuration"),
("root=", None, "install everything relative to this alternate root directory"),
]
def initialize_options(self):
"""
TODO
"""
self.statepath = statepath
self.root = None
def finalize_options(self):
"""
TODO
"""
pass
def _copy(self, frm: str, to: str):
if os.path.isdir(frm):
to = os.path.join(to, os.path.basename(frm))
self.announce("copying %s/ to %s/" % (frm, to), 3)
if not self.dry_run: # type: ignore
if os.path.exists(to):
shutil.rmtree(to)
shutil.copytree(frm, to)
else:
self.announce(
"copying %s to %s" % (frm, os.path.join(to, os.path.basename(frm))), 3
)
if not self.dry_run: # type: ignore
shutil.copy2(frm, to)
#####################################################################
# # restorestate command #############################################
#####################################################################
class Restorestate(Statebase):
"""
TODO
"""
def _copy(self, frm: str, to: str):
if self.root:
to = self.root + to
super()._copy(frm, to)
def run(self):
self.announce("restoring the current configuration from %s" % self.statepath, 3)
if not os.path.exists(self.statepath):
self.warn("%s does not exist. Skipping" % self.statepath)
return
self._copy(os.path.join(self.statepath, "collections"), libpath)
self._copy(os.path.join(self.statepath, "cobbler.conf"), webconfig)
self._copy(os.path.join(self.statepath, "settings.yaml"), etcpath)
self._copy(os.path.join(self.statepath, "users.conf"), etcpath)
self._copy(os.path.join(self.statepath, "users.digest"), etcpath)
self._copy(os.path.join(self.statepath, "dhcp.template"), etcpath)
self._copy(os.path.join(self.statepath, "dhcp6.template"), etcpath)
self._copy(os.path.join(self.statepath, "rsync.template"), etcpath)
#####################################################################
# # savestate command ################################################
#####################################################################
class Savestate(Statebase):
description = "Backup the current configuration to /tmp/cobbler_settings."
def _copy(self, frm: str, to: str) -> None:
if self.root:
frm = self.root + frm
super()._copy(frm, to)
def run(self):
"""
TODO
"""
self.announce(f"backing up the current configuration to {self.statepath}", 3)
if os.path.exists(self.statepath):
self.announce("deleting existing {self.statepath}", 3)
if not self.dry_run: # type: ignore
shutil.rmtree(self.statepath)
if not self.dry_run: # type: ignore
os.makedirs(self.statepath)
self._copy(os.path.join(libpath, "collections"), self.statepath)
self._copy(os.path.join(webconfig, "cobbler.conf"), self.statepath)
self._copy(os.path.join(etcpath, "settings.yaml"), self.statepath)
self._copy(os.path.join(etcpath, "users.conf"), self.statepath)
self._copy(os.path.join(etcpath, "users.digest"), self.statepath)
self._copy(os.path.join(etcpath, "dhcp.template"), self.statepath)
self._copy(os.path.join(etcpath, "dhcp6.template"), self.statepath)
self._copy(os.path.join(etcpath, "rsync.template"), self.statepath)
#####################################################################
# # Actual Setup.py Script ###########################################
#####################################################################
if __name__ == "__main__":
setup(
distclass=Distribution,
cmdclass={
"build": Build, # type: ignore
"build_py": BuildPy,
"test": TestCommand,
"install": Install,
"savestate": Savestate,
"restorestate": Restorestate,
"build_cfg": BuildCfg,
},
name="cobbler",
version=VERSION,
description="Network Boot and Update Server",
long_description=read_readme_file(),
long_description_content_type="text/markdown",
author="Team Cobbler",
author_email="cobbler.project@gmail.com",
project_urls={
"Website": "https://cobbler.github.io",
"Documentation (Users)": "https://cobbler.readthedocs.io/en/latest",
"Documentation (Devs)": "https://github.com/cobbler/cobbler/wiki",
"Source": "https://github.com/cobbler/cobbler",
"Tracker": "https://github.com/cobbler/cobbler/issues",
},
license="GPLv2+",
classifiers=[
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)",
"Programming Language :: Python :: 3.6",
"Topic :: System :: Installation/Setup",
"Topic :: System :: Systems Administration",
"Intended Audience :: System Administrators",
"Natural Language :: English",
"Operating System :: POSIX :: Linux",
],
keywords=["pxe", "autoinstallation", "dhcp", "tftp", "provisioning"],
install_requires=[
"requests",
"pyyaml",
"netaddr",
"Cheetah3",
"pymongo<4.2", # Cobbler requires Python 3.6; Version 4.2+ requires Python 3.7
"distro",
"python-ldap",
"dnspython",
"file-magic",
"schema",
"systemd-python",
"gunicorn",
],
extras_require={
"windows": [
# "hivex",
"pefile"
],
"extra": ["psutil"], # debugging startup performance
"lint": [
# pyright is not written in Python and has to be installed differently.
"pyflakes",
"pycodestyle",
"pylint",
"black==22.3.0", # See .pre-commit-config.yaml
"types-requests",
"types-PyYAML",
"types-psutil",
"types-netaddr",
"types-mock",
"isort",
],
"test": [
"pytest>6",
"pytest-cov",
"coverage",
"pytest-mock>3.3.0",
"pytest-benchmark",
],
"docs": ["sphinx", "sphinx-rtd-theme", "sphinxcontrib-apidoc"],
# We require the current version to properly detect duplicate issues
# See: https://github.com/twisted/towncrier/releases/tag/22.8.0
"changelog": ["towncrier>=22.8.0"],
},
packages=find_packages(exclude=["*tests*"]),
scripts=[
"bin/cobbler",
"bin/cobblerd",
"bin/cobbler-ext-nodes",
"bin/cobbler-settings",
],
configure_values={
"webroot": os.path.normpath(webroot),
"tftproot": os.path.normpath(tftproot),
"httpd_service": httpd_service,
"bind_zonefiles": bind_zonefiles,
"shim_folder": shim_folder,
"shim_file": shim_file,
"secure_grub_folder": secure_boot_folder,
"secure_grub_file": secure_boot_file,
"ipxe_folder": ipxe_folder,
"memdisk_folder": memdisk_folder,
"pxelinux_folder": pxelinux_folder,
"syslinux_dir": syslinux_dir,
"grub_mod_folder": grub_mod_folder,
},
configure_files=[
"config/apache/cobbler.conf",
"config/nginx/cobbler.conf",
"config/cobbler/settings.yaml",
"config/service/cobblerd.service",
"templates/etc/named.template",
"templates/etc/secondary.template",
],
man_pages=["docs/cobblerd.rst", "docs/cobbler-conf.rst", "docs/cobbler.rst"],
data_files=[
("%s" % webconfig, ["build/config/apache/cobbler.conf"]),
("%s/templates" % libpath, glob("autoinstall_templates/*")),
(
"%s/templates/install_profiles" % libpath,
glob("autoinstall_templates/install_profiles/*"),
),
("%s/snippets" % libpath, glob("autoinstall_snippets/*", recursive=True)),
("%s/scripts" % libpath, glob("autoinstall_scripts/*")),
("%s" % libpath, ["config/cobbler/distro_signatures.json"]),
("share/cobbler/bin", glob("scripts/*")),
("%s/loaders" % libpath, []),
("%s/misc" % libpath, glob("misc/*")),
# Configuration
(f"{etcpath}/apache", ["build/config/apache/cobbler.conf"]),
(f"{etcpath}/nginx", ["build/config/nginx/cobbler.conf"]),
(
"%s" % etcpath,
[
"build/config/service/cobblerd.service",
"build/config/cobbler/settings.yaml",
],
),
(
"%s" % etcpath,
[
"config/cobbler/auth.conf",
"config/cobbler/users.conf",
"config/cobbler/users.digest",
"config/cheetah/cheetah_macros",
"config/rotate/cobblerd_rotate",
"config/rsync/import_rsync_whitelist",
"config/rsync/rsync.exclude",
"config/service/cobblerd-gunicorn.service",
"config/version",
],
),
("%s" % etcpath, glob("cobbler/etc/*")),
(
"%s" % etcpath,
[
"templates/etc/named.template",
"templates/etc/genders.template",
"templates/etc/secondary.template",
"templates/etc/zone.template",
"templates/etc/dnsmasq.template",
"templates/etc/rsync.template",
"templates/etc/dhcp.template",
"templates/etc/dhcp6.template",
"templates/etc/ndjbdns.template",
],
),
("%s/iso" % etcpath, glob("templates/iso/*")),
("%s/boot_loader_conf" % etcpath, glob("templates/boot_loader_conf/*")),
# completion_file
("%s" % completion_path, ["config/bash/completion/cobbler"]),
("%s/grub_config" % libpath, glob("config/grub/*")),
# ToDo: Find a nice way to copy whole config/grub structure recursively
# files
("%s/grub_config/grub" % libpath, glob("config/grub/grub/*")),
# dirs
("%s/grub_config/grub/system" % libpath, []),
("%s/grub_config/grub/system_link" % libpath, []),
("%s/reporting" % etcpath, glob("templates/reporting/*")),
# logfiles
("%s/cobbler/kicklog" % logpath, []),
("%s/cobbler/syslog" % logpath, []),
("%s/httpd/cobbler" % logpath, []),
("%s/cobbler/anamon" % logpath, []),
("%s/cobbler/tasks" % logpath, []),
# zone-specific templates directory
("%s/zone_templates" % etcpath, glob("templates/zone_templates/*")),
# windows-specific templates directory
("%s/windows" % etcpath, glob("templates/windows/*")),
("%s" % etcpath, ["config/cobbler/logging_config.conf"]),
# man pages
("%s/man1" % docpath, glob("build/sphinx/man/*.1")),
("%s/man5" % docpath, glob("build/sphinx/man/*.5")),
("%s/man8" % docpath, glob("build/sphinx/man/*.8")),
# tests
("%s/tests" % datadir, glob("tests/*.py")),
("%s/tests/actions" % datadir, glob("tests/actions/*.py")),
(
"%s/tests/actions/buildiso" % datadir,
glob("tests/actions/buildiso/*.py"),
),
("%s/tests/api" % datadir, glob("tests/api/*.py")),
("%s/tests/cli" % datadir, glob("tests/cli/*.py")),
("%s/tests/collections" % datadir, glob("tests/collections/*.py")),
("%s/tests/items" % datadir, glob("tests/items/*.py")),
("%s/tests/modules" % datadir, glob("tests/modules/*.py")),
(
"%s/tests/modules/authentication" % datadir,
glob("tests/modules/authentication/*.py"),
),
(
"%s/tests/modules/authorization" % datadir,
glob("tests/modules/authorization/*.py"),
),
(
"%s/tests/modules/installation" % datadir,
glob("tests/modules/installation/*.py"),
),
(
"%s/tests/modules/managers" % datadir,
glob("tests/modules/managers/*.py"),
),
(
"%s/tests/modules/serializer" % datadir,
glob("tests/modules/serializer/*.py"),
),
("%s/tests/settings" % datadir, glob("tests/settings/*.py")),
(
"%s/tests/settings/migrations" % datadir,
glob("tests/settings/migrations/*.py"),
),
("%s/tests/special_cases" % datadir, glob("tests/special_cases/*.py")),
("%s/tests/test_data" % datadir, glob("tests/test_data/*")),
("%s/tests/test_data/V2_8_5" % datadir, glob("tests/test_data/V2_8_5/*")),
("%s/tests/test_data/V3_0_0" % datadir, glob("tests/test_data/V3_0_0/*")),
(
"%s/tests/test_data/V3_0_0/settings.d" % datadir,
glob("tests/test_data/V3_0_0/settings.d/*"),
),
("%s/tests/test_data/V3_0_1" % datadir, glob("tests/test_data/V3_0_1/*")),
(
"%s/tests/test_data/V3_0_1/settings.d" % datadir,
glob("tests/test_data/V3_0_1/settings.d/*"),
),
("%s/tests/test_data/V3_1_0" % datadir, glob("tests/test_data/V3_1_0/*")),
(
"%s/tests/test_data/V3_1_0/settings.d" % datadir,
glob("tests/test_data/V3_1_0/settings.d/*"),
),
("%s/tests/test_data/V3_1_1" % datadir, glob("tests/test_data/V3_1_1/*")),
(
"%s/tests/test_data/V3_1_1/settings.d" % datadir,
glob("tests/test_data/V3_1_1/settings.d/*"),
),
("%s/tests/test_data/V3_1_2" % datadir, glob("tests/test_data/V3_1_2/*")),
(
"%s/tests/test_data/V3_1_2/settings.d" % datadir,
glob("tests/test_data/V3_1_2/settings.d/*"),
),
("%s/tests/test_data/V3_2_0" % datadir, glob("tests/test_data/V3_2_0/*")),
(
"%s/tests/test_data/V3_2_0/settings.d" % datadir,
glob("tests/test_data/V3_2_0/settings.d/*"),
),
("%s/tests/test_data/V3_2_1" % datadir, glob("tests/test_data/V3_2_1/*")),
(
"%s/tests/test_data/V3_2_1/settings.d" % datadir,
glob("tests/test_data/V3_2_1/settings.d/*"),
),
("%s/tests/test_data/V3_3_0" % datadir, glob("tests/test_data/V3_3_0/*")),
(
"%s/tests/test_data/V3_3_0/settings.d" % datadir,
glob("tests/test_data/V3_3_0/settings.d/*"),
),
("%s/tests/test_data/V3_3_1" % datadir, glob("tests/test_data/V3_3_1/*")),
(
"%s/tests/test_data/V3_3_1/settings.d" % datadir,
glob("tests/test_data/V3_3_1/settings.d/*"),
),
("%s/tests/test_data/V3_3_2" % datadir, glob("tests/test_data/V3_3_2/*")),
(
"%s/tests/test_data/V3_3_2/settings.d" % datadir,
glob("tests/test_data/V3_3_2/settings.d/*"),
),
("%s/tests/test_data/V3_3_3" % datadir, glob("tests/test_data/V3_3_3/*")),
(
"%s/tests/test_data/V3_3_3/settings.d" % datadir,
glob("tests/test_data/V3_3_3/settings.d/*"),
),
("%s/tests/xmlrpcapi" % datadir, glob("tests/xmlrpcapi/*.py")),
("%s/tests/test_data/V3_4_0" % datadir, glob("tests/test_data/V3_4_0/*")),
("%s/tests/utils" % datadir, glob("tests/utils/*.py")),
(f"{datadir}/tests/performance", glob("tests/performance/*.py")),
# tests containers subpackage
("%s/docker" % datadir, glob("docker/*")),
("%s/docker/debs" % datadir, glob("docker/debs/*")),
("%s/docker/debs/Debian_10" % datadir, glob("docker/debs/Debian_10/*")),
(
"%s/docker/debs/Debian_10/supervisord" % datadir,
glob("docker/debs/Debian_10/supervisord/*"),
),
(
"%s/docker/debs/Debian_10/supervisord/conf.d" % datadir,
glob("docker/debs/Debian_10/supervisord/conf.d/*"),
),
("%s/docker/debs/Debian_11" % datadir, glob("docker/debs/Debian_11/*")),
(
"%s/docker/debs/Debian_11/supervisord" % datadir,
glob("docker/debs/Debian_11/supervisord/*"),
),
(
"%s/docker/debs/Debian_11/supervisord/conf.d" % datadir,
glob("docker/debs/Debian_11/supervisord/conf.d/*"),
),
("%s/docker/develop" % datadir, glob("docker/develop/*")),
("%s/docker/develop/openldap" % datadir, glob("docker/develop/openldap/*")),
("%s/docker/develop/pam" % datadir, glob("docker/develop/pam/*")),
("%s/docker/develop/scripts" % datadir, glob("docker/develop/scripts/*")),
(
"%s/docker/develop/supervisord" % datadir,
glob("docker/develop/supervisord/*"),
),
(
"%s/docker/develop/supervisord/conf.d" % datadir,
glob("docker/develop/supervisord/conf.d/*"),
),
("%s/docker/rpms" % datadir, glob("docker/rpms/*")),
("%s/docker/rpms/Fedora_34" % datadir, glob("docker/rpms/Fedora_34/*")),
(
"%s/docker/rpms/Fedora_34/supervisord" % datadir,
glob("docker/rpms/Fedora_34/supervisord/*"),
),
(
"%s/docker/rpms/Fedora_34/supervisord/conf.d" % datadir,
glob("docker/rpms/Fedora_34/supervisord/conf.d/*"),
),
(
"%s/docker/rpms/Rocky_Linux_8" % datadir,
glob("docker/rpms/Rocky_Linux_8/*"),
),
(
"%s/docker/rpms/opensuse_leap" % datadir,
glob("docker/rpms/opensuse_leap/*"),
),
(
"%s/docker/rpms/opensuse_leap/supervisord" % datadir,
glob("docker/rpms/opensuse_leap/supervisord/*"),
),
(
"%s/docker/rpms/opensuse_leap/supervisord/conf.d" % datadir,
glob("docker/rpms/opensuse_leap/supervisord/conf.d/*"),
),
(
"%s/docker/rpms/opensuse_tumbleweed" % datadir,
glob("docker/rpms/opensuse_tumbleweed/*"),
),
(
"%s/docker/rpms/opensuse_tumbleweed/supervisord" % datadir,
glob("docker/rpms/opensuse_tumbleweed/supervisord/*"),
),
(
"%s/docker/rpms/opensuse_tumbleweed/supervisord/conf.d" % datadir,
glob("docker/rpms/opensuse_tumbleweed/supervisord/conf.d/*"),
),
],
)
| 35,181
|
Python
|
.py
| 813
| 32.220172
| 103
| 0.505821
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,955
|
.pylintrc
|
cobbler_cobbler/.pylintrc
|
[MASTER]
# Specify a score threshold to be exceeded before program exits with error.
fail-under=9.5
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=pylint.extensions.no_self_use
[MESSAGES CONTROL]
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
disable=W0511,R0801
[FORMAT]
# Maximum number of characters on a single line.
max-line-length=120
| 654
|
Python
|
.py
| 15
| 42.2
| 79
| 0.797788
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,956
|
copyright
|
cobbler_cobbler/debian/copyright
|
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: cobbler
Upstream-Contact: Enno Gotthold <enno@4seul.de>
Source: https://github.com/cobbler/cobbler
Files: *
Copyright: 2006-2022 The Cobbler Team
License: GPL-2+
# TODO: Add individual copyright of all files having explicit spdx headers
| 329
|
Python
|
.py
| 8
| 39.875
| 74
| 0.808777
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,957
|
conf.py
|
cobbler_cobbler/docs/conf.py
|
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# https://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath(".."))
# -- Project information -----------------------------------------------------
project = "Cobbler"
copyright = "2022, Enno Gotthold"
author = "Enno Gotthold"
# The short X.Y version
version = "3.4"
# The full version, including alpha/beta/rc tags
release = "3.4.0"
# -- General configuration ---------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
"sphinx.ext.coverage",
"sphinx.ext.mathjax",
"sphinx.ext.ifconfig",
"sphinx.ext.viewcode",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"
# The master toctree document.
master_doc = "index"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path .
exclude_patterns = ["_build"]
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
"canonical_url": "",
# 'analytics_id': '', # Provided by Google in your dashboard
"logo_only": False,
"display_version": True,
"prev_next_buttons_location": "bottom",
# Toc options
"collapse_navigation": True,
"sticky_navigation": True,
"navigation_depth": 4,
}
html_css_files = ["extend_width.css"]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# see https://github.com/readthedocs/readthedocs.org/issues/1776
html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself. Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = "Cobblerdoc"
# -- Options for LaTeX output ------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
"papersize": "a4paper",
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
# Latex figure (float) alignment
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, "Cobbler.tex", "Cobbler Documentation", "Enno Gotthold", "manual"),
]
# -- Options for manual page output ------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
("cobbler", "cobbler", "Cobbler CLI Documentation", ["Jörgen Maas"], 1),
("cobblerd", "cobblerd", "Cobblerd Documentation", ["Enno Gotthold"], 8),
(
"cobbler-conf",
"cobbler.conf",
"Cobbler Configuration File Documentation",
["Enno Gotthold"],
5,
),
]
# -- Options for Texinfo output ----------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"Cobbler",
"Cobbler Documentation",
author,
"Cobbler",
"One line description of project.",
"Miscellaneous",
),
]
# -- Options for Epub output -------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''
# A unique identification for the text.
#
# epub_uid = ''
# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]
# -- Extension configuration -------------------------------------------------
# -- Options for intersphinx extension ---------------------------------------
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {"python": ("https://docs.python.org/3", None)}
# -- Options for todo extension ----------------------------------------------
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
| 6,553
|
Python
|
.py
| 167
| 36.60479
| 84
| 0.653779
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,958
|
conftest.py
|
cobbler_cobbler/tests/conftest.py
|
"""
Fixtures that are shared between all tests inside the testsuite.
"""
import os
import pathlib
import shutil
from contextlib import contextmanager
from pathlib import Path
from typing import Callable
import pytest
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.menu import Menu
from cobbler.items.network_interface import NetworkInterface
from cobbler.items.profile import Profile
from cobbler.items.system import System
@contextmanager
def does_not_raise():
"""
Fixture that represents a context manager that will expect that no raise occurs.
"""
yield
@pytest.fixture(scope="function")
def cobbler_api() -> CobblerAPI:
"""
Fixture that represents the Cobbler API for a single test.
"""
# pylint: disable=protected-access
CobblerAPI.__shared_state = {} # type: ignore
CobblerAPI.__has_loaded = False # type: ignore
return CobblerAPI()
@pytest.fixture(scope="function", autouse=True)
def reset_settings_yaml(tmp_path: pathlib.Path):
"""
Fixture that automatically resets the settings YAML after every test.
"""
filename = "settings.yaml"
filepath = "/etc/cobbler/%s" % filename
shutil.copy(filepath, tmp_path.joinpath(filename))
yield
shutil.copy(tmp_path.joinpath(filename), filepath)
@pytest.fixture(scope="function", autouse=True)
def reset_items(cobbler_api: CobblerAPI):
"""
Fixture that deletes all items automatically after every test.
"""
for system in cobbler_api.systems():
cobbler_api.remove_system(system.name)
for image in cobbler_api.images():
cobbler_api.remove_image(image.name)
for profile in cobbler_api.profiles():
cobbler_api.remove_profile(profile.name)
for distro in cobbler_api.distros():
cobbler_api.remove_distro(distro.name)
for repo in cobbler_api.repos():
cobbler_api.remove_repo(repo.name)
for menu in cobbler_api.menus():
cobbler_api.remove_menu(menu.name)
@pytest.fixture(scope="function")
def create_testfile(tmp_path: pathlib.Path):
"""
Fixture that provides a method to create an arbitrary file inside the folder specifically for a single test.
"""
def _create_testfile(filename: str) -> str:
path = os.path.join(tmp_path, filename)
if not os.path.exists(path):
Path(path).touch()
return path
return _create_testfile
@pytest.fixture(scope="function")
def create_kernel_initrd(create_testfile: Callable[[str], None]):
"""
Creates a kernel and initrd pair in the folder for the current test.
"""
def _create_kernel_initrd(name_kernel: str, name_initrd: str) -> str:
create_testfile(name_kernel)
return os.path.dirname(create_testfile(name_initrd)) # type: ignore
return _create_kernel_initrd
@pytest.fixture(scope="function")
def create_distro(
request: "pytest.FixtureRequest",
cobbler_api: CobblerAPI,
create_kernel_initrd: Callable[[str, str], str],
fk_kernel: str,
fk_initrd: str,
):
"""
Returns a function which has the distro name as an argument. The function returns a distro object. The distro is
already added to the CobblerAPI.
"""
def _create_distro(name: str = "") -> Distro:
test_folder = create_kernel_initrd(fk_kernel, fk_initrd)
test_distro = cobbler_api.new_distro()
test_distro.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
if name != "":
test_distro.name = name
test_distro.kernel = os.path.join(test_folder, fk_kernel)
test_distro.initrd = os.path.join(test_folder, fk_initrd)
cobbler_api.add_distro(test_distro)
return test_distro
return _create_distro
@pytest.fixture(scope="function")
def create_profile(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Returns a function which has the distro or profile name as an argument. The function returns a profile object. The profile is
already added to the CobblerAPI.
"""
def _create_profile(
distro_name: str = "", profile_name: str = "", name: str = ""
) -> Profile:
test_profile = cobbler_api.new_profile()
test_profile.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
if name != "":
test_profile.name = name
if profile_name == "":
test_profile.distro = distro_name
else:
test_profile.parent = profile_name
cobbler_api.add_profile(test_profile)
return test_profile
return _create_profile
@pytest.fixture(scope="function")
def create_image(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Returns a function which has the image name as an argument. The function returns an image object. The image is already added to the
CobblerAPI.
"""
def _create_image(name: str = "") -> Image:
test_image = cobbler_api.new_image()
test_image.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
if name != "":
test_image.name = name
cobbler_api.add_image(test_image)
return test_image
return _create_image
@pytest.fixture(scope="function")
def create_system(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Returns a function which has the profile name as an argument. The function returns a system object. The system is
already added to the CobblerAPI.
"""
def _create_system(
profile_name: str = "", image_name: str = "", name: str = ""
) -> System:
test_system = cobbler_api.new_system()
if name == "":
test_system.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
else:
test_system.name = name
if profile_name != "":
test_system.profile = profile_name
if image_name != "":
test_system.image = image_name
test_system.interfaces = {
"default": NetworkInterface(cobbler_api, test_system.name) # type: ignore
}
cobbler_api.add_system(test_system)
return test_system
return _create_system
@pytest.fixture(scope="function")
def create_menu(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Returns a function which has the profile name as an argument. The function returns a system object. The system is
already added to the CobblerAPI.
"""
def _create_menu(name: str = "", display_name: str = "") -> Menu:
test_menu = cobbler_api.new_menu()
if name == "":
test_menu.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
test_menu.display_name = display_name
cobbler_api.add_menu(test_menu)
return test_menu
return _create_menu
@pytest.fixture(scope="function", autouse=True)
def cleanup_leftover_items():
"""
Will delete all JSON files which are left in Cobbler before a testrun!
"""
cobbler_collections = [
"distros",
"images",
"menus",
"profiles",
"repos",
"systems",
]
for collection in cobbler_collections:
path = os.path.join("/var/lib/cobbler/collections", collection)
for file in os.listdir(path):
json_file = os.path.join(path, file)
os.remove(json_file)
@pytest.fixture(scope="function")
def fk_initrd(request: "pytest.FixtureRequest") -> str:
"""
The path to the first fake initrd.
:return: A filename as a string.
"""
return "initrd_%s.img" % (
request.node.originalname if request.node.originalname else request.node.name # type: ignore
)
@pytest.fixture(scope="function")
def fk_kernel(request: "pytest.FixtureRequest") -> str:
"""
The path to the first fake kernel.
:return: A path as a string.
"""
return "vmlinuz_%s" % (
request.node.originalname if request.node.originalname else request.node.name # type: ignore
)
@pytest.fixture(scope="function")
def redhat_autoinstall() -> str:
"""
The path to the test.ks file for redhat autoinstall.
:return: A path as a string.
"""
return "test.ks"
@pytest.fixture(scope="function")
def suse_autoyast() -> str:
"""
The path to the suse autoyast xml-file.
:return: A path as a string.
"""
return "test.xml"
@pytest.fixture(scope="function")
def ubuntu_preseed() -> str:
"""
The path to the ubuntu preseed file.
:return: A path as a string.
"""
return "test.seed"
| 9,257
|
Python
|
.py
| 251
| 30.442231
| 135
| 0.658509
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,959
|
tftpgen_test.py
|
cobbler_cobbler/tests/tftpgen_test.py
|
"""
Tests that validate the functionality of the module that is responsible for generating the TFTP boot tree.
"""
import glob
import os
import pathlib
import shutil
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Union
import pytest
from cobbler import enums, tftpgen
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from cobbler.templar import Templar
if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_copy_bootloaders(tmpdir: pathlib.Path, cobbler_api: CobblerAPI):
"""
Tests copying the bootloaders from the bootloaders_dir (setting specified in /etc/cobbler/settings.yaml) to the
tftpboot directory.
"""
# Instantiate TFTPGen class with collection_mgr parameter
generator = tftpgen.TFTPGen(cobbler_api)
# Arrange
# Create temporary bootloader files using tmpdir fixture
file_contents = "I am a bootloader"
sub_path = tmpdir.mkdir("loaders") # type: ignore
sub_path.join("bootloader1").write(file_contents) # type: ignore
sub_path.join("bootloader2").write(file_contents) # type: ignore
# Copy temporary bootloader files from tmpdir to expected source directory
for file in glob.glob(str(sub_path + "/*")): # type: ignore
bootloader_src = "/var/lib/cobbler/loaders/"
shutil.copy(file, bootloader_src + file.split("/")[-1])
# Act
generator.copy_bootloaders("/srv/tftpboot")
# Assert
assert os.path.isfile("/srv/tftpboot/bootloader1")
assert os.path.isfile("/srv/tftpboot/bootloader2")
def test_copy_single_distro_file(cobbler_api: CobblerAPI):
"""
Tests copy_single_distro_file() method using a sample initrd file pulled from CentOS 8
"""
# Instantiate TFTPGen class with collection_mgr parameter
generator = tftpgen.TFTPGen(cobbler_api)
# Arrange
distro_file = "/code/tests/test_data/dummy_initramfs"
distro_dir = "/srv/tftpboot/images/"
symlink_ok = True
initramfs_dst_path = "/srv/tftpboot/images/dummy_initramfs"
# Act
generator.copy_single_distro_file(distro_file, distro_dir, symlink_ok)
# Assert
assert os.path.isfile(initramfs_dst_path)
def test_copy_single_distro_files(
create_kernel_initrd: Callable[[str, str], str],
fk_initrd: str,
fk_kernel: str,
cobbler_api: CobblerAPI,
):
# Arrange
# Create fake files
directory = create_kernel_initrd(fk_kernel, fk_initrd)
(pathlib.Path(directory) / "images").mkdir()
# Create a test Distro
test_distro = Distro(cobbler_api)
test_distro.name = "test_copy_single_distro_files"
test_distro.kernel = str(os.path.join(directory, fk_kernel))
test_distro.initrd = str(os.path.join(directory, fk_initrd))
# Add test distro to the API
cobbler_api.add_distro(test_distro)
# Create class under test
test_gen = tftpgen.TFTPGen(cobbler_api)
# Act
test_gen.copy_single_distro_files(test_distro, directory, False)
# Assert that path created by function under test is actually there
result_kernel = os.path.join(directory, "images", test_distro.name, fk_kernel)
result_initrd = os.path.join(directory, "images", test_distro.name, fk_initrd)
assert os.path.exists(result_kernel)
assert os.path.exists(result_initrd)
@pytest.mark.skip("Test broken atm.")
def test_copy_single_image_files(
cobbler_api: CobblerAPI, create_image: Callable[[], Image]
):
# Arrange
test_image = create_image()
test_gen = tftpgen.TFTPGen(cobbler_api)
expected_file = pathlib.Path(test_gen.bootloc) / "images2" / test_image.name
# Act
test_gen.copy_single_image_files(test_image)
# Assert
assert expected_file.exists()
@pytest.fixture()
def setup_test_write_all_system_files(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Any,
) -> Tuple[System, tftpgen.TFTPGen]:
"""
Setup fixture for "test_write_all_system_files".
"""
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_system: System = create_system(profile_name=test_profile.name)
test_gen = tftpgen.TFTPGen(cobbler_api)
return test_system, test_gen
@pytest.mark.parametrize(
"mock_is_management_supported,mock_get_config_filename,expected_pxe_file,expected_rmfile,expected_mkdir,expected_symlink",
[
(True, ["A", "B"], 2, 1, 1, 1),
(True, ["A", None], 1, 0, 0, 0),
(True, [None, "B"], 1, 1, 1, 1),
# TODO: Add image based scenario
(False, ["A", "B"], 0, 2, 0, 0),
(False, ["A", None], 0, 1, 0, 0),
],
)
def test_write_all_system_files(
mocker: "MockerFixture",
setup_test_write_all_system_files: Tuple[System, tftpgen.TFTPGen],
mock_is_management_supported: bool,
mock_get_config_filename: List[Any],
expected_pxe_file: int,
expected_rmfile: int,
expected_mkdir: int,
expected_symlink: int,
):
"""
Test that asserts if the "write_all_system_files" subroutine is working as intended.
Two main scenarios must be tested for
* normal hardware and
* S390(X) hardware
as they generate a different set of files. This method handles only GRUB and pxelinux.
ESXI bootloader and iPXE generation is handled in a different test.
"""
# Arrange
test_system, test_gen = setup_test_write_all_system_files
result: Dict[str, Union[str, Dict[str, str]]] = {}
mocker.patch.object(
test_system,
"is_management_supported",
return_value=mock_is_management_supported,
)
mocker.patch.object(
test_system, "get_config_filename", side_effect=mock_get_config_filename
)
mock_write_pxe_file = mocker.patch.object(test_gen, "write_pxe_file")
mock_write_pxe_file_s390 = mocker.patch.object(
test_gen, "_write_all_system_files_s390"
)
mock_fs_helpers_rmfile = mocker.patch("cobbler.utils.filesystem_helpers.rmfile")
mock_fs_helpers_mkdir = mocker.patch("cobbler.utils.filesystem_helpers.mkdir")
mock_os_symlink = mocker.patch("os.symlink")
# Act
test_gen.write_all_system_files(test_system, result)
# Assert
assert mock_write_pxe_file_s390.call_count == 0
assert mock_write_pxe_file.call_count == expected_pxe_file
assert mock_fs_helpers_rmfile.call_count == expected_rmfile
assert mock_fs_helpers_mkdir.call_count == expected_mkdir
assert mock_os_symlink.call_count == expected_symlink
def test_write_all_system_files_s390(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Any,
create_image: Callable[[], Image],
):
"""
Test that asserts if the generated kernel options are longer then 79 character we insert a newline for S390X.
"""
# Arrange
test_distro = create_distro()
test_distro.kernel_options = {
"foobar1": "whatever",
"autoyast": "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/this-is-a-long-string-that-need-to-be-splitted/zzzzzzzzzzzzzzzzz",
"foobar2": "woohooo",
}
test_profile = create_profile(test_distro.name)
test_system: System = create_system(profile_name=test_profile.name)
test_system.netboot_enabled = True
test_image = create_image()
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch.object(test_system, "is_management_supported", return_value=True)
open_mock = mocker.mock_open()
open_mock.write = mocker.MagicMock()
mocker.patch("builtins.open", open_mock)
# Act
# pylint: disable-next=protected-access
test_gen._write_all_system_files_s390( # type: ignore[reportPrivateUsage]
test_distro, test_profile, test_image, test_system
)
# Assert - ensure generated parm file has fixed 80 characters format
open_mock().write.assert_called()
open_mock().write.assert_any_call(
"foobar1=whatever \nautoyast=http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/this-is-a-\nlong-string-that-need-to-be-splitted/zzzzzzzzzzzzzzzzz \nfoobar2=woohooo\n"
)
def test_make_pxe_menu(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
metadata_mock = {
"menu_items": "",
"menu_labels": "",
}
mocker.patch.object(test_gen, "get_menu_items", return_value=metadata_mock)
mocker.patch.object(test_gen, "_make_pxe_menu_pxe")
mocker.patch.object(test_gen, "_make_pxe_menu_ipxe")
mocker.patch.object(test_gen, "_make_pxe_menu_grub")
# Act
result = test_gen.make_pxe_menu()
# Assert
assert isinstance(result, dict)
assert metadata_mock["pxe_timeout_profile"] == "local"
def test_get_menu_items(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
expected_result = {"expected": "dict"}
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch.object(test_gen, "get_menu_level", return_value=expected_result)
# Act
result = test_gen.get_menu_items()
# Assert
assert result == expected_result
@pytest.mark.skip("Test broken atm.")
def test_get_submenus(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# TODO: Mock self.menus
mocker.patch.object(test_gen, "get_menu_level")
# Act
test_gen.get_submenus(None, {}, enums.Archs.X86_64)
# Assert
assert False
@pytest.mark.skip("Test broken atm.")
def test_get_profiles_menu(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# FIXME: Mock self.profiles()
mocker.patch.object(test_gen, "write_pxe_file")
# Act
test_gen.get_profiles_menu(None, {}, enums.Archs.X86_64)
# Assert
# TODO: Via metadata dict content
assert False
@pytest.mark.skip("Test broken atm.")
def test_get_images_menu(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# FIXME: Mock self.images()
mocker.patch.object(test_gen, "write_pxe_file")
# Act
test_gen.get_images_menu(None, {}, enums.Archs.X86_64)
# Assert
# TODO: Via metadata dict content
assert False
@pytest.mark.skip("Test broken atm.")
def test_get_menu_level(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# FIXME: Mock self.settings.boot_loader_conf_template_dir - maybe?
# FIXME: Mock open() for template loading and writing
mocker.patch.object(test_gen, "get_submenus")
mocker.patch.object(test_gen, "get_profiles_menu")
mocker.patch.object(test_gen, "get_images_menu")
test_gen.templar = mocker.MagicMock(spec=Templar, autospec=True)
# Act
result = test_gen.get_menu_level()
# Assert
assert isinstance(result, dict)
@pytest.mark.skip("Test broken atm.")
def test_write_pxe_file(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# FIXME: Mock self.settings.to_dict() - maybe?
# FIXME: Mock self.settings.boot_loader_conf_template_dir - maybe?
mocker.patch.object(test_gen, "build_kernel")
mocker.patch.object(test_gen, "build_kernel_options")
# Act
result = test_gen.write_pxe_file(
"", None, None, None, enums.Archs.X86_64, None, {}, ""
)
# Assert
assert isinstance(result, str)
@pytest.mark.skip("Test broken atm.")
def test_build_kernel(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch("cobbler.utils.blender", return_value={})
# Act
test_gen.build_kernel({}, None, None, None, None, "pxe") # type: ignore
# Assert
assert False
@pytest.mark.skip("Test broken atm.")
def test_build_kernel_options(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch("cobbler.utils.blender", return_value={})
mocker.patch("cobbler.utils.dict_to_string", return_value="")
# FIXME: Mock self.settings.server - maybe?
# FIXME: Mock self.settings.convert_server_to_ip - maybe?
test_gen.templar = mocker.MagicMock(spec=Templar, autospec=True)
# Act
test_gen.build_kernel_options(None, None, None, None, enums.Archs.X86_64, "")
# Assert
assert False
@pytest.mark.skip("Test broken atm.")
def test_write_templates(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
):
# Arrange
test_distro = create_distro()
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch("cobbler.utils.blender", return_value={})
test_gen.templar = mocker.MagicMock(spec=Templar, autospec=True)
# FIXME: Mock self.bootloc
# FIXME: Mock self.settings.webdir - maybe?
# FIXME: Mock open()
# Act
result = test_gen.write_templates(test_distro, False, "TODO")
# Assert
assert isinstance(result, dict)
@pytest.mark.skip("Test broken atm.")
def test_generate_ipxe(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_gen = tftpgen.TFTPGen(cobbler_api)
expected_result = "test"
mock_write_pxe_file = mocker.patch.object(
test_gen, "write_pxe_file", return_value=expected_result
)
# Act
result = test_gen.generate_ipxe("profile", test_profile.name)
# Assert
mock_write_pxe_file.assert_called_with(
None, None, test_profile, test_distro, enums.Archs.X86_64, None, format="ipxe"
)
assert result == expected_result
@pytest.mark.skip("Test broken atm.")
def test_generate_bootcfg(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_gen = tftpgen.TFTPGen(cobbler_api)
# TODO: Mock self.api.find_system/find_profile()
mocker.patch("cobbler.utils.blender", return_value={})
# FIXME: Mock self.settings.boot_loader_conf_template_dir - maybe?
# FIXME: Mock self.settings.server - maybe?
# FIXME: Mock self.settings.http_port - maybe?
mocker.patch.object(test_gen, "build_kernel_options")
mocker.patch("builtins.open", mocker.mock_open(read_data="test"))
test_gen.templar = mocker.MagicMock(spec=Templar, autospec=True)
# Act
result = test_gen.generate_bootcfg("profile", test_profile.name)
# Assert
assert isinstance(result, str)
def test_generate_script(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch("cobbler.utils.blender", return_value={})
mocker.patch("builtins.open", mocker.mock_open(read_data="test"))
mocker.patch("os.path.exists", return_value=True)
test_gen.templar = mocker.MagicMock(spec=Templar, autospec=True)
# Act
result = test_gen.generate_script("profile", test_profile.name, "script_name.xml")
# Assert
assert isinstance(result, mocker.MagicMock)
test_gen.templar.render.assert_called_with(
"test", {"img_path": f"/images/{test_distro.name}"}, None
)
def test_generate_windows_initrd(cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
# Act
# pylint: disable-next=protected-access
result = test_gen._build_windows_initrd("custom_loader", "my_custom_loader", "ipxe") # type: ignore[reportPrivateUsage]
# Assert
assert result == "--name custom_loader my_custom_loader custom_loader"
def test_generate_initrd(mocker: "MockerFixture", cobbler_api: CobblerAPI):
# Arrange
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch.object(test_gen, "_build_windows_initrd", return_value="Test")
input_metadata: Dict[str, Union[List[str], str]] = {
"initrd": [],
"bootmgr": "True",
"bcd": "True",
"winpe": "True",
}
expected_result = []
# Act
# pylint: disable-next=protected-access
result = test_gen._generate_initrd(input_metadata, "", "", "ipxe") # type: ignore[reportPrivateUsage]
# Assert
assert result == expected_result
@pytest.fixture(scope="function")
def cleanup_tftproot():
"""
Fixture that is responsible for cleaning up for ESXi generated content.
"""
yield
pathlib.Path("/srv/tftpboot/esxi/example.txt").unlink()
def test_write_bootcfg_file(
mocker: "MockerFixture",
cleanup_tftproot: Callable[[], None],
cobbler_api: CobblerAPI,
):
# Arrange
expected_result = "generated bootcfg"
test_gen = tftpgen.TFTPGen(cobbler_api)
mocker.patch.object(test_gen, "generate_bootcfg", return_value=expected_result)
# Act
# pylint: disable-next=protected-access
result = test_gen._write_bootcfg_file("profile", "test", "example.txt") # type: ignore[reportPrivateUsage]
# Assert
assert result == expected_result
assert pathlib.Path("/srv/tftpboot/esxi/example.txt").is_file()
| 17,579
|
Python
|
.py
| 437
| 35.336384
| 167
| 0.69973
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,960
|
configgen_test.py
|
cobbler_cobbler/tests/configgen_test.py
|
"""
Tests that validate the functionality of the module that is responsible for generating configuration data.
"""
import os
from typing import Any, Callable, Generator
import pytest
from cobbler.api import CobblerAPI
from cobbler.configgen import ConfigGen
from cobbler.items.distro import Distro
from cobbler.items.profile import Profile
from cobbler.items.system import System
# TODO: If the action items of the configgen class are done then the tests need to test the robustness of the class.
@pytest.fixture(name="create_testbed")
def fixture_create_testbed(
create_kernel_initrd: Callable[[str, str], str],
cobbler_api: CobblerAPI,
cleanup_testbed: Any,
):
def _create_testbed() -> CobblerAPI:
folder = create_kernel_initrd("vmlinux", "initrd.img")
test_distro = Distro(cobbler_api)
test_distro.name = "test_configgen_distro"
test_distro.kernel = os.path.join(folder, "vmlinux")
test_distro.initrd = os.path.join(folder, "initrd.img")
cobbler_api.add_distro(test_distro)
test_profile = Profile(cobbler_api)
test_profile.name = "test_configgen_profile"
test_profile.distro = "test_configgen_distro"
cobbler_api.add_profile(test_profile)
test_system = System(cobbler_api)
test_system.name = "test_configgen_system"
test_system.profile = "test_configgen_profile"
test_system.hostname = "testhost.test.de"
test_system.autoinstall_meta = {"test": "teststring"}
cobbler_api.add_system(test_system)
return cobbler_api
return _create_testbed
@pytest.fixture(name="cleanup_testbed", autouse=True)
def fixture_cleanup_testbed(cobbler_api: CobblerAPI) -> Generator[None, Any, None]:
yield
cobbler_api.remove_system("test_configgen_system")
cobbler_api.remove_profile("test_configgen_profile")
cobbler_api.remove_distro("test_configgen_distro")
def test_object_value_error(cobbler_api: CobblerAPI):
# Arrange
# Act & Assert
with pytest.raises(ValueError):
ConfigGen(cobbler_api, "nonexistant")
def test_object_creation(create_testbed: Callable[[], CobblerAPI]):
# Arrange
test_api = create_testbed()
# FIXME: Arrange distro, profile and system
# Act
test_configgen = ConfigGen(test_api, "testhost.test.de")
# Assert
assert isinstance(test_configgen, ConfigGen)
def test_resolve_resource_var(create_testbed: Callable[[], CobblerAPI]):
# Arrange
test_api = create_testbed()
# FIXME: Arrange distro, profile and system
config_gen = ConfigGen(test_api, "testhost.test.de")
# Act
result = config_gen.resolve_resource_var("Hello $test !")
# Assert
assert isinstance(result, str)
assert result == "Hello teststring !"
def test_get_cobbler_resource(create_testbed: Callable[[], CobblerAPI]):
# Arrange
test_api = create_testbed()
# FIXME: Arrange distro, profile and system
config_gen = ConfigGen(test_api, "testhost.test.de")
# Act
result = config_gen.get_cobbler_resource("")
# Assert
assert isinstance(result, (list, str, dict))
def test_get_config_data(create_testbed: Callable[[], CobblerAPI]):
# Arrange
test_api = create_testbed()
# FIXME: Arrange distro, profile and system
config_gen = ConfigGen(test_api, "testhost.test.de")
# Act
result = config_gen.gen_config_data()
# Assert
assert isinstance(result, dict)
def test_get_config_data_for_koan(create_testbed: Callable[[], CobblerAPI]):
# Arrange
test_api = create_testbed()
# FIXME: Arrange distro, profile and system
config_gen = ConfigGen(test_api, "testhost.test.de")
# Act
result = config_gen.gen_config_data_for_koan()
# Assert
assert isinstance(result, str)
| 3,796
|
Python
|
.py
| 93
| 35.677419
| 116
| 0.711717
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,961
|
templar_test.py
|
cobbler_cobbler/tests/templar_test.py
|
"""
Tests that validate the functionality of the module that is responsible for abstracting access to the different
template rendering engines that Cobbler supports.
"""
import pytest
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.templar import Templar
@pytest.fixture(scope="function")
def setup_cheetah_macros_file():
with open("/etc/cobbler/cheetah_macros", "w") as f:
f.writelines(
[
"## define Cheetah functions here and reuse them throughout your templates\n",
"\n",
"#def $myMethodInMacros($a)\n",
"Text in method: $a\n",
"#end def\n",
]
)
yield
with open("/etc/cobbler/cheetah_macros", "w") as f:
f.writelines(
[
"## define Cheetah functions here and reuse them throughout your templates\n",
"\n",
"\n",
]
)
def test_check_for_invalid_imports(cobbler_api: CobblerAPI):
# Arrange
test_templar = Templar(cobbler_api)
testdata = "#import json"
# Act & Assert
with pytest.raises(CX):
test_templar.check_for_invalid_imports(testdata)
def test_render(cobbler_api: CobblerAPI):
# Arrange
test_templar = Templar(cobbler_api)
# Act
result = test_templar.render("", {}, None, template_type="cheetah")
# Assert
assert result == ""
def test_render_cheetah(cobbler_api: CobblerAPI):
# Arrange
test_templar = Templar(cobbler_api)
# Act
result = test_templar.render_cheetah("$test", {"test": 5})
# Assert
assert result == "5"
@pytest.mark.usefixtures("setup_cheetah_macros_file")
@pytest.mark.skip("Macros only work if we restart cobblerd")
def test_cheetah_macros(cobbler_api: CobblerAPI):
# Arrange
templar = Templar(cobbler_api)
# Act
result = templar.render_cheetah("$myMethodInMacros(5)", {})
# Assert
assert result == "Text in method: 5\n"
def test_render_jinja2(cobbler_api: CobblerAPI):
# Arrange
test_templar = Templar(cobbler_api)
# Act
result = test_templar.render_jinja2("{{ foo }}", {"foo": "Test successful"})
# Assert
assert result == "Test successful"
| 2,265
|
Python
|
.py
| 66
| 27.757576
| 111
| 0.641544
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,962
|
module_loader_test.py
|
cobbler_cobbler/tests/module_loader_test.py
|
"""
Tests that validate the functionality of the module that is responsible for dynamically loading Python modules for
Cobbler. This includes both custom plugins and built-in ones.
"""
from typing import Any, Callable, List
import pytest
from cobbler import module_loader
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from tests.conftest import does_not_raise
@pytest.fixture(scope="function")
def create_module_loader(
cobbler_api: CobblerAPI,
) -> Callable[[], module_loader.ModuleLoader]:
def _create_module_loader() -> module_loader.ModuleLoader:
test_module_loader = module_loader.ModuleLoader(cobbler_api)
test_module_loader.load_modules()
return test_module_loader
return _create_module_loader
def test_object_creation(cobbler_api: CobblerAPI):
# Arrange & Act
result = module_loader.ModuleLoader(cobbler_api)
# Assert
assert isinstance(result, module_loader.ModuleLoader)
def test_load_modules(create_module_loader: Callable[[], module_loader.ModuleLoader]):
# Arrange
test_module_loader = create_module_loader()
# Act
test_module_loader.load_modules()
# Assert
assert test_module_loader.module_cache != {}
assert test_module_loader.modules_by_category != {}
@pytest.mark.parametrize(
"module_name",
[
("nsupdate_add_system_post"),
("nsupdate_delete_system_pre"),
("scm_track"),
("sync_post_restart_services"),
# ("sync_post_wingen")
],
)
def test_get_module_by_name(
create_module_loader: Callable[[], module_loader.ModuleLoader], module_name: str
):
# Arrange
test_module_loader = create_module_loader()
# Act
returned_module = test_module_loader.get_module_by_name(module_name)
# Assert
assert returned_module is not None
assert isinstance(returned_module.register(), str)
@pytest.mark.parametrize(
"module_section,fallback_name,expected_result,expected_exception",
[
("authentication", "", "authentication.configfile", does_not_raise()),
("authorization", "", "authorization.allowall", does_not_raise()),
("dns", "", "managers.bind", does_not_raise()),
("dhcp", "", "managers.isc", does_not_raise()),
("tftpd", "", "managers.in_tftpd", does_not_raise()),
("wrong_section", None, "", pytest.raises(CX)),
(
"wrong_section",
"authentication.configfile",
"authentication.configfile",
does_not_raise(),
),
],
)
def test_get_module_name(
create_module_loader: Callable[[], module_loader.ModuleLoader],
module_section: str,
fallback_name: str,
expected_result: str,
expected_exception: Any,
):
# Arrange
test_module_loader = create_module_loader()
# Act
with expected_exception:
result_name = test_module_loader.get_module_name(
module_section, "module", fallback_name
)
# Assert
assert result_name == expected_result
@pytest.mark.parametrize(
"module_section,fallback_name,expected_exception",
[
("authentication", "", does_not_raise()),
("authorization", "", does_not_raise()),
("dns", "", does_not_raise()),
("dhcp", "", does_not_raise()),
("tftpd", "", does_not_raise()),
("wrong_section", "", pytest.raises(CX)),
("wrong_section", "authentication.configfile", does_not_raise()),
],
)
def test_get_module_from_file(
create_module_loader: Callable[[], module_loader.ModuleLoader],
module_section: str,
fallback_name: str,
expected_exception: Any,
):
# Arrange
test_module_loader = create_module_loader()
# Act
with expected_exception:
result_module = test_module_loader.get_module_from_file(
module_section, "module", fallback_name
)
# Assert
assert isinstance(result_module.register(), str)
@pytest.mark.parametrize(
"category,expected_names",
[
(
"/var/lib/cobbler/triggers/add/system/post/*",
["cobbler.modules.nsupdate_add_system_post"],
),
(
"/var/lib/cobbler/triggers/sync/post/*",
[
"cobbler.modules.sync_post_restart_services",
"cobbler.modules.sync_post_wingen",
],
),
(
"/var/lib/cobbler/triggers/delete/system/pre/*",
["cobbler.modules.nsupdate_delete_system_pre"],
),
(
"/var/lib/cobbler/triggers/change/*",
["cobbler.modules.managers.genders", "cobbler.modules.scm_track"],
),
(
"/var/lib/cobbler/triggers/install/post/*",
[
"cobbler.modules.installation.post_log",
"cobbler.modules.installation.post_power",
"cobbler.modules.installation.post_puppet",
"cobbler.modules.installation.post_report",
],
),
(
"/var/lib/cobbler/triggers/install/pre/*",
[
"cobbler.modules.installation.pre_clear_anamon_logs",
"cobbler.modules.installation.pre_log",
"cobbler.modules.installation.pre_puppet",
],
),
(
"manage",
[
"cobbler.modules.managers.bind",
"cobbler.modules.managers.dnsmasq",
"cobbler.modules.managers.in_tftpd",
"cobbler.modules.managers.isc",
"cobbler.modules.managers.ndjbdns",
],
),
("manage/import", ["cobbler.modules.managers.import_signatures"]),
(
"serializer",
[
"cobbler.modules.serializers.file",
"cobbler.modules.serializers.mongodb",
"cobbler.modules.serializers.sqlite",
],
),
(
"authz",
[
"cobbler.modules.authorization.allowall",
"cobbler.modules.authorization.configfile",
"cobbler.modules.authorization.ownership",
],
),
(
"authn",
[
"cobbler.modules.authentication.configfile",
"cobbler.modules.authentication.denyall",
"cobbler.modules.authentication.ldap",
"cobbler.modules.authentication.pam",
"cobbler.modules.authentication.passthru",
"cobbler.modules.authentication.spacewalk",
],
),
],
)
def test_get_modules_in_category(
create_module_loader: Callable[[], module_loader.ModuleLoader],
category: str,
expected_names: List[str],
):
# Arrange
test_module_loader = create_module_loader()
# Act
result = test_module_loader.get_modules_in_category(category)
# Assert
assert len(result) > 0
actual_result: List[str] = []
for name in result:
actual_result.append(name.__name__)
actual_result.sort()
assert actual_result == expected_names
| 7,124
|
Python
|
.py
| 207
| 26.062802
| 114
| 0.604472
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,963
|
grub_test.py
|
cobbler_cobbler/tests/grub_test.py
|
"""
Tests that validate the functionality of the module that is responsible for GRUB functionality.
"""
from typing import Any, Optional
import pytest
from cobbler import grub
from tests.conftest import does_not_raise
@pytest.mark.parametrize(
"input_file_location,expected_output,expected_exception",
[
(None, None, pytest.raises(TypeError)),
("ftp://testuri", None, does_not_raise()),
("http://testuri", None, pytest.raises(ValueError)),
("tftp://testuri", None, pytest.raises(ValueError)),
("wss://testuri", None, does_not_raise()),
("http://10.0.0.1", "(http,10.0.0.1)/", does_not_raise()),
("tftp://10.0.0.1", "(tftp,10.0.0.1)/", does_not_raise()),
(
"tftp://10.0.0.1/testpath/testpath/",
"(tftp,10.0.0.1)/testpath/testpath/",
does_not_raise(),
),
],
)
def test_parse_grub_remote_file(
input_file_location: str, expected_output: Optional[str], expected_exception: Any
):
# Arrange & Act
with expected_exception:
result = grub.parse_grub_remote_file(input_file_location)
# Assert
assert result == expected_output
| 1,180
|
Python
|
.py
| 32
| 30.78125
| 95
| 0.632778
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,964
|
template_api_test.py
|
cobbler_cobbler/tests/template_api_test.py
|
"""
Tests that validate the functionality of the module that is responsible for extending Cheetah to work with Cobbler.
"""
import pytest
from cobbler.template_api import CobblerTemplate
class TestCobblerTemplate:
def test_compile(self):
# Arrange
# Act
compiled_template = CobblerTemplate(
searchList=[{"autoinstall_snippets_dir": "/var/lib/cobbler/snippets"}]
).compile(source="$test")
result = str(compiled_template(namespaces={"test": 5})) # type: ignore
# Assert
assert result == "5"
def test_no_snippets_dir(self):
# Arrange
test_template = CobblerTemplate()
# Act & Assert
with pytest.raises(AttributeError):
test_template.read_snippet("nonexistingsnippet")
def test_read_snippet_none(self):
# Arrange
test_template = CobblerTemplate(
searchList=[{"autoinstall_snippets_dir": "/var/lib/cobbler/snippets"}]
)
# Act
result = test_template.read_snippet("nonexistingsnippet")
# Assert
assert result is None
def test_read_snippet(self):
# Arrange
test_template = CobblerTemplate(
searchList=[{"autoinstall_snippets_dir": "/var/lib/cobbler/snippets"}]
)
expected = (
"#errorCatcher ListErrors\n"
+ "set -x -v\n"
+ "exec 1>/root/ks-post.log 2>&1\n"
)
# Act
result = test_template.read_snippet("log_ks_post")
# Assert
assert result == expected
def test_nonexisting_snippet(self):
# Arrange
test_template = CobblerTemplate(
searchList=[{"autoinstall_snippets_dir": "/var/lib/cobbler/snippets"}]
)
# Act
result = test_template.SNIPPET("preseed_early_default")
# Assert
assert result == "# Error: no snippet data for preseed_early_default\n"
def test_snippet(self):
# Arrange
test_template = CobblerTemplate(
searchList=[{"autoinstall_snippets_dir": "/var/lib/cobbler/snippets"}]
)
# Act
result = test_template.SNIPPET("post_run_deb")
# Assert
assert (
result
== "# A general purpose snippet to add late-command actions for preseeds\n"
)
def test_sedesc(self):
# Arrange
test_input = "This () needs [] to ^ be * escaped {}."
expected = "This \\(\\) needs \\[\\] to \\^ be \\* escaped \\{\\}\\."
test_template = CobblerTemplate()
# Act
result = test_template.sedesc(test_input)
# Assert
assert result == expected
| 2,692
|
Python
|
.py
| 74
| 27.5
| 115
| 0.594605
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,965
|
validate_test.py
|
cobbler_cobbler/tests/validate_test.py
|
"""
Tests that validate the functionality of the module that is responsible for validating data before it is consumed by
the application.
"""
import uuid
from ipaddress import AddressValueError, NetmaskValueError
from typing import Any
import pytest
from cobbler import enums, validate
from cobbler.api import CobblerAPI
from cobbler.utils import signatures
from tests.conftest import does_not_raise
@pytest.mark.parametrize(
"input_dnsname,expected_result,expected_exception",
[
(0, "", pytest.raises(TypeError)),
("", "", does_not_raise()),
("host", "host", does_not_raise()),
("host.cobbler.org", "host.cobbler.org", does_not_raise()),
],
)
def test_hostname(input_dnsname: Any, expected_result: str, expected_exception: Any):
# Arrange
# Act
with expected_exception:
result = validate.hostname(input_dnsname)
# Assert
assert result == expected_result
@pytest.mark.parametrize(
"input_addr,expected_result,expected_exception",
[
("", "", does_not_raise()),
("192.168.1.5", "192.168.1.5", does_not_raise()),
("my-invalid-ip", "", pytest.raises(AddressValueError)),
("255.255.255.0", "", pytest.raises(NetmaskValueError)),
(0, "", pytest.raises(TypeError)),
],
)
def test_ipv4_address(input_addr: Any, expected_result: str, expected_exception: Any):
# Arrange
# Act
with expected_exception:
result = validate.ipv4_address(input_addr)
# Assert
assert result == expected_result
def test_validate_os_version():
# Arrange
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
# Act
result = validate.validate_os_version("rhel4", "redhat")
# Assert
assert result == "rhel4"
def test_validate_breed():
# Arrange
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
# Act
result = validate.validate_breed("redhat")
# Assert
assert result == "redhat"
def test_set_repos(cobbler_api: CobblerAPI):
# Arrange
# Act
# TODO: Test this also with the bypass check
result = validate.validate_repos(
"testrepo1 testrepo2", cobbler_api, bypass_check=True
)
# Assert
assert result == ["testrepo1", "testrepo2"]
def test_set_virt_file_size():
# Arrange
# Act
# TODO: Test multiple disks via comma separation
result = validate.validate_virt_file_size("8")
# Assert
assert isinstance(result, float)
assert result == 8
@pytest.mark.parametrize(
"test_autoboot,expectation",
[
(True, does_not_raise()),
(False, does_not_raise()),
(0, does_not_raise()),
(1, does_not_raise()),
(2, does_not_raise()),
("Test", does_not_raise()),
],
)
def test_set_virt_auto_boot(test_autoboot: Any, expectation: Any):
# Arrange
# Act
with expectation:
result = validate.validate_virt_auto_boot(test_autoboot)
# Assert
assert isinstance(result, bool)
assert result is True or result is False
@pytest.mark.parametrize(
"test_input,expected_exception",
[
(True, does_not_raise()),
(False, does_not_raise()),
(0, does_not_raise()),
(1, does_not_raise()),
(5, does_not_raise()),
("", does_not_raise()),
],
)
def test_set_virt_pxe_boot(test_input: Any, expected_exception: Any):
# Arrange
# Act
with expected_exception:
result = validate.validate_virt_pxe_boot(test_input)
# Assert
assert isinstance(result, bool)
assert result or not result
def test_set_virt_ram():
# Arrange
# Act
result = validate.validate_virt_ram(1024)
# Assert
assert result == 1024
def test_set_virt_bridge():
# Arrange
# Act
result = validate.validate_virt_bridge("testbridge")
# Assert
assert result == "testbridge"
def test_validate_virt_path():
# Arrange
test_location = "/somerandomfakelocation"
# Act
result = validate.validate_virt_path(test_location)
# Assert
assert result == test_location
@pytest.mark.parametrize(
"value,expected_exception",
[
(0, does_not_raise()),
(5, does_not_raise()),
(enums.VALUE_INHERITED, does_not_raise()),
(False, does_not_raise()),
(0.0, pytest.raises(TypeError)),
(-5, pytest.raises(ValueError)),
("test", pytest.raises(TypeError)),
],
)
def test_set_virt_cpus(value: Any, expected_exception: Any):
# Arrange
# Act
with expected_exception:
result = validate.validate_virt_cpus(value)
# Assert
if value == enums.VALUE_INHERITED:
assert result == 0
else:
assert result == int(value)
def test_set_serial_device():
# Arrange
# Act
result = validate.validate_serial_device(0)
# Assert
assert result == 0
def test_set_serial_baud_rate():
# Arrange
# Act
result = validate.validate_serial_baud_rate(9600)
# Assert
assert result == enums.BaudRates.B9600
@pytest.mark.parametrize(
"test_value,expected_result",
[
("test", False),
(0, False),
("ftp://test/test", False),
("http://test_invalid/test", False),
("http://test§invalid/test", False),
("http://test.local/test", True),
# ("http://test.local:80/test", True),
("http://test/test", True),
("http://@@server@@/test", True),
("http://10.0.0.1/test", True),
("http://fe80::989c:95ff:fe42:47bf/test", True),
],
)
def test_validate_boot_remote_file(test_value: Any, expected_result: bool):
# Arrange
# Act
result = validate.validate_boot_remote_file(test_value)
# Assert
assert expected_result == result
@pytest.mark.parametrize(
"test_value,expected_result",
[
("test", False),
(0, False),
("http://test.local/test", False),
("http://test/test", False),
("ftp://test/test", False),
# ("(tftp,10.0.0.1:invalid)/test", False),
# ("(tftp,local_invalid)/test", False),
("(http,10.0.0.1)/test", True),
("(tftp,10.0.0.1)/test", True),
("(tftp,test.local)/test", True),
("(tftp,10.0.0.1:8080)/test", True),
],
)
def test_validate_grub_remote_file(test_value: Any, expected_result: bool):
# Arrange
# Act
result = validate.validate_grub_remote_file(test_value)
# Assert
assert expected_result == result
def test_validate_uuid():
# Arrange
test_uuid = uuid.uuid4().hex
expected_result = True
# Act
result = validate.validate_uuid(test_uuid)
# Arrange
assert result is expected_result
| 6,785
|
Python
|
.py
| 219
| 25.109589
| 116
| 0.630485
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,966
|
enums_test.py
|
cobbler_cobbler/tests/enums_test.py
|
"""
Tests that validate the functionality of the module that is responsible for defining constants and parsing them from
given data.
"""
from typing import Any, Union
import pytest
from cobbler import enums
from tests.conftest import does_not_raise
@pytest.mark.parametrize(
"test_architecture,test_raise",
[
(enums.Archs.X86_64, does_not_raise()),
("x86_64", does_not_raise()),
("abc", pytest.raises(ValueError)),
(0, pytest.raises(TypeError)),
],
)
def test_validate_arch(
test_architecture: Union[enums.Archs, str, int], test_raise: Any
):
# Arrange
# Act
with test_raise:
result = enums.Archs.to_enum(test_architecture) # type: ignore
# Assert
if isinstance(test_architecture, str):
assert result.value == test_architecture
elif isinstance(test_architecture, enums.Archs):
assert result == test_architecture
else:
raise TypeError("result had a non expected result")
@pytest.mark.parametrize(
"value,expected_exception",
[
("qemu", does_not_raise()),
("<<inherit>>", does_not_raise()),
(enums.VirtType.QEMU, does_not_raise()),
(enums.VirtType.INHERITED, does_not_raise()),
(0, pytest.raises(TypeError)),
],
)
def test_set_virt_type(value: Union[enums.VirtType, str, int], expected_exception: Any):
# Arrange
# Act
with expected_exception:
result = enums.VirtType.to_enum(value) # type: ignore
# Assert
if isinstance(value, str):
assert result.value == value
elif isinstance(value, enums.VirtType):
assert result == value
else:
raise TypeError("Unexpected type for value!")
@pytest.mark.parametrize(
"value,expected_exception",
[
("allow", does_not_raise()),
(enums.TlsRequireCert.ALLOW, does_not_raise()),
(enums.VALUE_INHERITED, pytest.raises(ValueError)),
(0, pytest.raises(TypeError)),
],
)
def test_validate_ldap_tls_reqcert(
value: Union[enums.TlsRequireCert, str, int], expected_exception: Any
):
# Arrange
# Act
with expected_exception:
result = enums.TlsRequireCert.to_enum(value) # type: ignore
# Assert
if isinstance(value, str):
assert result.value == value
elif isinstance(value, enums.TlsRequireCert):
assert result == value
else:
raise TypeError("Unexpected type for value!")
@pytest.mark.parametrize(
"test_driver,test_raise",
[
(enums.VirtDiskDrivers.RAW, does_not_raise()),
(enums.VALUE_INHERITED, does_not_raise()),
(enums.VirtDiskDrivers.INHERITED, does_not_raise()),
("qcow2", does_not_raise()),
("<<inherit>>", does_not_raise()),
("bad_driver", pytest.raises(ValueError)),
(0, pytest.raises(TypeError)),
],
)
def test_set_virt_disk_driver(
test_driver: Union[enums.VirtDiskDrivers, str, int], test_raise: Any
):
# Arrange
# Act
with test_raise:
result = enums.VirtDiskDrivers.to_enum(test_driver) # type: ignore
# Assert
if isinstance(test_driver, str):
assert result.value == test_driver
elif isinstance(test_driver, enums.VirtDiskDrivers):
assert result == test_driver
else:
raise TypeError("Unexpected type for value!")
| 3,443
|
Python
|
.py
| 102
| 26.95098
| 116
| 0.636254
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,967
|
autoinstallation_manager_test.py
|
cobbler_cobbler/tests/autoinstallation_manager_test.py
|
"""
Tests that validate the functionality of the module that is responsible for generating auto-installation control files.
"""
from unittest.mock import MagicMock
import pytest
from cobbler import autoinstall_manager
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.profile import Profile
from cobbler.items.system import System
from cobbler.settings import Settings
@pytest.fixture
def api_mock():
api_mock = MagicMock(spec=CobblerAPI)
settings_mock = MagicMock(name="autoinstall_setting_mock", spec=Settings)
settings_mock.autoinstall_snippets_dir = "/var/lib/cobbler/snippets"
settings_mock.autoinstall_templates_dir = "/var/lib/cobbler/templates"
settings_mock.next_server_v4 = ""
settings_mock.next_server_v6 = ""
settings_mock.default_virt_bridge = ""
settings_mock.default_virt_type = "auto"
settings_mock.default_virt_ram = 64
settings_mock.run_install_triggers = True
settings_mock.yum_post_install_mirror = True
settings_mock.enable_ipxe = True
settings_mock.enable_menu = True
settings_mock.virt_auto_boot = True
settings_mock.default_ownership = []
settings_mock.default_name_servers = []
settings_mock.default_name_servers_search = []
settings_mock.default_virt_disk_driver = "raw"
settings_mock.cache_enabled = False
api_mock.settings.return_value = settings_mock
test_distro = Distro(api_mock)
test_distro.name = "test"
api_mock.distros.return_value = MagicMock(return_value=[test_distro])
test_profile = Profile(api_mock)
test_profile.name = "test"
api_mock.profiles.return_value = MagicMock(return_value=[test_profile])
test_system = System(api_mock)
test_system.name = "test"
return api_mock
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - DEBUG | running python triggers from /var/lib/cobbler/triggers/task/validate_autoinstall_files/pre/*
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - DEBUG | running shell triggers from /var/lib/cobbler/triggers/task/validate_autoinstall_files/pre/*
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - DEBUG | shell triggers finished successfully
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - INFO | validate_autoinstall_files
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - INFO | ----------------------------
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - DEBUG | osversion:
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - INFO | Exception occurred: <class 'TypeError'>
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - INFO | Exception value: unhashable type: 'Profile'
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - INFO | Exception Info:
# File "/usr/lib/python3.6/site-packages/cobbler/remote.py", line 99, in run
# rc = self._run(self)
#
# File "/usr/lib/python3.6/site-packages/cobbler/remote.py", line 260, in runner
# return self.remote.api.validate_autoinstall_files()
#
# File "/usr/lib/python3.6/site-packages/cobbler/api.py", line 1372, in validate_autoinstall_files
# autoinstall_mgr.validate_autoinstall_files()
#
# File "/usr/lib/python3.6/site-packages/cobbler/autoinstall_manager.py", line 329, in validate_autoinstall_files
# (success, errors_type, errors) = self.validate_autoinstall_file(x, True)
#
# File "/usr/lib/python3.6/site-packages/cobbler/autoinstall_manager.py", line 309, in validate_autoinstall_file
# self.generate_autoinstall(profile=obj)
#
# File "/usr/lib/python3.6/site-packages/cobbler/autoinstall_manager.py", line 268, in generate_autoinstall
# return self.autoinstallgen.generate_autoinstall_for_profile(profile)
#
# File "/usr/lib/python3.6/site-packages/cobbler/autoinstallgen.py", line 347, in generate_autoinstall_for_profile
# g = self.api.find_profile(name=g)
#
# File "/usr/lib/python3.6/site-packages/cobbler/api.py", line 931, in find_profile
# return self._collection_mgr.profiles().find(name=name, return_list=return_list, no_errors=no_errors, **kargs)
#
# File "/usr/lib/python3.6/site-packages/cobbler/cobbler_collections/collection.py", line 127, in find
# return self.listing.get(kargs["name"], None)
#
# [2022-02-28_093028_validate_autoinstall_files] 2022-02-28T09:30:29 - ERROR | ### TASK FAILED ###
def test_create_autoinstallation_manager(api_mock: CobblerAPI):
# Arrange
# TODO
# Act
result = autoinstall_manager.AutoInstallationManager(api_mock)
# Assert
assert isinstance(result, autoinstall_manager.AutoInstallationManager)
| 4,703
|
Python
|
.py
| 86
| 51.930233
| 171
| 0.749023
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,968
|
serializer_test.py
|
cobbler_cobbler/tests/serializer_test.py
|
"""
Tests that validate the functionality of the module that is responsible for abstracting access to the item
(de)serializers.
"""
from typing import TYPE_CHECKING
import pytest
from cobbler import serializer
from cobbler.api import CobblerAPI
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="serializer_obj")
def fixture_serializer_obj(cobbler_api: CobblerAPI) -> serializer.Serializer:
"""
Fixture to provide a fresh serializer instance object for every test.
"""
return serializer.Serializer(cobbler_api)
def test_create_object(cobbler_api: CobblerAPI):
"""
Verify if the serializer can be initialized with a valid cobbler_api instance.
"""
# Arrange, Act & Assert
assert isinstance(serializer.Serializer(cobbler_api), serializer.Serializer)
def test_serialize(mocker: "MockerFixture", serializer_obj: serializer.Serializer):
"""
Verify that a full collection can be written with the help of the configured serialization module.
"""
# Arrange
open_mock = mocker.MagicMock()
open_mock.fileno.return_value = 5
mock_lock_file_location = mocker.patch(
"builtins.open", return_value=mocker.mock_open(mock=open_mock)
)
mocker.patch("fcntl.flock")
mocker.patch("os.path.exists", return_value=True)
mocker.patch.object(serializer_obj, "storage_object")
input_collection = mocker.MagicMock()
# Act
serializer_obj.serialize(input_collection)
# Assert
# One access for __grab_lock and one for __release_lock
assert mock_lock_file_location.call_count == 2
def test_serialize_item(mocker: "MockerFixture", serializer_obj: serializer.Serializer):
"""
Verify that a single item can be written with the help of the configured serialization module.
"""
# Arrange
open_mock = mocker.MagicMock()
open_mock.fileno.return_value = 5
mock_lock_file_location = mocker.patch(
"builtins.open", return_value=mocker.mock_open(mock=open_mock)
)
mocker.patch("fcntl.flock")
mocker.patch("os.path.exists", return_value=True)
input_collection = mocker.MagicMock()
input_item = mocker.MagicMock()
storage_object_mock = mocker.patch.object(serializer_obj, "storage_object")
# Act
serializer_obj.serialize_item(input_collection, input_item)
# Assert
storage_object_mock.serialize_item.assert_called_with(input_collection, input_item)
# One access for __grab_lock
# Two access for __release_lock (mtime is true in this case)
assert mock_lock_file_location.call_count == 3
def test_serialize_delete(
mocker: "MockerFixture", serializer_obj: serializer.Serializer
):
"""
Verify that a single item can be deleted with the help of the configured serialization module.
"""
# Arrange
input_collection = mocker.MagicMock()
input_item = mocker.MagicMock()
storage_object_mock = mocker.patch.object(serializer_obj, "storage_object")
# Act
serializer_obj.serialize_delete(input_collection, input_item)
# Assert
storage_object_mock.serialize_delete.assert_called_with(
input_collection, input_item
)
def test_deserialize(mocker: "MockerFixture", serializer_obj: serializer.Serializer):
"""
Verify that a full collection can be read with the help of the configured serialization module.
"""
# Arrange
storage_object_mock = mocker.patch.object(serializer_obj, "storage_object")
input_collection = mocker.MagicMock()
# Act
serializer_obj.deserialize(input_collection)
# Assert
storage_object_mock.deserialize.assert_called_with(input_collection, True)
def test_deserialize_item(
mocker: "MockerFixture", serializer_obj: serializer.Serializer
):
"""
Verify that a single item can be read with the help of the configured serialization module.
"""
# Arrange
storage_object_mock = mocker.patch.object(serializer_obj, "storage_object")
input_collection_type = mocker.MagicMock()
input_name = mocker.MagicMock()
# Act
serializer_obj.deserialize_item(input_collection_type, input_name)
# Assert
storage_object_mock.deserialize_item.assert_called_with(
input_collection_type, input_name
)
| 4,256
|
Python
|
.py
| 106
| 35.45283
| 106
| 0.73411
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,969
|
system_test.py
|
cobbler_cobbler/tests/items/system_test.py
|
"""
Test module that asserts that Cobbler System functionality is working as expected.
"""
from typing import TYPE_CHECKING, Any, Callable, List, Optional
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.network_interface import NetworkInterface
from cobbler.items.profile import Profile
from cobbler.items.system import System
from cobbler.settings import Settings
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(
name="profile_setting_mock", spec=cobbler_api.settings()
)
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
"""
Test that verifies that the object constructor can be successfully used.
"""
# Arrange
# Act
system = System(cobbler_api)
# Arrange
assert isinstance(system, System)
def test_make_clone(cobbler_api: CobblerAPI):
"""
Test that verifies that cloning an object logically is working as expected.
"""
# Arrange
system = System(cobbler_api)
# Act
result = system.make_clone()
# Assert
assert result != system
def test_to_dict(cobbler_api: CobblerAPI):
"""
Test that verfies that converting the System to a dict works as expected.
"""
# Arrange
titem = System(cobbler_api)
# Act
result = titem.to_dict()
# Assert
assert isinstance(result, dict)
assert result.get("autoinstall") == enums.VALUE_INHERITED
def test_to_dict_resolved_profile(
cobbler_api: CobblerAPI, create_distro: Callable[[], Distro]
):
"""
Test that verfies that a system which is based on a profile can be converted to a dictionary successfully.
"""
# Arrange
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
cobbler_api.add_distro(test_distro)
titem = Profile(cobbler_api)
titem.name = "to_dict_resolved_profile"
titem.distro = test_distro.name
titem.kernel_options = {"my_value": 5}
cobbler_api.add_profile(titem)
system = System(cobbler_api)
system.name = "to_dict_resolved_system_profile"
system.profile = titem.name
system.kernel_options = {"my_value": 10}
cobbler_api.add_system(system)
# Act
result = system.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("kernel_options") == {"test": True, "my_value": 10}
assert result.get("autoinstall") == "default.ks"
assert enums.VALUE_INHERITED not in str(result)
def test_to_dict_resolved_image(
cobbler_api: CobblerAPI, create_image: Callable[[], Image]
):
"""
Test that verfies that a system which is based on an image can be converted to a dictionary successfully.
"""
# Arrange
test_image = create_image()
test_image.kernel_options = {"test": True}
cobbler_api.add_image(test_image)
system = System(cobbler_api)
system.name = "to_dict_resolved_system_image"
system.image = test_image.name
system.kernel_options = {"my_value": 5}
cobbler_api.add_system(system)
# Act
result = system.to_dict(resolved=True)
print(str(result))
# Assert
assert isinstance(result, dict)
assert result.get("kernel_options") == {"test": True, "my_value": 5}
assert enums.VALUE_INHERITED not in str(result)
# Properties Tests
def test_ipv6_autoconfiguration(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "ipv6_autoconfiguration".
"""
# Arrange
system = System(cobbler_api)
# Act
system.ipv6_autoconfiguration = False
# Assert
assert not system.ipv6_autoconfiguration
def test_repos_enabled(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "repos_enabled".
"""
# Arrange
system = System(cobbler_api)
# Act
system.repos_enabled = False
# Assert
assert not system.repos_enabled
def test_autoinstall(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "autoinstall".
"""
# Arrange
system = System(cobbler_api)
# Act
system.autoinstall = ""
# Assert
assert system.autoinstall == ""
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
("", does_not_raise(), []),
([], does_not_raise(), []),
("<<inherit>>", does_not_raise(), ["grub", "pxe", "ipxe"]),
([""], pytest.raises(CX), []),
(["ipxe"], does_not_raise(), ["ipxe"]),
],
)
def test_boot_loaders(
request: "pytest.FixtureRequest",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
input_value: Any,
expected_exception: Any,
expected_output: List[str],
):
"""
Test that verfies the functionality of the property "boot_loaders".
"""
# Arrange
tmp_distro = create_distro()
tmp_profile = create_profile(tmp_distro.name)
system = System(cobbler_api)
system.name = (
request.node.originalname # type: ignore
if request.node.originalname # type: ignore
else request.node.name # type: ignore
)
system.profile = tmp_profile.name
# Act
with expected_exception:
system.boot_loaders = input_value
# Assert
assert system.boot_loaders == expected_output
@pytest.mark.parametrize(
"value,expected",
[
(0, does_not_raise()),
(0.0, pytest.raises(TypeError)),
("", does_not_raise()),
(
"<<inherit>>",
does_not_raise(),
), # FIXME: Test passes but it actually does not do the right thing
("Test", does_not_raise()),
([], pytest.raises(TypeError)),
({}, pytest.raises(TypeError)),
(None, pytest.raises(TypeError)),
(False, does_not_raise()),
(True, does_not_raise()),
],
)
def test_enable_ipxe(cobbler_api: CobblerAPI, value: Any, expected: Any):
"""
Test that verfies the functionality of the property "enable_ipxe".
"""
# Arrange
distro = System(cobbler_api)
# Act
with expected:
distro.enable_ipxe = value
# Assert
assert isinstance(distro.enable_ipxe, bool)
assert distro.enable_ipxe or not distro.enable_ipxe
def test_gateway(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "gateway".
"""
# Arrange
system = System(cobbler_api)
# Act
system.gateway = ""
# Assert
assert system.gateway == ""
def test_hostname(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "hostname".
"""
# Arrange
system = System(cobbler_api)
# Act
system.hostname = ""
# Assert
assert system.hostname == ""
def test_image(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "image".
"""
# Arrange
system = System(cobbler_api)
# Act
system.image = ""
# Assert
assert system.image == ""
def test_ipv6_default_device(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "ipv6_default_device".
"""
# Arrange
system = System(cobbler_api)
# Act
system.ipv6_default_device = ""
# Assert
assert system.ipv6_default_device == ""
def test_name_servers(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "name_servers".
"""
# Arrange
system = System(cobbler_api)
# Act
system.name_servers = []
# Assert
assert system.name_servers == []
def test_name_servers_search(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "name_servers_search".
"""
# Arrange
system = System(cobbler_api)
# Act
system.name_servers_search = ""
# Assert
assert system.name_servers_search == ""
@pytest.mark.parametrize(
"value,expected",
[
(0, does_not_raise()),
(0.0, pytest.raises(TypeError)),
("", does_not_raise()),
("Test", does_not_raise()),
([], pytest.raises(TypeError)),
({}, pytest.raises(TypeError)),
(None, pytest.raises(TypeError)),
(False, does_not_raise()),
(True, does_not_raise()),
],
)
def test_netboot_enabled(cobbler_api: CobblerAPI, value: Any, expected: Any):
"""
Test that verfies the functionality of the property "netboot_enabled".
"""
# Arrange
distro = System(cobbler_api)
# Act
with expected:
distro.netboot_enabled = value
# Assert
assert isinstance(distro.netboot_enabled, bool)
assert distro.netboot_enabled or not distro.netboot_enabled
@pytest.mark.parametrize(
"input_next_server,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), "192.168.1.1"),
(False, pytest.raises(TypeError), ""),
],
)
def test_next_server_v4(
cobbler_api: CobblerAPI,
input_next_server: Any,
expected_exception: Any,
expected_result: str,
):
"""
Test that verfies the functionality of the property "next_server_v4".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.next_server_v4 = input_next_server
# Assert
assert system.next_server_v4 == expected_result
@pytest.mark.parametrize(
"input_next_server,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), "::1"),
(False, pytest.raises(TypeError), ""),
],
)
def test_next_server_v6(
cobbler_api: CobblerAPI,
input_next_server: Any,
expected_exception: Any,
expected_result: str,
):
"""
Test that verfies the functionality of the property "next_server_v6".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.next_server_v6 = input_next_server
# Assert
assert system.next_server_v6 == expected_result
def test_filename(
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Callable[[str, str, str], System],
):
"""
Test that verfies the functionality of the property "filename".
"""
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_system: System = create_system(profile_name=test_profile.name) # type: ignore
# Act
test_system.filename = "<<inherit>>"
# Assert
assert test_system.filename == ""
def test_power_address(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_address".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_address = ""
# Assert
assert system.power_address == ""
def test_power_id(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_id".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_id = ""
# Assert
assert system.power_id == ""
def test_power_pass(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_pass".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_pass = ""
# Assert
assert system.power_pass == ""
def test_power_type(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_type".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_type = "docker"
# Assert
assert system.power_type == "docker"
def test_power_user(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_user".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_user = ""
# Assert
assert system.power_user == ""
def test_power_options(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_options".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_options = ""
# Assert
assert system.power_options == ""
def test_power_identity_file(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "power_identity_file".
"""
# Arrange
system = System(cobbler_api)
# Act
system.power_identity_file = ""
# Assert
assert system.power_identity_file == ""
def test_profile(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "profile".
"""
# Arrange
system = System(cobbler_api)
# Act
system.profile = ""
# Assert
assert system.profile == ""
@pytest.mark.parametrize(
"input_proxy,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), ""),
(False, pytest.raises(TypeError), ""),
],
)
def test_proxy(
cobbler_api: CobblerAPI,
input_proxy: Any,
expected_exception: Any,
expected_result: str,
):
"""
Test that verfies the functionality of the property "proxy".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.proxy = input_proxy
# Assert
assert system.proxy == expected_result
@pytest.mark.parametrize(
"input_redhat_management_key,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), ""),
(False, pytest.raises(TypeError), ""),
],
)
def test_redhat_management_key(
cobbler_api: CobblerAPI,
input_redhat_management_key: Any,
expected_exception: Any,
expected_result: str,
):
"""
Test that verfies the functionality of the property "redhat_management_key".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.redhat_management_key = input_redhat_management_key
# Assert
assert system.redhat_management_key == expected_result
@pytest.mark.parametrize(
"input_server,expected_exception,expected_result",
[
("", does_not_raise(), "192.168.1.1"),
("<<inherit>>", does_not_raise(), "192.168.1.1"),
("1.1.1.1", does_not_raise(), "1.1.1.1"),
(False, pytest.raises(TypeError), None),
],
)
def test_server(
cobbler_api: CobblerAPI,
input_server: Any,
expected_exception: Any,
expected_result: Optional[str],
):
"""
Test that verfies the functionality of the property "server".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.server = input_server
# Assert
assert system.server == expected_result
def test_status(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "status".
"""
# Arrange
system = System(cobbler_api)
# Act
system.status = ""
# Assert
assert system.status == ""
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
(False, does_not_raise(), False),
(True, does_not_raise(), True),
("True", does_not_raise(), True),
("1", does_not_raise(), True),
("", does_not_raise(), False),
("<<inherit>>", does_not_raise(), True),
],
)
def test_virt_auto_boot(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: bool
):
"""
Test that verfies the functionality of the property "virt_auto_boot".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.virt_auto_boot = value
# Assert
assert system.virt_auto_boot is expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), 0),
# FIXME: (False, pytest.raises(TypeError)), --> does not raise
(-5, pytest.raises(ValueError), -5),
(0, does_not_raise(), 0),
(5, does_not_raise(), 5),
],
)
def test_virt_cpus(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: int
):
"""
Test that verfies the functionality of the property "virt_cpus".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.virt_cpus = value
# Assert
assert system.virt_cpus == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("qcow2", does_not_raise(), enums.VirtDiskDrivers.QCOW2),
("<<inherit>>", does_not_raise(), enums.VirtDiskDrivers.RAW),
(enums.VirtDiskDrivers.QCOW2, does_not_raise(), enums.VirtDiskDrivers.QCOW2),
(False, pytest.raises(TypeError), None),
("", pytest.raises(ValueError), None),
],
)
def test_virt_disk_driver(
cobbler_api: CobblerAPI,
value: Any,
expected_exception: Any,
expected_result: Optional[enums.VirtDiskDrivers],
):
"""
Test that verfies the functionality of the property "virt_disk_driver".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.virt_disk_driver = value
# Assert
assert system.virt_disk_driver == expected_result
@pytest.mark.parametrize(
"input_virt_file_size,expected_exception,expected_result",
[
(15.0, does_not_raise(), 15.0),
(15, does_not_raise(), 15.0),
("<<inherit>>", does_not_raise(), 5.0),
],
)
def test_virt_file_size(
cobbler_api: CobblerAPI,
input_virt_file_size: Any,
expected_exception: Any,
expected_result: float,
):
"""
Test that verfies the functionality of the property "virt_file_size".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.virt_file_size = input_virt_file_size
# Assert
assert system.virt_file_size == expected_result
@pytest.mark.parametrize(
"input_path,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), ""),
(False, pytest.raises(TypeError), None),
],
)
def test_virt_path(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
input_path: Any,
expected_exception: Any,
expected_result: Optional[str],
):
"""
Test that verfies the functionality of the property "virt_path".
"""
# Arrange
tmp_distro = create_distro()
tmp_profile = create_profile(tmp_distro.name)
system = System(cobbler_api)
system.profile = tmp_profile.name
# Act
with expected_exception:
system.virt_path = input_path
# Assert
assert system.virt_path == expected_result
def test_virt_pxe_boot(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "virt_pxe_boot".
"""
# Arrange
system = System(cobbler_api)
# Act
system.virt_pxe_boot = False
# Assert
assert not system.virt_pxe_boot
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), 0),
("<<inherit>>", does_not_raise(), 512),
(0, does_not_raise(), 0),
(0.0, pytest.raises(TypeError), 0),
],
)
def test_virt_ram(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
value: Any,
expected_exception: Any,
expected_result: int,
):
"""
Test that verfies the functionality of the property "virt_ram".
"""
# Arrange
distro = create_distro()
profile = create_profile(distro.name)
system = System(cobbler_api)
system.profile = profile.name
# Act
with expected_exception:
system.virt_ram = value
# Assert
assert system.virt_ram == expected_result
@pytest.mark.parametrize(
"value,expected_exception, expected_result",
[
("<<inherit>>", does_not_raise(), enums.VirtType.KVM),
("qemu", does_not_raise(), enums.VirtType.QEMU),
(enums.VirtType.QEMU, does_not_raise(), enums.VirtType.QEMU),
("", pytest.raises(ValueError), None),
(False, pytest.raises(TypeError), None),
],
)
def test_virt_type(
cobbler_api: CobblerAPI,
value: Any,
expected_exception: Any,
expected_result: Optional[enums.VirtType],
):
"""
Test that verfies the functionality of the property "virt_type".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.virt_type = value
# Assert
assert system.virt_type == expected_result
def test_serial_device(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "serial_device".
"""
# Arrange
system = System(cobbler_api)
# Act
system.serial_device = 5
# Assert
assert system.serial_device == 5
@pytest.mark.parametrize(
"value,expected_exception",
[
(enums.BaudRates.B110, does_not_raise()),
(110, does_not_raise()),
# FIXME: (False, pytest.raises(TypeError)) --> This does not raise a TypeError but instead a value Error.
],
)
def test_serial_baud_rate(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Test that verfies the functionality of the property "serial_baud_rate".
"""
# Arrange
system = System(cobbler_api)
# Act
with expected_exception:
system.serial_baud_rate = value
# Assert
if isinstance(value, int):
assert system.serial_baud_rate.value == value
else:
assert system.serial_baud_rate == value
def test_from_dict_with_network_interface(cobbler_api: CobblerAPI):
"""
Test that verifies that the ``to_dict`` method works with network interfaces.
"""
# Arrange
system = System(cobbler_api)
system.interfaces = {"default": NetworkInterface(cobbler_api, system.name)}
sys_dict = system.to_dict()
# Act
system.from_dict(sys_dict)
# Assert
assert "default" in system.interfaces
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("foobar_not_existing", pytest.raises(ValueError), None),
("", pytest.raises(ValueError), None),
("na", does_not_raise(), enums.NetworkInterfaceType.NA),
("bond", does_not_raise(), enums.NetworkInterfaceType.BOND),
("bond_slave", does_not_raise(), enums.NetworkInterfaceType.BOND_SLAVE),
("bridge", does_not_raise(), enums.NetworkInterfaceType.BRIDGE),
("bridge_slave", does_not_raise(), enums.NetworkInterfaceType.BRIDGE_SLAVE),
(
"bonded_bridge_slave",
does_not_raise(),
enums.NetworkInterfaceType.BONDED_BRIDGE_SLAVE,
),
("bmc", does_not_raise(), enums.NetworkInterfaceType.BMC),
("infiniband", does_not_raise(), enums.NetworkInterfaceType.INFINIBAND),
(0, does_not_raise(), enums.NetworkInterfaceType.NA),
(1, does_not_raise(), enums.NetworkInterfaceType.BOND),
(2, does_not_raise(), enums.NetworkInterfaceType.BOND_SLAVE),
(3, does_not_raise(), enums.NetworkInterfaceType.BRIDGE),
(4, does_not_raise(), enums.NetworkInterfaceType.BRIDGE_SLAVE),
(5, does_not_raise(), enums.NetworkInterfaceType.BONDED_BRIDGE_SLAVE),
(6, does_not_raise(), enums.NetworkInterfaceType.BMC),
(7, does_not_raise(), enums.NetworkInterfaceType.INFINIBAND),
],
)
def test_network_interface_type(
cobbler_api: CobblerAPI,
value: Any,
expected_exception: Any,
expected_result: Optional[enums.NetworkInterfaceType],
):
"""
Test that verifies that the ``NetworkInterface.interface_type`` works as expected.
"""
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.interface_type = value
# Assert
assert interface.interface_type == expected_result
@pytest.mark.parametrize(
"input_mac,input_ipv4,input_ipv6,expected_result",
[
("AA:BB:CC:DD:EE:FF", "192.168.1.2", "::1", True),
("", "192.168.1.2", "", True),
("", "", "::1", True),
("AA:BB:CC:DD:EE:FF", "", "", True),
("", "", "", False),
],
)
def test_is_management_supported(
cobbler_api: CobblerAPI,
input_mac: str,
input_ipv4: str,
input_ipv6: str,
expected_result: bool,
):
"""
Test that verifies that the ``is_management_supported()`` works as expected.
"""
# Arrange
system = System(cobbler_api)
system.interfaces = {"default": NetworkInterface(cobbler_api, system.name)}
system.interfaces["default"].mac_address = input_mac
system.interfaces["default"].ip_address = input_ipv4
system.interfaces["default"].ipv6_address = input_ipv6
# Act
result = system.is_management_supported()
# Assert
assert result is expected_result
def test_display_name(cobbler_api: CobblerAPI):
"""
Test that verfies the functionality of the property "display_name".
"""
# Arrange
system = System(cobbler_api)
# Act
system.display_name = ""
# Assert
assert system.display_name == ""
def test_profile_inherit(
mocker: "MockerFixture",
test_settings: Settings,
create_distro: Callable[[], Distro],
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
distro = create_distro()
api = distro.api
mocker.patch.object(api, "settings", return_value=test_settings)
distro.arch = enums.Archs.X86_64
profile = Profile(api)
profile.name = "test_profile_inherit"
profile.distro = distro.name
api.add_profile(profile)
system = System(api)
system.profile = profile.name
# Act
for key, key_value in system.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(system, new_key)
settings_name = new_key
parent_obj = None
if hasattr(profile, settings_name):
parent_obj = profile
elif hasattr(distro, settings_name):
parent_obj = distro
else:
if new_key == "owners":
settings_name = "default_ownership"
elif new_key == "proxy":
settings_name = "proxy_url_int"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
parent_obj = test_settings
if parent_obj is not None:
setting = getattr(parent_obj, settings_name)
if new_key == "autoinstall":
new_value = "default.ks"
elif new_key == "boot_loaders":
new_value = ["grub"]
elif new_key == "next_server_v4":
new_value = "10.10.10.10"
elif new_key == "next_server_v6":
new_value = "fd00::"
elif isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value.update({"test_inheritance": "test_inheritance"})
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(parent_obj, settings_name, new_value)
prev_value = getattr(system, new_key)
setattr(system, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(system, new_key)
def test_image_inherit(
mocker: "MockerFixture", test_settings: Settings, create_image: Callable[[], Image]
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
image = create_image()
api = image.api
mocker.patch.object(api, "settings", return_value=test_settings)
system = System(api)
system.image = image.name
# Act
for key, key_value in system.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(system, new_key)
settings_name = new_key
parent_obj = None
if hasattr(image, settings_name):
parent_obj = image
else:
if new_key == "owners":
settings_name = "default_ownership"
elif new_key == "proxy":
settings_name = "proxy_url_int"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
parent_obj = test_settings
if parent_obj is not None:
setting = getattr(parent_obj, settings_name)
if new_key == "autoinstall":
new_value = "default.ks"
elif new_key == "boot_loaders":
new_value = ["grub"]
elif new_key == "next_server_v4":
new_value = "10.10.10.10"
elif new_key == "next_server_v6":
new_value = "fd00::"
elif isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value.update({"test_inheritance": "test_inheritance"})
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(parent_obj, settings_name, new_value)
prev_value = getattr(system, new_key)
setattr(system, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(system, new_key)
| 31,407
|
Python
|
.py
| 962
| 26.110187
| 113
| 0.628745
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,970
|
image_test.py
|
cobbler_cobbler/tests/items/image_test.py
|
"""
Tests that validate the functionality of the module that is responsible for providing image related functionality.
"""
from typing import TYPE_CHECKING, Any, Callable
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.image import Image
from cobbler.settings import Settings
from cobbler.utils import signatures
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(name="image_setting_mock", spec=cobbler_api.settings())
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
# Arrange
# Act
image = Image(cobbler_api)
# Arrange
assert isinstance(image, Image)
def test_make_clone(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
result = image.make_clone()
# Assert
assert image != result
def test_arch(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.arch = "x86_64"
# Assert
assert image.arch == enums.Archs.X86_64
def test_autoinstall(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.autoinstall = ""
# Assert
assert image.autoinstall == ""
def test_file(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.file = "/tmp/test"
# Assert
assert image.file == "/tmp/test"
def test_os_version(cobbler_api: CobblerAPI):
# Arrange
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
image = Image(cobbler_api)
image.breed = "suse"
# Act
image.os_version = "sles15generic"
# Assert
assert image.os_version == "sles15generic"
def test_breed(cobbler_api: CobblerAPI):
# Arrange
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
image = Image(cobbler_api)
# Act
image.breed = "suse"
# Assert
assert image.breed == "suse"
def test_image_type(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.image_type = enums.ImageTypes.DIRECT
# Assert
assert image.image_type == enums.ImageTypes.DIRECT
def test_virt_cpus(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_cpus = 5
# Assert
assert image.virt_cpus == 5
def test_network_count(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.network_count = 2
# Assert
assert image.network_count == 2
def test_virt_auto_boot(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_auto_boot = False
# Assert
assert not image.virt_auto_boot
@pytest.mark.parametrize(
"input_virt_file_size,expected_exception,expected_result",
[
(15.0, does_not_raise(), 15.0),
(15, does_not_raise(), 15.0),
("<<inherit>>", does_not_raise(), 5.0),
],
)
def test_virt_file_size(
cobbler_api: CobblerAPI,
input_virt_file_size: Any,
expected_exception: Any,
expected_result: float,
):
# Arrange
image = Image(cobbler_api)
# Act
with expected_exception:
image.virt_file_size = input_virt_file_size
# Assert
assert image.virt_file_size == expected_result
def test_virt_disk_driver(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_disk_driver = enums.VirtDiskDrivers.RAW
# Assert
assert image.virt_disk_driver == enums.VirtDiskDrivers.RAW
def test_virt_ram(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_ram = 5
# Assert
assert image.virt_ram == 5
def test_virt_type(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_type = enums.VirtType.AUTO
# Assert
assert image.virt_type == enums.VirtType.AUTO
def test_virt_bridge(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_bridge = "testbridge"
# Assert
assert image.virt_bridge == "testbridge"
def test_virt_path(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.virt_path = ""
# Assert
assert image.virt_path == ""
def test_menu(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.menu = ""
# Assert
assert image.menu == ""
def test_display_name(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.display_name = ""
# Assert
assert image.display_name == ""
def test_supported_boot_loaders(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act & Assert
assert image.supported_boot_loaders == ["grub", "pxe", "ipxe"]
def test_boot_loaders(cobbler_api: CobblerAPI):
# Arrange
image = Image(cobbler_api)
# Act
image.boot_loaders = ""
# Assert
assert image.boot_loaders == []
def test_to_dict(create_image: Callable[[], Image]):
# Arrange
test_image = create_image()
# Act
result = test_image.to_dict(resolved=False)
# Assert
assert isinstance(result, dict)
assert result.get("autoinstall") == enums.VALUE_INHERITED
def test_to_dict_resolved(create_image: Callable[[], Image]):
# Arrange
test_image = create_image()
# Act
result = test_image.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("autoinstall") == "default.ks"
assert enums.VALUE_INHERITED not in str(result)
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
image = Image(cobbler_api)
# Act
for key, key_value in image.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(image, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(image, new_key)
setattr(image, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(image, new_key)
| 7,716
|
Python
|
.py
| 238
| 26.281513
| 114
| 0.656678
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,971
|
distro_test.py
|
cobbler_cobbler/tests/items/distro_test.py
|
"""
Test module to confirm that the Cobbler Item Distro is working as expected.
"""
import os
import pathlib
from typing import TYPE_CHECKING, Any, Callable
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.settings import Settings
from cobbler.utils import signatures
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(name="distro_setting_mock", spec=cobbler_api.settings())
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
"""
Verify that the constructor is working as expected.
"""
# Arrange
# Act
distro = Distro(cobbler_api)
# Arrange
assert isinstance(distro, Distro)
def test_non_equality(cobbler_api: CobblerAPI):
"""
Test that verifies if two created Distros don't match each other.
"""
# Arrange
distro1 = Distro(cobbler_api)
distro2 = Distro(cobbler_api)
# Act & Assert
assert distro1 != distro2
assert "" != distro1
def test_equality(cobbler_api: CobblerAPI):
"""
Test that verifies if the equality check for Distros is working.
"""
# Arrange
distro = Distro(cobbler_api)
# Act & Assert
assert distro == distro
def test_make_clone(
cobbler_api: CobblerAPI,
create_kernel_initrd: Callable[[str, str], str],
fk_kernel: str,
fk_initrd: str,
):
"""
Test that verifies that cloning a Distro is working as expected.
"""
# Arrange
folder = create_kernel_initrd(fk_kernel, fk_initrd)
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
distro = Distro(cobbler_api)
distro.breed = "suse"
distro.os_version = "sles15generic"
distro.kernel = os.path.join(folder, fk_kernel)
distro.initrd = os.path.join(folder, fk_initrd)
# Act
result = distro.make_clone()
# Assert
# TODO: When in distro.py the FIXME of this method is done then adjust this here
assert result != distro
def test_parent(cobbler_api: CobblerAPI):
"""
Test that verifies if the parent of a Distro cannot be set.
"""
# Arrange
distro = Distro(cobbler_api)
# Act & Assert
assert distro.parent is None
def test_check_if_valid(
cobbler_api: CobblerAPI,
create_kernel_initrd: Callable[[str, str], str],
fk_kernel: str,
fk_initrd: str,
):
"""
Test that verifies if the check for the validity of a Distro is working as expected.
"""
# Arrange
test_folder = create_kernel_initrd(fk_kernel, fk_initrd)
test_distro = Distro(cobbler_api)
test_distro.name = "testname"
test_distro.kernel = os.path.join(test_folder, fk_kernel)
test_distro.initrd = os.path.join(test_folder, fk_initrd)
# Act
test_distro.check_if_valid()
# Assert
assert True
def test_to_dict(cobbler_api: CobblerAPI):
"""
Test that verifies if conversion to a pure dictionary works as expected (with raw data).
"""
# Arrange
titem = Distro(cobbler_api)
# Act
result = titem.to_dict()
# Assert
assert isinstance(result, dict)
assert "autoinstall_meta" in result
assert "ks_meta" in result
assert result.get("boot_loaders") == enums.VALUE_INHERITED
# TODO check more fields
def test_to_dict_resolved(cobbler_api: CobblerAPI, create_distro: Callable[[], Distro]):
"""
Test that verifies if conversion to a pure dictionary works as expected (with resolved data).
"""
# Arrange
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
cobbler_api.add_distro(test_distro)
# Act
result = test_distro.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("kernel_options") == {"test": True}
assert result.get("boot_loaders") == ["grub", "pxe", "ipxe"]
assert enums.VALUE_INHERITED not in str(result)
# Properties Tests
@pytest.mark.parametrize(
"value,expected",
[
(0, does_not_raise()),
(0.0, does_not_raise()),
("", pytest.raises(TypeError)),
("Test", pytest.raises(TypeError)),
([], pytest.raises(TypeError)),
({}, pytest.raises(TypeError)),
(None, pytest.raises(TypeError)),
],
)
def test_tree_build_time(cobbler_api: CobblerAPI, value: Any, expected: Any):
"""
Test that verifies if the tree build time can be correctly set and read as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected:
distro.tree_build_time = value
# Assert
assert distro.tree_build_time == value
@pytest.mark.parametrize(
"value,expected",
[
("", pytest.raises(ValueError)),
("Test", pytest.raises(ValueError)),
(0, pytest.raises(TypeError)),
(0.0, pytest.raises(TypeError)),
([], pytest.raises(TypeError)),
({}, pytest.raises(TypeError)),
(None, pytest.raises(TypeError)),
("x86_64", does_not_raise()),
(enums.Archs.X86_64, does_not_raise()),
],
)
def test_arch(cobbler_api: CobblerAPI, value: Any, expected: Any):
"""
Test that verifies if the architecture of the Distro can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected:
distro.arch = value
# Assert
if isinstance(value, str):
assert distro.arch.value == value
else:
assert distro.arch == value
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), ["grub", "pxe", "ipxe"]),
("Test", pytest.raises(ValueError), ""),
(0, pytest.raises(TypeError), ""),
(["grub"], does_not_raise(), ["grub"]),
],
)
def test_boot_loaders(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: Any
):
"""
Test that verifies if the boot loaders can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.boot_loaders = value
# Assert
if value == "":
assert distro.boot_loaders == []
else:
assert distro.boot_loaders == expected_result
@pytest.mark.parametrize(
"value,expected_exception",
[("", does_not_raise()), (0, pytest.raises(TypeError)), ("suse", does_not_raise())],
)
def test_breed(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Test that verifies if the OS breed can be set as expected.
"""
# Arrange
signatures.load_signatures("/var/lib/cobbler/distro_signatures.json")
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.breed = value
# Assert
assert distro.breed == value
@pytest.mark.parametrize(
"value,expected_exception",
[
([], pytest.raises(TypeError)),
(False, pytest.raises(TypeError)),
],
)
def test_initrd(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Test that verifies if the initrd path can be set as expected.
"""
# TODO: Create fake initrd so we can set it successfully
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.initrd = value
# Assert
assert distro.initrd == value
@pytest.mark.parametrize(
"value,expected_exception",
[
([], pytest.raises(TypeError)),
(False, pytest.raises(TypeError)),
],
)
def test_kernel(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Test that verifies if the kernel path can be set as expected.
"""
# TODO: Create fake kernel so we can set it successfully
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.kernel = value
# Assert
assert distro.kernel == value
@pytest.mark.parametrize(
"value,expected_exception",
[([""], pytest.raises(TypeError)), (False, pytest.raises(TypeError))],
)
def test_os_version(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Test that verifies if the OS version can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.os_version = value
# Assert
assert distro.os_version == value
@pytest.mark.parametrize("value", [[""], ["Test"]])
def test_owners(cobbler_api: CobblerAPI, value: Any):
"""
Test that verifies if the owners of a Distro can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
distro.owners = value
# Assert
assert distro.owners == value
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), ""),
(["Test"], pytest.raises(TypeError), ""),
("<<inherit>>", does_not_raise(), ""),
],
)
def test_redhat_management_key(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: str
):
"""
Test that verifies if the redhat management key can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.redhat_management_key = value
# Assert
assert distro.redhat_management_key == expected_result
@pytest.mark.parametrize("value", [[""], ["Test"]])
def test_source_repos(cobbler_api: CobblerAPI, value: Any):
"""
Test that verifies if the source repositories can be set as expected.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
distro.source_repos = value
# Assert
assert distro.source_repos == value
@pytest.mark.parametrize(
"value,expected_exception",
[
([""], pytest.raises(TypeError)),
("", does_not_raise()),
],
)
def test_remote_boot_kernel(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any
):
"""
Test that verifies if a remote boot path can be set as expected.
"""
# Arrange
# TODO: Create fake kernel so we can test positive paths
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.remote_boot_kernel = value
# Assert
assert distro.remote_boot_kernel == value
@pytest.mark.parametrize(
"value,expected_exception",
[
([""], pytest.raises(TypeError)),
(["Test"], pytest.raises(TypeError)),
("", does_not_raise()),
],
)
def test_remote_grub_kernel(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any
):
"""
Test that verifies if a remote GRUB path can be set as expected for the kernel.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.remote_boot_kernel = value
# Assert
assert distro.remote_grub_kernel == value
@pytest.mark.parametrize(
"value,expected_exception",
[([""], pytest.raises(TypeError)), ("", does_not_raise())],
)
def test_remote_boot_initrd(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any
):
"""
Test that verifies if a remote initrd path can be set as expected for the initrd.
"""
# TODO: Create fake initrd to have a real test
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.remote_boot_initrd = value
# Assert
assert distro.remote_boot_initrd == value
@pytest.mark.parametrize(
"value,expected_exception",
[([""], pytest.raises(TypeError)), ("", does_not_raise())],
)
def test_remote_grub_initrd(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any
):
"""
Test that verifies if a given remote initrd path is correctly converted to its GRUB counter part.
"""
# Arrange
distro = Distro(cobbler_api)
# Act
with expected_exception:
distro.remote_boot_initrd = value
# Assert
assert distro.remote_grub_initrd == value
def test_supported_boot_loaders(cobbler_api: CobblerAPI):
"""
Test that verifies if the supported bootloaders are correctly detected for the current Distro.
"""
# Arrange
distro = Distro(cobbler_api)
# Assert
assert isinstance(distro.supported_boot_loaders, list)
assert distro.supported_boot_loaders == ["grub", "pxe", "ipxe"]
@pytest.mark.skip(
"This is hard to test as we are creating a symlink in the method. For now we skip it."
)
def test_link_distro(cobbler_api: CobblerAPI):
"""
Test that verifies if the Distro is correctly linked inside the web directory.
"""
# Arrange
test_distro = Distro(cobbler_api)
# Act
test_distro.link_distro()
# Assert
assert False
def test_find_distro_path(
cobbler_api: CobblerAPI,
create_testfile: Callable[[str], None],
tmp_path: pathlib.Path,
):
"""
Test that verifies if the method "find_distro_path()" can correctly identify the folder of the Distro in the
web directory.
"""
# Arrange
fk_kernel = "vmlinuz1"
create_testfile(fk_kernel)
test_distro = Distro(cobbler_api)
test_distro.kernel = os.path.join(tmp_path, fk_kernel)
# Act
result = test_distro.find_distro_path()
# Assert
assert result == tmp_path.as_posix()
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
distro = Distro(cobbler_api)
# Act
for key, key_value in distro.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(distro, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(distro, new_key)
setattr(distro, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(distro, new_key)
| 15,487
|
Python
|
.py
| 474
| 26.799578
| 112
| 0.648259
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,972
|
inmemory_test.py
|
cobbler_cobbler/tests/items/inmemory_test.py
|
"""
Tests that validate the functionality of the module that is responsible for lazy loading items.
"""
import os
import pathlib
from typing import Callable
import pytest
from cobbler.api import CobblerAPI
from cobbler.cobbler_collections import manager
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.menu import Menu
from cobbler.items.profile import Profile
from cobbler.items.repo import Repo
from cobbler.items.system import System
@pytest.fixture(scope="function")
def inmemory_api() -> CobblerAPI:
"""
Fixture to provide an CobblerAPI object that is suitable for testing lazy loading items.
"""
CobblerAPI.__shared_state = {} # type: ignore[reportPrivateUsage]
CobblerAPI.__has_loaded = False # type: ignore[reportPrivateUsage]
api = CobblerAPI()
api.settings().lazy_start = True
manager.CollectionManager.has_loaded = False
manager.CollectionManager.__shared_state = {} # type: ignore[reportPrivateUsage]
api._collection_mgr = manager.CollectionManager(api) # type: ignore[reportPrivateUsage]
return api
def test_inmemory(
inmemory_api: CobblerAPI,
create_kernel_initrd: Callable[[str, str], str],
fk_initrd: str,
fk_kernel: str,
):
"""
Test that verifies that lazy loading of items works.
"""
# Arrange
test_repo = Repo(inmemory_api, **{"name": "test_repo", "comment": "test comment"})
inmemory_api.add_repo(test_repo)
test_menu1 = Menu(inmemory_api, **{"name": "test_menu1", "comment": "test comment"})
inmemory_api.add_menu(test_menu1)
test_menu2 = Menu(
inmemory_api,
**{
"name": "test_menu2",
"parent": test_menu1.name,
"comment": "test comment",
},
)
inmemory_api.add_menu(test_menu2)
directory = create_kernel_initrd(fk_kernel, fk_initrd)
(pathlib.Path(directory) / "images").mkdir()
test_distro = Distro(
inmemory_api,
**{
"name": "test_distro",
"kernel": str(os.path.join(directory, fk_kernel)),
"initrd": str(os.path.join(directory, fk_initrd)),
"comment": "test comment",
},
)
inmemory_api.add_distro(test_distro)
test_profile1 = Profile(
inmemory_api,
**{
"name": "test_profile1",
"distro": test_distro.name,
"enable_menu": False,
"repos": [test_repo.name],
"menu": test_menu1.name,
"comment": "test comment",
},
)
inmemory_api.add_profile(test_profile1)
test_profile2 = Profile(
inmemory_api,
**{
"name": "test_profile2",
"parent": test_profile1.name,
"enable_menu": False,
"menu": test_menu2.name,
"comment": "test comment",
},
)
inmemory_api.add_profile(test_profile2)
test_profile3 = Profile(
inmemory_api,
**{
"name": "test_profile3",
"parent": test_profile1.name,
"enable_menu": False,
"repos": [test_repo.name],
"menu": test_menu1.name,
"comment": "test comment",
},
)
inmemory_api.add_profile(test_profile3)
test_image = Image(
inmemory_api,
**{"name": "test_image", "menu": test_menu1.name, "comment": "test comment"},
)
inmemory_api.add_image(test_image)
test_system1 = System(
inmemory_api,
**{
"name": "test_system1",
"profile": test_profile1.name,
"comment": "test comment",
},
)
inmemory_api.add_system(test_system1)
test_system2 = System(
inmemory_api,
**{"name": "test_system2", "image": test_image.name, "comment": "test comment"},
)
inmemory_api.add_system(test_system2)
inmemory_api.systems().listing.pop(test_system2.name)
inmemory_api.systems().listing.pop(test_system1.name)
inmemory_api.images().listing.pop(test_image.name)
inmemory_api.profiles().listing.pop(test_profile3.name)
inmemory_api.profiles().listing.pop(test_profile2.name)
inmemory_api.profiles().listing.pop(test_profile1.name)
inmemory_api.distros().listing.pop(test_distro.name)
inmemory_api.menus().listing.pop(test_menu2.name)
inmemory_api.menus().listing.pop(test_menu1.name)
inmemory_api.repos().listing.pop(test_repo.name)
inmemory_api.deserialize()
test_repo: Repo = inmemory_api.find_repo("test_repo") # type: ignore[reportAssignmentType]
test_menu1: Menu = inmemory_api.find_menu("test_menu1") # type: ignore[reportAssignmentType]
test_menu2: Menu = inmemory_api.find_menu("test_menu2") # type: ignore[reportAssignmentType]
test_distro: Distro = inmemory_api.find_distro("test_distro") # type: ignore[reportAssignmentType]
test_profile1: Profile = inmemory_api.find_profile("test_profile1") # type: ignore[reportAssignmentType]
test_profile2: Profile = inmemory_api.find_profile("test_profile2") # type: ignore[reportAssignmentType]
test_profile3: Profile = inmemory_api.find_profile("test_profile3") # type: ignore[reportAssignmentType]
test_image: Image = inmemory_api.find_image("test_image") # type: ignore[reportAssignmentType]
test_system1: System = inmemory_api.find_system("test_system1") # type: ignore[reportAssignmentType]
test_system2: System = inmemory_api.find_system("test_system2") # type: ignore[reportAssignmentType]
# Act
result = True
for collection in [
"repo",
"distro",
"menu",
"image",
"profile",
"system",
]:
for obj in inmemory_api.get_items(collection):
result = obj.inmemory is False if result else result
result = obj.__dict__["_comment"] == "" if result else result
comment = test_system1.comment if result else result # type: ignore[reportUnusedVariable]
result = test_repo.inmemory if result else result
result = test_menu1.inmemory if result else result
result = not test_menu2.inmemory if result else result
result = test_distro.inmemory if result else result
result = test_profile1.inmemory if result else result
result = not test_profile2.inmemory if result else result
result = not test_profile3.inmemory if result else result
result = not test_image.inmemory if result else result
result = test_system1.inmemory if result else result
result = not test_system2.inmemory if result else result
result = test_repo.__dict__["_comment"] == "test comment" if result else result
result = test_menu1.__dict__["_comment"] == "test comment" if result else result
result = test_menu2.__dict__["_comment"] == "" if result else result
result = test_distro.__dict__["_comment"] == "test comment" if result else result
result = test_profile1.__dict__["_comment"] == "test comment" if result else result
result = test_profile2.__dict__["_comment"] == "" if result else result
result = test_profile3.__dict__["_comment"] == "" if result else result
result = test_image.__dict__["_comment"] == "" if result else result
result = test_system1.__dict__["_comment"] == "test comment" if result else result
result = test_system2.__dict__["_comment"] == "" if result else result
# Cleanup
inmemory_api.remove_system(test_system1)
inmemory_api.remove_system(test_system2)
inmemory_api.remove_image(test_image)
inmemory_api.remove_profile(test_profile3)
inmemory_api.remove_profile(test_profile2)
inmemory_api.remove_profile(test_profile1)
inmemory_api.remove_distro(test_distro)
inmemory_api.remove_menu(test_menu2)
inmemory_api.remove_menu(test_menu1)
inmemory_api.remove_repo(test_repo)
# Assert
assert result
| 7,835
|
Python
|
.py
| 185
| 35.789189
| 109
| 0.662649
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,973
|
inheritance_test.py
|
cobbler_cobbler/tests/items/inheritance_test.py
|
"""
Test that verifies that the inheritance concept in Cobbler works for all data types.
"""
from typing import Callable
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.profile import Profile
# pylint: disable=protected-access
def test_resolved_dict_deduplication(
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
"""
Test that verifies if properties with dictionaries correctly deduplicate.
"""
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_distro.kernel_options = {"a": True, "b": 5}
expected_result_raw = {"b": 6, "c": "test"}
expected_result_resolved = {"a": True, "b": 6, "c": "test"}
expected_result_distro = {"a": True, "b": 5}
# Act
test_profile.kernel_options = {"a": True, "b": 6, "c": "test"}
# Assert
assert test_profile._kernel_options == expected_result_raw # type: ignore
assert test_profile.kernel_options == expected_result_resolved
assert test_distro.kernel_options == expected_result_distro
def test_resolved_list_deduplication(
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
"""
Test that verifies if properties with lists correctly resolve.
"""
# Arrange
test_distro = create_distro()
test_profile = create_profile(test_distro.name)
test_distro.owners = ["owner1"]
expected_result_raw = ["owner2"]
expected_result_resolved = ["owner2"]
expected_result_distro = ["owner1"]
# Act
test_profile.owners = ["owner2"]
# Assert
assert test_profile._owners == expected_result_raw # type: ignore
assert test_profile.owners == expected_result_resolved
assert test_distro.owners == expected_result_distro
def test_to_dict_filter_resolved(
cobbler_api: CobblerAPI, create_distro: Callable[[], Distro]
):
"""
Test that verifies if properties with dictionaries correctly resolve.
"""
# Arrange
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
test_distro.autoinstall_meta = {"tree": "http://test/url"}
cobbler_api.add_distro(test_distro)
titem = Profile(cobbler_api)
titem.name = "to_dict_filter_resolved_profile"
titem.distro = test_distro.name
new_kernel_options = titem.kernel_options
new_autoinstall_meta = titem.autoinstall_meta
new_kernel_options["test"] = False
new_autoinstall_meta["tree"] = "http://newtest/url"
titem.kernel_options = new_kernel_options
titem.autoinstall_meta = new_autoinstall_meta
cobbler_api.add_profile(titem)
# Act
result = titem.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("kernel_options") == {"test": False}
assert result.get("autoinstall_meta") == {"tree": "http://newtest/url"}
| 2,906
|
Python
|
.py
| 75
| 34.28
| 84
| 0.696625
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,974
|
cache_test.py
|
cobbler_cobbler/tests/items/cache_test.py
|
"""
Tests that validate the functionality of the module that is responsible for caching the results of the to_dict method.
"""
from typing import Any, Callable, List, Sequence
import pytest
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.items.abstract.base_item import BaseItem
from cobbler.items.abstract.bootable_item import BootableItem
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.menu import Menu
from cobbler.items.profile import Profile
from cobbler.items.repo import Repo
from cobbler.items.system import System
from tests.conftest import does_not_raise
def test_collection_types(cobbler_api: CobblerAPI):
# Arrange
mgr = cobbler_api._collection_mgr # type: ignore[reportPrivateUsage]
# Act
result = mgr.__dict__.items()
# Assert
print(result)
assert len(result) == 8
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_repo_dict_cache_load(
cobbler_api: CobblerAPI,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_repo = Repo(cobbler_api)
test_repo.name = "test_repo"
cobbler_api.add_repo(test_repo)
# Act
with expected_exception:
result1 = test_repo.to_dict(resolved=True)
result2 = test_repo.to_dict(resolved=False)
cached_result1 = test_repo.cache.get_dict_cache(True)
cached_result2 = test_repo.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_distro_dict_cache_load(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
input_value: bool,
expected_exception: Any,
expected_output: str,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
# Act
with expected_exception:
result1 = test_distro.to_dict(resolved=True)
result2 = test_distro.to_dict(resolved=False)
cached_result1 = test_distro.cache.get_dict_cache(True)
cached_result2 = test_distro.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_image_dict_cache_load(
cobbler_api: CobblerAPI,
create_image: Callable[[], Image],
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_image = create_image()
# Act
with expected_exception:
result1 = test_image.to_dict(resolved=True)
result2 = test_image.to_dict(resolved=False)
cached_result1 = test_image.cache.get_dict_cache(True)
cached_result2 = test_image.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_menu_dict_cache_load(
cobbler_api: CobblerAPI,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_menu = Menu(cobbler_api)
test_menu.name = "test_menu"
cobbler_api.add_menu(test_menu)
# Act
with expected_exception:
result1 = test_menu.to_dict(resolved=True)
result2 = test_menu.to_dict(resolved=False)
cached_result1 = test_menu.cache.get_dict_cache(True)
cached_result2 = test_menu.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_profile_dict_cache_load(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
test_profile = create_profile(test_distro.name)
test_profile.kernel_options = {"my_value": 5}
# Act
with expected_exception:
result1 = test_profile.to_dict(resolved=True)
result2 = test_profile.to_dict(resolved=False)
cached_result1 = test_profile.cache.get_dict_cache(True)
cached_result2 = test_profile.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_system_dict_cache_load(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Any,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
test_profile = create_profile(test_distro.name)
test_profile.kernel_options = {"my_value": 5}
test_system: System = create_system(profile_name=test_profile.name)
# Act
with expected_exception:
result1 = test_system.to_dict(resolved=True)
result2 = test_system.to_dict(resolved=False)
cached_result1 = test_system.cache.get_dict_cache(True)
cached_result2 = test_system.cache.get_dict_cache(False)
# Assert
assert (cached_result1 == result1) == expected_output
assert (cached_result2 == result2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_repo_dict_cache_use(
cobbler_api: CobblerAPI,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_repo = Repo(cobbler_api)
test_repo.name = "test_repo"
cobbler_api.add_repo(test_repo)
test_repo.to_dict(resolved=True)
test_repo.to_dict(resolved=False)
test_cache1 = "test1"
test_cache2 = "test2"
# Act
with expected_exception:
test_repo.cache.set_dict_cache(test_cache1, True) # type: ignore
test_repo.cache.set_dict_cache(test_cache2, False) # type: ignore
result1 = test_repo.cache.get_dict_cache(True)
result2 = test_repo.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_distro_dict_cache_use(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
test_distro.to_dict(resolved=True)
test_distro.to_dict(resolved=False)
test_cache1 = "test1"
test_cache2 = "test2"
# Act
with expected_exception:
test_distro.cache.set_dict_cache(test_cache1, True) # type: ignore
test_distro.cache.set_dict_cache(test_cache2, False) # type: ignore
result1 = test_distro.cache.get_dict_cache(True)
result2 = test_distro.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_image_dict_cache_use(
cobbler_api: CobblerAPI,
create_image: Callable[[], Image],
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_image = create_image()
test_image.to_dict(resolved=True)
test_image.to_dict(resolved=False)
test_cache1 = "test1"
test_cache2 = "test2"
# Act
with expected_exception:
test_image.cache.set_dict_cache(test_cache1, True) # type: ignore
test_image.cache.set_dict_cache(test_cache2, False) # type: ignore
result1 = test_image.cache.get_dict_cache(True)
result2 = test_image.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_menu_dict_cache_use(
cobbler_api: CobblerAPI,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_menu = Menu(cobbler_api)
test_menu.name = "test_menu"
cobbler_api.add_menu(test_menu)
test_menu.to_dict(resolved=True)
test_menu.to_dict(resolved=False)
test_cache1 = "test1"
test_cache2 = "test2"
# Act
with expected_exception:
test_menu.cache.set_dict_cache(test_cache1, True) # type: ignore
test_menu.cache.set_dict_cache(test_cache2, False) # type: ignore
result1 = test_menu.cache.get_dict_cache(True)
result2 = test_menu.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_profile_dict_cache_use(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
test_profile = create_profile(test_distro.name)
test_profile.kernel_options = {"my_value": 5}
test_profile.to_dict(resolved=True)
test_profile.to_dict(resolved=False)
test_cache1 = {"test": True}
test_cache2 = {"test": False}
# Act
with expected_exception:
test_profile.cache.set_dict_cache(test_cache1, True)
test_profile.cache.set_dict_cache(test_cache2, False)
result1 = test_profile.cache.get_dict_cache(True)
result2 = test_profile.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"input_value,expected_exception,expected_output",
[
(True, does_not_raise(), True),
(False, does_not_raise(), False),
],
)
def test_system_dict_cache_use(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Any,
create_system: Any,
input_value: bool,
expected_exception: Any,
expected_output: bool,
):
# Arrange
cobbler_api.settings().cache_enabled = input_value
test_distro = create_distro()
test_distro.kernel_options = {"test": True}
test_profile: Profile = create_profile(test_distro.name)
test_profile.kernel_options = {"my_value": 5}
test_system: System = create_system(profile_name=test_profile.name)
test_system.to_dict(resolved=True)
test_system.to_dict(resolved=False)
test_cache1 = {"test": True}
test_cache2 = {"test": False}
# Act
with expected_exception:
test_system.cache.set_dict_cache(test_cache1, True)
test_system.cache.set_dict_cache(test_cache2, False)
result1 = test_system.cache.get_dict_cache(True)
result2 = test_system.cache.get_dict_cache(False)
# Assert
assert (result1 == test_cache1) == expected_output
assert (result2 == test_cache2) == expected_output
@pytest.mark.parametrize(
"cache_enabled,expected_exception,expected_output",
[
(True, pytest.raises(CX), True),
(False, pytest.raises(CX), False),
],
)
def test_dict_cache_invalidate(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_image: Callable[[], Image],
create_profile: Any,
create_system: Any,
cache_enabled: bool,
expected_exception: Any,
expected_output: bool,
):
def validate_caches(
test_api: CobblerAPI,
objs: List[BaseItem],
obj_test: BaseItem,
dep: Sequence[BaseItem],
):
for obj in objs:
obj.to_dict(resolved=False)
obj.to_dict(resolved=True)
remain_objs = set(objs) - set(dep)
if isinstance(obj_test, BootableItem):
remain_objs.remove(obj_test)
obj_test.owners = "test"
if (
obj_test.cache.get_dict_cache(True) is not None
or obj_test.cache.get_dict_cache(False) is not None
):
return False
elif obj_test == test_api.settings():
test_api.clean_items_cache(obj_test) # type: ignore
elif obj_test == test_api.get_signatures():
test_api.signature_update()
for obj in dep:
if obj.cache.get_dict_cache(True) is not None:
return False
if obj.cache.get_dict_cache(False) is None:
return False
for obj in remain_objs:
if obj.cache.get_dict_cache(True) is None:
return False
if obj.cache.get_dict_cache(False) is None:
return False
return True
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
objs: List[BaseItem] = []
test_repo = Repo(cobbler_api)
test_repo.name = "test_repo"
cobbler_api.add_repo(test_repo)
objs.append(test_repo)
test_menu1 = Menu(cobbler_api)
test_menu1.name = "test_menu1"
cobbler_api.add_menu(test_menu1)
objs.append(test_menu1)
test_menu2 = Menu(cobbler_api)
test_menu2.name = "test_menu2"
test_menu2.parent = test_menu1.name
cobbler_api.add_menu(test_menu2)
objs.append(test_menu2)
test_distro = create_distro()
test_distro.source_repos = [test_repo.name]
objs.append(test_distro)
test_profile1: Profile = create_profile(
distro_name=test_distro.name, name="test_profile1"
)
test_profile1.enable_menu = False
objs.append(test_profile1)
test_profile2: Profile = create_profile(
profile_name=test_profile1.name, name="test_profile2"
)
test_profile2.enable_menu = False
test_profile2.menu = test_menu2.name
objs.append(test_profile2)
test_profile3: Profile = create_profile(
profile_name=test_profile1.name, name="test_profile3"
)
test_profile3.enable_menu = False
test_profile3.repos = [test_repo.name]
objs.append(test_profile3)
test_image = create_image()
test_image.menu = test_menu1.name
objs.append(test_image)
test_system1 = create_system(profile_name=test_profile1.name, name="test_system1")
objs.append(test_system1)
test_system2 = create_system(image_name=test_image.name, name="test_system2")
objs.append(test_system2)
# Act
repo_dep = test_repo.descendants
menu1_dep = test_menu1.descendants
menu2_dep = test_menu2.descendants
distro_dep = test_distro.descendants
profile1_dep = test_profile1.descendants
profile2_dep = test_profile2.descendants
profile3_dep = test_profile3.descendants
image_dep = test_image.descendants
system1_dep = test_system1.descendants
system2_dep = test_system2.descendants
settings_dep = objs
signatures_dep = [
test_distro,
test_profile1,
test_profile2,
test_profile3,
test_image,
test_system1,
test_system2,
]
# Assert
assert validate_caches(cobbler_api, objs, test_repo, repo_dep) == expected_output
assert validate_caches(cobbler_api, objs, test_menu1, menu1_dep) == expected_output
assert validate_caches(cobbler_api, objs, test_menu2, menu2_dep) == expected_output
assert (
validate_caches(cobbler_api, objs, test_distro, distro_dep) == expected_output
)
assert (
validate_caches(cobbler_api, objs, test_profile1, profile1_dep)
== expected_output
)
assert (
validate_caches(cobbler_api, objs, test_profile2, profile2_dep)
== expected_output
)
assert (
validate_caches(cobbler_api, objs, test_profile3, profile3_dep)
== expected_output
)
assert validate_caches(cobbler_api, objs, test_image, image_dep) == expected_output
assert (
validate_caches(cobbler_api, objs, test_system1, system1_dep) == expected_output
)
assert (
validate_caches(cobbler_api, objs, test_system2, system2_dep) == expected_output
)
assert (
validate_caches(cobbler_api, objs, cobbler_api.settings(), settings_dep) # type: ignore
== expected_output
)
assert (
validate_caches(cobbler_api, objs, cobbler_api.get_signatures(), signatures_dep) # type: ignore
== expected_output
)
with expected_exception:
cobbler_api.clean_items_cache(True) # type: ignore
| 18,660
|
Python
|
.py
| 534
| 29.181648
| 118
| 0.671483
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,975
|
menu_test.py
|
cobbler_cobbler/tests/items/menu_test.py
|
"""
Tests that validate the functionality of the module that is responsible for providing menu related functionality.
"""
from typing import TYPE_CHECKING
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.menu import Menu
from cobbler.settings import Settings
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(name="menu_setting_mock", spec=cobbler_api.settings())
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
# Arrange
# Act
distro = Menu(cobbler_api)
# Arrange
assert isinstance(distro, Menu)
def test_make_clone(cobbler_api: CobblerAPI):
# Arrange
menu = Menu(cobbler_api)
# Act
result = menu.make_clone()
# Assert
assert menu != result
def test_display_name(cobbler_api: CobblerAPI):
# Arrange
menu = Menu(cobbler_api)
# Act
menu.display_name = ""
# Assert
assert menu.display_name == ""
def test_to_dict(cobbler_api: CobblerAPI):
# Arrange
titem = Menu(cobbler_api)
# Act
result = titem.to_dict()
# Assert
assert isinstance(result, dict)
def test_to_dict_resolved(cobbler_api: CobblerAPI):
# Arrange
titem = Menu(cobbler_api)
# Act
result = titem.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert enums.VALUE_INHERITED not in str(result)
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
menu = Menu(cobbler_api)
# Act
for key, key_value in menu.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(menu, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(menu, new_key)
setattr(menu, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(menu, new_key)
| 3,461
|
Python
|
.py
| 93
| 29.344086
| 113
| 0.639796
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,976
|
base_item_test.py
|
cobbler_cobbler/tests/items/base_item_test.py
|
"""
Tests that validate the functionality of the module that is responsible for providing basic item functionality.
"""
import copy
from typing import Any, List, Optional
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.abstract.base_item import BaseItem
from tests.conftest import does_not_raise
class MockItem(BaseItem):
def __init__(self, api: "CobblerAPI", *args: Any, **kwargs: Any):
super().__init__(api, *args, **kwargs)
self._inmemory = True
if len(kwargs) > 0:
self.from_dict(kwargs)
if not self._has_initialized:
self._has_initialized = True
def make_clone(self) -> BaseItem:
_dict = copy.deepcopy(self.to_dict())
# Drop attributes which are computed from other attributes
computed_properties = ["uid"]
for property_name in computed_properties:
_dict.pop(property_name, None)
return MockItem(self.api, **_dict)
def _resolve(self, property_name: str) -> Any:
settings_name = property_name
if property_name == "owners":
settings_name = "default_ownership"
attribute = "_" + property_name
attribute_value = getattr(self, attribute)
if attribute_value == enums.VALUE_INHERITED:
settings = self.api.settings()
possible_return = None
if hasattr(settings, settings_name):
possible_return = getattr(settings, settings_name)
elif hasattr(settings, f"default_{settings_name}"):
possible_return = getattr(settings, f"default_{settings_name}")
if possible_return is not None:
return possible_return
return attribute_value
def test_uid(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the uid property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
titem.uid = "uid"
# Assert
assert titem.uid == "uid"
@pytest.mark.parametrize(
"input_ctime,expected_exception,expected_result",
[("", pytest.raises(TypeError), None), (0.0, does_not_raise(), 0.0)],
)
def test_ctime(
cobbler_api: CobblerAPI,
input_ctime: Any,
expected_exception: Any,
expected_result: float,
):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the ctime property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
with expected_exception:
titem.ctime = input_ctime
# Assert
assert titem.ctime == expected_result
@pytest.mark.parametrize(
"value,expected_exception",
[
(0.0, does_not_raise()),
(0, pytest.raises(TypeError)),
("", pytest.raises(TypeError)),
],
)
def test_mtime(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the mtime property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
with expected_exception:
titem.mtime = value
# Assert
assert titem.mtime == value
def test_name(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the name property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
titem.name = "testname"
# Assert
assert titem.name == "testname"
def test_comment(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the comment property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
titem.comment = "my comment"
# Assert
assert titem.comment == "my comment"
@pytest.mark.parametrize(
"input_owners,expected_exception,expected_result",
[
("", does_not_raise(), []),
(enums.VALUE_INHERITED, does_not_raise(), ["admin"]),
("Test1 Test2", does_not_raise(), ["Test1", "Test2"]),
(["Test1", "Test2"], does_not_raise(), ["Test1", "Test2"]),
(False, pytest.raises(TypeError), None),
],
)
def test_owners(
cobbler_api: CobblerAPI,
input_owners: Any,
expected_exception: Any,
expected_result: Optional[List[str]],
):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the owners property correctly.
"""
# Arrange
titem = MockItem(cobbler_api)
# Act
with expected_exception:
titem.owners = input_owners
# Assert
assert titem.owners == expected_result
def test_check_if_valid(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Asserts that the check for a valid item is performed successfuly.
"""
# Arrange
titem = MockItem(cobbler_api)
titem.name = (
request.node.originalname if request.node.originalname else request.node.name # type: ignore
)
# Act
titem.check_if_valid()
# Assert
assert True # This test passes if there is no exception raised
| 5,103
|
Python
|
.py
| 149
| 28.067114
| 111
| 0.654253
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,977
|
bootable_item_test.py
|
cobbler_cobbler/tests/items/bootable_item_test.py
|
"""
Test module that asserts that generic Cobbler BootableItem functionality is working as expected.
"""
import os
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.abstract.bootable_item import BootableItem
from cobbler.items.distro import Distro
from cobbler.settings import Settings
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI):
"""
Test fixture that mocks the settings for the bootable items.
"""
settings = mocker.MagicMock(name="item_setting_mock", spec=cobbler_api.settings())
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_item_create(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler BootableItem can be successfully created.
"""
# Arrange
# Act
titem = Distro(cobbler_api)
# Assert
assert isinstance(titem, BootableItem)
def test_from_dict(
cobbler_api: CobblerAPI,
create_kernel_initrd: Callable[[str, str], str],
fk_kernel: str,
fk_initrd: str,
):
"""
Assert that an abstract Cobbler BootableItem can be loaded from dict.
"""
# Arrange
folder = create_kernel_initrd(fk_kernel, fk_initrd)
name = "test_from_dict"
kernel_path = os.path.join(folder, fk_kernel)
initrd_path = os.path.join(folder, fk_initrd)
titem = Distro(cobbler_api)
# Act
titem.from_dict({"name": name, "kernel": kernel_path, "initrd": initrd_path})
# Assert
titem.check_if_valid() # This raises an exception if something is not right.
assert titem.name == name
assert titem.kernel == kernel_path
assert titem.initrd == initrd_path
@pytest.mark.parametrize(
"input_kernel_options,expected_exception,expected_result",
[
("", does_not_raise(), {}),
(False, pytest.raises(TypeError), None),
],
)
def test_kernel_options(
cobbler_api: CobblerAPI,
input_kernel_options: Any,
expected_exception: Any,
expected_result: Optional[Dict[Any, Any]],
):
"""
Assert that an abstract Cobbler BootableItem can use the Getter and Setter of the kernel_options property correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
with expected_exception:
titem.kernel_options = input_kernel_options
# Assert
assert titem.kernel_options == expected_result
@pytest.mark.parametrize(
"input_kernel_options,expected_exception,expected_result",
[
("", does_not_raise(), {}),
(False, pytest.raises(TypeError), None),
],
)
def test_kernel_options_post(
cobbler_api: CobblerAPI,
input_kernel_options: Any,
expected_exception: Any,
expected_result: Optional[Dict[Any, Any]],
):
"""
Assert that an abstract Cobbler BootableItem can use the Getter and Setter of the kernel_options_post property
correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
with expected_exception:
titem.kernel_options_post = input_kernel_options
# Assert
assert titem.kernel_options_post == expected_result
@pytest.mark.parametrize(
"input_autoinstall_meta,expected_exception,expected_result",
[
("", does_not_raise(), {}),
(False, pytest.raises(TypeError), None),
],
)
def test_autoinstall_meta(
cobbler_api: CobblerAPI,
input_autoinstall_meta: Any,
expected_exception: Any,
expected_result: Optional[Dict[Any, Any]],
):
"""
Assert that an abstract Cobbler BootableItem can use the Getter and Setter of the autoinstall_meta property
correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
with expected_exception:
titem.autoinstall_meta = input_autoinstall_meta
# Assert
assert titem.autoinstall_meta == expected_result
def test_template_files(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler BootableItem can use the Getter and Setter of the template_files property correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
titem.template_files = {}
# Assert
assert titem.template_files == {}
def test_sort_key(request: "pytest.FixtureRequest", cobbler_api: CobblerAPI):
"""
Assert that the exported dict contains only the fields given in the argument.
"""
# Arrange
titem = Distro(cobbler_api)
titem.name = (
request.node.originalname if request.node.originalname else request.node.name # type: ignore
)
# Act
result = titem.sort_key(sort_fields=["name"])
# Assert
assert result == [
request.node.originalname if request.node.originalname else request.node.name # type: ignore
]
@pytest.mark.parametrize(
"in_keys, check_keys, expect_match",
[
({"uid": "test-uid"}, {"uid": "test-uid"}, True),
({"name": "test-object"}, {"name": "test-object"}, True),
({"comment": "test-comment"}, {"comment": "test-comment"}, True),
({"uid": "test-uid"}, {"uid": ""}, False),
],
)
def test_find_match(
cobbler_api: CobblerAPI,
in_keys: Dict[str, Any],
check_keys: Dict[str, Any],
expect_match: bool,
):
"""
Assert that given a desired amount of key-value pairs is matching the item or not.
"""
# Arrange
titem = Distro(cobbler_api, **in_keys)
# Act
result = titem.find_match(check_keys)
# Assert
assert expect_match == result
@pytest.mark.parametrize(
"data_keys, check_key, check_value, expect_match",
[
({"uid": "test-uid"}, "uid", "test-uid", True),
({"menu": "testmenu0"}, "menu", "testmenu0", True),
({"uid": "test", "name": "test-name"}, "uid", "test", True),
({"depth": "1"}, "name", "test", False),
({"uid": "test", "name": "test-name"}, "menu", "testmenu0", False),
],
)
def test_find_match_single_key(
cobbler_api: CobblerAPI,
data_keys: Dict[str, Any],
check_key: str,
check_value: Any,
expect_match: bool,
):
"""
Assert that a single given key and value match the object or not.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
result = titem.find_match_single_key(data_keys, check_key, check_value)
# Assert
assert expect_match == result
def test_dump_vars(cobbler_api: CobblerAPI):
"""
Assert that you can dump all variables of an item.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
result = titem.dump_vars(formatted_output=False)
# Assert
print(result)
assert "default_ownership" in result
assert "owners" in result
assert len(result) == 169
def test_to_dict(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler BootableItem can be converted to a dictionary.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
result = titem.to_dict()
# Assert
assert isinstance(result, dict)
assert result.get("owners") == enums.VALUE_INHERITED
def test_to_dict_resolved(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler BootableItem can be converted to a dictionary with resolved values.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
result = titem.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("owners") == ["admin"]
assert enums.VALUE_INHERITED not in str(result)
def test_serialize(cobbler_api: CobblerAPI):
"""
Assert that a given Cobbler BootableItem can be serialized.
"""
# Arrange
kernel_url = "http://10.0.0.1/custom-kernels-are-awesome"
titem = Distro(cobbler_api)
titem.remote_boot_kernel = kernel_url
# Act
result = titem.serialize()
# Assert
assert titem.remote_boot_kernel == kernel_url
assert titem.remote_grub_kernel.startswith("(http,")
assert "remote_grub_kernel" not in result
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
item = Distro(cobbler_api)
# Act
for key, key_value in item.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(item, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(item, new_key)
setattr(item, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(item, new_key)
| 9,929
|
Python
|
.py
| 291
| 28.103093
| 120
| 0.65281
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,978
|
network_interface_test.py
|
cobbler_cobbler/tests/items/network_interface_test.py
|
"""
Tests that validate the functionality of the module that is responsible for providing network interface related
functionality.
"""
import logging
from ipaddress import AddressValueError
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.network_interface import NetworkInterface
from cobbler.items.profile import Profile
from cobbler.items.system import System
from cobbler.settings import Settings
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(
name="interface_setting_mock", spec=cobbler_api.settings()
)
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_network_interface_object_creation(cobbler_api: CobblerAPI):
# Arrange
# Act
interface = NetworkInterface(cobbler_api, "")
# Assert
assert isinstance(interface, NetworkInterface)
def test_network_interface_to_dict(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
result = interface.to_dict()
# Assert
assert isinstance(result, dict)
assert "logger" not in result
assert "api" not in result
assert result.get("virt_bridge") == enums.VALUE_INHERITED
assert len(result) == 23
def test_network_interface_to_dict_resolved(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
result = interface.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("virt_bridge") == "virbr0"
assert enums.VALUE_INHERITED not in str(result)
@pytest.mark.parametrize(
"input_dict,modified_field,expected_result,expect_logger_warning",
[
({"dns_name": "host.example.com"}, "dns_name", "host.example.com", False),
({"not_existing": "invalid"}, "dhcp_tag", "", True),
],
)
def test_network_interface_from_dict(
caplog: pytest.LogCaptureFixture,
cobbler_api: CobblerAPI,
input_dict: Dict[str, str],
modified_field: str,
expected_result: str,
expect_logger_warning: bool,
):
# Arrange
caplog.set_level(logging.INFO)
interface = NetworkInterface(cobbler_api, "")
# Act
interface.from_dict(input_dict)
# Assert
assert getattr(interface, f"_{modified_field}") == expected_result
if expect_logger_warning:
assert "The following keys were ignored" in caplog.records[0].message
else:
assert len(caplog.records) == 0
def test_serialize():
pass
def test_deserialize():
pass
@pytest.mark.parametrize(
"input_dhcp_tag,expected_result,expected_exception",
[
("", "", does_not_raise()),
("test", "test", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_dhcp_tag(
cobbler_api: CobblerAPI,
input_dhcp_tag: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.dhcp_tag = input_dhcp_tag
# Assert
assert isinstance(interface.dhcp_tag, str)
assert interface.dhcp_tag == expected_result
def test_cnames(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
interface.cnames = []
# Assert
assert isinstance(interface.cnames, list)
assert interface.cnames == []
def test_static_routes(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
interface.static_routes = []
# Assert
assert isinstance(interface.static_routes, list)
assert interface.static_routes == []
@pytest.mark.parametrize(
"input_static,expected_result,expected_exception",
[
("", False, does_not_raise()),
(0, False, does_not_raise()),
(1, True, does_not_raise()),
([], "", pytest.raises(TypeError)),
],
)
def test_static(
cobbler_api: CobblerAPI,
input_static: Union[int, List[int], str],
expected_result: Union[bool, str],
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.static = input_static # type: ignore
# Assert
assert isinstance(interface.static, bool)
assert interface.static is expected_result
@pytest.mark.parametrize(
"input_management,expected_result,expected_exception",
[
("", False, does_not_raise()),
(0, False, does_not_raise()),
(1, True, does_not_raise()),
([], "", pytest.raises(TypeError)),
],
)
def test_management(
cobbler_api: CobblerAPI,
input_management: Any,
expected_result: Union[bool, str],
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.management = input_management
# Assert
assert isinstance(interface.management, bool)
assert interface.management is expected_result
@pytest.mark.parametrize(
"input_dns_name,expected_result,expected_exception",
[
("", "", does_not_raise()),
("host.example.org", "host.example.org", does_not_raise()),
("duplicate.example.org", "", pytest.raises(ValueError)),
],
)
def test_dns_name(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Callable[[str], System],
input_dns_name: str,
expected_result: str,
expected_exception: Any,
):
# Arrange
distro = create_distro()
profile = create_profile(distro.name)
system = create_system(profile.name)
system.interfaces["default"].dns_name = "duplicate.example.org"
cobbler_api.add_system(system)
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
# TODO: Test matching self
interface.dns_name = input_dns_name
# Assert
assert isinstance(interface.dns_name, str)
assert interface.dns_name == expected_result
@pytest.mark.parametrize(
"input_mac,expected_result,expected_exception",
[
("", "", does_not_raise()),
("AA:BB", "", pytest.raises(ValueError)),
(0, "", pytest.raises(TypeError)),
("random", "AA:BB:CC:DD:EE:FF", does_not_raise()),
(
"80:00:0a:43:fe:80:00:00:00:00:00:00:0e:fa:aa:bb:cc:dd:ee:ff",
"80:00:0a:43:fe:80:00:00:00:00:00:00:0e:fa:aa:bb:cc:dd:ee:ff",
does_not_raise(),
),
("AA:AA:AA:AA:AA:AA", "", pytest.raises(ValueError)),
],
)
def test_mac_address(
mocker: "MockerFixture",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Any,
input_mac: str,
expected_result: str,
expected_exception: Any,
):
# Arrange
distro = create_distro()
profile = create_profile(distro.name)
system: System = create_system(profile.name)
system.interfaces["default"].mac_address = "AA:AA:AA:AA:AA:AA"
cobbler_api.add_system(system)
system2: System = create_system(profile_name=profile.name, name="test_system2")
system2.interfaces["default"].mac_address = "random"
cobbler_api.add_system(system2)
mocker.patch("cobbler.utils.get_random_mac", return_value="AA:BB:CC:DD:EE:FF")
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
# TODO: match self
interface.mac_address = input_mac
# Assert
assert isinstance(interface.mac_address, str)
assert interface.mac_address == expected_result
def test_netmask(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
interface.netmask = ""
# Assert
assert isinstance(interface.netmask, str)
assert interface.netmask == ""
def test_if_gateway(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
interface.if_gateway = ""
# Assert
assert isinstance(interface.if_gateway, str)
assert interface.if_gateway == ""
@pytest.mark.parametrize(
"input_virt_bridge,expected_result,expected_exception",
[
("", "virbr0", does_not_raise()),
("<<inherit>>", "virbr0", does_not_raise()),
("test", "test", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_virt_bridge(
cobbler_api: CobblerAPI,
input_virt_bridge: Union[str, int],
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.virt_bridge = input_virt_bridge # type: ignore
# Assert
assert isinstance(interface.virt_bridge, str)
assert interface.virt_bridge == expected_result
@pytest.mark.parametrize(
"input_interface_type,expected_result,expected_exception",
[
([], enums.NetworkInterfaceType.NA, pytest.raises(TypeError)),
(0, enums.NetworkInterfaceType.NA, does_not_raise()),
(100, enums.NetworkInterfaceType.NA, pytest.raises(ValueError)),
("INVALID", enums.NetworkInterfaceType.NA, pytest.raises(ValueError)),
# TODO: Create test for last ValueError
("NA", enums.NetworkInterfaceType.NA, does_not_raise()),
("na", enums.NetworkInterfaceType.NA, does_not_raise()),
],
)
def test_interface_type(
cobbler_api: CobblerAPI,
input_interface_type: Any,
expected_result: enums.NetworkInterfaceType,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.interface_type = input_interface_type
# Assert
assert isinstance(interface.interface_type, enums.NetworkInterfaceType)
assert interface.interface_type == expected_result
@pytest.mark.parametrize(
"input_interface_master,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_interface_master(
cobbler_api: CobblerAPI,
input_interface_master: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.interface_master = input_interface_master
# Assert
assert isinstance(interface.interface_master, str)
assert interface.interface_master == expected_result
@pytest.mark.parametrize(
"input_bonding_opts,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_bonding_opts(
cobbler_api: CobblerAPI,
input_bonding_opts: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.bonding_opts = input_bonding_opts
# Assert
assert isinstance(interface.bonding_opts, str)
assert interface.bonding_opts == expected_result
@pytest.mark.parametrize(
"input_bridge_opts,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_bridge_opts(
cobbler_api: CobblerAPI,
input_bridge_opts: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.bridge_opts = input_bridge_opts
# Assert
assert isinstance(interface.bridge_opts, str)
assert interface.bridge_opts == expected_result
@pytest.mark.parametrize(
"input_ip_address,expected_result,expected_exception",
[
("", "", does_not_raise()),
("172.30.0.1", "172.30.0.1", does_not_raise()),
("172.30.0.2", "", pytest.raises(ValueError)),
],
)
def test_ip_address(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Callable[[str], System],
input_ip_address: str,
expected_result: str,
expected_exception: Any,
):
# Arrange
distro = create_distro()
profile = create_profile(distro.name)
system = create_system(profile.name)
system.interfaces["default"].ip_address = "172.30.0.2"
cobbler_api.add_system(system)
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
# TODO: Match self in loop
interface.ip_address = input_ip_address
# Assert
assert isinstance(interface.ip_address, str)
assert interface.ip_address == expected_result
@pytest.mark.parametrize(
"input_address,expected_result,expected_exception",
[
("", "", does_not_raise()),
("2001:db8:3c4d::1", "2001:db8:3c4d::1", does_not_raise()),
("2001:db8:3c4d::2", "", pytest.raises(ValueError)),
],
)
def test_ipv6_address(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
create_system: Callable[[str], System],
input_address: str,
expected_result: str,
expected_exception: Any,
):
# Arrange
distro = create_distro()
profile = create_profile(distro.name)
system = create_system(profile.name)
system.interfaces["default"].ipv6_address = "2001:db8:3c4d::2"
cobbler_api.add_system(system)
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
# TODO: match self
interface.ipv6_address = input_address
# Assert
assert isinstance(interface.ipv6_address, str)
assert interface.ipv6_address == expected_result
@pytest.mark.parametrize(
"input_ipv6_prefix,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_ipv6_prefix(
cobbler_api: CobblerAPI,
input_ipv6_prefix: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.ipv6_prefix = input_ipv6_prefix
# Assert
assert isinstance(interface.ipv6_prefix, str)
assert interface.ipv6_prefix == expected_result
@pytest.mark.parametrize(
"input_secondaries,expected_result,expected_exception",
[
([""], [""], does_not_raise()),
(["::1"], ["::1"], does_not_raise()),
("invalid", [], pytest.raises(AddressValueError)),
],
)
def test_ipv6_secondaries(
cobbler_api: CobblerAPI,
input_secondaries: Any,
expected_result: List[str],
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.ipv6_secondaries = input_secondaries
# Assert
assert isinstance(interface.ipv6_secondaries, list)
assert interface.ipv6_secondaries == expected_result # type: ignore
@pytest.mark.parametrize(
"input_address,expected_result,expected_exception",
[
("", "", does_not_raise()),
("::1", "::1", does_not_raise()),
(None, "", pytest.raises(TypeError)),
("invalid", "", pytest.raises(AddressValueError)),
],
)
def test_ipv6_default_gateway(
cobbler_api: CobblerAPI,
input_address: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.ipv6_default_gateway = input_address
# Assert
assert isinstance(interface.ipv6_default_gateway, str)
assert interface.ipv6_default_gateway == expected_result
def test_ipv6_static_routes(cobbler_api: CobblerAPI):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
interface.ipv6_static_routes = []
# Assert
assert isinstance(interface.ipv6_static_routes, list)
assert interface.ipv6_static_routes == []
@pytest.mark.parametrize(
"input_ipv6_mtu,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_ipv6_mtu(
cobbler_api: CobblerAPI,
input_ipv6_mtu: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.ipv6_mtu = input_ipv6_mtu
# Assert
assert isinstance(interface.ipv6_mtu, str)
assert interface.ipv6_mtu == expected_result
@pytest.mark.parametrize(
"input_mtu,expected_result,expected_exception",
[
("", "", does_not_raise()),
(0, "", pytest.raises(TypeError)),
],
)
def test_mtu(
cobbler_api: CobblerAPI,
input_mtu: Any,
expected_result: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.mtu = input_mtu
# Assert
assert isinstance(interface.mtu, str)
assert interface.mtu == expected_result
@pytest.mark.parametrize(
"input_connected_mode,expected_result,expected_exception",
[
("", False, does_not_raise()),
(0, False, does_not_raise()),
(1, True, does_not_raise()),
([], "", pytest.raises(TypeError)),
],
)
def test_connected_mode(
cobbler_api: CobblerAPI,
input_connected_mode: Any,
expected_result: Any,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.connected_mode = input_connected_mode
# Assert
assert isinstance(interface.connected_mode, bool)
assert interface.connected_mode is expected_result
@pytest.mark.parametrize(
"input_modify_interface,expected_modified_field,expected_value,expected_exception",
[
({}, "mtu", "", does_not_raise()),
({"mtu-eth0": "test"}, "mtu", "test", does_not_raise()),
],
)
def test_modify_interface(
cobbler_api: CobblerAPI,
input_modify_interface: Dict[str, str],
expected_modified_field: str,
expected_value: str,
expected_exception: Any,
):
# Arrange
interface = NetworkInterface(cobbler_api, "")
# Act
with expected_exception:
interface.modify_interface(input_modify_interface)
# Assert
assert getattr(interface, expected_modified_field) == expected_value
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
interface = NetworkInterface(cobbler_api, "")
# Act
for key, key_value in interface.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(interface, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(interface, new_key)
setattr(interface, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(interface, new_key)
| 20,961
|
Python
|
.py
| 631
| 27.255151
| 111
| 0.65741
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,979
|
inheritable_item_test.py
|
cobbler_cobbler/tests/items/inheritable_item_test.py
|
"""
Test module that asserts that generic Cobbler InheritableItem functionality is working as expected.
"""
from typing import Any, Callable, Optional
import pytest
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.menu import Menu
from cobbler.items.profile import Profile
from cobbler.items.repo import Repo
from cobbler.items.system import System
from tests.conftest import does_not_raise
@pytest.mark.parametrize(
"input_depth,expected_exception,expected_result",
[
("", pytest.raises(TypeError), None),
(5, does_not_raise(), 5),
],
)
def test_depth(
cobbler_api: CobblerAPI,
input_depth: Any,
expected_exception: Any,
expected_result: Optional[int],
):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the depth property correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
with expected_exception:
titem.depth = input_depth
# Assert
assert titem.depth == expected_result
def test_parent(cobbler_api: CobblerAPI):
"""
Assert that an abstract Cobbler Item can use the Getter and Setter of the parent property correctly.
"""
# Arrange
titem = Distro(cobbler_api)
# Act
titem.parent = ""
# Assert
assert titem.parent is None
def test_get_conceptual_parent(
request: "pytest.FixtureRequest",
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_profile: Callable[[str], Profile],
):
"""
Assert that retrieving the conceptual parent is working as expected.
"""
# Arrange
tmp_distro = create_distro()
tmp_profile = create_profile(tmp_distro.name)
titem = Profile(cobbler_api)
titem.name = "subprofile_%s" % (
request.node.originalname if request.node.originalname else request.node.name # type: ignore
)
titem.parent = tmp_profile.name
# Act
result = titem.get_conceptual_parent()
# Assert
assert result is not None
assert result.name == tmp_distro.name
def test_children(cobbler_api: CobblerAPI):
"""
Assert that a given Cobbler Item successfully returns the list of child objects.
"""
# Arrange
titem = Distro(cobbler_api, name="test_children")
# Act
result = titem.children
# Assert
assert result == []
def test_item_descendants(cobbler_api: CobblerAPI):
"""
Assert that all descendants of a Cobbler BootableItem are correctly captured by called the property.
"""
# Arrange
titem = Distro(cobbler_api, name="test_item_descendants")
# Act
result = titem.descendants
# Assert
assert result == []
def test_descendants(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
create_image: Callable[[], Image],
create_profile: Any,
create_system: Any,
):
"""
Assert that the descendants property is also working with an enabled Cache.
"""
# Arrange
test_repo = Repo(cobbler_api)
test_repo.name = "test_repo"
cobbler_api.add_repo(test_repo)
test_menu1 = Menu(cobbler_api)
test_menu1.name = "test_menu1"
cobbler_api.add_menu(test_menu1)
test_menu2 = Menu(cobbler_api)
test_menu2.name = "test_menu2"
test_menu2.parent = test_menu1.name
cobbler_api.add_menu(test_menu2)
test_distro = create_distro()
test_profile1: Profile = create_profile(
distro_name=test_distro.name, name="test_profile1"
)
test_profile1.enable_menu = False
test_profile1.repos = [test_repo.name]
test_profile2: Profile = create_profile(
profile_name=test_profile1.name, name="test_profile2"
)
test_profile2.enable_menu = False
test_profile2.menu = test_menu2.name
test_profile3: Profile = create_profile(
profile_name=test_profile1.name, name="test_profile3"
)
test_profile3.enable_menu = False
test_profile3.repos = [test_repo.name]
test_image = create_image()
test_image.menu = test_menu1.name
test_system1: System = create_system(
profile_name=test_profile1.name, name="test_system1"
)
test_system2: System = create_system(
image_name=test_image.name, name="test_system2"
)
# Act
cache_tests = [
test_repo.descendants,
test_distro.descendants,
test_image.descendants,
test_profile1.descendants,
test_profile2.descendants,
test_profile3.descendants,
test_menu1.descendants,
test_menu2.descendants,
test_system1.descendants,
test_system2.descendants,
]
results = [
[test_profile1, test_profile2, test_profile3, test_system1],
[test_profile1, test_profile2, test_profile3, test_system1],
[test_system2],
[test_profile2, test_profile3, test_system1],
[],
[],
[test_image, test_menu2, test_profile2, test_system2],
[test_profile2],
[],
[],
]
# Assert
for x in range(len(cache_tests)):
assert set(cache_tests[x]) == set(results[x])
def test_tree_walk(cobbler_api: CobblerAPI):
"""
Assert that all descendants of a Cobbler Item are correctly captured by called the method.
"""
# Arrange
titem = Distro(cobbler_api, name="test_tree_walk")
# Act
result = titem.tree_walk()
# Assert
assert result == []
def test_grab_tree(cobbler_api: CobblerAPI):
"""
Assert that grabbing the item tree is containing the settings.
"""
# Arrange
object_to_check = Distro(cobbler_api)
# TODO: Create some objects and give them some inheritance.
# Act
result = object_to_check.grab_tree()
# Assert
assert isinstance(result, list)
# pylint: disable-next=no-member
assert result[-1].server == "192.168.1.1" # type: ignore
| 5,892
|
Python
|
.py
| 184
| 26.695652
| 104
| 0.678773
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,980
|
repo_test.py
|
cobbler_cobbler/tests/items/repo_test.py
|
"""
Tests that validate the functionality of the module that is responsible for providing repository related functionality.
"""
from typing import TYPE_CHECKING, Any
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.items.repo import Repo
from cobbler.settings import Settings
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(name="repo_setting_mock", spec=cobbler_api.settings())
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
# Arrange
# Act
repo = Repo(cobbler_api)
# Arrange
assert isinstance(repo, Repo)
def test_make_clone(cobbler_api: CobblerAPI):
# Arrange
repo = Repo(cobbler_api)
# Act
result = repo.make_clone()
# Assert
assert result != repo
def test_to_dict(cobbler_api: CobblerAPI):
# Arrange
titem = Repo(cobbler_api)
# Act
result = titem.to_dict()
# Assert
assert isinstance(result, dict)
assert result.get("proxy") == enums.VALUE_INHERITED
def test_to_dict_resolved(cobbler_api: CobblerAPI):
# Arrange
titem = Repo(cobbler_api)
# Act
result = titem.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("proxy") == ""
assert enums.VALUE_INHERITED not in str(result)
# Properties Tests
def test_mirror(cobbler_api: CobblerAPI):
# Arrange
repo = Repo(cobbler_api)
# Act
repo.mirror = "https://mymirror.com"
# Assert
assert repo.mirror == "https://mymirror.com"
def test_mirror_type(cobbler_api: CobblerAPI):
# Arrange
repo = Repo(cobbler_api)
# Act
repo.mirror_type = enums.MirrorType.BASEURL
# Assert
assert repo.mirror_type == enums.MirrorType.BASEURL
def test_keep_updated(cobbler_api: CobblerAPI):
# Arrange
repo = Repo(cobbler_api)
# Act
repo.keep_updated = False
# Assert
assert not repo.keep_updated
def test_yumopts(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.yumopts = {}
# Assert
assert testrepo.yumopts == {}
def test_rsyncopts(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.rsyncopts = {}
# Assert
assert testrepo.rsyncopts == {}
def test_environment(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.environment = {}
# Assert
assert testrepo.environment == {}
def test_priority(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.priority = 5
# Assert
assert testrepo.priority == 5
def test_rpm_list(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.rpm_list = []
# Assert
assert testrepo.rpm_list == []
@pytest.mark.parametrize(
"input_flags,expected_exception,expected_result",
[
("", does_not_raise(), ""),
(
"<<inherit>>",
does_not_raise(),
"-c cache -s sha",
), # Result is coming from settings.yaml
(0, pytest.raises(TypeError), ""),
],
)
def test_createrepo_flags(
cobbler_api: CobblerAPI,
input_flags: Any,
expected_exception: Any,
expected_result: str,
):
# Arrange
testrepo = Repo(cobbler_api)
# Act
with expected_exception:
testrepo.createrepo_flags = input_flags
# Assert
assert testrepo.createrepo_flags == expected_result
def test_breed(cobbler_api: CobblerAPI):
# Arrange
repo = Repo(cobbler_api)
# Act
repo.breed = "yum"
# Assert
assert repo.breed == enums.RepoBreeds.YUM
def test_os_version(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
testrepo.breed = "yum"
# Act
testrepo.os_version = "rhel4"
# Assert
assert testrepo.breed == enums.RepoBreeds.YUM
assert testrepo.os_version == "rhel4"
@pytest.mark.parametrize(
"value,expected_exception",
[
("x86_64", does_not_raise()),
(enums.RepoArchs.X86_64, does_not_raise()),
(enums.Archs.X86_64, pytest.raises(AssertionError)),
(False, pytest.raises(TypeError)),
("", pytest.raises(ValueError)),
],
)
def test_arch(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
# Arrange
testrepo = Repo(cobbler_api)
# Act
with expected_exception:
testrepo.arch = value
# Assert
if isinstance(value, str):
assert testrepo.arch.value == value
else:
assert testrepo.arch == value
def test_mirror_locally(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.mirror_locally = False
# Assert
assert not testrepo.mirror_locally
def test_apt_components(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.apt_components = []
# Assert
assert testrepo.apt_components == []
def test_apt_dists(cobbler_api: CobblerAPI):
# Arrange
testrepo = Repo(cobbler_api)
# Act
testrepo.apt_dists = []
# Assert
assert testrepo.apt_dists == []
@pytest.mark.parametrize(
"input_proxy,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), ""),
(0, pytest.raises(TypeError), ""),
],
)
def test_proxy(
cobbler_api: CobblerAPI,
input_proxy: Any,
expected_exception: Any,
expected_result: str,
):
# Arrange
testrepo = Repo(cobbler_api)
# Act
with expected_exception:
testrepo.proxy = input_proxy
# Assert
assert testrepo.proxy == expected_result
def test_inheritance(
mocker: "MockerFixture", cobbler_api: CobblerAPI, test_settings: Settings
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
mocker.patch.object(cobbler_api, "settings", return_value=test_settings)
testrepo = Repo(cobbler_api)
# Act
for key, key_value in testrepo.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(testrepo, new_key)
settings_name = new_key
if new_key == "owners":
settings_name = "default_ownership"
elif new_key == "proxy":
settings_name = "proxy_url_ext"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
setting = getattr(test_settings, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value = {"test_inheritance": "test_inheritance"}
elif isinstance(setting, list):
new_value = ["test_inheritance"]
setattr(test_settings, settings_name, new_value)
prev_value = getattr(testrepo, new_key)
setattr(testrepo, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(testrepo, new_key)
| 7,971
|
Python
|
.py
| 252
| 25.130952
| 119
| 0.642492
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,981
|
profile_test.py
|
cobbler_cobbler/tests/items/profile_test.py
|
"""
Test module to validate the functionality of the Cobbler Profile item.
"""
from typing import TYPE_CHECKING, Any, Callable, Dict, List
import pytest
from cobbler import enums
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.settings import Settings
from tests.conftest import does_not_raise
if TYPE_CHECKING:
from pytest_mock import MockerFixture
@pytest.fixture(name="test_settings")
def fixture_test_settings(mocker: "MockerFixture", cobbler_api: CobblerAPI) -> Settings:
settings = mocker.MagicMock(
name="profile_setting_mock", spec=cobbler_api.settings()
)
orig = cobbler_api.settings()
for key in orig.to_dict():
setattr(settings, key, getattr(orig, key))
return settings
def test_object_creation(cobbler_api: CobblerAPI):
"""
Assert that the Profile object can be successfully created.
"""
# Arrange
# Act
profile = Profile(cobbler_api)
# Arrange
assert isinstance(profile, Profile)
def test_make_clone(cobbler_api: CobblerAPI):
"""
Assert that a profile can be cloned and NOT have the same identity.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
result = profile.make_clone()
# Assert
assert result != profile
def test_to_dict(
create_distro: Callable[[], Distro],
create_profile: Any,
):
"""
Assert that the Profile can be successfully converted to a dictionary.
"""
# Arrange
distro = create_distro()
profile: Profile = create_profile(distro_name=distro.name)
# Act
result = profile.to_dict()
# Assert
assert len(result) == 41
assert result["distro"] == distro.name
assert result.get("boot_loaders") == enums.VALUE_INHERITED
def test_to_dict_resolved(
cobbler_api: CobblerAPI, create_distro: Callable[[str], Distro]
):
"""
Assert that the Profile can be successfully converted to a dictionary with resolved values.
"""
# Arrange
test_distro_obj = create_distro() # type: ignore
test_distro_obj.kernel_options = {"test": True}
cobbler_api.add_distro(test_distro_obj) # type: ignore
titem = Profile(cobbler_api)
titem.name = "to_dict_resolved_profile"
titem.distro = test_distro_obj.name # type: ignore
titem.kernel_options = {"my_value": 5}
cobbler_api.add_profile(titem)
# Act
result = titem.to_dict(resolved=True)
# Assert
assert isinstance(result, dict)
assert result.get("kernel_options") == {"test": True, "my_value": 5}
assert result.get("boot_loaders") == ["grub", "pxe", "ipxe"]
assert enums.VALUE_INHERITED not in str(result)
# Properties Tests
def test_parent_empty(cobbler_api: CobblerAPI):
"""
Assert that if a parent is removed that the getter returns None.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.parent = ""
# Assert
assert profile.parent is None
def test_parent_profile(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
):
"""
Assert that if the parent is set via a parent profile name the correct object is returned.
"""
# Arrange
test_dist = create_distro() # type: ignore
test_profile = create_profile(test_dist.name) # type: ignore
profile = Profile(cobbler_api)
# Act
profile.parent = test_profile.name # type: ignore
# Assert
assert profile.parent is test_profile
def test_parent_other_object_type(
cobbler_api: CobblerAPI, create_image: Callable[[str], Image]
):
"""
Assert that if an invalid item type is set as a parent, the setter is raising a CobblerException.
"""
# Arrange
test_image = create_image() # type: ignore
profile = Profile(cobbler_api)
# Act
with pytest.raises(CX):
profile.parent = test_image.name # type: ignore
def test_parent_invalid_type(cobbler_api: CobblerAPI):
"""
Asert that if the parent is set with a completly invalid type, the setter raises a TypeError.
"""
# Arrange
profile = Profile(cobbler_api)
# Act & Assert
with pytest.raises(TypeError):
profile.parent = 0 # type: ignore
def test_parent_self(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can not set itself as a parent.
"""
# Arrange
profile = Profile(cobbler_api)
profile.name = "testname"
# Act & Assert
with pytest.raises(CX):
profile.parent = profile.name
def test_distro(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the distro property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.distro = ""
# Assert
assert profile.distro is None
def test_name_servers(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the name_servers property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.name_servers = []
# Assert
assert profile.name_servers == []
def test_name_servers_search(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the name_servers_search property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.name_servers_search = "" # type: ignore
# Assert
assert profile.name_servers_search == ""
def test_proxy(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the proxy property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.proxy = ""
# Assert
assert profile.proxy == ""
@pytest.mark.parametrize("value,expected_exception", [(False, does_not_raise())])
def test_enable_ipxe(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the enable_ipxe property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.enable_ipxe = value
# Assert
assert profile.enable_ipxe is value
@pytest.mark.parametrize(
"value,expected_exception",
[
(True, does_not_raise()),
(False, does_not_raise()),
("", does_not_raise()),
(0, does_not_raise()),
],
)
def test_enable_menu(cobbler_api: CobblerAPI, value: Any, expected_exception: Any):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the enable_menu property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.enable_menu = value
# Assert
assert isinstance(profile.enable_menu, bool)
assert profile.enable_menu or not profile.enable_menu
def test_dhcp_tag(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the dhcp_tag property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.dhcp_tag = ""
# Assert
assert profile.dhcp_tag == ""
@pytest.mark.parametrize(
"input_server,expected_exception,expected_result",
[
("", does_not_raise(), ""),
("<<inherit>>", does_not_raise(), "192.168.1.1"),
(False, pytest.raises(TypeError), ""),
],
)
def test_server(
cobbler_api: CobblerAPI,
input_server: Any,
expected_exception: Any,
expected_result: str,
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the server property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.server = input_server
# Assert
assert profile.server == expected_result
def test_next_server_v4(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the next_server_v4 property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.next_server_v4 = ""
# Assert
assert profile.next_server_v4 == ""
def test_next_server_v6(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the next_server_v6 property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.next_server_v6 = ""
# Assert
assert profile.next_server_v6 == ""
@pytest.mark.parametrize(
"input_filename,expected_result,is_subitem,expected_exception",
[
("", "", False, does_not_raise()),
("", "", True, does_not_raise()),
("<<inherit>>", "", False, does_not_raise()),
("<<inherit>>", "", True, does_not_raise()),
("test", "test", False, does_not_raise()),
("test", "test", True, does_not_raise()),
(0, "", True, pytest.raises(TypeError)),
],
)
def test_filename(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
input_filename: Any,
expected_result: str,
is_subitem: bool,
expected_exception: Any,
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the filename property correctly.
"""
# Arrange
test_dist = create_distro() # type: ignore
profile = Profile(cobbler_api)
profile.name = "filename_test_profile"
if is_subitem:
test_profile = create_profile(test_dist.name) # type: ignore
profile.parent = test_profile.name # type: ignore
profile.distro = test_dist.name # type: ignore
# Act
with expected_exception:
profile.filename = input_filename
# Assert
assert profile.filename == expected_result
def test_autoinstall(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the autoinstall property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.autoinstall = ""
# Assert
assert profile.autoinstall == ""
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), False),
("<<inherit>>", does_not_raise(), True),
(False, does_not_raise(), False),
(True, does_not_raise(), True),
],
)
def test_virt_auto_boot(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: bool
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_auto_boot property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_auto_boot = value
# Assert
assert isinstance(profile.virt_auto_boot, bool)
assert profile.virt_auto_boot is expected_result
@pytest.mark.parametrize(
"value,expected_exception, expected_result",
[
("", does_not_raise(), 0),
# FIXME: (False, pytest.raises(TypeError)), --> does not raise
(-5, pytest.raises(ValueError), -5),
(0, does_not_raise(), 0),
(5, does_not_raise(), 5),
],
)
def test_virt_cpus(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: int
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_cpus property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_cpus = value
# Assert
assert profile.virt_cpus == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("5", does_not_raise(), 5.0),
("<<inherit>>", does_not_raise(), 5.0),
# FIXME: (False, pytest.raises(TypeError)), --> does not raise
(-5, pytest.raises(ValueError), 0),
(0, does_not_raise(), 0.0),
(5, does_not_raise(), 5.0),
],
)
def test_virt_file_size(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: Any
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_file_size property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_file_size = value
# Assert
assert profile.virt_file_size == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("qcow2", does_not_raise(), enums.VirtDiskDrivers.QCOW2),
("<<inherit>>", does_not_raise(), enums.VirtDiskDrivers.RAW),
(enums.VirtDiskDrivers.QCOW2, does_not_raise(), enums.VirtDiskDrivers.QCOW2),
(False, pytest.raises(TypeError), None),
("", pytest.raises(ValueError), None),
],
)
def test_virt_disk_driver(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: Any
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_disk_driver property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_disk_driver = value
# Assert
assert profile.virt_disk_driver == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("", does_not_raise(), 0),
("<<inherit>>", does_not_raise(), 512),
(0, does_not_raise(), 0),
(0.0, pytest.raises(TypeError), 0),
],
)
def test_virt_ram(
cobbler_api: CobblerAPI, value: Any, expected_exception: Any, expected_result: Any
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_ram property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_ram = value
# Assert
assert profile.virt_ram == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("<<inherit>>", does_not_raise(), enums.VirtType.KVM),
("qemu", does_not_raise(), enums.VirtType.QEMU),
(enums.VirtType.QEMU, does_not_raise(), enums.VirtType.QEMU),
("", pytest.raises(ValueError), None),
(False, pytest.raises(TypeError), None),
],
)
def test_virt_type(
cobbler_api: CobblerAPI,
value: Any,
expected_exception: Any,
expected_result: Any,
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_type property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_type = value
# Assert
assert profile.virt_type == expected_result
@pytest.mark.parametrize(
"value,expected_exception,expected_result",
[
("<<inherit>>", does_not_raise(), "virbr0"),
("random-bridge", does_not_raise(), "random-bridge"),
("", does_not_raise(), "virbr0"),
(False, pytest.raises(TypeError), None),
],
)
def test_virt_bridge(
cobbler_api: CobblerAPI,
value: Any,
expected_exception: Any,
expected_result: Any,
):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_bridge property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
with expected_exception:
profile.virt_bridge = value
# Assert
# This is the default from the settings
assert profile.virt_bridge == expected_result
def test_virt_path(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the virt_path property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.virt_path = ""
# Assert
assert profile.virt_path == ""
def test_repos(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the repos property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.repos = ""
# Assert
assert profile.repos == []
def test_redhat_management_key(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can use the Getter and Setter of the redhat_management_key property correctly.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.redhat_management_key = ""
# Assert
assert profile.redhat_management_key == ""
@pytest.mark.parametrize(
"input_boot_loaders,expected_result,expected_exception",
[
("", [], does_not_raise()),
("grub", ["grub"], does_not_raise()),
("grub ipxe", ["grub", "ipxe"], does_not_raise()),
("<<inherit>>", ["grub", "pxe", "ipxe"], does_not_raise()),
([], [], does_not_raise()),
],
)
def test_boot_loaders(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
input_boot_loaders: Any,
expected_result: List[str],
expected_exception: Any,
):
"""
Assert that a Cobbler Profile can resolve the boot loaders it has available successfully.
"""
# Arrange
distro: Distro = create_distro()
profile = Profile(cobbler_api)
profile.distro = distro.name
# Act
with expected_exception:
profile.boot_loaders = input_boot_loaders
# Assert
assert profile.boot_loaders == expected_result
def test_menu(cobbler_api: CobblerAPI):
"""
Assert that a Cobbler Profile can be attached to a Cobbler Menu successfully.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.menu = ""
# Assert
assert profile.menu == ""
def test_display_name(cobbler_api: CobblerAPI):
"""
Assert that the display name of a Cobbler Profile can be set successfully.
"""
# Arrange
profile = Profile(cobbler_api)
# Act
profile.display_name = ""
# Assert
assert profile.display_name == ""
@pytest.mark.parametrize(
"data_keys, check_key, check_value, expect_match",
[
({"uid": "test-uid"}, "uid", "test-uid", True),
({"menu": "testmenu0"}, "menu", "testmenu0", True),
({"uid": "test", "name": "test-name"}, "uid", "test", True),
({"uid": "test"}, "arch", "x86_64", True),
({"uid": "test"}, "arch", "aarch64", False),
({"depth": "1"}, "name", "test", False),
({"uid": "test", "name": "test-name"}, "menu", "testmenu0", False),
],
)
def test_find_match_single_key(
cobbler_api: CobblerAPI,
create_distro: Callable[[], Distro],
data_keys: Dict[str, Any],
check_key: str,
check_value: Any,
expect_match: bool,
):
"""
Assert that a single given key and value match the object or not.
"""
# Arrange
test_distro_obj = create_distro()
test_distro_obj.arch = enums.Archs.X86_64
profile = Profile(cobbler_api)
profile.distro = test_distro_obj.name
# Act
result = profile.find_match_single_key(data_keys, check_key, check_value)
# Assert
assert expect_match == result
def test_distro_inherit(
mocker: "MockerFixture",
test_settings: Settings,
create_distro: Callable[[], Distro],
):
"""
Checking that inherited properties are correctly inherited from settings and
that the <<inherit>> value can be set for them.
"""
# Arrange
distro = create_distro()
api = distro.api
mocker.patch.object(api, "settings", return_value=test_settings)
distro.arch = enums.Archs.X86_64
profile = Profile(api)
profile.distro = distro.name
# Act
for key, key_value in profile.__dict__.items():
if key_value == enums.VALUE_INHERITED:
new_key = key[1:].lower()
new_value = getattr(profile, new_key)
settings_name = new_key
parent_obj = None
if hasattr(distro, settings_name):
parent_obj = distro
else:
if new_key == "owners":
settings_name = "default_ownership"
elif new_key == "proxy":
settings_name = "proxy_url_int"
if hasattr(test_settings, f"default_{settings_name}"):
settings_name = f"default_{settings_name}"
if hasattr(test_settings, settings_name):
parent_obj = test_settings
if parent_obj is not None:
setting = getattr(parent_obj, settings_name)
if isinstance(setting, str):
new_value = "test_inheritance"
elif isinstance(setting, bool):
new_value = True
elif isinstance(setting, int):
new_value = 1
elif isinstance(setting, float):
new_value = 1.0
elif isinstance(setting, dict):
new_value.update({"test_inheritance": "test_inheritance"})
elif isinstance(setting, list):
if new_key == "boot_loaders":
new_value = ["grub"]
else:
new_value = ["test_inheritance"]
setattr(parent_obj, settings_name, new_value)
prev_value = getattr(profile, new_key)
setattr(profile, new_key, enums.VALUE_INHERITED)
# Assert
assert prev_value == new_value
assert prev_value == getattr(profile, new_key)
| 21,606
|
Python
|
.py
| 648
| 27.310185
| 112
| 0.641817
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,982
|
sync_test.py
|
cobbler_cobbler/tests/performance/sync_test.py
|
"""
Test module to assert the performance of "cobbler sync".
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_sync(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if "cobbler sync" without arguments is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
api = cobbler_api
CobblerTree.remove_all_objs(api)
CobblerTree.create_all_objs(
api, create_distro, create_profile, create_image, create_system
)
del api
return (cobbler_api,), {}
def sync(api: CobblerAPI):
api.sync()
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic(sync, setup=setup_func, rounds=CobblerTree.test_rounds) # type: ignore
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 1,888
|
Python
|
.py
| 66
| 22.454545
| 103
| 0.642541
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,983
|
get_autoinstall_test.py
|
cobbler_cobbler/tests/performance/get_autoinstall_test.py
|
"""
Test module to assert the performance of retrieving an auto-installation file.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler import autoinstall_manager
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"what",
[
"profile",
"system",
],
)
@pytest.mark.parametrize(
"cache_enabled",
[
False,
True,
],
)
def test_get_autoinstall(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
what: str,
):
"""
Test that asserts if retrieving rendered autoinstallation templates is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_all_objs(
cobbler_api, create_distro, create_profile, create_image, create_system
)
return (cobbler_api, what), {}
def item_get_autoinstall(api: CobblerAPI, what: str):
autoinstall_mgr = autoinstall_manager.AutoInstallationManager(cobbler_api)
for test_item in api.get_items(what):
if what == "profile":
autoinstall_mgr.generate_autoinstall(profile=test_item.name)
elif what == "system":
autoinstall_mgr.generate_autoinstall(system=test_item.name)
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = False
# Act
result = benchmark.pedantic( # type: ignore
item_get_autoinstall, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,204
|
Python
|
.py
| 65
| 28.538462
| 114
| 0.697696
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,984
|
item_copy_test.py
|
cobbler_cobbler/tests/performance/item_copy_test.py
|
"""
Test module to assert the performance of copying items.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"what",
[
"repo",
"distro",
"menu",
"profile",
"image",
"system",
],
)
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_item_copy(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
what: str,
):
"""
Test that asserts if copying an item is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_all_objs(
cobbler_api, create_distro, create_profile, create_image, create_system
)
return (cobbler_api, what), {}
def item_copy(api: CobblerAPI, what: str):
for test_item in api.get_items(what):
api.copy_item(what, test_item, test_item.name + "_copy")
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
item_copy, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,157
|
Python
|
.py
| 79
| 21.088608
| 83
| 0.625363
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,985
|
deserialize_test.py
|
cobbler_cobbler/tests/performance/deserialize_test.py
|
"""
Test module to assert the performance of deserializing the object tree.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_deserialize(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that benchmarks the file based deserialization process of Cobbler.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
api = cobbler_api
CobblerTree.remove_all_objs(api)
CobblerTree.create_all_objs(
api, create_distro, create_profile, create_image, create_system
)
del api
return (), {}
def deserialize():
# pylint: disable=protected-access
CobblerAPI.__shared_state = {} # pyright: ignore [reportPrivateUsage]
CobblerAPI.__has_loaded = False # pyright: ignore [reportPrivateUsage]
api = CobblerAPI()
api.deserialize()
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
deserialize, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,122
|
Python
|
.py
| 72
| 23.138889
| 79
| 0.643768
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,986
|
make_pxe_menu_test.py
|
cobbler_cobbler/tests/performance/make_pxe_menu_test.py
|
"""
Test module to assert the performance of creating the PXE menu.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_make_pxe_menu(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if creating the PXE menu is running wihtout a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
api = cobbler_api
CobblerTree.remove_all_objs(api)
CobblerTree.create_all_objs(
api, create_distro, create_profile, create_image, create_system
)
del api
return (cobbler_api,), {}
def make_pxe_menu(api: CobblerAPI):
api.tftpgen.make_pxe_menu()
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
make_pxe_menu, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 1,942
|
Python
|
.py
| 68
| 22.382353
| 89
| 0.64232
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,987
|
item_rename_test.py
|
cobbler_cobbler/tests/performance/item_rename_test.py
|
"""
Test module to assert the performance of renaming items.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"what",
[
"repo",
"distro",
"menu",
"profile",
"image",
"system",
],
)
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_item_rename(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
what: str,
):
"""
Test that asserts if renaming an item is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_all_objs(
cobbler_api, create_distro, create_profile, create_image, create_system
)
return (cobbler_api, what), {}
def item_rename(api: CobblerAPI, what: str):
for test_item in api.get_items(what):
api.rename_item(what, test_item, test_item.name + "_renamed")
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
item_rename, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,170
|
Python
|
.py
| 79
| 21.253165
| 84
| 0.627706
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,988
|
item_remove_test.py
|
cobbler_cobbler/tests/performance/item_remove_test.py
|
"""
Test module to assert the performance of removing items.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"what",
[
"repo",
"distro",
"menu",
"profile",
"image",
"system",
],
)
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_item_remove(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
what: str,
):
"""
Test that asserts if removing one or more items is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_all_objs(
cobbler_api, create_distro, create_profile, create_image, create_system
)
return (cobbler_api, what), {}
def item_remove(api: CobblerAPI, what: str):
while len(api.get_items(what)) > 0:
api.remove_item(what, list(api.get_items(what))[0], recursive=True)
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
item_remove, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,184
|
Python
|
.py
| 79
| 21.43038
| 94
| 0.628285
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,989
|
item_edit_test.py
|
cobbler_cobbler/tests/performance/item_edit_test.py
|
"""
Test module to assert the performance of editing items.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"inherit_property",
[
False,
True,
],
)
@pytest.mark.parametrize(
"what",
[
"repo",
"distro",
"menu",
"profile",
"image",
"system",
],
)
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_item_edit(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
inherit_property: bool,
what: str,
):
"""
Test that asserts if editing items is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_all_objs(
cobbler_api, create_distro, create_profile, create_image, create_system
)
return (cobbler_api, what), {}
def item_edit(api: CobblerAPI, what: str):
for test_item in api.get_items(what):
if inherit_property:
test_item.owners = "test owners"
else:
test_item.comment = "test commect"
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
item_edit, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,359
|
Python
|
.py
| 90
| 19.788889
| 83
| 0.614533
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,990
|
start_test.py
|
cobbler_cobbler/tests/performance/start_test.py
|
"""
Test module to assert the performance of the startup of the daemon.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_start(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if the startup of Cobbler is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
api = cobbler_api
CobblerTree.remove_all_objs(api)
CobblerTree.create_all_objs(
api, create_distro, create_profile, create_image, create_system
)
del api
return (), {}
def start_cobbler():
# pylint: disable=protected-access,unused-variable
CobblerAPI.__shared_state = {} # type: ignore[reportPrivateUsage]
CobblerAPI.__has_loaded = False # type: ignore[reportPrivateUsage]
api = CobblerAPI() # type: ignore[reportUnusedVariable]
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
start_cobbler, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 2,151
|
Python
|
.py
| 71
| 24
| 90
| 0.647002
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,991
|
__init__.py
|
cobbler_cobbler/tests/performance/__init__.py
|
"""
Module that contains a helper class which supports the performance testsuite. This is not a pytest style fixture but
rather related pytest-benchmark. Thus, the different style in usage.
"""
from typing import Any, Callable
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.menu import Menu
from cobbler.items.profile import Profile
from cobbler.items.repo import Repo
from cobbler.items.system import System
class CobblerTree:
"""
Helper class that defines methods that can be used during benchmark testing.
"""
objs_count = 2
test_rounds = 1
tree_levels = 3
@staticmethod
def create_repos(api: CobblerAPI):
"""
Create a number of repos for benchmark testing.
"""
for i in range(CobblerTree.objs_count):
test_item = Repo(api)
test_item.name = f"test_repo_{i}"
api.add_repo(test_item)
@staticmethod
def create_distros(api: CobblerAPI, create_distro: Any):
"""
Create a number of distros for benchmark testing. This pairs the distros with the repositories and mgmt classes.
"""
for i in range(CobblerTree.objs_count):
test_item: Distro = create_distro(name=f"test_distro_{i}")
test_item.source_repos = [f"test_repo_{i}"]
@staticmethod
def create_menus(api: CobblerAPI):
"""
Create a number of menus for benchmark testing. Depending on the menu depth this method also adds children for
the menus.
"""
for l in range(CobblerTree.tree_levels):
for i in range(CobblerTree.objs_count):
test_item = Menu(api)
test_item.name = f"level_{l}_test_menu_{i}"
if l > 0:
test_item.parent = f"level_{l - 1}_test_menu_{i}"
else:
test_item.parent = ""
api.add_menu(test_item)
@staticmethod
def create_profiles(api: CobblerAPI, create_profile: Any):
"""
Create a number of profiles for benchmark testing. Depending on the menu depth this method also pairs the
profile with a menu.
"""
for l in range(CobblerTree.tree_levels):
for i in range(CobblerTree.objs_count):
if l > 0:
test_item: Profile = create_profile(
profile_name=f"level_{l - 1}_test_profile_{i}",
name=f"level_{l}_test_profile_{i}",
)
else:
test_item: Profile = create_profile(
distro_name=f"test_distro_{i}",
name=f"level_{l}_test_profile_{i}",
)
test_item.menu = f"level_{l}_test_menu_{i}"
test_item.autoinstall = "sample.ks"
@staticmethod
def create_images(api: CobblerAPI, create_image: Any):
"""
Create a number of images for benchmark testing.
"""
for i in range(CobblerTree.objs_count):
test_item: Image = create_image(name=f"test_image_{i}")
test_item.menu = f"level_{CobblerTree.tree_levels - 1}_test_menu_{i}"
test_item.autoinstall = "sample.ks"
@staticmethod
def create_systems(api: CobblerAPI, create_system: Any):
"""
Create a number of systems for benchmark testing. Depending on the strategy the system is paired with a profile
or image.
"""
for i in range(CobblerTree.objs_count):
if i % 2 == 0:
create_system(
name=f"test_system_{i}",
profile_name=f"level_{CobblerTree.tree_levels - 1}_test_profile_{i}",
)
else:
create_system(name=f"test_system_{i}", image_name=f"test_image_{i}")
@staticmethod
def create_all_objs(
api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
):
"""
Method that collectively creates all items at the same time.
"""
CobblerTree.create_repos(api)
CobblerTree.create_distros(api, create_distro)
CobblerTree.create_menus(api)
CobblerTree.create_profiles(api, create_profile)
CobblerTree.create_images(api, create_image)
CobblerTree.create_systems(api, create_system)
@staticmethod
def remove_repos(api: CobblerAPI):
"""
Method that removes all repositories.
"""
for test_item in api.repos():
api.remove_repo(test_item.name)
@staticmethod
def remove_distros(api: CobblerAPI):
"""
Method that removes all distributions.
"""
for test_item in api.distros():
api.remove_distro(test_item.name)
@staticmethod
def remove_menus(api: CobblerAPI):
"""
Method that removes all menus.
"""
while len(api.menus()) > 0:
api.remove_menu(list(api.menus())[0], recursive=True)
@staticmethod
def remove_profiles(api: CobblerAPI):
"""
Method that removes all profiles.
"""
while len(api.profiles()) > 0:
api.remove_profile(list(api.profiles())[0], recursive=True)
@staticmethod
def remove_images(api: CobblerAPI):
"""
Method that removes all images.
"""
for test_item in api.images():
api.remove_image(test_item.name)
@staticmethod
def remove_systems(api: CobblerAPI):
"""
Method that removes all systems.
"""
for test_item in api.systems():
api.remove_system(test_item.name)
@staticmethod
def remove_all_objs(api: CobblerAPI):
"""
Method that collectively removes all items at the same time.
"""
CobblerTree.remove_systems(api)
CobblerTree.remove_images(api)
CobblerTree.remove_profiles(api)
CobblerTree.remove_menus(api)
CobblerTree.remove_distros(api)
CobblerTree.remove_repos(api)
| 6,293
|
Python
|
.py
| 164
| 28.743902
| 120
| 0.598036
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,992
|
item_add_test.py
|
cobbler_cobbler/tests/performance/item_add_test.py
|
"""
Test module to assert the performance of adding different kinds of items.
"""
from typing import Any, Callable, Dict, Tuple
import pytest
from pytest_benchmark.fixture import ( # type: ignore[reportMissingTypeStubs]
BenchmarkFixture,
)
from cobbler.api import CobblerAPI
from cobbler.items.distro import Distro
from cobbler.items.image import Image
from cobbler.items.profile import Profile
from cobbler.items.system import System
from tests.performance import CobblerTree
@pytest.mark.parametrize(
"cache_enabled",
[
(False,),
(True,),
],
)
def test_repos_create(
benchmark: BenchmarkFixture, cobbler_api: CobblerAPI, cache_enabled: bool
):
"""
Test that asserts if creating a repository is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
return (cobbler_api,), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_repos, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled",
[
(False,),
(True,),
],
)
def test_distros_create(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
cache_enabled: bool,
):
"""
Test that asserts if creating a distro is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_repos(cobbler_api)
return (cobbler_api, create_distro), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_distros, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled",
[
(False,),
(True,),
],
)
def test_menus_create(
benchmark: BenchmarkFixture, cobbler_api: CobblerAPI, cache_enabled: bool
):
"""
Test that asserts if creating a menu is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
return (cobbler_api,), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_menus, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_profiles_create(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if creating a profile is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_repos(cobbler_api)
CobblerTree.create_distros(cobbler_api, create_distro)
CobblerTree.create_menus(cobbler_api)
return (cobbler_api, create_profile), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_profiles, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled",
[
(False,),
(True,),
],
)
def test_images_create(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_image: Callable[[str], Image],
cache_enabled: bool,
):
"""
Test that asserts if creating an image is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_menus(cobbler_api)
return (cobbler_api, create_image), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_images, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_systems_create(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if creating a system is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
CobblerTree.create_repos(cobbler_api)
CobblerTree.create_distros(cobbler_api, create_distro)
CobblerTree.create_menus(cobbler_api)
CobblerTree.create_images(cobbler_api, create_image)
CobblerTree.create_profiles(cobbler_api, create_profile)
return (cobbler_api, create_system), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_systems, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
@pytest.mark.parametrize(
"cache_enabled,enable_menu",
[
(
False,
False,
),
(
True,
False,
),
(
False,
True,
),
(
True,
True,
),
],
)
def test_all_items_create(
benchmark: BenchmarkFixture,
cobbler_api: CobblerAPI,
create_distro: Callable[[str], Distro],
create_profile: Callable[[str, str, str], Profile],
create_image: Callable[[str], Image],
create_system: Callable[[str, str, str], System],
cache_enabled: bool,
enable_menu: bool,
):
"""
Test that asserts if creating all items at once is running without a performance decrease.
"""
def setup_func() -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
CobblerTree.remove_all_objs(cobbler_api)
return (
cobbler_api,
create_distro,
create_profile,
create_image,
create_system,
), {}
# Arrange
cobbler_api.settings().cache_enabled = cache_enabled
cobbler_api.settings().enable_menu = enable_menu
# Act
result = benchmark.pedantic( # type: ignore
CobblerTree.create_all_objs, setup=setup_func, rounds=CobblerTree.test_rounds
)
# Cleanup
CobblerTree.remove_all_objs(cobbler_api)
# Assert
| 7,949
|
Python
|
.py
| 275
| 22.534545
| 94
| 0.632857
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,993
|
conftest.py
|
cobbler_cobbler/tests/cobbler_collections/conftest.py
|
"""
Fixtures that are common for testing the cobbler collections.
"""
import pytest
from cobbler.api import CobblerAPI
from cobbler.cobbler_collections.manager import CollectionManager
@pytest.fixture()
def collection_mgr(cobbler_api: CobblerAPI) -> CollectionManager:
"""
Fixture that provides access to the collection manager instance for testing.
"""
# pylint: disable=protected-access
return cobbler_api._collection_mgr # pyright: ignore [reportPrivateUsage]
| 488
|
Python
|
.py
| 13
| 34.692308
| 80
| 0.789809
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,994
|
distro_collection_test.py
|
cobbler_cobbler/tests/cobbler_collections/distro_collection_test.py
|
"""
Tests that validate the functionality of the module that is responsible for managing the list of distros.
"""
import os.path
from typing import Callable
import pytest
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.cobbler_collections import distros
from cobbler.cobbler_collections.manager import CollectionManager
from cobbler.items import distro
@pytest.fixture
def distro_collection(collection_mgr: CollectionManager):
"""
Fixture to provide a concrete implementation (Distros) of a generic collection.
"""
return distros.Distros(collection_mgr)
def test_obj_create(collection_mgr: CollectionManager):
# Arrange & Act
distro_collection = distros.Distros(collection_mgr)
# Assert
assert isinstance(distro_collection, distros.Distros)
def test_factory_produce(cobbler_api: CobblerAPI, distro_collection: distros.Distros):
# Arrange & Act
result_distro = distro_collection.factory_produce(cobbler_api, {})
# Assert
assert isinstance(result_distro, distro.Distro)
def test_get(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "test_get"
item1 = create_distro(name)
distro_collection.add(item1)
# Act
item = distro_collection.get(name)
fake_item = distro_collection.get("fake_name")
# Assert
assert isinstance(item, distro.Distro)
assert item.name == name
assert fake_item is None
def test_find(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "test_find"
item1 = create_distro(name)
distro_collection.add(item1)
# Act
result = distro_collection.find(name, True, True)
# Assert
assert isinstance(result, list)
assert len(result) == 1
assert result[0].name == name
def test_to_list(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "test_to_list"
item1 = create_distro(name)
distro_collection.add(item1)
# Act
result = distro_collection.to_list()
# Assert
assert len(result) == 1
assert result[0].get("name") == name
def test_from_list(
distro_collection: distros.Distros,
create_kernel_initrd: Callable[[str, str], str],
fk_initrd: str,
fk_kernel: str,
):
# Arrange
folder = create_kernel_initrd(fk_kernel, fk_initrd)
test_kernel = os.path.join(folder, fk_kernel)
item_list = [{"name": "test_from_list", "kernel": test_kernel}]
# Act
distro_collection.from_list(item_list)
# Assert
assert len(distro_collection.listing) == 1
assert len(distro_collection.indexes["uid"]) == 1
def test_copy(
cobbler_api: CobblerAPI,
distro_collection: distros.Distros,
create_kernel_initrd: Callable[[str, str], str],
fk_initrd: str,
fk_kernel: str,
):
# Arrange
folder = create_kernel_initrd(fk_kernel, fk_initrd)
name = "test_copy"
item1 = distro.Distro(cobbler_api)
item1.name = name
item1.initrd = os.path.join(folder, fk_initrd)
item1.kernel = os.path.join(folder, fk_kernel)
distro_collection.add(item1)
# Act
new_item_name = "test_copy_new"
distro_collection.copy(item1, new_item_name)
item2: distro.Distro = distro_collection.find(new_item_name, False) # type: ignore
# Assert
assert len(distro_collection.listing) == 2
assert name in distro_collection.listing
assert new_item_name in distro_collection.listing
assert len(distro_collection.indexes["uid"]) == 2
assert (distro_collection.indexes["uid"])[item1.uid] == name
assert (distro_collection.indexes["uid"])[item2.uid] == new_item_name
@pytest.mark.parametrize(
"input_new_name",
[
("to_be_renamed"),
("UpperCase"),
],
)
def test_rename(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
input_new_name: str,
):
# Arrange
item1 = create_distro("old_name")
distro_collection.add(item1)
# Act
distro_collection.rename(item1, input_new_name)
# Assert
assert input_new_name in distro_collection.listing
assert distro_collection.listing[input_new_name].name == input_new_name
assert (distro_collection.indexes["uid"])[item1.uid] == input_new_name
def test_collection_add(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "collection_add"
item1 = create_distro(name)
# Act
distro_collection.add(item1)
# Assert
assert name in distro_collection.listing
assert item1.uid in distro_collection.indexes["uid"]
def test_duplicate_add(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "duplicate_name"
item1 = create_distro(name)
distro_collection.add(item1)
item2 = create_distro(name)
# Act & Assert
with pytest.raises(CX):
distro_collection.add(item2, check_for_duplicate_names=True)
def test_remove(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "to_be_removed"
item1 = create_distro(name)
distro_collection.add(item1)
assert name in distro_collection.listing
assert len(distro_collection.indexes["uid"]) == 1
assert (distro_collection.indexes["uid"])[item1.uid] == item1.name
# Act
distro_collection.remove(name)
# Assert
assert name not in distro_collection.listing
assert len(distro_collection.indexes["uid"]) == 0
def test_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
# Assert
assert len(distro_collection.indexes) == 1
assert len(distro_collection.indexes["uid"]) == 0
def test_add_to_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "to_be_removed"
item1 = create_distro(name)
distro_collection.add(item1)
# Act
del (distro_collection.indexes["uid"])[item1.uid]
distro_collection.add_to_indexes(item1)
# Assert
assert item1.uid in distro_collection.indexes["uid"]
def test_remove_from_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "to_be_removed"
item1 = create_distro(name)
distro_collection.add(item1)
# Act
distro_collection.remove_from_indexes(item1)
# Assert
assert item1.uid not in distro_collection.indexes["uid"]
def test_find_by_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[str], distro.Distro],
distro_collection: distros.Distros,
):
# Arrange
name = "to_be_removed"
item1 = create_distro(name)
distro_collection.add(item1)
kargs1 = {"uid": item1.uid}
kargs2 = {"uid": "fake_uid"}
kargs3 = {"fake_index": item1.uid}
# Act
result1 = distro_collection.find_by_indexes(kargs1)
result2 = distro_collection.find_by_indexes(kargs2)
result3 = distro_collection.find_by_indexes(kargs3)
# Assert
assert isinstance(result1, list)
assert len(result1) == 1
assert result1[0] == item1
assert len(kargs1) == 0
assert result2 is None
assert len(kargs2) == 0
assert result3 is None
assert len(kargs3) == 1
| 7,754
|
Python
|
.py
| 239
| 27.857741
| 105
| 0.702978
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,995
|
__init__.py
|
cobbler_cobbler/tests/cobbler_collections/__init__.py
|
"""
Tests cannot be written with a generic Collection. Thus we always need a specific one. See the base collection as an
abstract class when being under test!
"""
| 163
|
Python
|
.py
| 4
| 39.75
| 116
| 0.786164
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,996
|
system_collection_test.py
|
cobbler_cobbler/tests/cobbler_collections/system_collection_test.py
|
"""
Tests that validate the functionality of the module that is responsible for managing the list of systems.
"""
from typing import Any, Callable, Dict
import pytest
from cobbler.api import CobblerAPI
from cobbler.cexceptions import CX
from cobbler.cobbler_collections import systems
from cobbler.cobbler_collections.manager import CollectionManager
from cobbler.items import distro, network_interface, profile, system
@pytest.fixture(name="system_collection")
def fixture_system_collection(collection_mgr: CollectionManager):
"""
Fixture to provide a concrete implementation (Systems) of a generic collection.
"""
return systems.Systems(collection_mgr)
def test_obj_create(collection_mgr: CollectionManager):
"""
Validate that a system collection can be instantiated.
"""
# Arrange & Act
test_system_collection = systems.Systems(collection_mgr)
# Assert
assert isinstance(test_system_collection, systems.Systems)
def test_factory_produce(cobbler_api: CobblerAPI, system_collection: systems.Systems):
"""
Validate that a system can be correctly produced by the factory method.
"""
# Arrange & Act
result_system = system_collection.factory_produce(cobbler_api, {})
# Assert
assert isinstance(result_system, system.System)
def test_get(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that a system can be successfully retrieved from the collection.
"""
# Arrange
name = "test_get"
create_distro()
create_profile(name)
create_system(name)
system_collection = cobbler_api.systems()
# Act
item = system_collection.get(name)
fake_item = system_collection.get("fake_name")
# Assert
assert item is not None
assert item.name == name
assert fake_item is None
def test_find(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that a system can be successfully found inside the collection.
"""
# Arrange
name = "test_find"
create_distro()
create_profile(name)
create_system(name)
system_collection = cobbler_api.systems()
# Act
result = system_collection.find(name, True, True)
# Assert
assert isinstance(result, list)
assert len(result) == 1
assert result[0].name == name
def test_to_list(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the collection can be converted to a list.
"""
# Arrange
name = "test_to_list"
create_distro()
create_profile(name)
create_system(name)
system_collection = cobbler_api.systems()
# Act
result = system_collection.to_list()
# Assert
assert len(result) == 1
assert result[0].get("name") == name
def test_from_list(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
):
"""
Validate that the collection can be converted from a list.
"""
# Arrange
name = "test_from_list"
create_distro()
create_profile(name)
system_collection = cobbler_api.systems()
item_list = [
{
"name": "test_from_list",
"profile": name,
"interfaces": {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
},
}
]
# Act
system_collection.from_list(item_list)
# Assert
assert len(system_collection.listing) == 1
for indx in system_collection.indexes.values():
assert len(indx) == 1
def test_copy(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that a system can be copied.
"""
# Arrange
name = "test_copy"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
# Act
test1 = { # type: ignore[reportUnusedVariable]
x for y in system_collection.listing.values() for x in y.interfaces.values()
}
new_item_name = "test_copy_successful"
system_collection.copy(system1, new_item_name)
system2 = system_collection.find(new_item_name, False)
# Assert
assert len(system_collection.listing) == 2
assert name in system_collection.listing
assert new_item_name in system_collection.listing
for key, value in system_collection.indexes.items():
if key == "uid":
assert len(value) == 2
assert value[getattr(system1, key)] == name
assert value[getattr(system2, key)] == new_item_name
else:
assert len(value) == 1
assert value[getattr(system1.interfaces["default"], key)] == name
@pytest.mark.parametrize(
"input_new_name",
[
("to_be_renamed"),
("UpperCase"),
],
)
def test_rename(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
input_new_name: str,
):
"""
Validate that a system can be renamed inside the collection.
"""
# Arrange
name = "test_rename"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
# Act
system_collection.rename(system1, input_new_name)
# Assert
assert input_new_name in system_collection.listing
assert system_collection.listing[input_new_name].name == input_new_name
for interface in system1.interfaces.values():
assert interface.system_name == input_new_name
for key, value in system_collection.indexes.items():
if key == "uid":
assert value[getattr(system1, key)] == input_new_name
else:
assert value[getattr(system1.interfaces["default"], key)] == input_new_name
def test_collection_add(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
):
"""
Validate that a system can be added to the collection.
"""
# Arrange
name = "test_collection_add"
create_distro()
profile1 = create_profile(name)
system1 = system.System(cobbler_api)
system1.name = name
system1.profile = profile1.name
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
# Act
system_collection.add(system1)
# Assert
assert name in system_collection.listing
assert system_collection.listing[name].name == name
for interface in system1.interfaces.values():
assert interface.system_name == name
for key, value in system_collection.indexes.items():
if key == "uid":
assert value[getattr(system1, key)] == name
else:
assert value[getattr(system1.interfaces["default"], key)] == name
def test_duplicate_add(
cobbler_api: CobblerAPI,
create_distro: Any,
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that a system with an identical name cannot be added to the collection.
"""
# Arrange
name = "test_duplicate_add"
distro1: distro.Distro = create_distro(name="duplicate_add")
create_profile(distro1.name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
system2 = system.System(cobbler_api)
system2.name = name
system2.profile = name
# Act & Assert
assert len(system_collection.indexes["uid"]) == 1
with pytest.raises(CX):
system_collection.add(system2, check_for_duplicate_names=True)
for key, _ in system_collection.indexes.items():
assert len(system_collection.indexes[key]) == 1
def test_remove(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that a system can be removed from the collection.
"""
# Arrange
name = "test_remove"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
assert name in system_collection.listing
# Pre-Assert to validate if the index is in its correct state
for key, _ in system_collection.indexes.items():
assert len(system_collection.indexes[key]) == 1
# Act
system_collection.remove(name)
# Assert
assert name not in system_collection.listing
for key, _ in system_collection.indexes.items():
assert len(system_collection.indexes[key]) == 0
def test_indexes(
cobbler_api: CobblerAPI,
create_system: Callable[[str], system.System],
system_collection: systems.Systems,
):
"""
Validate that the secondary indices on the system collection work as expected with an empty collection.
"""
# Arrange
# Assert
assert len(system_collection.indexes) == 5
assert len(system_collection.indexes["uid"]) == 0
assert len(system_collection.indexes["mac_address"]) == 0
assert len(system_collection.indexes["ip_address"]) == 0
assert len(system_collection.indexes["ipv6_address"]) == 0
assert len(system_collection.indexes["dns_name"]) == 0
assert len(system_collection.disabled_indexes) == 4
assert not system_collection.disabled_indexes["mac_address"]
assert not system_collection.disabled_indexes["ip_address"]
assert not system_collection.disabled_indexes["ipv6_address"]
assert not system_collection.disabled_indexes["dns_name"]
def test_add_to_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected while adding a system.
"""
# Arrange
name = "test_add_to_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
for key, value in system_collection.indexes.items():
if key == "uid":
del value[getattr(system1, key)]
else:
del value[getattr(system1.interfaces["default"], key)]
# Act
system_collection.add_to_indexes(system1)
# Assert
for key, value in system_collection.indexes.items():
if key == "uid":
assert {getattr(system1, key): system1.name} == value
else:
assert {getattr(system1.interfaces["default"], key): system1.name} == value
def test_update_interfaces_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected while updating a systems network
interface.
"""
# Arrange
name = "test_update_interfaces_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"test1": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "test1.example.org",
"mac_address": "52:54:00:7d:81:f4",
},
"test2": {
"ip_address": "192.168.1.2",
"ipv6_address": "::2",
"dns_name": "test2.example.org",
"mac_address": "52:54:00:7d:81:f5",
},
}
system_collection = cobbler_api.systems()
interface1 = network_interface.NetworkInterface(cobbler_api, system1.name)
interface1.from_dict(
{
"ip_address": "192.168.1.3",
"ipv6_address": "::3",
"dns_name": "",
"mac_address": "52:54:00:7d:81:f6",
}
)
interface2 = network_interface.NetworkInterface(cobbler_api, system1.name)
interface2.from_dict(
{
"ip_address": "192.168.1.4",
"ipv6_address": "",
"dns_name": "test4.example.org",
"mac_address": "52:54:00:7d:81:f7",
}
)
new_interfaces = {
"test1": interface1,
"test2": interface2,
"test3": system1.interfaces["test2"],
}
# Act
system_collection.update_interfaces_indexes(system1, new_interfaces)
# Assert
assert set(system_collection.indexes["ip_address"].keys()) == {
"192.168.1.2",
"192.168.1.3",
"192.168.1.4",
}
assert set(system_collection.indexes["ipv6_address"].keys()) == {"::2", "::3"}
assert set(system_collection.indexes["dns_name"].keys()) == {
"test2.example.org",
"test4.example.org",
}
assert set(system_collection.indexes["mac_address"].keys()) == {
"52:54:00:7d:81:f5",
"52:54:00:7d:81:f6",
"52:54:00:7d:81:f7",
}
# Cleanup
for indx_key, _ in system_collection.indexes.items():
if indx_key == "uid":
continue
system_collection.indexes[indx_key] = {}
def test_update_interface_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected when updating a network interface.
"""
# Arrange
name = "test_update_interface_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"test1": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "test1.example.org",
"mac_address": "52:54:00:7d:81:f4",
},
"test2": {
"ip_address": "192.168.1.2",
"ipv6_address": "::2",
"dns_name": "test2.example.org",
"mac_address": "52:54:00:7d:81:f5",
},
}
system_collection = cobbler_api.systems()
interface1 = network_interface.NetworkInterface(cobbler_api, system1.name)
interface1.from_dict(
{
"ip_address": "192.168.1.3",
"ipv6_address": "::3",
"dns_name": "",
"mac_address": "52:54:00:7d:81:f6",
}
)
# Act
system_collection.update_interface_indexes(system1, "test2", interface1)
# Assert
assert set(system_collection.indexes["ip_address"].keys()) == {
"192.168.1.1",
"192.168.1.3",
}
assert set(system_collection.indexes["ipv6_address"].keys()) == {"::1", "::3"}
assert set(system_collection.indexes["dns_name"].keys()) == {"test1.example.org"}
assert set(system_collection.indexes["mac_address"].keys()) == {
"52:54:00:7d:81:f4",
"52:54:00:7d:81:f6",
}
# Cleanup
for indx_key, _ in system_collection.indexes.items():
if indx_key == "uid":
continue
system_collection.indexes[indx_key] = {}
def test_update_system_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected when updating a network interface.
"""
# Arrange
name = "test_update_system_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"test1": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "test1.example.org",
"mac_address": "52:54:00:7d:81:f4",
},
}
system_collection = cobbler_api.systems()
interface1 = network_interface.NetworkInterface(cobbler_api, system1.name)
interface1.from_dict(
{
"ip_address": "192.168.1.3",
"ipv6_address": "::3",
"dns_name": "",
"mac_address": "52:54:00:7d:81:f6",
}
)
# Act
original_uid = system1.uid
system1.uid = "test_uid"
system1.interfaces["test1"].ip_address = "192.168.1.2"
system1.interfaces["test1"].ipv6_address = "::2"
system1.interfaces["test1"].dns_name = "test2.example.org"
system1.interfaces["test1"].mac_address = "52:54:00:7d:81:f5"
interface1.ip_address = "192.168.1.4"
interface1.ipv6_address = "::4"
interface1.dns_name = "test4.example.org"
interface1.mac_address = "52:54:00:7d:81:f7"
# Assert
assert original_uid not in system_collection.indexes["uid"]
assert (system_collection.indexes["uid"])["test_uid"] == system1.name
assert "192.168.1.1" not in system_collection.indexes["ip_address"]
assert (system_collection.indexes["ip_address"])["192.168.1.2"] == system1.name
assert "::1" not in system_collection.indexes["ipv6_address"]
assert (system_collection.indexes["ipv6_address"])["::2"] == system1.name
assert "test1.example.org" not in system_collection.indexes["dns_name"]
assert (system_collection.indexes["dns_name"])["test2.example.org"] == system1.name
assert "52:54:00:7d:81:f4" not in system_collection.indexes["mac_address"]
assert (system_collection.indexes["mac_address"])[
"52:54:00:7d:81:f5"
] == system1.name
assert interface1.ip_address not in system_collection.indexes["ip_address"]
assert interface1.ipv6_address not in system_collection.indexes["ipv6_address"]
assert interface1.dns_name not in system_collection.indexes["dns_name"]
assert interface1.mac_address not in system_collection.indexes["mac_address"]
def test_remove_from_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected when removing a system.
"""
# Arrange
name = "test_remove_from_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
original_uid = system1.uid
# Act
system_collection.remove_from_indexes(system1)
# Assert
assert system1.uid not in system_collection.indexes["uid"]
assert (
system1.interfaces["default"].ip_address
not in system_collection.indexes["ip_address"]
)
assert (
system1.interfaces["default"].ipv6_address
not in system_collection.indexes["ipv6_address"]
)
assert (
system1.interfaces["default"].dns_name
not in system_collection.indexes["dns_name"]
)
assert (
system1.interfaces["default"].mac_address
not in system_collection.indexes["mac_address"]
)
# Cleanup
system1.uid = original_uid
def test_find_by_indexes(
cobbler_api: CobblerAPI,
create_distro: Callable[[], distro.Distro],
create_profile: Callable[[str], profile.Profile],
create_system: Callable[[str], system.System],
):
"""
Validate that the secondary indices on the system collection work as expected for finding items in a collection.
"""
# Arrange
name = "test_find_by_indexes"
create_distro()
create_profile(name)
system1 = create_system(name)
system1.interfaces = {
"default": {
"ip_address": "192.168.1.1",
"ipv6_address": "::1",
"dns_name": "example.org",
"mac_address": "52:54:00:7d:81:f4",
}
}
system_collection = cobbler_api.systems()
kargs = {
"uid": [
{"uid": system1.uid},
{"uid": "fake_uid"},
{"fake_index": system1.uid},
],
"ip_address": [
{"ip_address": system1.interfaces["default"].ip_address},
{"ip_address": "fake_ip_addres"},
{"fake_index": system1.interfaces["default"].ip_address},
],
"ipv6_address": [
{"ipv6_address": system1.interfaces["default"].ipv6_address},
{"ipv6_address": "fake_ipv6_addres"},
{"fake_index": system1.interfaces["default"].ipv6_address},
],
"dns_name": [
{"dns_name": system1.interfaces["default"].dns_name},
{"dns_name": "fake_dns_name"},
{"fake_index": system1.interfaces["default"].dns_name},
],
"mac_address": [
{"mac_address": system1.interfaces["default"].mac_address},
{"mac_address": "fake_mac_address"},
{"fake_index": system1.interfaces["default"].mac_address},
],
}
results: Dict[str, Any] = {}
# Act
for indx, args in kargs.items():
results[indx] = []
for arg in args:
results[indx].append(system_collection.find_by_indexes(arg))
# Assert
for indx, result in results.items():
assert isinstance(result[0], list)
assert len(result[0]) == 1
assert (result[0])[0] == system1
assert len((kargs[indx])[0]) == 0
assert result[1] is None
assert len((kargs[indx])[1]) == 0
assert result[2] is None
assert len((kargs[indx])[2]) == 1
| 23,517
|
Python
|
.py
| 675
| 28.037037
| 116
| 0.623611
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,997
|
mtab_test.py
|
cobbler_cobbler/tests/utils/mtab_test.py
|
import os
from cobbler.utils import mtab
def test_get_mtab():
# Arrange
# Act
result = mtab.get_mtab()
# Assert
assert isinstance(result, list)
def test_get_file_device_path():
# Arrange
test_symlink = "/tmp/test_symlink"
os.symlink("/foobar/test", test_symlink)
# Act
result = mtab.get_file_device_path(test_symlink)
# Cleanup
os.remove(test_symlink)
# Assert
assert len(result) == 2
assert isinstance(result[0], str)
assert result[1] == "/foobar/test"
def test_is_remote_file():
# Arrange
# Act
result = mtab.is_remote_file("/etc/os-release")
# Assert
assert not result
| 670
|
Python
|
.py
| 26
| 21
| 52
| 0.65873
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,998
|
process_management_test.py
|
cobbler_cobbler/tests/utils/process_management_test.py
|
"""
Tests that validate the functionality of the module that is responsible for process management in Cobbler.
"""
from typing import TYPE_CHECKING
from cobbler.utils import process_management
if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_is_systemd():
# Arrange
# Act
result = process_management.is_systemd()
# Assert
assert result
def test_service_restart_no_manager(mocker: "MockerFixture"):
# Arrange
mocker.patch(
"cobbler.utils.process_management.is_supervisord",
autospec=True,
return_value=False,
)
mocker.patch(
"cobbler.utils.process_management.is_systemd", autospec=True, return_value=False
)
mocker.patch(
"cobbler.utils.process_management.is_service", autospec=True, return_value=False
)
# Act
result = process_management.service_restart("testservice")
# Assert
assert result == 1
def test_service_restart_supervisord(mocker: "MockerFixture"):
mocker.patch(
"cobbler.utils.process_management.is_supervisord",
autospec=True,
return_value=True,
)
# TODO Mock supervisor API and return value
# Act
result = process_management.service_restart("dhcpd")
# Assert
assert result == 0
def test_service_restart_systemctl(mocker: "MockerFixture"):
mocker.patch(
"cobbler.utils.process_management.is_supervisord",
autospec=True,
return_value=False,
)
mocker.patch(
"cobbler.utils.process_management.is_systemd", autospec=True, return_value=True
)
mocker.patch(
"cobbler.utils.process_management.is_service", autospec=True, return_value=False
)
subprocess_mock = mocker.patch(
"cobbler.utils.subprocess_call", autospec=True, return_value=0
)
# Act
result = process_management.service_restart("testservice")
# Assert
assert result == 0
subprocess_mock.assert_called_with(
["systemctl", "restart", "testservice"], shell=False
)
def test_service_restart_service(mocker: "MockerFixture"):
# Arrange
mocker.patch(
"cobbler.utils.process_management.is_supervisord",
autospec=True,
return_value=False,
)
mocker.patch(
"cobbler.utils.process_management.is_systemd", autospec=True, return_value=False
)
mocker.patch(
"cobbler.utils.process_management.is_service", autospec=True, return_value=True
)
subprocess_mock = mocker.patch(
"cobbler.utils.subprocess_call", autospec=True, return_value=0
)
# Act
result = process_management.service_restart("testservice")
# Assert
assert result == 0
subprocess_mock.assert_called_with(
["service", "testservice", "restart"], shell=False
)
| 2,799
|
Python
|
.py
| 86
| 26.767442
| 106
| 0.692937
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|
11,999
|
input_converters_test.py
|
cobbler_cobbler/tests/utils/input_converters_test.py
|
"""
Tests that validate the functionality of the module that is responsible for input conversion.
"""
from typing import Any
import pytest
from cobbler.utils import input_converters
from tests.conftest import does_not_raise
@pytest.mark.parametrize(
"test_input,expected_result,expected_exception",
[
("<<inherit>>", "<<inherit>>", does_not_raise()),
("delete", [], does_not_raise()),
(["test"], ["test"], does_not_raise()),
("my_test", ["my_test"], does_not_raise()),
("my_test my_test", ["my_test", "my_test"], does_not_raise()),
(5, None, pytest.raises(TypeError)),
],
)
def test_input_string_or_list(
test_input: Any, expected_result: Any, expected_exception: Any
):
# Arrange & Act
with expected_exception:
result = input_converters.input_string_or_list(test_input)
# Assert
assert expected_result == result
@pytest.mark.parametrize(
"testinput,expected_result,possible_exception",
[
("<<inherit>>", "<<inherit>>", does_not_raise()),
([""], None, pytest.raises(TypeError)),
("a b=10 c=abc", {"a": None, "b": "10", "c": "abc"}, does_not_raise()),
({"ab": 0}, {"ab": 0}, does_not_raise()),
(0, None, pytest.raises(TypeError)),
],
)
def test_input_string_or_dict(
testinput: Any, expected_result: Any, possible_exception: Any
):
# Arrange
# Act
with possible_exception:
result = input_converters.input_string_or_dict(testinput)
# Assert
assert expected_result == result
@pytest.mark.parametrize(
"testinput,expected_exception,expected_result",
[
(True, does_not_raise(), True),
(1, does_not_raise(), True),
("oN", does_not_raise(), True),
("yEs", does_not_raise(), True),
("Y", does_not_raise(), True),
("Test", does_not_raise(), False),
(-5, does_not_raise(), False),
(0.5, pytest.raises(TypeError), False),
],
)
def test_input_boolean(testinput: Any, expected_exception: Any, expected_result: bool):
# Arrange
# Act
with expected_exception:
result = input_converters.input_boolean(testinput)
# Assert
assert expected_result == result
@pytest.mark.parametrize(
"testinput,expected_exception,expected_result",
[
(None, pytest.raises(TypeError), 1),
(True, does_not_raise(), 1),
(1, does_not_raise(), 1),
("1", does_not_raise(), 1),
("text", pytest.raises(TypeError), 1),
("5.0", pytest.raises(TypeError), 0),
([], pytest.raises(TypeError), 0),
({}, pytest.raises(TypeError), 0),
(-5, does_not_raise(), -5),
(0.5, does_not_raise(), 0),
],
)
def test_input_int(testinput: Any, expected_exception: Any, expected_result: int):
# Arrange --> Not needed
# Act
with expected_exception:
result = input_converters.input_int(testinput)
# Assert
assert expected_result == result
| 3,017
|
Python
|
.py
| 87
| 28.54023
| 93
| 0.607695
|
cobbler/cobbler
| 2,597
| 653
| 318
|
GPL-2.0
|
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
|