예제 #1
0
 def test_from_device_file_no_device_file(self, tmpdir, a_context):
     filename = tmpdir.join('test')
     filename.ensure(file=True)
     with pytest.raises(DeviceNotFoundByFileError) as excinfo:
         Devices.from_device_file(a_context, str(filename))
     message = 'not a device file: {0!r}'.format(str(filename))
     assert str(excinfo.value) == message
예제 #2
0
 def test_from_path_strips_leading_slash(self, a_context, a_device):
     """
     from_path() yields the same value, even if initial '/' is missing.
     """
     path = a_device.device_path
     assert Devices.from_path(a_context, path[1:]) == \
            Devices.from_path(a_context, path)
예제 #3
0
 def test_from_sys_path_device_not_found(self, a_context):
     sys_path = 'there_will_not_be_such_a_device'
     with pytest.raises(DeviceNotFoundAtPathError) as exc_info:
         Devices.from_sys_path(a_context, sys_path)
     error = exc_info.value
     assert error.sys_path == sys_path
     assert str(error) == 'No device at {0!r}'.format(sys_path)
예제 #4
0
 def test_from_device_file_no_device_file(self, tmpdir, a_context):
     filename = tmpdir.join('test')
     filename.ensure(file=True)
     with pytest.raises(DeviceNotFoundByFileError) as excinfo:
         Devices.from_device_file(a_context, str(filename))
     message = 'not a device file: {0!r}'.format(str(filename))
     assert str(excinfo.value) == message
예제 #5
0
 def test_from_sys_path_device_not_found(self, a_context):
     sys_path = 'there_will_not_be_such_a_device'
     with pytest.raises(DeviceNotFoundAtPathError) as exc_info:
         Devices.from_sys_path(a_context, sys_path)
     error = exc_info.value
     assert error.sys_path == sys_path
     assert str(error) == 'No device at {0!r}'.format(sys_path)
예제 #6
0
        def test_from_name_is_path(self, a_context, a_device):
            """
            Lookup using a sys_name which is actually a path should always fail.

            See: rhbz#1263351.
            """
            with pytest.raises(DeviceNotFoundByNameError):
                Devices.from_name(a_context, a_device.subsystem, a_device.sys_name)
예제 #7
0
 def test_from_name_nonexisting_subsystem(self, a_context):
     with pytest.raises(DeviceNotFoundByNameError) as exc_info:
         Devices.from_name(a_context, 'no_such_subsystem', 'foobar')
     error = exc_info.value
     assert error.subsystem == 'no_such_subsystem'
     assert error.sys_name == 'foobar'
     assert str(error) == 'No device {0!r} in {1!r}'.format(
         error.sys_name, error.subsystem)
예제 #8
0
 def test_from_name_nonexisting_subsystem(self, a_context):
     with pytest.raises(DeviceNotFoundByNameError) as exc_info:
         Devices.from_name(a_context, 'no_such_subsystem', 'foobar')
     error = exc_info.value
     assert error.subsystem == 'no_such_subsystem'
     assert error.sys_name == 'foobar'
     assert str(error) == 'No device {0!r} in {1!r}'.format(
         error.sys_name, error.subsystem)
예제 #9
0
 def test_from_device_file_non_existing(self, tmpdir, a_context):
     """
     Test that an OSError is raised when constructing a ``Device`` from
     a file that does not actually exist.
     """
     filename = tmpdir.join('test_from_device_file_non_existing')
     assert not tmpdir.check(file=True)
     with pytest.raises(DeviceNotFoundByFileError):
         Devices.from_device_file(a_context, str(filename))
예제 #10
0
        def test_from_name_is_path(self, a_context, a_device):
            """
            Lookup using a sys_name which is actually a path should always fail.

            See: rhbz#1263351.
            """
            with pytest.raises(DeviceNotFoundByNameError):
                Devices.from_name(a_context, a_device.subsystem,
                                  a_device.sys_name)
예제 #11
0
 def test_from_sys_path_device_not_found(self):
     """
     Verify that a non-existant sys_path causes an exception.
     """
     sys_path = 'there_will_not_be_such_a_device'
     with pytest.raises(DeviceNotFoundAtPathError) as exc_info:
         Devices.from_sys_path(_CONTEXT, sys_path)
     error = exc_info.value
     assert error.sys_path == sys_path
예제 #12
0
 def test_from_name_nonexisting_subsystem(self):
     """
     Verify that a non-existant subsystem causes an exception.
     """
     with pytest.raises(DeviceNotFoundByNameError) as exc_info:
         Devices.from_name(_CONTEXT, 'no_such_subsystem', 'foobar')
     error = exc_info.value
     assert error.subsystem == 'no_such_subsystem'
     assert error.sys_name == 'foobar'
예제 #13
0
def _check_device(device):
    """
    Check that device exists by getting it.
    """
    try:
        Devices.from_path(_CONTEXT, device.sys_path)
        return True
    except DeviceNotFoundError:
        return False
예제 #14
0
def _check_device(device):
    """
    Check that device exists by getting it.
    """
    try:
        Devices.from_path(_CONTEXT, device.sys_path)
        return True
    except DeviceNotFoundError:
        return False
예제 #15
0
 def test_from_device_file_non_existing(self, tmpdir):
     """
     Test that an OSError is raised when constructing a ``Device`` from
     a file that does not actually exist.
     """
     filename = tmpdir.join('test_from_device_file_non_existing')
     assert not tmpdir.check(file=True)
     with pytest.raises(DeviceNotFoundByFileError):
         Devices.from_device_file(_CONTEXT, str(filename))
예제 #16
0
 def test_from_device_file_no_device_file(self, tmpdir):
     """
     Verify that a file that is not a device file will cause an exception
     to be raised.
     """
     filename = tmpdir.join('test')
     filename.ensure(file=True)
     with pytest.raises(DeviceNotFoundByFileError):
         Devices.from_device_file(_CONTEXT, str(filename))
예제 #17
0
 def test_from_name_no_device_in_existing_subsystem(self, a_context,
                                                    subsys):
     """
     Verify that a real subsystem and non-existant name causes an
     exception to be raised.
     """
     with pytest.raises(DeviceNotFoundByNameError) as exc_info:
         Devices.from_name(a_context, subsys, 'foobar')
     error = exc_info.value
     assert error.subsystem == subsys
     assert error.sys_name == 'foobar'
예제 #18
0
 def test_from_kernel_device(self, a_context, entry):
     """
     Test that kernel devices can be obtained.
     """
     kernel_device = entry['_KERNEL_DEVICE']
     device = Devices.from_kernel_device(a_context, kernel_device)
     assert device is not None
예제 #19
0
 def test_getitem(self, a_context, device_datum):
     """
     Test that attribute value exists and is instance of bytes.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert all(isinstance(device.attributes.get(key), bytes) \
        for key in device_datum.attributes.keys())
예제 #20
0
 def test_from_device_file(self, a_context, device_datum):
     device = Devices.from_device_file(
        a_context,
        device_datum.device_node
     )
     assert device.device_node == device_datum.device_node
     assert device.device_path == device_datum.device_path
예제 #21
0
 def test_key_subset(self, a_context, device_datum):
     """
     Verify that the device contains all the keys in the device datum.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert frozenset(device_datum.properties.keys()) <= \
        frozenset(device.properties.keys())
예제 #22
0
 def test_asstring(self, a_context, device_datum):
     """
     Test that attribute exists for actual device and is unicode.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert all(is_unicode_string(device.attributes.asstring(key)) \
        for key in device_datum.attributes.keys())
예제 #23
0
 def test_iteration_and_contains(self, a_context, device_datum):
     """
     Test that iteration yields all tags and contains checks them.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert frozenset(device.tags) == frozenset(device_datum.tags)
     assert all(is_unicode_string(tag) for tag in device.tags)
예제 #24
0
 def test_getitem(self, a_context, device_datum):
     """
     Test that attribute value exists and is instance of bytes.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert all(isinstance(device.attributes.get(key), bytes) \
        for key in device_datum.attributes.keys())
    def test_events_real(self, context, monitor):
        # make sure that the module is unloaded initially
        pytest.unload_dummy()
        monitor.filter_by('net')
        monitor.start()
        self.prepare_test(monitor)
        # setup signal handlers
        event_callback = mock.Mock(side_effect=self.stop_when_done)
        added_callback = mock.Mock(side_effect=self.stop_when_done)
        removed_callback = mock.Mock(side_effect=self.stop_when_done)
        self.connect_signal(event_callback)
        self.connect_signal(added_callback, action='add')
        self.connect_signal(removed_callback, action='remove')

        # test add event
        self.start_event_loop(pytest.load_dummy)
        device = Devices.from_path(context, '/devices/virtual/net/dummy0')
        event_callback.assert_called_with('add', device)
        added_callback.assert_called_with(device)
        assert not removed_callback.called

        for callback in (event_callback, added_callback, removed_callback):
            callback.reset_mock()

        self.start_event_loop(pytest.unload_dummy)
        event_callback.assert_called_with('remove', device)
        assert not added_callback.called
        removed_callback.assert_called_with(device)
예제 #26
0
 def test_iteration_and_contains(self, a_context, device_datum):
     """
     Test that iteration yields all tags and contains checks them.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert frozenset(device.tags) == frozenset(device_datum.tags)
     assert all(is_unicode_string(tag) for tag in device.tags)
예제 #27
0
    def map_nvme(self, info, acpihandles):
        mapped = info[-1]
        num_of_nvme_slots = info[-2]
        ctx = Context()
        for i in filter(lambda x: x.attributes.get('path') in acpihandles,
                        ctx.list_devices(subsystem='acpi')):
            acpi_handle = i.attributes.get('path')
            try:
                phys_node = Devices.from_path(ctx,
                                              f'{i.sys_path}/physical_node')
            except DeviceNotFoundAtPathError:
                return info

            slot = acpihandles[acpi_handle]
            for nvme in filter(lambda x: x.sys_name.startswith('nvme'),
                               phys_node.children):
                mapped[slot] = nvme.sys_name
                break
            else:
                mapped[slot] = None

            if len(mapped) == num_of_nvme_slots:
                return info

        return info
예제 #28
0
 def test_getitem_devname(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     data_devname = os.path.join(
         a_context.device_path, device_datum.properties['DEVNAME'])
     device_devname = \
        os.path.join(a_context.device_path, device.properties['DEVNAME'])
     assert device_devname == data_devname
예제 #29
0
 def test_from_device_file(self, a_context, device_datum):
     device = Devices.from_device_file(
        a_context,
        device_datum.device_node
     )
     assert device.device_node == device_datum.device_node
     assert device.device_path == device_datum.device_path
예제 #30
0
 def test_asstring(self, a_context, device_datum):
     """
     Test that attribute exists for actual device and is unicode.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert all(is_unicode_string(device.attributes.asstring(key)) \
        for key in device_datum.attributes.keys())
예제 #31
0
 def test_from_kernel_device(self, a_context, entry):
     """
     Test that kernel devices can be obtained.
     """
     kernel_device = entry['_KERNEL_DEVICE']
     device = Devices.from_kernel_device(a_context, kernel_device)
     assert device is not None
예제 #32
0
    def test_events_real(self, context, monitor):
        # make sure that the module is unloaded initially
        pytest.unload_dummy()
        monitor.filter_by('net')
        monitor.start()
        self.prepare_test(monitor)
        # setup signal handlers
        event_callback = mock.Mock(side_effect=self.stop_when_done)
        added_callback = mock.Mock(side_effect=self.stop_when_done)
        removed_callback = mock.Mock(side_effect=self.stop_when_done)
        self.connect_signal(event_callback)
        self.connect_signal(added_callback, action='add')
        self.connect_signal(removed_callback, action='remove')

        # test add event
        self.start_event_loop(pytest.load_dummy)
        device = Devices.from_path(context, '/devices/virtual/net/dummy0')
        event_callback.assert_called_with('add', device)
        added_callback.assert_called_with(device)
        assert not removed_callback.called

        for callback in (event_callback, added_callback, removed_callback):
            callback.reset_mock()

        self.start_event_loop(pytest.unload_dummy)
        event_callback.assert_called_with('remove', device)
        assert not added_callback.called
        removed_callback.assert_called_with(device)
    def findGoodWeUSBDevice(self, vendorId, modelId):
        context = Context()

        # directory = "/dev/bus/usb/001/"
        directory = "/dev/"
        usb_list = [d for d in os.listdir("/dev") if d.startswith("hidraw")]
        # usb_list = [d for d in os.listdir(directory)]
        self.log.debug(usb_list)

        for hidraw in usb_list:
            # device = directory + hidraw
            device = "/dev/" + hidraw

            try:
                udev = Devices.from_device_file(context, device)
                self.log.debug(udev['DEVPATH'])

                if udev['DEVPATH'].find(vendorId + ":" + modelId) > -1:
                    self.log.debug("Using: %s", hidraw)
                    return device

            except Exception as e:
                self.log.debug(e)
                pass

        return None
예제 #34
0
 def test_length(self, a_context, device_datum):
     """
     Verify that the keys in the device and in the datum are equal.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     assert frozenset(device_datum.properties.keys()) == \
        frozenset(device.properties.keys())
예제 #35
0
 def test_from_device_number(self, a_context, device_datum):
     mode = os.stat(device_datum.device_node).st_mode
     typ = 'block' if stat.S_ISBLK(mode) else 'char'
     device = Devices.from_device_number(
         a_context, typ, device_datum.device_number)
     assert device.device_number == device_datum.device_number
     # make sure, we are really referring to the same device
     assert device.device_path == device_datum.device_path
예제 #36
0
 def test_iteration(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for property in device:
         assert is_unicode_string(property)
     # test that iteration really yields all properties
     device_properties = set(device)
     for property in device_datum.properties:
         assert property in device_properties
예제 #37
0
 def __isCDInserted(self) -> bool:
     # using another udev context - running in a different thread
     try:
         context = pyudev.Context()
         device = Devices.from_device_file(context, DEV_CDROM)
         return MEDIA_TRACK_COUNT_AUDIO_UDEV_TAG in device
     except Exception:
         return False
예제 #38
0
 def test_from_device_number(self, a_context, device_datum):
     mode = os.stat(device_datum.device_node).st_mode
     typ = 'block' if stat.S_ISBLK(mode) else 'char'
     device = Devices.from_device_number(
         a_context, typ, device_datum.device_number)
     assert device.device_number == device_datum.device_number
     # make sure, we are really referring to the same device
     assert device.device_path == device_datum.device_path
예제 #39
0
 def test_iteration(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for property in device:
         assert is_unicode_string(property)
     # test that iteration really yields all properties
     device_properties = set(device)
     for property in device_datum.properties:
         assert property in device_properties
예제 #40
0
 def test_from_name(self, a_context, a_device):
     """
     Test that getting a new device based on the name and subsystem
     yields an equivalent device.
     """
     new_device = Devices.from_name(a_context, a_device.subsystem,
                                    a_device.sys_name)
     assert new_device == a_device
예제 #41
0
 def test_from_journal_name(self, a_context, entry):
     """
     Test that kernel subsystem combined with udev sysname yields
     a device.
     """
     udev_sysname = entry['_UDEV_SYSNAME']
     subsystem = entry['_KERNEL_SUBSYSTEM']
     device = Devices.from_name(a_context, subsystem, udev_sysname)
     assert device is not None
예제 #42
0
 def test_from_journal_name(self, a_context, entry):
     """
     Test that kernel subsystem combined with udev sysname yields
     a device.
     """
     udev_sysname = entry['_UDEV_SYSNAME']
     subsystem = entry['_KERNEL_SUBSYSTEM']
     device = Devices.from_name(a_context, subsystem, udev_sysname)
     assert device is not None
예제 #43
0
 def test_from_device_number(self, a_context, a_device):
     """
     Verify that from_device_number() yields the correct device.
     """
     mode = os.stat(a_device.device_node).st_mode
     typ = 'block' if stat.S_ISBLK(mode) else 'char'
     device = \
        Devices.from_device_number(a_context, typ, a_device.device_number)
     assert a_device == device
예제 #44
0
 def test_asint(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for property, value in device_datum.properties.items():
         try:
             value = int(value)
         except ValueError:
             with pytest.raises(ValueError):
                 device.asint(property)
         else:
             assert device.asint(property) == value
예제 #45
0
 def test_asint(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for property, value in device_datum.properties.items():
         try:
             value = int(value)
         except ValueError:
             with pytest.raises(ValueError):
                 device.asint(property)
         else:
             assert device.asint(property) == value
예제 #46
0
 def test_asbool(self, a_context, device_datum):
     """
     Test that bool result is a bool or ValueError raised.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     for key, value in device_datum.attributes.items():
         if value in ('0', '1'):
             assert device.attributes.asbool(key) in (False, True)
         else:
             with pytest.raises(ValueError):
                 device.attributes.asbool(key)
예제 #47
0
 def test_asint(self, a_context, device_datum):
     """
     Test that integer result is an int or ValueError raised.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     for key, value in device_datum.attributes.items():
         try:
             value = int(value)
         except ValueError:
             with pytest.raises(ValueError):
                 device.attributes.asint(key)
예제 #48
0
 def test_getitem(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for prop in device_datum.properties:
         if prop == 'DEVLINKS':
             assert sorted(device.properties[prop].split(),) == \
                sorted(device_datum.properties[prop].split(),)
         elif prop == 'TAGS':
             assert sorted(device.properties[prop].split(':'),) == \
                sorted(device_datum.properties[prop].split(':'),)
         else:
             assert device.properties[prop] == device_datum.properties[prop]
예제 #49
0
 def test_asint(self, a_context, device_datum):
     """
     Test that integer result is an int or ValueError raised.
     """
     device = Devices.from_path(a_context, device_datum.device_path)
     for key, value in device_datum.attributes.items():
         try:
             value = int(value)
         except ValueError:
             with pytest.raises(ValueError):
                 device.attributes.asint(key)
예제 #50
0
    def test_from_device_file_links(self, a_context, device_datum):
        """
        For each link in DEVLINKS, test that the constructed device's
        path matches the orginal devices path.

        This does not hold true in the case of multipath. In this case
        udevadm's DEVLINKS fields holds some links that do not actually
        point to the originating device.

        See: https://bugzilla.redhat.com/show_bug.cgi?id=1263441.
        """
        device = Devices.from_path(a_context, device_datum.device_path)
        assume(not 'DM_MULTIPATH_TIMESTAMP' in device)

        for link in device_datum.device_links:
            link = os.path.join(a_context.device_path, link)

            device = Devices.from_device_file(a_context, link)
            assert device.device_path == device_datum.device_path
            assert link in device.device_links
예제 #51
0
 def test_from_name(self, a_context, a_device):
     """
     Test that getting a new device based on the name and subsystem
     yields an equivalent device.
     """
     new_device = Devices.from_name(
        a_context,
        a_device.subsystem,
        a_device.sys_name
     )
     assert new_device == a_device
예제 #52
0
 def test_asbool(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for prop, value in device_datum.properties.items():
         if value == '1':
             assert device.asbool(prop)
         elif value == '0':
             assert not device.asbool(prop)
         else:
             with pytest.raises(ValueError) as exc_info:
                 device.asbool(prop)
             message = 'Not a boolean value: {0!r}'
             assert str(exc_info.value) == message.format(value)
예제 #53
0
    def test_asbool(self, a_context, device_datum):
        """
        Test that values of 1 and 0 get properly interpreted as bool
        and that all other values raise a ValueError.

        :param Context a_context: libudev context
        :param device_datum: a device datum
        """
        device = Devices.from_path(a_context, device_datum.device_path)
        for prop, value in device_datum.properties.items():
            if value == '1':
                assert device.properties.asbool(prop)
            elif value == '0':
                assert not device.properties.asbool(prop)
            else:
                with pytest.raises(ValueError) as exc_info:
                    device.properties.asbool(prop)
예제 #54
0
    def test_events_real(self, context, monitor):
        # make sure that the module is unloaded initially
        pytest.unload_dummy()
        monitor.filter_by('net')
        monitor.start()
        self.prepare_test(monitor)
        # setup signal handlers
        event_callback = mock.Mock(
            side_effect=lambda *args: self.stop_event_loop())
        self.connect_signal(event_callback)

        # test add event
        self.start_event_loop(pytest.load_dummy)
        device = Devices.from_path(context, '/devices/virtual/net/dummy0')
        event_callback.assert_called_with(device)

        event_callback.reset_mock()

        self.start_event_loop(pytest.unload_dummy)
        event_callback.assert_called_with(device)
예제 #55
0
 def test_from_device_number_wrong_type(
     self,
     a_context,
     device_datum
 ):
     mode = os.stat(device_datum.device_node).st_mode
     # deliberately use the wrong type here to cause either failure
     # or at least device mismatch
     typ = 'char' if stat.S_ISBLK(mode) else 'block'
     try:
         # this either fails, in which case the caught exception is
         # raised, or succeeds, but returns a wrong device
         # (device numbers are not unique across device types)
         device = Devices.from_device_number(
             a_context, typ, device_datum.device_number)
         # if it succeeds, the resulting device must not match the
         # one, we are actually looking for!
         assert device.device_path != device_datum.device_path
     except DeviceNotFoundByNumberError as error:
         # check the correctness of the exception attributes
         assert error.device_type == typ
         assert error.device_number == device_datum.device_number
예제 #56
0
 def test_getitem(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     for prop in device_datum.properties:
         assert device[prop] == device_datum.properties[prop]
예제 #57
0
 def test_length(self, a_context, device_datum):
     device = Devices.from_path(a_context, device_datum.device_path)
     assert len(device) == len(device_datum.properties)