Esempio n. 1
0
class ReusingTestCaseComponent(TestCaseComponent):
    """A version of TestCaseComponent that reuses existing disk images
       rather than create its own.  It will, however, delete these disk images
       after use.

       This class knows which disk images to reuse by the reusedComponents
       parameter passed in at object instantiation.  This is a list of other
       TestCaseComponent instances.  This class will reuse all disk images
       from each instance in that list, in the order given.

       A typical pipeline of components would thus look like this:

           class ComponentA(ReusableTestCaseComponent):
               ...

           class ComponentB(ReusingTestCaseComponent):
               ...

           ComponentA -> ComponentB

       A component may also derive from both, if it's in the middle of the
       pipeline:

           class ComponentA(ReusableTestCaseComponent):
               ...

           class ComponentB(ReusableTestCaseComponent, ReusingTestCaseComponent):
               ...

           class ComponentC(ReusingTestCaseComponent):
               ...

           ComponentA -> ComponentB -> ComponentC
    """

    def __init__(self, reusedComponents=None):
        """Create a new ReusingTestCaseComponent.  reusedComponents is a list
           of other TestCaseComponent objects that this instance should make
           use of.  All disk images in that list will be used by this instance,
           and all will be cleaned up at the end of the test.
        """
        TestCaseComponent.__init__(self)

        if reusedComponents is None:
            self._reusedComponents = []
        else:
            self._reusedComponents = reusedComponents

    def setupDisks(self, ksdata):
        self._storage = InstallerStorage()

        for component in self._reusedComponents:
            self._disks.update(component._disks)

        for (name, image) in self._disks.items():
            self._storage.disk_images[name] = image

        self._storage.reset()
Esempio n. 2
0
    def test_bootloader_in_kickstart(self):
        '''
        test that a bootloader such as prepboot/biosboot shows up
        in the kickstart data
        '''

        # prepboot test case
        with patch(
                'pyanaconda.storage.osinstall.InstallerStorage.bootloader_device',
                new_callable=PropertyMock) as mock_bootloader_device:
            with patch(
                    'pyanaconda.storage.osinstall.InstallerStorage.mountpoints',
                    new_callable=PropertyMock) as mock_mountpoints:
                # set up prepboot partition
                bootloader_device_obj = PartitionDevice(
                    "test_partition_device")
                bootloader_device_obj.size = Size('5 MiB')
                bootloader_device_obj.format = formats.get_format("prepboot")

                prepboot_blivet_obj = InstallerStorage()

                # mountpoints must exist for update_ksdata to run
                mock_bootloader_device.return_value = bootloader_device_obj
                mock_mountpoints.values.return_value = []

                # initialize ksdata
                prepboot_ksdata = returnClassForVersion()()
                prepboot_blivet_obj.ksdata = prepboot_ksdata
                prepboot_blivet_obj.update_ksdata()

        self.assertIn("part prepboot", str(prepboot_blivet_obj.ksdata))

        # biosboot test case
        with patch('pyanaconda.storage.osinstall.InstallerStorage.devices',
                   new_callable=PropertyMock) as mock_devices:
            with patch(
                    'pyanaconda.storage.osinstall.InstallerStorage.mountpoints',
                    new_callable=PropertyMock) as mock_mountpoints:
                # set up biosboot partition
                biosboot_device_obj = PartitionDevice(
                    "biosboot_partition_device")
                biosboot_device_obj.size = Size('1MiB')
                biosboot_device_obj.format = formats.get_format("biosboot")

                biosboot_blivet_obj = InstallerStorage()

                # mountpoints must exist for updateKSData to run
                mock_devices.return_value = [biosboot_device_obj]
                mock_mountpoints.values.return_value = []

                # initialize ksdata
                biosboot_ksdata = returnClassForVersion()()
                biosboot_blivet_obj.ksdata = biosboot_ksdata
                biosboot_blivet_obj.update_ksdata()

        self.assertIn("part biosboot", str(biosboot_blivet_obj.ksdata))
Esempio n. 3
0
    def setupDisks(self, ksdata):
        self._storage = InstallerStorage()

        for component in self._reusedComponents:
            self._disks.update(component._disks)

        for (name, image) in self._disks.items():
            self._storage.disk_images[name] = image

        self._storage.reset()
Esempio n. 4
0
    def setupDisks(self, ksdata):
        """Create all disk images given by self.disksToCreate and initialize
           the storage module.  Subclasses may override this method, but they
           should be sure to call the base method as well.
        """
        self._storage = InstallerStorage()

        for (name, size) in self.disksToCreate:
            self._disks[name] = blivet.util.create_sparse_tempfile(name, size)
            self._storage.disk_images[name] = self._disks[name]

        self._storage.reset()
Esempio n. 5
0
    def setupDisks(self, ksdata):
        self._storage = InstallerStorage(ksdata=ksdata)

        # See comment in super class's method.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for component in self._reusedComponents:
            self._disks.update(component._disks)

        for (name, image) in self._disks.items():
            self._storage.disk_images[name] = image

        self._storage.reset()
Esempio n. 6
0
def create_storage():
    """Create the storage object.

    :return: an instance of the Blivet's storage object
    """
    storage = InstallerStorage()

    # Set the default filesystem type.
    storage.set_default_fstype(conf.storage.file_system_type or storage.default_fstype)

    # Set the default LUKS version.
    storage.set_default_luks_version(conf.storage.luks_version or storage.default_luks_version)

    return storage
Esempio n. 7
0
    def test_biosboot_bootloader_in_kickstart(self, mock_mountpoints, mock_devices, dbus):
        """Test that a biosboot bootloader shows up in the ks data."""
        # set up biosboot partition
        biosboot_device_obj = PartitionDevice("biosboot_partition_device")
        biosboot_device_obj.size = Size('1MiB')
        biosboot_device_obj.format = formats.get_format("biosboot")

        # mountpoints must exist for updateKSData to run
        mock_devices.return_value = [biosboot_device_obj]
        mock_mountpoints.values.return_value = []

        # initialize ksdata
        biosboot_blivet_obj = InstallerStorage(makeVersion())
        biosboot_blivet_obj.update_ksdata()

        self.assertIn("part biosboot", str(biosboot_blivet_obj.ksdata))
Esempio n. 8
0
    def test_biosboot_bootloader_in_kickstart(self, mock_mountpoints,
                                              mock_devices, dbus):
        """Test that a biosboot bootloader shows up in the ks data."""
        # set up biosboot partition
        biosboot_device_obj = PartitionDevice("biosboot_partition_device")
        biosboot_device_obj.size = Size('1MiB')
        biosboot_device_obj.format = formats.get_format("biosboot")

        # mountpoints must exist for updateKSData to run
        mock_devices.return_value = [biosboot_device_obj]
        mock_mountpoints.values.return_value = []

        # initialize ksdata
        biosboot_blivet_obj = InstallerStorage(makeVersion())
        biosboot_blivet_obj.update_ksdata()

        self.assertIn("part biosboot", str(biosboot_blivet_obj.ksdata))
Esempio n. 9
0
    def setUp(self):
        self.storage = InstallerStorage()

        # anaconda first configures disk images
        for (name, size) in iter(self.disks.items()):
            path = util.create_sparse_tempfile(name, size)
            self.storage.disk_images[name] = path

        # at this point the DMLinearDevice has correct size
        self.storage.setup_disk_images()

        # anaconda calls initialize_storage regardless of whether or not
        # this is an image install. Somewhere along the line this will
        # execute setup_disk_images() once more and the DMLinearDevice created
        # in this second execution has size 0
        with patch('blivet.flags'):
            reset_storage(self.storage)
Esempio n. 10
0
class setupDiskImagesNonZeroSizeTestCase(unittest.TestCase):
    """
        Test if size of disk images is > 0. Related: rhbz#1252703.
        This test emulates how anaconda configures its storage.
    """

    disks = {"disk1": Size("2 GiB")}

    def setUp(self):
        self.storage = InstallerStorage()

        # anaconda first configures disk images
        for (name, size) in iter(self.disks.items()):
            path = util.create_sparse_tempfile(name, size)
            self.storage.disk_images[name] = path

        # at this point the DMLinearDevice has correct size
        self.storage.setup_disk_images()

        # emulates setting the anaconda flags which later update
        flags.image_install = True
        # no kickstart available
        ksdata = kickstart.AnacondaKSHandler([])
        # anaconda calls storage_initialize regardless of whether or not
        # this is an image install. Somewhere along the line this will
        # execute setup_disk_images() once more and the DMLinearDevice created
        # in this second execution has size 0
        with patch('blivet.flags'):
            storage_initialize(self.storage, ksdata, [])

    def tearDown(self):
        self.storage.reset()
        self.storage.devicetree.teardown_disk_images()
        for fn in self.storage.disk_images.values():
            if os.path.exists(fn):
                os.unlink(fn)

        flags.image_install = False

    def runTest(self):
        disk = self.storage.disks[0]
        self.assertEqual(disk.name, list(self.disks.keys())[0])
        for d in self.storage.devicetree.devices:
            if d == disk or disk.depends_on(d):
                self.assertTrue(d.size > 0)
Esempio n. 11
0
    def setupDisks(self, ksdata):
        """Create all disk images given by self.disksToCreate and initialize
           the storage module.  Subclasses may override this method, but they
           should be sure to call the base method as well.
        """
        self._storage = InstallerStorage(ksdata=ksdata)

        # blivet only sets up the bootloader in installer_mode.  We don't
        # want installer_mode, though, because that involves running lots
        # of programs on the host and setting up all sorts of other things.
        # Thus, we set it up manually.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for (name, size) in self.disksToCreate:
            self._disks[name] = blivet.util.create_sparse_tempfile(name, size)
            self._storage.disk_images[name] = self._disks[name]

        self._storage.reset()
Esempio n. 12
0
class setupDiskImagesNonZeroSizeTestCase(unittest.TestCase):
    """
        Test if size of disk images is > 0. Related: rhbz#1252703.
        This test emulates how anaconda configures its storage.
    """

    disks = {"disk1": Size("2 GiB")}

    def setUp(self):
        self.storage = InstallerStorage()

        # anaconda first configures disk images
        for (name, size) in iter(self.disks.items()):
            path = util.create_sparse_tempfile(name, size)
            self.storage.disk_images[name] = path

        # at this point the DMLinearDevice has correct size
        self.storage.setup_disk_images()

        # no kickstart available
        ksdata = kickstart.AnacondaKSHandler([])
        # anaconda calls storage_initialize regardless of whether or not
        # this is an image install. Somewhere along the line this will
        # execute setup_disk_images() once more and the DMLinearDevice created
        # in this second execution has size 0
        with patch('blivet.flags'):
            storage_initialize(self.storage, ksdata, [])

    def tearDown(self):
        self.storage.reset()
        self.storage.devicetree.teardown_disk_images()
        for fn in self.storage.disk_images.values():
            if os.path.exists(fn):
                os.unlink(fn)

    def runTest(self):
        disk = self.storage.disks[0]
        self.assertEqual(disk.name, list(self.disks.keys())[0])
        for d in self.storage.devicetree.devices:
            if d == disk or disk.depends_on(d):
                self.assertTrue(d.size > 0)
Esempio n. 13
0
    def storage(self):
        if not self._storage:
            from pyanaconda.storage.osinstall import InstallerStorage
            import blivet.arch

            self._storage = InstallerStorage(ksdata=self.ksdata)
            self._set_storage_defaults(self._storage)

            if blivet.arch.is_s390():
                self._load_plugin_s390()

        return self._storage
Esempio n. 14
0
    def setUp(self):
        self.storage = InstallerStorage()

        # anaconda first configures disk images
        for (name, size) in iter(self.disks.items()):
            path = util.create_sparse_tempfile(name, size)
            self.storage.disk_images[name] = path

        # at this point the DMLinearDevice has correct size
        self.storage.setup_disk_images()

        # emulates setting the anaconda flags which later update
        flags.image_install = True
        # no kickstart available
        ksdata = kickstart.AnacondaKSHandler([])
        # anaconda calls storage_initialize regardless of whether or not
        # this is an image install. Somewhere along the line this will
        # execute setup_disk_images() once more and the DMLinearDevice created
        # in this second execution has size 0
        with patch('blivet.flags'):
            storage_initialize(self.storage, ksdata, [])
Esempio n. 15
0
    def setupDisks(self, ksdata):
        self._storage = InstallerStorage()

        # See comment in super class's method.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for component in self._reusedComponents:
            self._disks.update(component._disks)

        for (name, image) in self._disks.items():
            self._storage.disk_images[name] = image

        self._storage.reset()
Esempio n. 16
0
    def test_prepboot_bootloader_in_kickstart(self, mock_mountpoints, mock_bootloader_device, dbus):
        """Test that a prepboot bootloader shows up in the ks data."""
        # set up prepboot partition
        bootloader_device_obj = PartitionDevice("test_partition_device")
        bootloader_device_obj.size = Size('5 MiB')
        bootloader_device_obj.format = formats.get_format("prepboot")

        # mountpoints must exist for update_ksdata to run
        mock_bootloader_device.return_value = bootloader_device_obj
        mock_mountpoints.values.return_value = []

        # initialize ksdata
        ksdata = makeVersion()
        prepboot_blivet_obj = InstallerStorage()
        update_storage_ksdata(prepboot_blivet_obj, ksdata)

        self.assertIn("part prepboot", str(ksdata))
Esempio n. 17
0
    def setupDisks(self, ksdata):
        """Create all disk images given by self.disksToCreate and initialize
           the storage module.  Subclasses may override this method, but they
           should be sure to call the base method as well.
        """
        self._storage = InstallerStorage()

        # blivet only sets up the bootloader in installer_mode.  We don't
        # want installer_mode, though, because that involves running lots
        # of programs on the host and setting up all sorts of other things.
        # Thus, we set it up manually.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for (name, size) in self.disksToCreate:
            self._disks[name] = blivet.util.create_sparse_tempfile(name, size)
            self._storage.disk_images[name] = self._disks[name]

        self._storage.reset()
Esempio n. 18
0
def create_storage():
    """Create the storage object.

    :return: an instance of the Blivet's storage object
    """
    storage = InstallerStorage()

    # Set the default filesystem type.
    storage.set_default_fstype(conf.storage.file_system_type or storage.default_fstype)

    # Set the default LUKS version.
    storage.set_default_luks_version(conf.storage.luks_version or storage.default_luks_version)

    return storage
Esempio n. 19
0
class TestCaseComponent(object):
    """A TestCaseComponent is one individual test that runs as part of a TestCase.
       It consists of a set of disk images provided by self.disksToCreate, a
       kickstart storage snippet provided by self.ks, and an expected error
       condition provided by self.expectedExceptionType and self.expectedExceptionText.
       If the TestCaseComponent is expected to succeed, these latter two should
       just be set to None.

       A TestCaseComponent succeeds in the following cases:

       * No exception is encountered, and self.expectedExceptionType is None.

       A TestCaseComponent fails in all other cases.

       Class attributes:

       name -- An identifying string given to this TestCaseComponent.
    """
    name = ""

    def __init__(self):
        """Create a new TestCaseComponent instance.  This __init__ method should
           typically do very little.  However, subclasses must be sure to set
           self.disksToCreate.  This attribute is a list of (disk name, blivet.Size)
           tuples that will be used in this test.  Disks given in this list will
           be automatically created by setupDisks and destroyed by tearDownDisks.
        """
        self._disks     = {}
        self._storage   = None

        self.disksToCreate = []

    @property
    def ks(self):
        """Return the storage-specific portion of a kickstart file used for
           performing this test.  The kickstart snippet must be provided as
           text.  Only storage commands will be tested.  No bootloader actions
           will be performed.
        """
        return ""

    def setupDisks(self, ksdata):
        """Create all disk images given by self.disksToCreate and initialize
           the storage module.  Subclasses may override this method, but they
           should be sure to call the base method as well.
        """
        self._storage = InstallerStorage()

        # blivet only sets up the bootloader in installer_mode.  We don't
        # want installer_mode, though, because that involves running lots
        # of programs on the host and setting up all sorts of other things.
        # Thus, we set it up manually.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for (name, size) in self.disksToCreate:
            self._disks[name] = blivet.util.create_sparse_tempfile(name, size)
            self._storage.disk_images[name] = self._disks[name]

        self._storage.reset()

    def tearDownDisks(self):
        """Disable any disk images used by this test component and remove their
           image files from the host system.  Subclasses may override this
           method, but they should call the base method as well to make sure
           the images get destroyed.
        """
        # pylint: disable=undefined-variable
        self._storage.devicetree.teardown_disk_images()

        for d in self._disks.values():
            os.unlink(d)

    @property
    def expectedExceptionType(self):
        """Should this test component be expected to fail, this property returns
           the exception type.  If this component is not expected to fail, this
           property returns None.  All components that are expected to fail
           should override this property.
        """
        return None

    @property
    def expectedExceptionText(self):
        """Should this test component be expected to fail, this property returns
           a regular expression that the raised exception's text must match.
           Otherwise, this property returns None.  All components that are
           expected to fail should override this property.
        """
        return None

    def _text_matches(self, s):
        prog = re.compile(self.expectedExceptionText)

        for line in s.splitlines():
            match = prog.match(line)
            if match:
                return match

        return None

    def _run(self):
        # Set up disks/blivet.
        try:
            # Parse the kickstart using anaconda's parser, since it has more
            # advanced error detection.  This also requires having storage set
            # up first.
            parser = AnacondaKSParser(AnacondaKSHandler())
            parser.readKickstartFromString(self.ks)

            self.setupDisks(parser.handler)

            configure_storage(self._storage, parser.handler)
            update_storage_ksdata(self._storage, parser.handler)
            self._storage.devicetree.teardown_all()
            self._storage.do_it()
        except (StorageConfigurationError, BootloaderConfigurationError) as e:
            # anaconda handles expected kickstart errors (like parsing busted
            # input files) by printing the error and quitting.  For testing, an
            # error might be expected so we should compare the result here with
            # what is expected.
            if self.expectedExceptionType and isinstance(e, self.expectedExceptionType):
                # We expected an exception, and we got one of the correct type.
                # If it also contains the string we were expecting, then the
                # test case passes.  Otherwise, it's a failure.
                if self.expectedExceptionText and self._text_matches(str(e)):
                    return
                else:
                    raise FailedTest(str(e), self.expectedExceptionText)
            else:
                # We either got an exception when we were not expecting one,
                # or we got one of a type other than what we were expecting.
                # Either of these cases indicates a failure of the test case.
                raise FailedTest(e, self.expectedExceptionType)
        finally:
            self.tearDownDisks()

        if self.expectedExceptionType:
            raise FailedTest(None, self.expectedExceptionType)
Esempio n. 20
0
 def setUp(self):
     flags.testing = True
     self._storage = InstallerStorage()
     self._config = DiskInitializationConfig()
Esempio n. 21
0
class ReusingTestCaseComponent(TestCaseComponent):
    """A version of TestCaseComponent that reuses existing disk images
       rather than create its own.  It will, however, delete these disk images
       after use.

       This class knows which disk images to reuse by the reusedComponents
       parameter passed in at object instantiation.  This is a list of other
       TestCaseComponent instances.  This class will reuse all disk images
       from each instance in that list, in the order given.

       A typical pipeline of components would thus look like this:

           class ComponentA(ReusableTestCaseComponent):
               ...

           class ComponentB(ReusingTestCaseComponent):
               ...

           ComponentA -> ComponentB

       A component may also derive from both, if it's in the middle of the
       pipeline:

           class ComponentA(ReusableTestCaseComponent):
               ...

           class ComponentB(ReusableTestCaseComponent, ReusingTestCaseComponent):
               ...

           class ComponentC(ReusingTestCaseComponent):
               ...

           ComponentA -> ComponentB -> ComponentC
    """

    def __init__(self, reusedComponents=None):
        """Create a new ReusingTestCaseComponent.  reusedComponents is a list
           of other TestCaseComponent objects that this instance should make
           use of.  All disk images in that list will be used by this instance,
           and all will be cleaned up at the end of the test.
        """
        TestCaseComponent.__init__(self)

        if reusedComponents is None:
            self._reusedComponents = []
        else:
            self._reusedComponents = reusedComponents

    def setupDisks(self, ksdata):
        self._storage = InstallerStorage()

        # See comment in super class's method.
        from pyanaconda.bootloader import get_bootloader
        self._storage._bootloader = get_bootloader()

        for component in self._reusedComponents:
            self._disks.update(component._disks)

        for (name, image) in self._disks.items():
            self._storage.disk_images[name] = image

        self._storage.reset()
Esempio n. 22
0
    def test_should_clear(self):
        """ Test the Blivet.should_clear method. """
        b = InstallerStorage()

        DiskDevice = blivet.devices.DiskDevice
        PartitionDevice = blivet.devices.PartitionDevice

        # sda is a disk with an existing disklabel containing two partitions
        sda = DiskDevice("sda", size=100000, exists=True)
        sda.format = blivet.formats.get_format("disklabel",
                                               device=sda.path,
                                               exists=True)
        sda.format._parted_disk = mock.Mock()
        sda.format._parted_device = mock.Mock()
        sda.format._parted_disk.configure_mock(partitions=[])
        b.devicetree._add_device(sda)

        # sda1 is a partition containing an existing ext4 filesystem
        sda1 = PartitionDevice("sda1", size=500, exists=True, parents=[sda])
        sda1._parted_partition = mock.Mock(
            **{
                'type': PARTITION_NORMAL,
                'getLength.return_value': int(sda1.size),
                'getFlag.return_value': 0
            })
        sda1.format = blivet.formats.get_format("ext4",
                                                mountpoint="/boot",
                                                device=sda1.path,
                                                exists=True)
        b.devicetree._add_device(sda1)

        # sda2 is a partition containing an existing vfat filesystem
        sda2 = PartitionDevice("sda2", size=10000, exists=True, parents=[sda])
        sda2._parted_partition = mock.Mock(
            **{
                'type': PARTITION_NORMAL,
                'getLength.return_value': int(sda2.size),
                'getFlag.return_value': 0
            })
        sda2.format = blivet.formats.get_format("vfat",
                                                mountpoint="/foo",
                                                device=sda2.path,
                                                exists=True)
        b.devicetree._add_device(sda2)

        # sdb is an unpartitioned disk containing an xfs filesystem
        sdb = DiskDevice("sdb", size=100000, exists=True)
        sdb.format = blivet.formats.get_format("xfs",
                                               device=sdb.path,
                                               exists=True)
        b.devicetree._add_device(sdb)

        # sdc is an unformatted/uninitialized/empty disk
        sdc = DiskDevice("sdc", size=100000, exists=True)
        b.devicetree._add_device(sdc)

        # sdd is a disk containing an existing disklabel with no partitions
        sdd = DiskDevice("sdd", size=100000, exists=True)
        sdd.format = blivet.formats.get_format("disklabel",
                                               device=sdd.path,
                                               exists=True)
        b.devicetree._add_device(sdd)

        #
        # clearpart type none
        #
        b.config.clear_part_type = CLEARPART_TYPE_NONE
        self.assertFalse(b.should_clear(sda1),
                         msg="type none should not clear any partitions")
        self.assertFalse(b.should_clear(sda2),
                         msg="type none should not clear any partitions")

        b.config.initialize_disks = False
        self.assertFalse(b.should_clear(sda),
                         msg="type none should not clear non-empty disks")
        self.assertFalse(b.should_clear(sdb),
                         msg="type none should not clear formatting from "
                         "unpartitioned disks")

        self.assertFalse(b.should_clear(sdc),
                         msg="type none should not clear empty disk without "
                         "initlabel")
        self.assertFalse(
            b.should_clear(sdd),
            msg="type none should not clear empty partition table "
            "without initlabel")

        b.config.initialize_disks = True
        self.assertFalse(b.should_clear(sda),
                         msg="type none should not clear non-empty disks even "
                         "with initlabel")
        self.assertFalse(b.should_clear(sdb),
                         msg="type non should not clear formatting from "
                         "unpartitioned disks even with initlabel")
        self.assertTrue(
            b.should_clear(sdc),
            msg="type none should clear empty disks when initlabel "
            "is set")
        self.assertTrue(
            b.should_clear(sdd),
            msg="type none should clear empty partition table when "
            "initlabel is set")

        #
        # clearpart type linux
        #
        b.config.clear_part_type = CLEARPART_TYPE_LINUX
        self.assertTrue(b.should_clear(sda1),
                        msg="type linux should clear partitions containing "
                        "ext4 filesystems")
        self.assertFalse(b.should_clear(sda2),
                         msg="type linux should not clear partitions "
                         "containing vfat filesystems")

        b.config.initialize_disks = False
        self.assertFalse(
            b.should_clear(sda),
            msg="type linux should not clear non-empty disklabels")
        self.assertTrue(b.should_clear(sdb),
                        msg="type linux should clear linux-native whole-disk "
                        "formatting regardless of initlabel setting")
        self.assertFalse(b.should_clear(sdc),
                         msg="type linux should not clear unformatted disks "
                         "unless initlabel is set")
        self.assertFalse(b.should_clear(sdd),
                         msg="type linux should not clear disks with empty "
                         "partition tables unless initlabel is set")

        b.config.initialize_disks = True
        self.assertFalse(
            b.should_clear(sda),
            msg="type linux should not clear non-empty disklabels")
        self.assertTrue(b.should_clear(sdb),
                        msg="type linux should clear linux-native whole-disk "
                        "formatting regardless of initlabel setting")
        self.assertTrue(b.should_clear(sdc),
                        msg="type linux should clear unformatted disks when "
                        "initlabel is set")
        self.assertTrue(b.should_clear(sdd),
                        msg="type linux should clear disks with empty "
                        "partition tables when initlabel is set")

        sda1.protected = True
        self.assertFalse(b.should_clear(sda1),
                         msg="protected devices should never be cleared")
        self.assertFalse(b.should_clear(sda),
                         msg="disks containing protected devices should never "
                         "be cleared")
        sda1.protected = False

        #
        # clearpart type all
        #
        b.config.clear_part_type = CLEARPART_TYPE_ALL
        self.assertTrue(b.should_clear(sda1),
                        msg="type all should clear all partitions")
        self.assertTrue(b.should_clear(sda2),
                        msg="type all should clear all partitions")

        b.config.initialize_disks = False
        self.assertTrue(b.should_clear(sda),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdb),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdc),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdd),
                        msg="type all should initialize all disks")

        b.config.initialize_disks = True
        self.assertTrue(b.should_clear(sda),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdb),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdc),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdd),
                        msg="type all should initialize all disks")

        sda1.protected = True
        self.assertFalse(b.should_clear(sda1),
                         msg="protected devices should never be cleared")
        self.assertFalse(b.should_clear(sda),
                         msg="disks containing protected devices should never "
                         "be cleared")
        sda1.protected = False
Esempio n. 23
0
class TestCaseComponent(object):
    """A TestCaseComponent is one individual test that runs as part of a TestCase.
       It consists of a set of disk images provided by self.disksToCreate, a
       kickstart storage snippet provided by self.ks, and an expected error
       condition provided by self.expectedExceptionType and self.expectedExceptionText.
       If the TestCaseComponent is expected to succeed, these latter two should
       just be set to None.

       A TestCaseComponent succeeds in the following cases:

       * No exception is encountered, and self.expectedExceptionType is None.

       A TestCaseComponent fails in all other cases.

       Class attributes:

       name -- An identifying string given to this TestCaseComponent.
    """
    name = ""

    def __init__(self):
        """Create a new TestCaseComponent instance.  This __init__ method should
           typically do very little.  However, subclasses must be sure to set
           self.disksToCreate.  This attribute is a list of (disk name, blivet.Size)
           tuples that will be used in this test.  Disks given in this list will
           be automatically created by setupDisks and destroyed by tearDownDisks.
        """
        self._disks = {}
        self._storage = None

        self.disksToCreate = []

    @property
    def ks(self):
        """Return the storage-specific portion of a kickstart file used for
           performing this test.  The kickstart snippet must be provided as
           text.  Only storage commands will be tested.  No bootloader actions
           will be performed.
        """
        return ""

    def setupDisks(self, ksdata):
        """Create all disk images given by self.disksToCreate and initialize
           the storage module.  Subclasses may override this method, but they
           should be sure to call the base method as well.
        """
        self._storage = InstallerStorage()

        for (name, size) in self.disksToCreate:
            self._disks[name] = blivet.util.create_sparse_tempfile(name, size)
            self._storage.disk_images[name] = self._disks[name]

        self._storage.reset()

    def tearDownDisks(self):
        """Disable any disk images used by this test component and remove their
           image files from the host system.  Subclasses may override this
           method, but they should call the base method as well to make sure
           the images get destroyed.
        """
        # pylint: disable=undefined-variable
        self._storage.devicetree.teardown_disk_images()

        for d in self._disks.values():
            os.unlink(d)

    @property
    def expectedExceptionType(self):
        """Should this test component be expected to fail, this property returns
           the exception type.  If this component is not expected to fail, this
           property returns None.  All components that are expected to fail
           should override this property.
        """
        return None

    @property
    def expectedExceptionText(self):
        """Should this test component be expected to fail, this property returns
           a regular expression that the raised exception's text must match.
           Otherwise, this property returns None.  All components that are
           expected to fail should override this property.
        """
        return None

    def _text_matches(self, s):
        prog = re.compile(self.expectedExceptionText)

        for line in s.splitlines():
            match = prog.match(line)
            if match:
                return match

        return None

    def _run(self):
        # Set up disks/blivet.
        try:
            # Parse the kickstart using anaconda's parser, since it has more
            # advanced error detection.  This also requires having storage set
            # up first.
            parser = AnacondaKSParser(AnacondaKSHandler())
            parser.readKickstartFromString(self.ks)

            self.setupDisks(parser.handler)

            configure_storage(self._storage, parser.handler)
            self._storage.devicetree.teardown_all()
            self._storage.do_it()
        except (StorageConfigurationError, BootloaderConfigurationError) as e:
            # anaconda handles expected kickstart errors (like parsing busted
            # input files) by printing the error and quitting.  For testing, an
            # error might be expected so we should compare the result here with
            # what is expected.
            if self.expectedExceptionType and isinstance(
                    e, self.expectedExceptionType):
                # We expected an exception, and we got one of the correct type.
                # If it also contains the string we were expecting, then the
                # test case passes.  Otherwise, it's a failure.
                if self.expectedExceptionText and self._text_matches(str(e)):
                    return
                else:
                    raise FailedTest(str(e), self.expectedExceptionText)
            else:
                # We either got an exception when we were not expecting one,
                # or we got one of a type other than what we were expecting.
                # Either of these cases indicates a failure of the test case.
                raise FailedTest(e, self.expectedExceptionType)
        finally:
            self.tearDownDisks()

        if self.expectedExceptionType:
            raise FailedTest(None, self.expectedExceptionType)
Esempio n. 24
0
    def test_should_clear(self):
        """ Test the Blivet.should_clear method. """
        b = InstallerStorage()

        DiskDevice = blivet.devices.DiskDevice
        PartitionDevice = blivet.devices.PartitionDevice

        # sda is a disk with an existing disklabel containing two partitions
        sda = DiskDevice("sda", size=100000, exists=True)
        sda.format = blivet.formats.get_format("disklabel", device=sda.path,
                                               exists=True)
        sda.format._parted_disk = mock.Mock()
        sda.format._parted_device = mock.Mock()
        sda.format._parted_disk.configure_mock(partitions=[])
        b.devicetree._add_device(sda)

        # sda1 is a partition containing an existing ext4 filesystem
        sda1 = PartitionDevice("sda1", size=500, exists=True,
                               parents=[sda])
        sda1._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL,
                                              'getLength.return_value': int(sda1.size),
                                              'getFlag.return_value': 0})
        sda1.format = blivet.formats.get_format("ext4", mountpoint="/boot",
                                                device=sda1.path,
                                                exists=True)
        b.devicetree._add_device(sda1)

        # sda2 is a partition containing an existing vfat filesystem
        sda2 = PartitionDevice("sda2", size=10000, exists=True,
                               parents=[sda])
        sda2._parted_partition = mock.Mock(**{'type': PARTITION_NORMAL,
                                              'getLength.return_value': int(sda2.size),
                                              'getFlag.return_value': 0})
        sda2.format = blivet.formats.get_format("vfat", mountpoint="/foo",
                                                device=sda2.path,
                                                exists=True)
        b.devicetree._add_device(sda2)

        # sdb is an unpartitioned disk containing an xfs filesystem
        sdb = DiskDevice("sdb", size=100000, exists=True)
        sdb.format = blivet.formats.get_format("xfs", device=sdb.path,
                                               exists=True)
        b.devicetree._add_device(sdb)

        # sdc is an unformatted/uninitialized/empty disk
        sdc = DiskDevice("sdc", size=100000, exists=True)
        b.devicetree._add_device(sdc)

        # sdd is a disk containing an existing disklabel with no partitions
        sdd = DiskDevice("sdd", size=100000, exists=True)
        sdd.format = blivet.formats.get_format("disklabel", device=sdd.path,
                                               exists=True)
        b.devicetree._add_device(sdd)

        #
        # clearpart type none
        #
        b.config.clear_part_type = CLEAR_PARTITIONS_NONE
        self.assertFalse(b.should_clear(sda1),
                         msg="type none should not clear any partitions")
        self.assertFalse(b.should_clear(sda2),
                         msg="type none should not clear any partitions")

        b.config.initialize_disks = False
        self.assertFalse(b.should_clear(sda),
                         msg="type none should not clear non-empty disks")
        self.assertFalse(b.should_clear(sdb),
                         msg="type none should not clear formatting from "
                             "unpartitioned disks")

        self.assertFalse(b.should_clear(sdc),
                         msg="type none should not clear empty disk without "
                             "initlabel")
        self.assertFalse(b.should_clear(sdd),
                         msg="type none should not clear empty partition table "
                             "without initlabel")

        b.config.initialize_disks = True
        self.assertFalse(b.should_clear(sda),
                         msg="type none should not clear non-empty disks even "
                             "with initlabel")
        self.assertFalse(b.should_clear(sdb),
                         msg="type non should not clear formatting from "
                             "unpartitioned disks even with initlabel")
        self.assertTrue(b.should_clear(sdc),
                        msg="type none should clear empty disks when initlabel "
                            "is set")
        self.assertTrue(b.should_clear(sdd),
                        msg="type none should clear empty partition table when "
                            "initlabel is set")

        #
        # clearpart type linux
        #
        b.config.clear_part_type = CLEAR_PARTITIONS_LINUX
        self.assertTrue(b.should_clear(sda1),
                        msg="type linux should clear partitions containing "
                            "ext4 filesystems")
        self.assertFalse(b.should_clear(sda2),
                         msg="type linux should not clear partitions "
                             "containing vfat filesystems")

        b.config.initialize_disks = False
        self.assertFalse(b.should_clear(sda),
                         msg="type linux should not clear non-empty disklabels")
        self.assertTrue(b.should_clear(sdb),
                        msg="type linux should clear linux-native whole-disk "
                            "formatting regardless of initlabel setting")
        self.assertFalse(b.should_clear(sdc),
                         msg="type linux should not clear unformatted disks "
                             "unless initlabel is set")
        self.assertFalse(b.should_clear(sdd),
                         msg="type linux should not clear disks with empty "
                             "partition tables unless initlabel is set")

        b.config.initialize_disks = True
        self.assertFalse(b.should_clear(sda),
                         msg="type linux should not clear non-empty disklabels")
        self.assertTrue(b.should_clear(sdb),
                        msg="type linux should clear linux-native whole-disk "
                            "formatting regardless of initlabel setting")
        self.assertTrue(b.should_clear(sdc),
                        msg="type linux should clear unformatted disks when "
                        "initlabel is set")
        self.assertTrue(b.should_clear(sdd),
                        msg="type linux should clear disks with empty "
                        "partition tables when initlabel is set")

        sda1.protected = True
        self.assertFalse(b.should_clear(sda1),
                         msg="protected devices should never be cleared")
        self.assertFalse(b.should_clear(sda),
                         msg="disks containing protected devices should never "
                             "be cleared")
        sda1.protected = False

        #
        # clearpart type all
        #
        b.config.clear_part_type = CLEAR_PARTITIONS_ALL
        self.assertTrue(b.should_clear(sda1),
                        msg="type all should clear all partitions")
        self.assertTrue(b.should_clear(sda2),
                        msg="type all should clear all partitions")

        b.config.initialize_disks = False
        self.assertTrue(b.should_clear(sda),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdb),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdc),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdd),
                        msg="type all should initialize all disks")

        b.config.initialize_disks = True
        self.assertTrue(b.should_clear(sda),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdb),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdc),
                        msg="type all should initialize all disks")
        self.assertTrue(b.should_clear(sdd),
                        msg="type all should initialize all disks")

        sda1.protected = True
        self.assertFalse(b.should_clear(sda1),
                         msg="protected devices should never be cleared")
        self.assertFalse(b.should_clear(sda),
                         msg="disks containing protected devices should never "
                             "be cleared")
        sda1.protected = False