示例#1
0
class TestSettings:
    @pytest.mark.parametrize("test_name,test_value,expected_exception,expected_result", [
        ("server", "127.0.0.1", does_not_raise(), "127.0.0.1"),
        ("manage_forward_zones", True, pytest.raises(AttributeError), []),
        ("does_not_exist", None, pytest.raises(KeyError), None)
    ])
    def test_set(self, test_name, test_value, expected_exception, expected_result):
        # Arrange
        test_settings = Settings()

        # Act
        with expected_exception:
            test_settings.set(test_name, test_value)

            # Assert
            assert test_settings.__dict__[test_name] == expected_result

    def test_to_string(self):
        # Arrange
        test_settings = Settings()

        # Act
        result = test_settings.to_string()

        # Assert
        result_list = result.split("\n")
        assert len(result_list) == 3
        assert result_list[1] == "kernel options  : {}"

    def test_to_dict(self):
        # Arrange
        test_settings = Settings()

        # Act
        result = test_settings.to_dict()

        # Assert
        assert result == test_settings.__dict__

    @pytest.mark.parametrize("parameter,expected_exception,expected_result", [
        ({}, does_not_raise(), "127.0.0.1"),
        (None, does_not_raise(), "127.0.0.1")
    ])
    def test_from_dict(self, parameter, expected_exception, expected_result):
        # Arrange
        test_settings = Settings()

        # Act
        with expected_exception:
            test_settings.from_dict(parameter)

        # Assert
        assert test_settings.server == expected_result
示例#2
0
class TestSettings:
    def test_to_string(self):
        # Arrange
        test_settings = Settings()

        # Act
        result = test_settings.to_string()

        # Assert
        result_list = result.split("\n")
        assert len(result_list) == 3
        assert result_list[1] == "kernel options  : {}"

    def test_to_dict(self):
        # Arrange
        test_settings = Settings()

        # Act
        result = test_settings.to_dict()

        # Assert
        assert result == test_settings.__dict__

    @pytest.mark.parametrize("parameter,expected_exception,expected_result",
                             [({}, does_not_raise(), "127.0.0.1"),
                              (None, does_not_raise(), "127.0.0.1")])
    def test_from_dict(self, parameter, expected_exception, expected_result):
        # Arrange
        test_settings = Settings()

        # Act
        with expected_exception:
            test_settings.from_dict(parameter)

        # Assert
        assert test_settings.server == expected_result
示例#3
0

def test_boot_loaders():
    # Arrange
    test_api = CobblerAPI()
    system = System(test_api)

    # Act
    system.boot_loaders = []

    # Assert
    assert system.boot_loaders == []


@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_enable_ipxe(value, expected):
    # Arrange
    test_api = CobblerAPI()
    distro = System(test_api)

    # Act
示例#4
0
from cobbler.api import CobblerAPI
from tests.conftest import does_not_raise

# TODO: Extend the fillup and add more testcases


@pytest.fixture
def find_fillup():
    test_api = CobblerAPI()

    return test_api


@pytest.mark.parametrize(
    "what,criteria,name,return_list,no_errors,expected_exception,expected_result",
    [("", None, "test", False, False, does_not_raise(), None),
     ("", None, "", False, False, pytest.raises(ValueError), None),
     ("distro", {}, "test", False, False, does_not_raise(), None),
     ("distro", {}, "", False, False, pytest.raises(ValueError), None)])
def test_find_items(find_fillup, what, criteria, name, return_list, no_errors,
                    expected_exception, expected_result):
    # Arrange
    test_api = find_fillup

    # Act
    with expected_exception:
        result = test_api.find_items(what, criteria, name, return_list,
                                     no_errors)

        # Assert
        if expected_result is None:
示例#5
0
class TestIndexFileStudentDataAccess:
    @pytest.mark.parametrize(
        'students, expected_index',
        ((
            [
                (Student(record_id=PrimaryKey(1),
                         first_name='first',
                         last_name='last',
                         birthday_date='2020-03-03'), 11),
                (Student(record_id=PrimaryKey(3),
                         first_name='das',
                         last_name='das',
                         birthday_date='2020-03-03'), 22),
                (Student(record_id=PrimaryKey(8),
                         first_name='cccc',
                         last_name='aaa',
                         birthday_date='2020-03-03'), 33),
            ],
            [
                None, 11, None, 22, None, None, None, None, 33, None, None,
                None, None, None
            ],
        ), ),
    )
    def test_create_index(self, students, expected_index):
        file_client = MagicMock()
        file_client.iter_read.return_value = students

        dao = IndexFileStudentDataAccess(file_client)
        assert dao._index_array == expected_index

    @pytest.mark.parametrize(
        'current_index, record_id, expected_index, expected_exception',
        (
            ([], PrimaryKey(3), [
                None, None, None, None, None, None, None, None
            ], does_not_raise()),
            ([None, 123], PrimaryKey(1), [None, 123
                                          ], pytest.raises(DuplicateRecordId)),
        ),
    )
    def test_validate_record_id(self, current_index, record_id, expected_index,
                                expected_exception):
        file_client = MagicMock()
        file_client.iter_read.return_value = ()

        dao = IndexFileStudentDataAccess(file_client)
        dao._index_array = current_index

        with expected_exception:
            dao._validate_record_id(record_id)
            assert dao._index_array == expected_index

    @pytest.mark.parametrize(
        'key, current_index, expected_result, expected_exception',
        ((PrimaryKey(2), [None, None, 12], 12, does_not_raise()),
         (PrimaryKey(1), [None, None, 12
                          ], None, pytest.raises(RecordNotFound)),
         (PrimaryKey(10), [None, None, 12
                           ], None, pytest.raises(RecordNotFound))),
    )
    def test_get_position_by_key(self, key, current_index, expected_result,
                                 expected_exception):
        file_client = MagicMock()
        file_client.iter_read.return_value = ()

        dao = IndexFileStudentDataAccess(file_client)
        dao._index_array = current_index

        with expected_exception:
            result = dao._get_position_by_key(key)
            assert result == expected_result

    @pytest.mark.parametrize(
        'record_id, current_index, position, expected_index, expected_exception',
        (
            (PrimaryKey(2), [], 123, [None, None, 123, None, None, None
                                      ], does_not_raise()),
            (PrimaryKey(1), [None, 222], 123, [None, 222],
             pytest.raises(DuplicateRecordId)),
        ),
    )
    def test_add_student(self, record_id, current_index, position,
                         expected_index, expected_exception):
        file_client = MagicMock()
        file_client.iter_read.return_value = ()
        file_client.write.return_value = position

        dao = IndexFileStudentDataAccess(file_client)
        dao._index_array = current_index

        student = Student(record_id=record_id,
                          first_name='123',
                          last_name='123',
                          birthday_date='123')

        with expected_exception:
            dao.add_student(student)

        assert dao._index_array == expected_index
)
def test_home_data_homes_by_id(home_data, home_id, expected):
    assert home_data.homes[home_id]["name"] == expected


def test_home_data_get_selected_schedule(home_data):
    assert (home_data._get_selected_schedule("91763b24c43d3e344f424e8b")
            ["name"] == "Default")
    assert home_data._get_selected_schedule("Unknown") == {}


@pytest.mark.parametrize(
    "t_home_id, t_sched_id, expected",
    [
        ("91763b24c43d3e344f424e8b", "591b54a2764ff4d50d8b5795",
         does_not_raise()),
        (
            "91763b24c43d3e344f424e8b",
            "123456789abcdefg12345678",
            pytest.raises(pyatmo.NoSchedule),
        ),
    ],
)
def test_home_data_switch_home_schedule(
    home_data,
    requests_mock,
    t_home_id,
    t_sched_id,
    expected,
):
    with open("fixtures/status_ok.json") as json_file:
示例#7
0
import pytest
from unittest.mock import Mock, MagicMock, create_autospec, PropertyMock

import cobbler.actions.sync
import cobbler.modules.managers.bind
import cobbler.modules.managers.isc
from cobbler.api import CobblerAPI
from tests.conftest import does_not_raise


@pytest.mark.parametrize("input_verbose,input_what,expected_exception",
                         [(None, None, does_not_raise()),
                          (True, [], does_not_raise()),
                          (False, [], does_not_raise()),
                          (True, ["dhcp"], does_not_raise()),
                          (True, ["dns"], does_not_raise()),
                          (True, ["dns", "dhcp"], does_not_raise())])
def test_sync(input_verbose, input_what, expected_exception, mocker):
    # Arrange
    stub = create_autospec(spec=cobbler.actions.sync.CobblerSync)
    stub_dhcp = mocker.stub()
    stub_dns = mocker.stub()
    mocker.patch.object(CobblerAPI, "get_sync", return_value=stub)
    mocker.patch.object(CobblerAPI, "sync_dhcp", new=stub_dhcp)
    mocker.patch.object(CobblerAPI, "sync_dns", new=stub_dns)
    test_api = CobblerAPI()

    # Act
    with expected_exception:
        test_api.sync(input_verbose, input_what)
示例#8
0

@pytest.mark.parametrize("test_input,expected_result",
                         [("<<inherit>>", "<<inherit>>"), ("delete", [])])
def test_input_string_or_list(test_input, expected_result):
    # Arrange

    # Act
    result = utils.input_string_or_list(test_input)

    # Assert
    assert expected_result == result


@pytest.mark.parametrize("testinput,expected_result,possible_exception",
                         [("<<inherit>>", (True, {}), does_not_raise()),
                          ([""], None, pytest.raises(CX)),
                          ("a b=10 c=abc", (True, {
                              "a": None,
                              "b": '10',
                              "c": "abc"
                          }), does_not_raise()),
                          ({
                              "ab": 0
                          }, (True, {
                              "ab": 0
                          }), does_not_raise()), (0, None, pytest.raises(CX))])
def test_input_string_or_dict(testinput, expected_result, possible_exception):
    # Arrange

    # Act
示例#9
0
     # ("sync_post_wingen")
     ])
def test_get_module_by_name(module_name):
    # Arrange -> Done in fixtures

    # Act
    returned_module = module_loader.get_module_by_name(module_name)

    # Assert
    assert isinstance(returned_module.register(), str)


@pytest.mark.usefixtures("reset_modules", "load_modules")
@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(module_section, fallback_name, expected_result,
                         expected_exception):
    # Arrange -> Done in fixtures

    # Act
    with expected_exception:
        result_name = module_loader.get_module_name(module_section, "module",
                                                    fallback_name)
示例#10
0

def test_make_clone():
    # Arrange
    test_api = CobblerAPI()
    file = File(test_api)

    # Act
    clone = file.make_clone()

    # Assert
    assert clone != file


# Properties Tests


@pytest.mark.parametrize("value,expected_exception",
                         [(False, does_not_raise())])
def test_is_dir(value, expected_exception):
    # Arrange
    test_api = CobblerAPI()
    file = File(test_api)

    # Act
    with expected_exception:
        file.is_dir = value

        # Assert
        assert file.is_dir is value
示例#11
0

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, expectation):
    # 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",
示例#12
0
import pytest

from cobbler import enums, utils, validate
from cobbler.api import CobblerAPI
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, test_raise):
    # Arrange

    # Act
    with test_raise:
        result = validate.validate_arch(test_architecture)

        # 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")


def test_validate_os_version():
    # Arrange
    utils.load_signatures("/var/lib/cobbler/distro_signatures.json")
示例#13
0
文件: test_utils.py 项目: nodeg/koan
    (True),
    (False)
])
def test_is_uefi_system(os_path_return, mocker):
    # Arrange
    mocker.patch("os.path.exists", return_value=os_path_return)

    # Act
    result = utils.is_uefi_system()

    # Assert
    assert result is os_path_return


@pytest.mark.parametrize("shutil_which_return,expected_exception", [
    ("/usr/bin/grub2-mkrelpath", does_not_raise()),
    (None, pytest.raises(RuntimeError))
])
def test_get_grub2_mkrelpath_executable(shutil_which_return, expected_exception, mocker):
    # Arrange
    mocker.patch("shutil.which", return_value=shutil_which_return)

    # Act
    with expected_exception:
        result = utils.get_grub2_mkrelpath_executable()

        # Assert
        assert result == shutil_which_return


@pytest.mark.parametrize("mocked_process_result,mocked_os_path_exists,expected_exception", [
示例#14
0
from libcobblersignatures.models.osversion import Osversion
from tests.conftest import does_not_raise


def test_new_osversion():
    Osversion()


def test_osversion_equality():
    assert Osversion() == Osversion()


@pytest.mark.parametrize("param,result,raises",
                         [({"RedHat/RPMS", "CentOS/RPMS"},
                           {"RedHat/RPMS", "CentOS/RPMS"}, does_not_raise()),
                          ("", set(), pytest.raises(TypeError))])
def test_signatures(param, result, raises):
    # Arrange
    version = Osversion()

    # Act
    with raises:
        version.signatures = param

        # Assert
        assert version.signatures == result


def test_signatures_del():
    # Arrange
示例#15
0
    titem = Distro(test_api)

    # Act
    result = titem.to_dict()

    # Assert
    assert isinstance(result, dict)
    assert "autoinstall_meta" in result
    assert "ks_meta" in result
    # TODO check more fields


# 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(value, expected):
    # Arrange
    test_api = CobblerAPI()
    distro = Distro(test_api)

    # Act
    with expected:
        distro.tree_build_time = value
示例#16
0
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, expected_output,
                                expected_exception):
    # Arrange & Act
    with expected_exception:
        result = grub.parse_grub_remote_file(input_file_location)

        # Assert
        assert result == expected_output
示例#17
0
@pytest.mark.parametrize("test_input,expected_result", [
    ("<<inherit>>", "<<inherit>>"),
    ("delete", [])
])
def test_input_string_or_list(test_input, expected_result):
    # Arrange

    # Act
    result = utils.input_string_or_list(test_input)

    # Assert
    assert expected_result == result


@pytest.mark.parametrize("testinput,expected_result,possible_exception", [
    ("<<inherit>>", (True, {}), does_not_raise()),
    ([""], None, pytest.raises(CX)),
    ("a b=10 c=abc", (True, {"a": None, "b": '10', "c": "abc"}), does_not_raise()),
    ({"ab": 0}, (True, {"ab": 0}), does_not_raise()),
    (0, None, pytest.raises(CX))
])
def test_input_string_or_dict(testinput, expected_result, possible_exception):
    # Arrange

    # Act
    with possible_exception:
        result = utils.input_string_or_dict(testinput)

        # Assert
        assert expected_result == result
示例#18
0
    assert system.autoinstall == ""


def test_boot_loaders():
    # Arrange
    test_api = CobblerAPI()
    system = System(test_api)

    # Act
    system.boot_loaders = []

    # Assert
    assert system.boot_loaders == []


@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_enable_ipxe(value, expected):
    # Arrange
    test_api = CobblerAPI()
    distro = System(test_api)

    # Act
    with expected:
示例#19
0
    titem = Distro(test_api)

    # Act
    result = titem.to_dict()

    # Assert
    assert isinstance(result, dict)
    assert "autoinstall_meta" in result
    assert "ks_meta" in result
    # TODO check more fields


# 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(value, expected):
    # Arrange
    test_api = CobblerAPI()
    distro = Distro(test_api)

    # Act
    with expected:
        distro.tree_build_time = value
示例#20
0
class TestBuildiso:
    """Since BuildIso needs the collection manager and thus the api, as well as other information this test will
    require greater setup, although only this class shall be tested. Mocks are hard to program and we will try to
    avoid them.
    """
    @pytest.mark.parametrize(
        "input_arch,result_binary_name,expected_exception",
        [
            (enums.Archs.X86_64, "grubx86.efi", does_not_raise()),
            (enums.Archs.PPC, "grub.ppc64le", does_not_raise()),
            (enums.Archs.PPC64, "grub.ppc64le", does_not_raise()),
            (enums.Archs.PPC64EL, "grub.ppc64le", does_not_raise()),
            (enums.Archs.PPC64LE, "grub.ppc64le", does_not_raise()),
            (enums.Archs.AARCH64, "grubaa64.efi", does_not_raise()),
            (enums.Archs.ARM, "bootarm.efi", does_not_raise()),
            (enums.Archs.I386, "bootia32.efi", does_not_raise()),
            (enums.Archs.IA64, "bootia64.efi", does_not_raise()),
        ],
    )
    def test_calculate_grub_name(self, input_arch, result_binary_name,
                                 expected_exception, api):
        # Arrange
        test_builder = buildiso.BuildIso(api)
        test_distro = Distro(api)
        test_distro.name = "testdistro"
        test_distro.arch = input_arch

        # Act
        with expected_exception:
            result = test_builder.calculate_grub_name(test_distro)

            # Assert
            assert result == result_binary_name

    @pytest.mark.parametrize(
        "input_kopts_dict,exepcted_output",
        [
            ({}, ""),
            ({
                "test": 1
            }, " test=1"),
            ({
                "test": None
            }, " test"),
            ({
                "test": '"test"'
            }, ' test="test"'),
            ({
                "test": "test test test"
            }, ' test="test test test"'),
            ({
                "test": 'test "test" test'
            }, ' test="test "test" test"'),
            ({
                "test": ['"test"']
            }, ' test="test"'),
            ({
                "test": ['"test"', "test"]
            }, ' test="test" test=test'),
        ],
    )
    def test_add_remaining_kopts(self, input_kopts_dict, exepcted_output):
        # Arrange (missing)
        # Act
        output = buildiso.add_remaining_kopts(input_kopts_dict)

        # Assert
        assert output == exepcted_output

    def test_make_shorter(self, api):
        # Arrange
        build_iso = NetbootBuildiso(api)
        distroname = "Testdistro"

        # Act
        result = build_iso.make_shorter(distroname)

        # Assert
        assert type(result) == str
        assert distroname in build_iso.distmap
        assert result == "1"

    def test_copy_boot_files(self, api, create_kernel_initrd, fk_kernel,
                             fk_initrd, tmpdir):
        # Arrange
        target_folder = tmpdir.mkdir("target")
        folder = create_kernel_initrd(fk_kernel, fk_initrd)
        kernel_path = os.path.join(folder, fk_kernel)
        initrd_path = os.path.join(folder, fk_initrd)
        build_iso = buildiso.BuildIso(api)
        testdistro = Distro(api)
        testdistro.name = "testdistro"
        testdistro.kernel = kernel_path
        testdistro.initrd = initrd_path

        # Act
        build_iso.copy_boot_files(testdistro, target_folder)

        # Assert
        assert len(os.listdir(target_folder)) == 2

    def test_filter_system(self, api, create_kernel_initrd, fk_kernel,
                           fk_initrd):
        # Arrange
        folder = create_kernel_initrd(fk_kernel, fk_initrd)
        kernel_path = os.path.join(folder, fk_kernel)
        initrd_path = os.path.join(folder, fk_initrd)
        test_distro = Distro(api)
        test_distro.name = "testdistro"
        test_distro.kernel = kernel_path
        test_distro.initrd = initrd_path
        api.add_distro(test_distro)
        test_profile = Profile(api)
        test_profile.name = "testprofile"
        test_profile.distro = test_distro.name
        api.add_profile(test_profile)
        test_system = System(api)
        test_system.name = "testsystem"
        test_system.profile = test_profile.name
        api.add_system(test_system)
        itemlist = [test_system.name]
        build_iso = NetbootBuildiso(api)
        expected_result = [test_system]

        # Act
        result = build_iso.filter_systems(itemlist)

        # Assert
        assert expected_result == result

    def test_filter_profile(self, api, create_kernel_initrd, fk_kernel,
                            fk_initrd, cleanup_items):
        # Arrange
        folder = create_kernel_initrd(fk_kernel, fk_initrd)
        kernel_path = os.path.join(folder, fk_kernel)
        initrd_path = os.path.join(folder, fk_initrd)
        test_distro = Distro(api)
        test_distro.name = "testdistro"
        test_distro.kernel = kernel_path
        test_distro.initrd = initrd_path
        api.add_distro(test_distro)
        test_profile = Profile(api)
        test_profile.name = "testprofile"
        test_profile.distro = test_distro.name
        api.add_profile(test_profile)
        itemlist = [test_profile.name]
        build_iso = buildiso.BuildIso(api)
        expected_result = [test_profile]

        # Act
        result = build_iso.filter_profiles(itemlist)

        # Assert
        assert expected_result == result

    def test_netboot_run(
        self,
        api,
        create_kernel_initrd,
        fk_kernel,
        fk_initrd,
        cleanup_items,
        create_loaders,
        tmpdir,
    ):
        # Arrange
        folder = create_kernel_initrd(fk_kernel, fk_initrd)
        kernel_path = os.path.join(folder, fk_kernel)
        initrd_path = os.path.join(folder, fk_initrd)
        test_distro = Distro(api)
        test_distro.name = "testdistro"
        test_distro.kernel = kernel_path
        test_distro.initrd = initrd_path
        api.add_distro(test_distro)
        build_iso = NetbootBuildiso(api)
        iso_location = tmpdir.join("autoinst.iso")

        # Act
        build_iso.run(iso=str(iso_location), distro_name=test_distro.name)

        # Assert
        assert iso_location.exists()

    def test_standalone_run(
        self,
        api,
        create_kernel_initrd,
        fk_kernel,
        fk_initrd,
        create_loaders,
        tmpdir_factory,
        cleanup_items,
    ):
        # Arrange
        iso_directory = tmpdir_factory.mktemp("isodir")
        iso_source = tmpdir_factory.mktemp("isosource")
        iso_location = iso_directory.join("autoinst.iso")
        folder = create_kernel_initrd(fk_kernel, fk_initrd)
        kernel_path = os.path.join(folder, fk_kernel)
        initrd_path = os.path.join(folder, fk_initrd)
        test_distro = Distro(api)
        test_distro.name = "testdistro"
        test_distro.kernel = kernel_path
        test_distro.initrd = initrd_path
        api.add_distro(test_distro)
        build_iso = StandaloneBuildiso(api)

        # Act
        build_iso.run(iso=str(iso_location),
                      distro_name=test_distro.name,
                      source=str(iso_source))

        # Assert
        assert iso_location.exists()
示例#21
0
@pytest.mark.parametrize("test_input,expected_result", [
    ("<<inherit>>", "<<inherit>>"),
    ("delete", [])
])
def test_input_string_or_list(test_input, expected_result):
    # Arrange

    # Act
    result = utils.input_string_or_list(test_input)

    # Assert
    assert expected_result == result


@pytest.mark.parametrize("testinput,expected_result,possible_exception", [
    ("<<inherit>>", (True, {}), does_not_raise()),
    ([""], None, pytest.raises(TypeError)),
    ("a b=10 c=abc", (True, {"a": None, "b": '10', "c": "abc"}), does_not_raise()),
    ({"ab": 0}, (True, {"ab": 0}), does_not_raise()),
    (0, None, pytest.raises(TypeError))
])
def test_input_string_or_dict(testinput, expected_result, possible_exception):
    # Arrange

    # Act
    with possible_exception:
        result = utils.input_string_or_dict(testinput)

        # Assert
        assert expected_result == result
示例#22
0

@pytest.mark.parametrize("test_input,expected_result",
                         [("<<inherit>>", "<<inherit>>"), ("delete", [])])
def test_input_string_or_list(test_input, expected_result):
    # Arrange

    # Act
    result = utils.input_string_or_list(test_input)

    # Assert
    assert expected_result == result


@pytest.mark.parametrize("testinput,expected_result,possible_exception",
                         [("<<inherit>>", (True, {}), does_not_raise()),
                          ([""], None, pytest.raises(TypeError)),
                          ("a b=10 c=abc", (True, {
                              "a": None,
                              "b": '10',
                              "c": "abc"
                          }), does_not_raise()),
                          ({
                              "ab": 0
                          }, (True, {
                              "ab": 0
                          }), does_not_raise()),
                          (0, None, pytest.raises(TypeError))])
def test_input_string_or_dict(testinput, expected_result, possible_exception):
    # Arrange
示例#23
0

def test_proxy():
    # Arrange
    test_api = CobblerAPI()
    profile = Profile(test_api)

    # Act
    profile.proxy = ""

    # Assert
    assert profile.proxy == ""


@pytest.mark.parametrize("value,expected_exception", [
    (False, does_not_raise())
])
def test_enable_ipxe(value, expected_exception):
    # Arrange
    test_api = CobblerAPI()
    profile = Profile(test_api)

    # Act
    with expected_exception:
        profile.enable_ipxe = value

        # Assert
        assert profile.enable_ipxe is value


@pytest.mark.parametrize("value,expected_exception", [
示例#24
0
import pytest
from unittest.mock import Mock, MagicMock, create_autospec, PropertyMock

import cobbler.actions.sync
import cobbler.modules.managers.bind
import cobbler.modules.managers.isc
from cobbler.api import CobblerAPI
from tests.conftest import does_not_raise


@pytest.mark.parametrize("input_verbose,input_what,expected_exception",
                         [(None, None, does_not_raise()),
                          (True, [], does_not_raise()),
                          (False, [], does_not_raise()),
                          (True, ["dhcp"], does_not_raise()),
                          (True, ["dns"], does_not_raise()),
                          (True, ["dns", "dhcp"], does_not_raise())])
def test_sync(input_verbose, input_what, expected_exception, mocker):
    # Arrange
    stub = create_autospec(spec=cobbler.actions.sync.CobblerSync)
    stub_dhcp = mocker.stub()
    stub_dns = mocker.stub()
    mocker.patch.object(CobblerAPI, "get_sync", return_value=stub)
    mocker.patch.object(CobblerAPI, "sync_dhcp", new=stub_dhcp)
    mocker.patch.object(CobblerAPI, "sync_dns", new=stub_dns)
    test_api = CobblerAPI()

    # Act
    with expected_exception:
        test_api.sync(input_verbose, input_what)
示例#25
0
class TestFileStudentDataAccess:
    def test_add_student(self):
        file_client = MagicMock()
        dao = FileStudentDataAccess(file_client)

        student = Student(record_id=PrimaryKey(1),
                          first_name='first',
                          last_name='last',
                          birthday_date='2020-03-03')
        dao.add_student(student)

        file_client.write.assert_called_once_with(student)

    @pytest.mark.parametrize(
        'students, record_id_to_find, expected_result, expected_exception',
        (
            (
                [
                    (Student(record_id=PrimaryKey(1),
                             first_name='first',
                             last_name='last',
                             birthday_date='2020-03-03'), 0),
                    (Student(record_id=PrimaryKey(2),
                             first_name='das',
                             last_name='das',
                             birthday_date='2020-03-03'), 1),
                    (Student(record_id=PrimaryKey(3),
                             first_name='cccc',
                             last_name='aaa',
                             birthday_date='2020-03-03'), 2),
                ],
                PrimaryKey(2),
                Student(record_id=PrimaryKey(2),
                        first_name='das',
                        last_name='das',
                        birthday_date='2020-03-03'),
                does_not_raise(),
            ),
            (
                [
                    (Student(record_id=PrimaryKey(1),
                             first_name='first',
                             last_name='last',
                             birthday_date='2020-03-03'), 0),
                    (Student(record_id=PrimaryKey(2),
                             first_name='das',
                             last_name='das',
                             birthday_date='2020-03-03'), 1),
                ],
                PrimaryKey(3),
                None,
                pytest.raises(RecordNotFound),
            ),
        ),
    )
    def test_get_student(self, students, record_id_to_find, expected_result,
                         expected_exception):
        file_client = MagicMock()
        file_client.iter_read.return_value = students

        dao = FileStudentDataAccess(file_client)

        with expected_exception:
            result = dao.get_student(record_id_to_find)
            assert result == expected_result
示例#26
0
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, test_raise):
    # Arrange

    # Act
    with test_raise:
        result = enums.Archs.to_enum(test_architecture)

        # 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")

示例#27
0
    assert False


@pytest.mark.skip
def test_set_ctime():
    # Arrange
    titem = Item()

    # Act
    titem.set_ctime()
    # Assert
    assert False


@pytest.mark.parametrize("value,expected_exception",
                         [(0.0, does_not_raise()),
                          (0, pytest.raises(TypeError)),
                          ("", pytest.raises(TypeError))])
def test_mtime(value, expected_exception):
    # Arrange
    test_api = CobblerAPI()
    titem = Item(test_api)

    # Act
    with expected_exception:
        titem.mtime = value

        # Assert
        assert titem.mtime == value

    assert expected == result


def test_exportsignatures_unkown():
    # Arrange
    os_signatures = Signatures()
    os_signatures.importsignatures(ImportTypes.STRING, "{\"breeds\": {}}")

    # Act & Assert
    with pytest.raises(ValueError):
        os_signatures.exportsignatures(100)


@pytest.mark.parametrize("input_data,result,raises", [
    ("{\"breeds; {}}", {}, pytest.raises(JSONDecodeError)),
    ("{\"breeds\": {}}", {"breeds": {}}, does_not_raise())
])
def test_signaturesjson(input_data, result, raises):
    # Arrange
    os_signatures = Signatures()
    with raises:
        os_signatures.importsignatures(ImportTypes.STRING, input_data)

        # Act
        os_signatures.signaturesjson = input_data

    # Assert
    assert result == os_signatures.signaturesjson


@pytest.mark.parametrize("input_data,expected_data", [