def test_returns_False_with_DBusException(self): connection_pid = self.getUniqueInteger() dbus_tuple = ("bus", "org.freedesktop.DBus") params = dict(pid=connection_pid) with patch.object(_s, '_get_bus_connections_pid', side_effect=DBusException()): self.assertFalse(_s.ConnectionHasPid.matches(dbus_tuple, params))
def test_proxy_instance_raises_uncaught_dbus_exceptions(self): query = xpathselect.Query.root('foo') e = DBusException() fake_dbus_address = Mock() fake_dbus_address.introspection_iface.GetState.side_effect = e backend = backends.Backend(fake_dbus_address) self.assertRaises(DBusException, backend.execute_query_get_data, query)
def test_proxy_instance_catches_unknown_service_exception(self): query = xpathselect.Query.root('foo') e = DBusException(name='org.freedesktop.DBus.Error.ServiceUnknown') fake_dbus_address = Mock() fake_dbus_address.introspection_iface.GetState.side_effect = e backend = backends.Backend(fake_dbus_address) self.assertRaises(RuntimeError, backend.execute_query_get_data, query)
def Set(self, property_name, new_value, sender=None): property_name = dbus_utils.dbus_to_python(property_name, str) new_value = dbus_utils.dbus_to_python(new_value, str) section, _dot, property_name = property_name.partition('.') if not property_name: raise DBusException( "Setting an entire section is not supported. Use 'section.property' format." ) self.config[section][property_name] = new_value self.config.persist()
def test_unknown_service_exception_gives_correct_msg(self): query = xpathselect.Query.root('foo') e = DBusException(name='org.freedesktop.DBus.Error.ServiceUnknown') fake_dbus_address = Mock() fake_dbus_address.introspection_iface.GetState.side_effect = e backend = backends.Backend(fake_dbus_address) try: backend.execute_query_get_data(query) except RuntimeError as e: msg = ("Lost dbus backend communication. It appears the " "application under test exited before the test " "finished!") self.assertEqual(str(e), msg)
def test_returns_False_on_dbus_exception(self, Interface): bus_obj = Mock() connection_name = "name" path = "path" dbus_tuple = (bus_obj, connection_name) Interface.side_effect = DBusException() self.assertFalse( _s.ConnectionHasPathWithAPInterface.matches( dbus_tuple, dict(object_path=path))) bus_obj.get_object.assert_called_once_with("name", path)
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except DBusException, e: if e.get_dbus_name( ) != None and "DBus.Error.AccessDenied" in e.get_dbus_name(): error( None, language['access_denied'].replace( "$A", "<b>" + wpath.wicd_group + "</b>")) #raise raise DBusException(e) else: print "warning: ignoring exception %s" % e return None
def add_connection(settings): key = settings['802-11-wireless-security']['psk'] if key != 'the right key': raise DBusException( '802-11-wireless-security.psk: invalid value', name='org.freedesktop.NetworkManager.Settings.InvalidProperty') ssid = settings['802-11-wireless']['ssid'] connection = NMConnection(True, ssid=ssid) NMSettings.ListConnections.side_effect = lambda: [connection] NM.ActiveConnections.append(NMActiveConnection(ssid=connection.ssid)) return connection
def restart(self, name: str) -> (int, str): """ Try to restart the service. :param name: service name (e.g. database.service) :return: tuple of (return code, status message) """ try: rc_stop, msg_stop = self.stop(name) rc_start, msg_start = self.start(name) if rc_stop + rc_start == 0: return 0, {'status': 'restarted'} else: raise DBusException('failed to restart service') except DBusException as e: return 1, {'error': str(e)}
def Set(self, property_name, new_value, locale, sender=None): """ Method used for setting only one value. When more than one value is going to be set, then it is strongly recomended to use method SetAll(), because configuration is saved to the configuration file at the end of method Set() :param property_name: string with property e.g. server.hostname :param new_value: string with new value :param locale: string with locale :param sender: not used :return: None """ property_name = dbus_utils.dbus_to_python(property_name, expected_type=str) new_value = dbus_utils.dbus_to_python(new_value, expected_type=str) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) section, _dot, property_name = property_name.partition(".") if not property_name: raise DBusException( "Setting an entire section is not supported. Use 'section.property' format." ) self.config[section][property_name] = new_value if section == "logging": logging_changed = True else: logging_changed = False # Try to temporary disable dir watcher, because 'self.config.persist()' writes configuration # file and it would trigger file system monitor callback function and saved values would be # read again. It can cause race conditions, when Set() is called multiple times Server.temporary_disable_dir_watchers({CONFIG_WATCHER}) # Write new config value to configuration file self.config.persist() Server.enable_dir_watchers({CONFIG_WATCHER}) # When anything in logging section was just chnaged, then we have to re-initialize logger if logging_changed is True: parser = rhsm.config.get_config_parser() self.config = Config(parser) rhsm.logutil.init_logger(parser)
def SetAll(self, configuration, locale, sender=None): """ Method for setting multiple configuration options. Of course all of them could be set. :param configuration: d-bus dictionary with configuration. Keys have to include section. e.g. server.hostname. Configuration file is saved to the file at the end of method. :param locale: string with locale :param sender: not used :return: None """ configuration = dbus_utils.dbus_to_python(configuration, expected_type=dict) locale = dbus_utils.dbus_to_python(locale, expected_type=str) Locale.set(locale) log.debug("Setting new configuration values: %s" % str(configuration)) logging_changed = False for property_name, new_value in configuration.items(): section_name, _dot, property_name = property_name.partition(".") if not property_name: raise DBusException( "Setting an entire section is not supported. Use 'section.property' format." ) self.config[section_name][property_name] = new_value if section_name == "logging": logging_changed = True # Try to temporary disable dir watcher, because 'self.config.persist()' writes configuration # file and it would trigger file system monitor callback function and saved values would be # read again. It can cause race conditions, when SetAll() is called multiple times Server.temporary_disable_dir_watchers({CONFIG_WATCHER}) # Write new config value to configuration file self.config.persist() Server.enable_dir_watchers({CONFIG_WATCHER}) # When anything in logging section was just changed, then we have to re-initialize logger if logging_changed is True: parser = rhsm.config.get_config_parser() self.config = Config(parser) rhsm.logutil.init_logger(parser)
def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except DBusException as e: if e.get_dbus_name() is not None and \ "DBus.Error.AccessDenied" in e.get_dbus_name(): error( None, _('Unable to contact the Wicd daemon due to an access ' 'denied error from DBus. Please check that your user is ' 'in the $A group.').replace( "$A", "<b>" + wpath.wicd_group + "</b>")) #raise raise DBusException(e) else: print(("warning: ignoring exception %s" % e)) return None
class ConnectionIsNotOurConnectionTests(TestCase): @patch.object(_s, '_get_bus_connections_pid') def test_doesnt_raise_exception_with_no_parameters(self, get_bus_pid): dbus_tuple = ("bus", "name") _s.ConnectionIsNotOurConnection.matches(dbus_tuple, {}) @patch.object(_s, '_get_bus_connections_pid', return_value=0) def test_returns_True_when_pid_isnt_our_connection(self, get_bus_pid): dbus_tuple = ("bus", "name") self.assertTrue(_s.ConnectionIsNotOurConnection.matches( dbus_tuple, {})) @patch.object(_s, '_get_bus_connections_pid', return_value=os.getpid()) def test_returns_False_when_pid_is_our_connection(self, get_bus_pid): dbus_tuple = ("bus", "name") self.assertFalse( _s.ConnectionIsNotOurConnection.matches(dbus_tuple, {})) @patch.object(_s, '_get_bus_connections_pid', side_effect=DBusException()) def test_returns_False_exception_raised(self, get_bus_pid): dbus_tuple = ("bus", "name") self.assertFalse( _s.ConnectionIsNotOurConnection.matches(dbus_tuple, {}))
class TestHardware(unittest.TestCase): @patch('hw_diag.utilities.hardware.get_public_keys_rust') def test_get_public_keys_no_error(self, mocked_get_public_keys_rust): mocked_get_public_keys_rust.return_value = { 'key': 'foo', 'name': 'bar' } keys = get_public_keys_and_ignore_errors() self.assertEqual(keys['key'], 'foo') self.assertEqual(keys['name'], 'bar') @patch('hw_diag.utilities.hardware.get_public_keys_rust') def test_get_public_keys_with_error(self, mocked_get_public_keys_rust): mocked_get_public_keys_rust.return_value = False keys = get_public_keys_and_ignore_errors() self.assertIsNone(keys['key']) self.assertIsNone(keys['name']) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_ble_devices_success(self, mocked_interface, _): # Prepare mocked BLE devices mocked_ble_devices = { '/org/bluez/hci0': { 'org.bluez.Adapter1': { 'Address': '00:E0:4C:19:D2:91', 'AddressType': 'public', 'Name': 'ble0', 'Alias': 'ble0', 'Class': '1835268', 'Powered': '1', 'Discoverable': '1', 'DiscoverableTimeout': 0, 'Pairable': '1', 'PairableTimeout': 0, 'Discovering': '0', 'UUIDs': [], 'Modalias': 'usb:v1D6Bp0246d0535' } } } # Set mocked BLE devices in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_ble_devices # Retrieve list of BLE devices ble_devices = get_ble_devices() # Assertion self.assertIsInstance(ble_devices, list) self.assertEqual(len(ble_devices), 1) self.assertDictEqual( ble_devices[0], { 'Address': '00:E0:4C:19:D2:91', 'Name': 'ble0', 'Powered': '1', 'Discoverable': '1', 'Pairable': '1', 'Discovering': '0', }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_ble_devices_no_devices(self, mocked_interface, _): # Prepare mocked BLE devices mocked_ble_devices = {} # Set mocked BLE devices in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_ble_devices # Retrieve list of BLE devices ble_devices = get_ble_devices() # Assertion self.assertIsInstance(ble_devices, list) self.assertEqual(len(ble_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface', side_effect=DBusException('Not authorized')) def test_get_ble_devices_exception(self, mocked_interface, _): # Prepare mocked BLE devices mocked_ble_devices = {} # Set mocked BLE devices in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_ble_devices # Retrieve list of BLE devices ble_devices = get_ble_devices() # Assertion self.assertIsInstance(ble_devices, list) self.assertEqual(len(ble_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_lte_devices_success(self, mocked_interface, _): # Make mocked modems modem0 = MagicMock() mocked_modems = [modem0] # Properties of a mocked modem with LTE capability mocked_modem0_properties = { 'Model': 'QUECTEL Mobile Broadband Module', 'Manufacturer': 'QUALCOMM INCORPORATED', 'CurrentCapabilities': 9, 'EquipmentIdentifier': '867698048214905', } # Set mocked modems and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems mocked_interface.GetAll.return_value = mocked_modem0_properties # Retrieve list of LTE devices lte_devices = get_lte_devices() # Assertion self.assertIsInstance(lte_devices, list) self.assertEqual(len(lte_devices), 1) self.assertDictEqual( lte_devices[0], { 'Model': 'QUECTEL Mobile Broadband Module', 'Manufacturer': 'QUALCOMM INCORPORATED', 'EquipmentIdentifier': '867698048214905', }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_lte_devices_missing_lte_capability(self, mocked_interface, _): # Make mocked modems modem0 = MagicMock() mocked_modems = [modem0] # Properties of a mocked modem without LTE capability mocked_modem0_properties = { 'Model': 'QUECTEL Mobile Broadband Module', 'Manufacturer': 'QUALCOMM INCORPORATED', 'CurrentCapabilities': 0, 'EquipmentIdentifier': '867698048214905', } # Set mocked modems and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems mocked_interface.GetAll.return_value = mocked_modem0_properties # Retrieve list of LTE devices lte_devices = get_lte_devices() # Assertion self.assertIsInstance(lte_devices, list) self.assertEqual(len(lte_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_lte_devices_no_devices(self, mocked_interface, _): # Make mocked modems mocked_modems = [] # Set mocked modems in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems # Retrieve list of LTE devices lte_devices = get_lte_devices() # Assertion self.assertIsInstance(lte_devices, list) self.assertEqual(len(lte_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface', side_effect=DBusException('Not authorized')) def test_get_lte_devices_exception(self, mocked_interface, _): # Make mocked modems mocked_modems = [] # Set mocked modems in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems # Retrieve list of LTE devices lte_devices = get_lte_devices() # Assertion self.assertIsInstance(lte_devices, list) self.assertEqual(len(lte_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_wifi_devices_success_state0(self, mocked_interface, _): # Make mocked NetworkManager devices nm_device0 = MagicMock() mocked_nm_devices = [nm_device0] # Properties of a mocked NetworkManager device(WiFi) mocked_nm_device0_properties = { 'Interface': 'wlx488ad22b280f', 'Driver': 'r8188eu', 'DriverVersion': '5.11.0-40-generic', 'Capabilities': 1, 'Ip4Address': 0, 'State': 100, 'Managed': '1', 'Autoconnect': '1', 'DeviceType': 2, 'Mtu': 1500, 'Real': '1', 'Ip4Connectivity': 1, 'Ip6Connectivity': 1, 'InterfaceFlags': 0 } # Set mocked NetworkManager devices and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetDevices.return_value = mocked_nm_devices mocked_interface.GetAll.return_value = mocked_nm_device0_properties # Retrieve list of WiFi devices wifi_devices = get_wifi_devices() # Assertion self.assertIsInstance(wifi_devices, list) self.assertEqual(len(wifi_devices), 1) self.assertDictEqual( wifi_devices[0], { 'Interface': 'wlx488ad22b280f', 'Type': 'Wi-Fi', 'Driver': 'r8188eu', 'State': 'Activated', }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_wifi_devices_success_state1(self, mocked_interface, _): # Make mocked NetworkManager devices nm_device0 = MagicMock() mocked_nm_devices = [nm_device0] # Properties of a mocked NetworkManager device(WiFi) mocked_nm_device0_properties = { 'Interface': 'wlx488ad22b280f', 'Driver': 'r8188eu', 'DriverVersion': '5.11.0-40-generic', 'Capabilities': 1, 'Ip4Address': 0, 'State': 20, 'Managed': '1', 'Autoconnect': '1', 'DeviceType': 2, 'Mtu': 1500, 'Real': '1', 'Ip4Connectivity': 1, 'Ip6Connectivity': 1, 'InterfaceFlags': 0 } # Set mocked NetworkManager devices and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetDevices.return_value = mocked_nm_devices mocked_interface.GetAll.return_value = mocked_nm_device0_properties # Retrieve list of WiFi devices wifi_devices = get_wifi_devices() # Assertion self.assertIsInstance(wifi_devices, list) self.assertEqual(len(wifi_devices), 1) self.assertDictEqual( wifi_devices[0], { 'Interface': 'wlx488ad22b280f', 'Type': 'Wi-Fi', 'Driver': 'r8188eu', 'State': 'Unavailable', }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_wifi_devices_no_wifi_devices(self, mocked_interface, _): # Make mocked NetworkManager devices nm_device0 = MagicMock() mocked_nm_devices = [nm_device0] # Properties of a mocked NetworkManager device(Ethernet) mocked_nm_device0_properties = { 'Interface': 'wlx488ad22b280f', 'Driver': 'r8188eu', 'DriverVersion': '5.11.0-40-generic', 'Capabilities': 1, 'Ip4Address': 0, 'State': 20, 'Managed': '1', 'Autoconnect': '1', 'DeviceType': 1, 'Mtu': 1500, 'Real': '1', 'Ip4Connectivity': 1, 'Ip6Connectivity': 1, 'InterfaceFlags': 0 } # Set mocked NetworkManager devices and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetDevices.return_value = mocked_nm_devices mocked_interface.GetAll.return_value = mocked_nm_device0_properties # Retrieve list of WiFi devices wifi_devices = get_wifi_devices() # Assertion self.assertIsInstance(wifi_devices, list) self.assertEqual(len(wifi_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_get_wifi_devices_no_nm_devices(self, mocked_interface, _): # Make mocked NetworkManager devices mocked_nm_devices = [] # Set mocked NetworkManager devices and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetDevices.return_value = mocked_nm_devices # Retrieve list of WiFi devices wifi_devices = get_wifi_devices() # Assertion self.assertIsInstance(wifi_devices, list) self.assertEqual(len(wifi_devices), 0) @patch('dbus.SystemBus') @patch('dbus.Interface', side_effect=DBusException('Not authorized')) def test_get_wifi_devices_exception(self, mocked_interface, _): # Make mocked NetworkManager devices mocked_nm_devices = [] # Set mocked NetworkManager devices and their properties in dbus mocked_interface = mocked_interface.return_value mocked_interface.GetDevices.return_value = mocked_nm_devices # Retrieve list of WiFi devices wifi_devices = get_wifi_devices() # Assertion self.assertIsInstance(wifi_devices, list) self.assertEqual(len(wifi_devices), 0)
class TestBtDiagnostic(unittest.TestCase): @patch('dbus.SystemBus') @patch('dbus.Interface') def test_success(self, mock_interface, mock_sys_bus): # Prepare mocked BT devices mock_bt_devices = { '/org/bluez/hci0': { 'org.bluez.Adapter1': { 'Address': '00:E0:4C:19:D2:91', 'AddressType': 'public', 'Name': 'ble0', 'Alias': 'ble0', 'Class': '1835268', 'Powered': '1', 'Discoverable': '1', 'DiscoverableTimeout': 0, 'Pairable': '1', 'PairableTimeout': 0, 'Discovering': '0', 'UUIDs': [], 'Modalias': 'usb:v1D6Bp0246d0535' } } } # Mock BT devices in dbus mock_interface = mock_interface.return_value mock_interface.GetManagedObjects.return_value = mock_bt_devices diagnostic = BtDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual( diagnostics_report, { DIAGNOSTICS_PASSED_KEY: True, DIAGNOSTICS_ERRORS_KEY: [], 'BT': [{ 'Address': '00:E0:4C:19:D2:91', 'Discoverable': '1', 'Discovering': '0', 'Name': 'ble0', 'Pairable': '1', 'Powered': '1' }], 'bluetooth': [{ 'Address': '00:E0:4C:19:D2:91', 'Discoverable': '1', 'Discovering': '0', 'Name': 'ble0', 'Pairable': '1', 'Powered': '1' }] }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_failure_no_devices(self, mock_interface, mock_sys_bus): # Prepare mocked BT devices mock_bt_devices = {} # Mock BT devices in dbus mock_interface = mock_interface.return_value mock_interface.GetManagedObjects.return_value = mock_bt_devices diagnostic = BtDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual( diagnostics_report, { DIAGNOSTICS_PASSED_KEY: False, DIAGNOSTICS_ERRORS_KEY: ['BT', 'bluetooth'], 'BT': 'Bluez is working but, no Bluetooth devices detected.', 'bluetooth': 'Bluez is working but, no Bluetooth devices detected.' }) @patch('dbus.SystemBus') @patch('dbus.Interface', side_effect=DBusException('Not authorized')) def test_failure_exception(self, mock_interface, mock_sys_bus): # Prepare mocked BT devices mock_bt_devices = {} # Mock BT devices in dbus mock_interface = mock_interface.return_value mock_interface.GetManagedObjects.return_value = mock_bt_devices diagnostic = BtDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual( diagnostics_report, { DIAGNOSTICS_PASSED_KEY: False, DIAGNOSTICS_ERRORS_KEY: ['BT', 'bluetooth'], 'BT': 'Not authorized', 'bluetooth': 'Not authorized' })
class TestLteDiagnostics(unittest.TestCase): @patch('dbus.SystemBus') @patch('dbus.Interface') def test_success(self, mock_interface, mock_sys_bus): # Make mocked modems modem0 = MagicMock() mock_modems = [modem0] # Properties of a mocked modem with LTE capability mock_modem0_properties = { 'Model': 'QUECTEL Mobile Broadband Module', 'Manufacturer': 'QUALCOMM INCORPORATED', 'CurrentCapabilities': 9, 'EquipmentIdentifier': '867698048214905', } # Set mocked modems and their properties in dbus mock_interface = mock_interface.return_value mock_interface.GetManagedObjects.return_value = mock_modems mock_interface.GetAll.return_value = mock_modem0_properties diagnostic = LteDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual(diagnostics_report, { DIAGNOSTICS_PASSED_KEY: True, DIAGNOSTICS_ERRORS_KEY: [], 'LTE': [ {'EquipmentIdentifier': '867698048214905', 'Manufacturer': 'QUALCOMM INCORPORATED', 'Model': 'QUECTEL Mobile Broadband Module'}], 'lte': [ {'EquipmentIdentifier': '867698048214905', 'Manufacturer': 'QUALCOMM INCORPORATED', 'Model': 'QUECTEL Mobile Broadband Module'}], }) @patch('dbus.SystemBus') @patch('dbus.Interface') def test_failure_no_devices(self, mock_interface, mock_sys_bus): # Make mocked modems mocked_modems = [] # Set mocked modems in dbus mocked_interface = mock_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems diagnostic = LteDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual(diagnostics_report, { DIAGNOSTICS_PASSED_KEY: False, DIAGNOSTICS_ERRORS_KEY: ['LTE', 'lte'], 'LTE': 'ModemManager is working but, no LTE devices detected.', 'lte': 'ModemManager is working but, no LTE devices detected.' }) @patch('dbus.SystemBus') @patch('dbus.Interface', side_effect=DBusException('Not authorized')) def test_failure_exception(self, mock_interface, mock_sys_bus): # Make mocked modems mocked_modems = [] # Set mocked modems in dbus mocked_interface = mock_interface.return_value mocked_interface.GetManagedObjects.return_value = mocked_modems diagnostic = LteDiagnostic() diagnostics_report = DiagnosticsReport([diagnostic]) diagnostics_report.perform_diagnostics() self.assertDictEqual(diagnostics_report, { DIAGNOSTICS_PASSED_KEY: False, DIAGNOSTICS_ERRORS_KEY: ['LTE', 'lte'], 'LTE': 'Not authorized', 'lte': 'Not authorized' })
def test_plugin_dbus_general(mock_mainloop, mock_byte, mock_bytearray, mock_interface, mock_sessionbus): """ NotifyDBus() General Tests """ # Our module base gi_name = 'gi' # First we do an import without the gi library available to ensure # we can handle cases when the library simply isn't available if gi_name in sys.modules: # Test cases where the gi library exists; we want to remove it # for the purpose of testing and capture the handling of the # library when it is missing del sys.modules[gi_name] reload(sys.modules['apprise.plugins.NotifyDBus']) # We need to fake our dbus environment for testing purposes since # the gi library isn't available in Travis CI gi = types.ModuleType(gi_name) gi.repository = types.ModuleType(gi_name + '.repository') mock_pixbuf = mock.Mock() mock_image = mock.Mock() mock_pixbuf.new_from_file.return_value = mock_image mock_image.get_width.return_value = 100 mock_image.get_height.return_value = 100 mock_image.get_rowstride.return_value = 1 mock_image.get_has_alpha.return_value = 0 mock_image.get_bits_per_sample.return_value = 8 mock_image.get_n_channels.return_value = 1 mock_image.get_pixels.return_value = '' gi.repository.GdkPixbuf = \ types.ModuleType(gi_name + '.repository.GdkPixbuf') gi.repository.GdkPixbuf.Pixbuf = mock_pixbuf # Emulate require_version function: gi.require_version = mock.Mock(name=gi_name + '.require_version') # Force the fake module to exist sys.modules[gi_name] = gi sys.modules[gi_name + '.repository'] = gi.repository # Exception Handling mock_mainloop.qt.DBusQtMainLoop.return_value = True mock_mainloop.qt.DBusQtMainLoop.side_effect = ImportError sys.modules['dbus.mainloop.qt'] = mock_mainloop.qt reload(sys.modules['apprise.plugins.NotifyDBus']) mock_mainloop.qt.DBusQtMainLoop.side_effect = None # Python v2.x mock_mainloop.glib.DBusGMainLoop.return_value = True mock_mainloop.glib.DBusGMainLoop.side_effect = ImportError() # Python 3.x mock_mainloop.glib.NativeMainLoop.return_value = True mock_mainloop.glib.NativeMainLoop.side_effect = ImportError() sys.modules['dbus.mainloop.glib'] = mock_mainloop.glib reload(sys.modules['apprise.plugins.NotifyDBus']) mock_mainloop.glib.DBusGMainLoop.side_effect = None mock_mainloop.glib.NativeMainLoop.side_effect = None # The following libraries need to be reloaded to prevent # TypeError: super(type, obj): obj must be an instance or subtype of type # This is better explained in this StackOverflow post: # https://stackoverflow.com/questions/31363311/\ # any-way-to-manually-fix-operation-of-\ # super-after-ipython-reload-avoiding-ty # reload(sys.modules['apprise.plugins.NotifyDBus']) reload(sys.modules['apprise.plugins']) reload(sys.modules['apprise.Apprise']) reload(sys.modules['apprise']) # Create our instance (identify all supported types) obj = apprise.Apprise.instantiate('dbus://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('dbus://_/') obj = apprise.Apprise.instantiate('kde://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('kde://_/') obj = apprise.Apprise.instantiate('qt://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('qt://_/') obj = apprise.Apprise.instantiate('glib://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('glib://_/') obj.duration = 0 # Test our class loading using a series of arguments with pytest.raises(TypeError): apprise.plugins.NotifyDBus(**{'schema': 'invalid'}) # Set our X and Y coordinate and try the notification assert apprise.plugins.NotifyDBus( x_axis=0, y_axis=0, **{'schema': 'dbus'})\ .notify(title='', body='body', notify_type=apprise.NotifyType.INFO) is True # test notifications assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # test notification without a title assert obj.notify( title='', body='body', notify_type=apprise.NotifyType.INFO) is True # Test our arguments through the instantiate call obj = apprise.Apprise.instantiate('dbus://_/?image=True', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('dbus://_/') assert re.search('image=yes', obj.url()) assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?image=False', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.url().startswith('dbus://_/') assert re.search('image=no', obj.url()) assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Test priority (alias to urgency) handling obj = apprise.Apprise.instantiate('dbus://_/?priority=invalid', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?priority=high', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?priority=2', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Test urgency handling obj = apprise.Apprise.instantiate('dbus://_/?urgency=invalid', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?urgency=high', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?urgency=2', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True obj = apprise.Apprise.instantiate('dbus://_/?urgency=', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Test x/y obj = apprise.Apprise.instantiate('dbus://_/?x=5&y=5', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True assert isinstance(obj.url(), six.string_types) is True assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True with pytest.raises(TypeError): obj = apprise.Apprise.instantiate('dbus://_/?x=invalid&y=invalid', suppress_exceptions=False) # Test configuration parsing content = """ urls: - dbus://: - priority: 0 tag: dbus_int low - priority: "0" tag: dbus_str_int low - priority: low tag: dbus_str low - urgency: 0 tag: dbus_int low - urgency: "0" tag: dbus_str_int low - urgency: low tag: dbus_str low # These will take on normal (default) urgency - priority: invalid tag: dbus_invalid - urgency: invalid tag: dbus_invalid - dbus://: - priority: 2 tag: dbus_int high - priority: "2" tag: dbus_str_int high - priority: high tag: dbus_str high - urgency: 2 tag: dbus_int high - urgency: "2" tag: dbus_str_int high - urgency: high tag: dbus_str high """ # Create ourselves a config object ac = apprise.AppriseConfig() assert ac.add_config(content=content) is True aobj = apprise.Apprise() # Add our configuration aobj.add(ac) # We should be able to read our 14 servers from that # 6x low # 6x high # 2x invalid (so takes on normal urgency) assert len(ac.servers()) == 14 assert len(aobj) == 14 assert len([x for x in aobj.find(tag='low')]) == 6 for s in aobj.find(tag='low'): assert s.urgency == DBusUrgency.LOW assert len([x for x in aobj.find(tag='high')]) == 6 for s in aobj.find(tag='high'): assert s.urgency == DBusUrgency.HIGH assert len([x for x in aobj.find(tag='dbus_str')]) == 4 assert len([x for x in aobj.find(tag='dbus_str_int')]) == 4 assert len([x for x in aobj.find(tag='dbus_int')]) == 4 assert len([x for x in aobj.find(tag='dbus_invalid')]) == 2 for s in aobj.find(tag='dbus_invalid'): assert s.urgency == DBusUrgency.NORMAL # If our underlining object throws for whatever rea on, we will # gracefully fail mock_notify = mock.Mock() mock_interface.return_value = mock_notify mock_notify.Notify.side_effect = AttributeError() assert obj.notify( title='', body='body', notify_type=apprise.NotifyType.INFO) is False mock_notify.Notify.side_effect = None # Test our loading of our icon exception; it will still allow the # notification to be sent mock_pixbuf.new_from_file.side_effect = AttributeError() assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Undo our change mock_pixbuf.new_from_file.side_effect = None # Test our exception handling during initialization # Toggle our testing for when we can't send notifications because the # package has been made unavailable to us obj.enabled = False assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is False # Test the setting of a the urgency apprise.plugins.NotifyDBus(urgency=0) # # We can still notify if the gi library is the only inaccessible # compontent # # Emulate require_version function: gi.require_version.side_effect = ImportError() # The following libraries need to be reloaded to prevent # TypeError: super(type, obj): obj must be an instance or subtype of type # This is better explained in this StackOverflow post: # https://stackoverflow.com/questions/31363311/\ # any-way-to-manually-fix-operation-of-\ # super-after-ipython-reload-avoiding-ty # reload(sys.modules['apprise.plugins.NotifyDBus']) reload(sys.modules['apprise.plugins']) reload(sys.modules['apprise.Apprise']) reload(sys.modules['apprise']) # Create our instance obj = apprise.Apprise.instantiate('glib://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True obj.duration = 0 # Test url() call assert isinstance(obj.url(), six.string_types) is True # Our notification succeeds even though the gi library was not loaded assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Verify this all works in the event a ValueError is also thronw # out of the call to gi.require_version() mock_sessionbus.side_effect = DBusException('test') # Handle Dbus Session Initialization error assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is False # Return side effect to normal mock_sessionbus.side_effect = None # Emulate require_version function: gi.require_version.side_effect = ValueError() # The following libraries need to be reloaded to prevent # TypeError: super(type, obj): obj must be an instance or subtype of type # This is better explained in this StackOverflow post: # https://stackoverflow.com/questions/31363311/\ # any-way-to-manually-fix-operation-of-\ # super-after-ipython-reload-avoiding-ty # reload(sys.modules['apprise.plugins.NotifyDBus']) reload(sys.modules['apprise.plugins']) reload(sys.modules['apprise.Apprise']) reload(sys.modules['apprise']) # Create our instance obj = apprise.Apprise.instantiate('glib://', suppress_exceptions=False) assert isinstance(obj, apprise.plugins.NotifyDBus) is True obj.duration = 0 # Test url() call assert isinstance(obj.url(), six.string_types) is True # Our notification succeeds even though the gi library was not loaded assert obj.notify(title='title', body='body', notify_type=apprise.NotifyType.INFO) is True # Force a global import error _session_bus = sys.modules['dbus'] sys.modules['dbus'] = compile('raise ImportError()', 'dbus', 'exec') # Reload our modules reload(sys.modules['apprise.plugins.NotifyDBus']) reload(sys.modules['apprise.plugins']) reload(sys.modules['apprise.Apprise']) reload(sys.modules['apprise']) # We can no longer instantiate an instance because dbus has been # officialy marked unavailable and thus the module is marked # as such obj = apprise.Apprise.instantiate('glib://', suppress_exceptions=False) assert obj is None # Since playing with the sys.modules is not such a good idea, # let's just put our old configuration back: sys.modules['dbus'] = _session_bus # Reload our modules reload(sys.modules['apprise.plugins.NotifyDBus']) reload(sys.modules['apprise.plugins']) reload(sys.modules['apprise.Apprise']) reload(sys.modules['apprise'])
def get_exp_name_msg(exp: dbus.DBusException) -> Tuple[str, str]: """Get name and message of DBusException.""" return exp.get_dbus_name(), exp.get_dbus_message()