python-dbusmock-0.16.3/0000775000175000017500000000000012633533065015545 5ustar martinmartin00000000000000python-dbusmock-0.16.3/dbusmock/0000775000175000017500000000000012633533065017354 5ustar martinmartin00000000000000python-dbusmock-0.16.3/dbusmock/templates/0000775000175000017500000000000012633533065021352 5ustar martinmartin00000000000000python-dbusmock-0.16.3/dbusmock/templates/__init__.py0000664000175000017500000000057612264500431023462 0ustar martinmartin00000000000000'''Mock templates for common D-BUS services''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. python-dbusmock-0.16.3/dbusmock/templates/bluez4.py0000664000175000017500000004011412605433744023133 0ustar martinmartin00000000000000# -*- coding: utf-8 -*- '''bluetoothd mock template This creates the expected methods and properties of the object manager org.bluez object (/), but no adapters or devices. This supports BlueZ 4 only. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __authors__ = ['Mathieu Trudel-Lapierre ', 'Philip Withnall '] __copyright__ = '(c) 2013 Collabora Ltd.' __copyright__ = '(c) 2014 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus from dbusmock import OBJECT_MANAGER_IFACE, mockobject BUS_NAME = 'org.bluez' MAIN_OBJ = '/' SYSTEM_BUS = True IS_OBJECT_MANAGER = True BLUEZ_MOCK_IFACE = 'org.bluez.Mock' AGENT_MANAGER_IFACE = 'org.bluez.Agent' MANAGER_IFACE = 'org.bluez.Manager' ADAPTER_IFACE = 'org.bluez.Adapter' DEVICE_IFACE = 'org.bluez.Device' AUDIO_IFACE = 'org.bluez.Audio' def load(mock, parameters): mock.AddObject('/org/bluez', AGENT_MANAGER_IFACE, {}, [ ('Release', '', '', ''), ]) mock.AddMethods(MANAGER_IFACE, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Manager")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Manager", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Manager", "PropertyChanged", "sv", [args[0], args[1]])'), ]) mock.AddProperties(MANAGER_IFACE, { 'Adapters': dbus.Array([], signature='o'), }) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='s') def AddAdapter(self, device_name, system_name): '''Convenience method to add a Bluetooth adapter You have to specify a device name which must be a valid part of an object path, e. g. "hci0", and an arbitrary system name (pretty hostname). Returns the new object path. ''' path = '/org/bluez/' + device_name adapter_properties = { 'UUIDs': dbus.Array([ '00001000-0000-1000-8000-00805f9b34fb', '00001001-0000-1000-8000-00805f9b34fb', '0000112d-0000-1000-8000-00805f9b34fb', '00001112-0000-1000-8000-00805f9b34fb', '0000111f-0000-1000-8000-00805f9b34fb', '0000111e-0000-1000-8000-00805f9b34fb', '0000110c-0000-1000-8000-00805f9b34fb', '0000110e-0000-1000-8000-00805f9b34fb', '0000110a-0000-1000-8000-00805f9b34fb', '0000110b-0000-1000-8000-00805f9b34fb', ], variant_level=1), 'Discoverable': dbus.Boolean(False, variant_level=1), 'Discovering': dbus.Boolean(False, variant_level=1), 'Pairable': dbus.Boolean(True, variant_level=1), 'Powered': dbus.Boolean(True, variant_level=1), 'Address': dbus.String('00:01:02:03:04:05', variant_level=1), 'Alias': dbus.String(system_name, variant_level=1), 'Name': dbus.String(system_name, variant_level=1), # Reference: # http://bluetooth-pentest.narod.ru/software/ # bluetooth_class_of_device-service_generator.html 'Class': dbus.UInt32(268, variant_level=1), # Computer, Laptop } self.AddObject(path, ADAPTER_IFACE, # Properties adapter_properties, # Methods [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Adapter")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Adapter", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Adapter", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ]) manager = mockobject.objects['/'] manager.props[MANAGER_IFACE]['Adapters'] \ = [dbus.ObjectPath(path, variant_level=1)] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path, variant_level=1), {ADAPTER_IFACE: adapter_properties}, ]) manager.EmitSignal(MANAGER_IFACE, 'AdapterAdded', 'o', [dbus.ObjectPath(path, variant_level=1)]) manager.EmitSignal(MANAGER_IFACE, 'DefaultAdapterChanged', 'o', [dbus.ObjectPath(path, variant_level=1)]) manager.EmitSignal(MANAGER_IFACE, 'PropertyChanged', 'sv', [ "Adapters", dbus.Array([dbus.ObjectPath(path, variant_level=1), ], variant_level=1), ]) return path @dbus.service.method(ADAPTER_IFACE, in_signature='', out_signature='') def StartDiscovery(self): '''Start discovery ''' adapter = mockobject.objects[self.path] adapter.props[ADAPTER_IFACE]['Discovering'] = dbus.Boolean(True, variant_level=1) adapter.EmitSignal(ADAPTER_IFACE, 'PropertyChanged', 'sv', [ 'Discovering', dbus.Boolean(True, variant_level=1), ]) @dbus.service.method(ADAPTER_IFACE, in_signature='', out_signature='') def StopDiscovery(self): '''Stop discovery ''' adapter = mockobject.objects[self.path] adapter.props[ADAPTER_IFACE]['Discovering'] = dbus.Boolean(True, variant_level=1) adapter.EmitSignal(ADAPTER_IFACE, 'PropertyChanged', 'sv', [ 'Discovering', dbus.Boolean(False, variant_level=1), ]) @dbus.service.method(MANAGER_IFACE, in_signature='', out_signature='o') def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_level=1) else: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter') @dbus.service.method(MANAGER_IFACE, in_signature='', out_signature='ao') def ListAdapters(self): '''List all known adapters ''' adapters = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: adapters.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(adapters, variant_level=1) @dbus.service.method(ADAPTER_IFACE, in_signature='s', out_signature='o') def CreateDevice(self, device_address): '''Create a new device ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = self.path path = adapter_path + '/' + device_name if path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Could not create device for %s.' % device_address, name='org.bluez.Error.Failed') adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceCreated', 'o', [dbus.ObjectPath(path, variant_level=1)]) return dbus.ObjectPath(path, variant_level=1) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='sss', out_signature='s') def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter') properties = { 'UUIDs': dbus.Array([], signature='s', variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), 'LegacyPairing': dbus.Boolean(False, variant_level=1), 'Paired': dbus.Boolean(False, variant_level=1), 'Trusted': dbus.Boolean(False, variant_level=1), 'RSSI': dbus.Int16(-79, variant_level=1), # arbitrary 'Adapter': dbus.ObjectPath(adapter_path, variant_level=1), 'Address': dbus.String(device_address, variant_level=1), 'Alias': dbus.String(alias, variant_level=1), 'Name': dbus.String(alias, variant_level=1), 'Class': dbus.UInt32(0x240404, variant_level=1), # Audio, headset. 'Icon': dbus.String('audio-headset', variant_level=1), } self.AddObject(path, DEVICE_IFACE, # Properties properties, # Methods [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Device")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Device", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Device", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path, variant_level=1), {DEVICE_IFACE: properties}, ]) adapter = mockobject.objects[adapter_path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceFound', 'sa{sv}', [ properties['Address'], properties, ]) return path @dbus.service.method(ADAPTER_IFACE, in_signature='', out_signature='ao') def ListDevices(self): '''List all known devices ''' devices = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: devices.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(devices, variant_level=1) @dbus.service.method(ADAPTER_IFACE, in_signature='s', out_signature='o') def FindDevice(self, address): '''Find a specific device by bluetooth address. ''' for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: o = mockobject.objects[obj] if o.props[DEVICE_IFACE]['Address'] \ == dbus.String(address, variant_level=1): return obj raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') @dbus.service.method(ADAPTER_IFACE, in_signature='sos', out_signature='o') def CreatePairedDevice(self, device_address, agent, capability): '''Convenience method to mark an existing device as paired. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() device_path = DefaultAdapter(self) + '/' + device_name if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] # Based off pairing with a Sennheise headset. uuids = [ '00001108-0000-1000-8000-00805f9b34fb', '0000110b-0000-1000-8000-00805f9b34fb', '0000110e-0000-1000-8000-00805f9b34fb', '0000111e-0000-1000-8000-00805f9b34fb', ] device.props[DEVICE_IFACE]['UUIDs'] = dbus.Array(uuids, variant_level=1) device.props[DEVICE_IFACE]['Paired'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['LegacyPairing'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['Trusted'] = dbus.Boolean(False, variant_level=1) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(True, variant_level=1) adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceCreated', 'o', [dbus.ObjectPath(device_path, variant_level=1)]) for prop in device.props[DEVICE_IFACE]: try: device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ prop, device.props[prop] ]) except KeyError: pass return dbus.ObjectPath(device_path, variant_level=1) @dbus.service.method(DEVICE_IFACE, in_signature='s', out_signature='a{us}') def DiscoverServices(self, pattern): device = mockobject.objects[self.path] try: device.AddProperties(AUDIO_IFACE, { 'State': dbus.String('disconnected', variant_level=1), }) except: pass device.props[AUDIO_IFACE]['State'] = dbus.String("disconnected", variant_level=1) device.AddMethods(AUDIO_IFACE, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Audio")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Audio", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Audio", "PropertyChanged", "sv", [args[0], args[1]])'), ]) return dbus.Dictionary({0: "dummy", }, variant_level=1) @dbus.service.method(AUDIO_IFACE, in_signature='', out_signature='') def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] device.props[AUDIO_IFACE]['State'] = dbus.String("connected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("connected", variant_level=1), ]) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(True, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(True, variant_level=1), ]) @dbus.service.method(AUDIO_IFACE, in_signature='', out_signature='') def Disconnect(self): '''Disconnect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] try: device.props[AUDIO_IFACE]['State'] = dbus.String("disconnected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("disconnected", variant_level=1), ]) except KeyError: pass device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(False, variant_level=1), ]) @dbus.service.method(ADAPTER_IFACE, in_signature='o', out_signature='') def RemoveDevice(self, object_path): '''Remove (forget) a device ''' adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceRemoved', 'o', [object_path]) python-dbusmock-0.16.3/dbusmock/templates/bluez5-obex.py0000664000175000017500000002506112506172770024072 0ustar martinmartin00000000000000# -*- coding: utf-8 -*- '''obexd mock template This creates the expected methods and properties of the object manager org.bluez.obex object (/), the manager object (/org/bluez/obex), but no agents or clients. This supports BlueZ 5 only. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Philip Withnall' __email__ = 'philip.withnall@collabora.co.uk' __copyright__ = '(c) 2013 Collabora Ltd.' __license__ = 'LGPL 3+' import dbus import tempfile import os from dbusmock import OBJECT_MANAGER_IFACE, mockobject BUS_NAME = 'org.bluez.obex' MAIN_OBJ = '/' SYSTEM_BUS = False IS_OBJECT_MANAGER = True OBEX_MOCK_IFACE = 'org.bluez.obex.Mock' AGENT_MANAGER_IFACE = 'org.bluez.AgentManager1' CLIENT_IFACE = 'org.bluez.obex.Client1' SESSION_IFACE = 'org.bluez.obex.Session1' PHONEBOOK_ACCESS_IFACE = 'org.bluez.obex.PhonebookAccess1' TRANSFER_IFACE = 'org.bluez.obex.Transfer1' TRANSFER_MOCK_IFACE = 'org.bluez.obex.transfer1.Mock' def load(mock, parameters): mock.AddObject('/org/bluez/obex', AGENT_MANAGER_IFACE, {}, [ ('RegisterAgent', 'os', '', ''), ('UnregisterAgent', 'o', '', ''), ]) obex = mockobject.objects['/org/bluez/obex'] obex.AddMethods(CLIENT_IFACE, [ ('CreateSession', 'sa{sv}', 'o', CreateSession), ('RemoveSession', 'o', '', RemoveSession), ]) @dbus.service.method(CLIENT_IFACE, in_signature='sa{sv}', out_signature='o') def CreateSession(self, destination, args): '''OBEX method to create a new transfer session. The destination must be the address of the destination Bluetooth device. The given arguments must be a map from well-known keys to values, containing at least the ‘Target’ key, whose value must be ‘PBAP’ (other keys and values are accepted by the real daemon, but not by this mock daemon at the moment). If the target is missing or incorrect, an Unsupported error is returned on the bus. Returns the path of a new Session object. ''' if 'Target' not in args or args['Target'].upper() != 'PBAP': raise dbus.exceptions.DBusException( 'Non-PBAP targets are not currently supported by this ' + 'python-dbusmock template.', name=OBEX_MOCK_IFACE + '.Unsupported') # Find the first unused session ID. client_path = '/org/bluez/obex/client' session_id = 0 while client_path + '/session' + str(session_id) in mockobject.objects: session_id += 1 path = client_path + '/session' + str(session_id) properties = { 'Source': dbus.String('FIXME', variant_level=1), 'Destination': dbus.String(destination, variant_level=1), 'Channel': dbus.Byte(0, variant_level=1), 'Target': dbus.String('FIXME', variant_level=1), 'Root': dbus.String('FIXME', variant_level=1), } self.AddObject(path, SESSION_IFACE, # Properties properties, # Methods [ ('GetCapabilities', '', 's', ''), # Currently a no-op ]) session = mockobject.objects[path] session.AddMethods(PHONEBOOK_ACCESS_IFACE, [ ('Select', 'ss', '', ''), # Currently a no-op # Currently a no-op ('List', 'a{sv}', 'a(ss)', 'ret = dbus.Array(signature="(ss)")'), # Currently a no-op ('ListFilterFields', '', 'as', 'ret = dbus.Array(signature="(s)")'), ('PullAll', 'sa{sv}', 'sa{sv}', PullAll), ('GetSize', '', 'q', 'ret = 0'), # TODO ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), {SESSION_IFACE: properties}, ]) return path @dbus.service.method(CLIENT_IFACE, in_signature='o', out_signature='') def RemoveSession(self, session_path): '''OBEX method to remove an existing transfer session. This takes the path of the transfer Session object and removes it. ''' manager = mockobject.objects['/'] # Remove all the session's transfers. transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_path = session_path + '/transfer' + str(transfer_id) transfer_id += 1 self.RemoveObject(transfer_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(transfer_path), [TRANSFER_IFACE], ]) # Remove the session itself. self.RemoveObject(session_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(session_path), [SESSION_IFACE, PHONEBOOK_ACCESS_IFACE], ]) @dbus.service.method(PHONEBOOK_ACCESS_IFACE, in_signature='sa{sv}', out_signature='sa{sv}') def PullAll(self, target_file, filters): '''OBEX method to start a pull transfer of a phone book. This doesn't complete the transfer; code to mock up activating and completing the transfer must be provided by the test driver, as it’s too complex and test-specific to put here. The target_file is the absolute path for a file which will have zero or more vCards, separated by new-line characters, written to it if the method is successful (and the transfer is completed). This target_file is actually emitted in a TransferCreated signal, which is a special part of the mock interface designed to be handled by the test driver, which should then populate that file and call UpdateStatus on the Transfer object. The test driver is responsible for deleting the file once the test is complete. The filters parameter is a map of filters to be applied to the results device-side before transmitting them back to the adapter. Returns a tuple containing the path for a new Transfer D-Bus object representing the transfer, and a map of the initial properties of that Transfer object. ''' # Find the first unused session ID. session_path = self.path transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_id += 1 transfer_path = session_path + '/transfer' + str(transfer_id) # Create a new temporary file to transfer to. temp_file = tempfile.NamedTemporaryFile(suffix='.vcf', prefix='tmp-bluez5-obex-PullAll_', delete=False) filename = os.path.abspath(temp_file.name) props = { 'Status': dbus.String('queued', variant_level=1), 'Session': dbus.ObjectPath(session_path, variant_level=1), 'Name': dbus.String(target_file, variant_level=1), 'Filename': dbus.String(filename, variant_level=1), 'Transferred': dbus.UInt64(0, variant_level=1), } self.AddObject(transfer_path, TRANSFER_IFACE, # Properties props, # Methods [ ('Cancel', '', '', ''), # Currently a no-op ]) transfer = mockobject.objects[transfer_path] transfer.AddMethods(TRANSFER_MOCK_IFACE, [ ('UpdateStatus', 'b', '', UpdateStatus), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(transfer_path), {TRANSFER_IFACE: props}, ]) # Emit a behind-the-scenes signal that a new transfer has been created. manager.EmitSignal(OBEX_MOCK_IFACE, 'TransferCreated', 'sa{sv}s', [transfer_path, filters, filename]) return (transfer_path, props) @dbus.service.signal(OBEX_MOCK_IFACE, signature='sa{sv}s') def TransferCreated(self, path, filters, transfer_filename): '''Mock signal emitted when a new Transfer object is created. This is not part of the BlueZ OBEX interface; it is purely for use by test driver code. It is emitted by the PullAll method, and is intended to be used as a signal to call UpdateStatus on the newly created Transfer (potentially after a timeout). The path is of the new Transfer object, and the filters are as provided to PullAll. The transfer filename is the full path and filename of a newly created empty temporary file which the test driver should write to. The test driver should then call UpdateStatus on the Transfer object each time a write is made to the transfer file. The final call to UpdateStatus should mark the transfer as complete. The test driver is responsible for deleting the transfer file once the test is complete. FIXME: Ideally the UpdateStatus method would only be used for completion, and all intermediate updates would be found by watching the size of the transfer file. However, that means adding a dependency on an inotify package, which seems a little much. ''' pass @dbus.service.method(TRANSFER_MOCK_IFACE, in_signature='', out_signature='') def UpdateStatus(self, is_complete): '''Mock method to update the transfer status. If is_complete is False, this marks the transfer is active; otherwise it marks the transfer as complete. It is an error to call this method after calling it with is_complete as True. In both cases, it updates the number of bytes transferred to be the current size of the transfer file (whose filename was emitted in the TransferCreated signal). ''' status = 'complete' if is_complete else 'active' transferred = os.path.getsize(self.props[TRANSFER_IFACE]['Filename']) self.props[TRANSFER_IFACE]['Status'] = status self.props[TRANSFER_IFACE]['Transferred'] = dbus.UInt64(transferred, variant_level=1) self.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ TRANSFER_IFACE, { 'Status': dbus.String(status, variant_level=1), 'Transferred': dbus.UInt64(transferred, variant_level=1), }, [], ]) python-dbusmock-0.16.3/dbusmock/templates/bluez5.py0000664000175000017500000003562112506172656023145 0ustar martinmartin00000000000000# -*- coding: utf-8 -*- '''bluetoothd mock template This creates the expected methods and properties of the object manager org.bluez object (/), the manager object (/org/bluez), but no adapters or devices. This supports BlueZ 5 only. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Philip Withnall' __email__ = 'philip.withnall@collabora.co.uk' __copyright__ = '(c) 2013 Collabora Ltd.' __license__ = 'LGPL 3+' import dbus from dbusmock import OBJECT_MANAGER_IFACE, mockobject BUS_NAME = 'org.bluez' MAIN_OBJ = '/' SYSTEM_BUS = True IS_OBJECT_MANAGER = True BLUEZ_MOCK_IFACE = 'org.bluez.Mock' AGENT_MANAGER_IFACE = 'org.bluez.AgentManager1' PROFILE_MANAGER_IFACE = 'org.bluez.ProfileManager1' ADAPTER_IFACE = 'org.bluez.Adapter1' MEDIA_IFACE = 'org.bluez.Media1' NETWORK_SERVER_IFACE = 'org.bluez.Network1' DEVICE_IFACE = 'org.bluez.Device1' def load(mock, parameters): mock.AddObject('/org/bluez', AGENT_MANAGER_IFACE, {}, [ ('RegisterAgent', 'os', '', ''), ('RequestDefaultAgent', 'o', '', ''), ('UnregisterAgent', 'o', '', ''), ]) bluez = mockobject.objects['/org/bluez'] bluez.AddMethods(PROFILE_MANAGER_IFACE, [ ('RegisterProfile', 'osa{sv}', '', ''), ('UnregisterProfile', 'o', '', ''), ]) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='s') def AddAdapter(self, device_name, system_name): '''Convenience method to add a Bluetooth adapter You have to specify a device name which must be a valid part of an object path, e. g. "hci0", and an arbitrary system name (pretty hostname). Returns the new object path. ''' path = '/org/bluez/' + device_name adapter_properties = { 'UUIDs': dbus.Array([ # Reference: # http://git.kernel.org/cgit/bluetooth/bluez.git/tree/lib/uuid.h # PNP '00001200-0000-1000-8000-00805f9b34fb', # Generic Access Profile '00001800-0000-1000-8000-00805f9b34fb', # Generic Attribute Profile '00001801-0000-1000-8000-00805f9b34fb', # Audio/Video Remote Control Profile (remote) '0000110e-0000-1000-8000-00805f9b34fb', # Audio/Video Remote Control Profile (target) '0000110c-0000-1000-8000-00805f9b34fb', ], variant_level=1), 'Discoverable': dbus.Boolean(True, variant_level=1), 'Discovering': dbus.Boolean(True, variant_level=1), 'Pairable': dbus.Boolean(True, variant_level=1), 'Powered': dbus.Boolean(True, variant_level=1), 'Address': dbus.String('00:01:02:03:04:05', variant_level=1), 'Alias': dbus.String(system_name, variant_level=1), 'Modalias': dbus.String('usb:v1D6Bp0245d050A', variant_level=1), 'Name': dbus.String(system_name, variant_level=1), # Reference: # http://bluetooth-pentest.narod.ru/software/ # bluetooth_class_of_device-service_generator.html 'Class': dbus.UInt32(268, variant_level=1), # Computer, Laptop 'DiscoverableTimeout': dbus.UInt32(180, variant_level=1), 'PairableTimeout': dbus.UInt32(180, variant_level=1), } self.AddObject(path, ADAPTER_IFACE, # Properties adapter_properties, # Methods [ ('RemoveDevice', 'o', '', ''), ('StartDiscovery', '', '', ''), ('StopDiscovery', '', '', ''), ]) adapter = mockobject.objects[path] adapter.AddMethods(MEDIA_IFACE, [ ('RegisterEndpoint', 'oa{sv}', '', ''), ('UnregisterEndpoint', 'o', '', ''), ]) adapter.AddMethods(NETWORK_SERVER_IFACE, [ ('Register', 'ss', '', ''), ('Unregister', 's', '', ''), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), {ADAPTER_IFACE: adapter_properties}, ]) return path @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='sss', out_signature='s') def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') properties = { 'UUIDs': dbus.Array([], signature='s', variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), 'LegacyPairing': dbus.Boolean(False, variant_level=1), 'Paired': dbus.Boolean(False, variant_level=1), 'Trusted': dbus.Boolean(False, variant_level=1), 'RSSI': dbus.Int16(-79, variant_level=1), # arbitrary 'Adapter': dbus.ObjectPath(adapter_path, variant_level=1), 'Address': dbus.String(device_address, variant_level=1), 'Alias': dbus.String(alias, variant_level=1), 'Name': dbus.String(alias, variant_level=1), } self.AddObject(path, DEVICE_IFACE, # Properties properties, # Methods [ ('CancelPairing', '', '', ''), ('Connect', '', '', ''), ('ConnectProfile', 's', '', ''), ('Disconnect', '', '', ''), ('DisconnectProfile', 's', '', ''), ('Pair', '', '', ''), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), {DEVICE_IFACE: properties}, ]) return path @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='') def PairDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as paired. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This unblocks the device if it was blocked. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] # Based off pairing with an Android phone. uuids = [ '00001105-0000-1000-8000-00805f9b34fb', '0000110a-0000-1000-8000-00805f9b34fb', '0000110c-0000-1000-8000-00805f9b34fb', '00001112-0000-1000-8000-00805f9b34fb', '00001115-0000-1000-8000-00805f9b34fb', '00001116-0000-1000-8000-00805f9b34fb', '0000111f-0000-1000-8000-00805f9b34fb', '0000112f-0000-1000-8000-00805f9b34fb', '00001200-0000-1000-8000-00805f9b34fb', ] device.props[DEVICE_IFACE]['UUIDs'] = dbus.Array(uuids, variant_level=1) device.props[DEVICE_IFACE]['Paired'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['LegacyPairing'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['Blocked'] = dbus.Boolean(False, variant_level=1) try: device.props[DEVICE_IFACE]['Modalias'] except KeyError: device.AddProperties(DEVICE_IFACE, { 'Modalias': dbus.String('bluetooth:v000Fp1200d1436', variant_level=1), 'Class': dbus.UInt32(5898764, variant_level=1), 'Icon': dbus.String('phone', variant_level=1), }) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'UUIDs': dbus.Array(uuids, variant_level=1), 'Paired': dbus.Boolean(True, variant_level=1), 'LegacyPairing': dbus.Boolean(True, variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'Modalias': dbus.String('bluetooth:v000Fp1200d1436', variant_level=1), 'Class': dbus.UInt32(5898764, variant_level=1), 'Icon': dbus.String('phone', variant_level=1), }, [], ]) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='') def BlockDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as blocked. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This disconnects the device if it was connected. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] device.props[DEVICE_IFACE]['Blocked'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'Blocked': dbus.Boolean(True, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), }, [], ]) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='') def ConnectDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as connected. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This unblocks the device if it was blocked. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] device.props[DEVICE_IFACE]['Blocked'] = dbus.Boolean(False, variant_level=1) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(True, variant_level=1) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'Blocked': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(True, variant_level=1), }, [], ]) @dbus.service.method(BLUEZ_MOCK_IFACE, in_signature='ss', out_signature='') def DisconnectDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as disconnected. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This does not change the device’s blocked status. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'Connected': dbus.Boolean(False, variant_level=1), }, [], ]) python-dbusmock-0.16.3/dbusmock/templates/gnome_screensaver.py0000664000175000017500000000234212264500431025421 0ustar martinmartin00000000000000'''gnome-shell screensaver mock template This creates the expected methods and properties of the org.gnome.ScreenSaver object. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Bastien Nocera' __email__ = 'hadess@hadess.net' __copyright__ = '(c) 2013 Red Hat Inc.' __license__ = 'LGPL 3+' BUS_NAME = 'org.gnome.ScreenSaver' MAIN_OBJ = '/org/gnome/ScreenSaver' MAIN_IFACE = 'org.gnome.ScreenSaver' SYSTEM_BUS = False def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [ ('GetActive', '', 'b', 'ret = self.is_active'), ('GetActiveTime', '', 'u', 'ret = 1'), ('SetActive', 'b', '', 'self.is_active = args[0]; self.EmitSignal(' '"", "ActiveChanged", "b", [self.is_active])'), ('Lock', '', '', 'time.sleep(1); self.SetActive(True)'), ('ShowMessage', 'sss', '', ''), ('SimulateUserActivity', '', '', ''), ]) # default state mock.is_active = False python-dbusmock-0.16.3/dbusmock/templates/logind.py0000664000175000017500000002472112506171753023207 0ustar martinmartin00000000000000'''systemd logind mock template This creates the expected methods and properties of the main org.freedesktop.login1.Manager object. You can specify D-BUS property values like "CanSuspend" or the return value of Inhibit() in "parameters". ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus import os from dbusmock import MOCK_IFACE, mockobject BUS_NAME = 'org.freedesktop.login1' MAIN_OBJ = '/org/freedesktop/login1' MAIN_IFACE = 'org.freedesktop.login1.Manager' SYSTEM_BUS = True def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [ ('PowerOff', 'b', '', ''), ('Reboot', 'b', '', ''), ('Suspend', 'b', '', ''), ('Hibernate', 'b', '', ''), ('HybridSleep', 'b', '', ''), ('CanPowerOff', '', 's', 'ret = "%s"' % parameters.get('CanPowerOff', 'yes')), ('CanReboot', '', 's', 'ret = "%s"' % parameters.get('CanReboot', 'yes')), ('CanSuspend', '', 's', 'ret = "%s"' % parameters.get('CanSuspend', 'yes')), ('CanHibernate', '', 's', 'ret = "%s"' % parameters.get('CanHibernate', 'yes')), ('CanHybridSleep', '', 's', 'ret = "%s"' % parameters.get('CanHybridSleep', 'yes')), ('GetSession', 's', 'o', 'ret = "/org/freedesktop/login1/session/" + args[0]'), ('ActivateSession', 's', '', ''), ('ActivateSessionOnSeat', 'ss', '', ''), ('KillSession', 'sss', '', ''), ('LockSession', 's', '', ''), ('LockSessions', '', '', ''), ('ReleaseSession', 's', '', ''), ('TerminateSession', 's', '', ''), ('UnlockSession', 's', '', ''), ('UnlockSessions', '', '', ''), ('GetSeat', 's', 'o', 'ret = "/org/freedesktop/login1/seat/" + args[0]'), ('ListSeats', '', 'a(so)', 'ret = [(k.split("/")[-1], k) for k in objects.keys() if "/seat/" in k]'), ('TerminateSeat', 's', '', ''), ('GetUser', 'u', 'o', 'ret = "/org/freedesktop/login1/user/%u" % args[0]'), ('KillUser', 'us', '', ''), ('TerminateUser', 'u', '', ''), ('Inhibit', 'ssss', 'h', 'ret = %i' % parameters.get('Inhibit_fd', 3)), ('ListInhibitors', '', 'a(ssssuu)', 'ret = []'), ]) mock.AddProperties(MAIN_IFACE, dbus.Dictionary({ 'IdleHint': parameters.get('IdleHint', False), 'IdleAction': parameters.get('IdleAction', 'ignore'), 'IdleSinceHint': dbus.UInt64(parameters.get('IdleSinceHint', 0)), 'IdleSinceHintMonotonic': dbus.UInt64(parameters.get('IdleSinceHintMonotonic', 0)), 'IdleActionUSec': dbus.UInt64(parameters.get('IdleActionUSec', 1)), 'PreparingForShutdown': parameters.get('PreparingForShutdown', False), 'PreparingForSleep': parameters.get('PreparingForSleep', False), 'PreparingForShutdown': parameters.get('PreparingForShutdown', False), }, signature='sv')) # # logind methods which are too big for squeezing into AddMethod() # @dbus.service.method(MAIN_IFACE, in_signature='', out_signature='a(uso)') def ListUsers(self): users = [] for k, obj in mockobject.objects.items(): if '/user/' in k: uid = dbus.UInt32(int(k.split("/")[-1])) users.append((uid, obj.Get('org.freedesktop.login1.User', 'Name'), k)) return users @dbus.service.method(MAIN_IFACE, in_signature='', out_signature='a(susso)') def ListSessions(self): sessions = [] for k, obj in mockobject.objects.items(): if '/session/' in k: session_id = k.split("/")[-1] uid = obj.Get('org.freedesktop.login1.Session', 'User')[0] username = obj.Get('org.freedesktop.login1.Session', 'Name') seat = obj.Get('org.freedesktop.login1.Session', 'Seat')[0] sessions.append((session_id, uid, username, seat, k)) return sessions # # Convenience methods on the mock # @dbus.service.method(MOCK_IFACE, in_signature='s', out_signature='s') def AddSeat(self, seat): '''Convenience method to add a seat. Return the object path of the new seat. ''' seat_path = '/org/freedesktop/login1/seat/' + seat if seat_path in mockobject.objects: raise dbus.exceptions.DBusException('Seat %s already exists' % seat, name=MOCK_IFACE + '.SeatExists') self.AddObject(seat_path, 'org.freedesktop.login1.Seat', { 'Sessions': dbus.Array([], signature='(so)'), 'CanGraphical': False, 'CanMultiSession': True, 'CanTTY': False, 'IdleHint': False, 'ActiveSession': ('', dbus.ObjectPath('/')), 'Id': seat, 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), }, [ ('ActivateSession', 's', '', ''), ('Terminate', '', '', '') ]) return seat_path @dbus.service.method(MOCK_IFACE, in_signature='usb', out_signature='s') def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, name=MOCK_IFACE + '.UserExists') self.AddObject(user_path, 'org.freedesktop.login1.User', { 'Sessions': dbus.Array([], signature='(so)'), 'IdleHint': False, 'DefaultControlGroup': 'systemd:/user/' + username, 'Name': username, 'RuntimePath': '/run/user/%i' % uid, 'Service': '', 'State': (active and 'active' or 'online'), 'Display': ('', dbus.ObjectPath('/')), 'UID': dbus.UInt32(uid), 'GID': dbus.UInt32(uid), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Kill', 's', '', ''), ('Terminate', '', '', ''), ]) return user_path @dbus.service.method(MOCK_IFACE, in_signature='ssusb', out_signature='s') def AddSession(self, session_id, seat, uid, username, active): '''Convenience method to add a session. If the given seat and/or user do not exit, they will be created. Return the object path of the new session. ''' seat_path = dbus.ObjectPath('/org/freedesktop/login1/seat/' + seat) if seat_path not in mockobject.objects: self.AddSeat(seat) user_path = dbus.ObjectPath('/org/freedesktop/login1/user/%i' % uid) if user_path not in mockobject.objects: self.AddUser(uid, username, active) session_path = dbus.ObjectPath('/org/freedesktop/login1/session/' + session_id) if session_path in mockobject.objects: raise dbus.exceptions.DBusException('Session %s already exists' % session_id, name=MOCK_IFACE + '.SessionExists') self.AddObject(session_path, 'org.freedesktop.login1.Session', { 'Controllers': dbus.Array([], signature='s'), 'ResetControllers': dbus.Array([], signature='s'), 'Active': active, 'IdleHint': False, 'KillProcesses': False, 'Remote': False, 'Class': 'user', 'DefaultControlGroup': 'systemd:/user/%s/%s' % (username, session_id), 'Display': os.getenv('DISPLAY', ''), 'Id': session_id, 'Name': username, 'RemoteHost': '', 'RemoteUser': '', 'Service': 'dbusmock', 'State': (active and 'active' or 'online'), 'TTY': '', 'Type': 'test', 'Seat': (seat, seat_path), 'User': (dbus.UInt32(uid), user_path), 'Audit': dbus.UInt32(0), 'Leader': dbus.UInt32(1), 'VTNr': dbus.UInt32(1), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Activate', '', '', ''), ('Kill', 'ss', '', ''), ('Lock', '', '', ''), ('SetIdleHint', 'b', '', ''), ('Terminate', '', '', ''), ('Unlock', '', '', ''), ]) # add session to seat obj_seat = mockobject.objects[seat_path] cur_sessions = obj_seat.Get('org.freedesktop.login1.Seat', 'Sessions') cur_sessions.append((session_id, session_path)) obj_seat.Set('org.freedesktop.login1.Seat', 'Sessions', cur_sessions) obj_seat.Set('org.freedesktop.login1.Seat', 'ActiveSession', (session_id, session_path)) # add session to user obj_user = mockobject.objects[user_path] cur_sessions = obj_user.Get('org.freedesktop.login1.User', 'Sessions') cur_sessions.append((session_id, session_path)) obj_user.Set('org.freedesktop.login1.User', 'Sessions', cur_sessions) return session_path python-dbusmock-0.16.3/dbusmock/templates/networkmanager.py0000664000175000017500000007674112631745401024764 0ustar martinmartin00000000000000'''NetworkManager mock template This creates the expected methods and properties of the main org.freedesktop.NetworkManager object, but no devices. You can specify any property such as 'NetworkingEnabled', or 'WirelessEnabled' etc. in "parameters". ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Iftikhar Ahmad' __email__ = 'iftikhar.ahmad@canonical.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus import uuid import binascii from dbusmock import MOCK_IFACE import dbusmock BUS_NAME = 'org.freedesktop.NetworkManager' MAIN_OBJ = '/org/freedesktop/NetworkManager' MAIN_IFACE = 'org.freedesktop.NetworkManager' SETTINGS_OBJ = '/org/freedesktop/NetworkManager/Settings' SETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings' DEVICE_IFACE = 'org.freedesktop.NetworkManager.Device' WIRELESS_DEVICE_IFACE = 'org.freedesktop.NetworkManager.Device.Wireless' ACCESS_POINT_IFACE = 'org.freedesktop.NetworkManager.AccessPoint' CSETTINGS_IFACE = 'org.freedesktop.NetworkManager.Settings.Connection' ACTIVE_CONNECTION_IFACE = 'org.freedesktop.NetworkManager.Connection.Active' SYSTEM_BUS = True class NMState: '''Global state As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_STATE ''' NM_STATE_UNKNOWN = 0 NM_STATE_ASLEEP = 10 NM_STATE_DISCONNECTED = 20 NM_STATE_DISCONNECTING = 30 NM_STATE_CONNECTING = 40 NM_STATE_CONNECTED_LOCAL = 50 NM_STATE_CONNECTED_SITE = 60 NM_STATE_CONNECTED_GLOBAL = 70 class NMConnectivityState: '''Connectvity state As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_CONNECTIVITY ''' NM_CONNECTIVITY_UNKNOWN = 0 NM_CONNECTIVITY_NONE = 1 NM_CONNECTIVITY_PORTAL = 2 NM_CONNECTIVITY_LIMITED = 3 NM_CONNECTIVITY_FULL = 4 class NMActiveConnectionState: '''Active connection state As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_ACTIVE_CONNECTION_STATE ''' NM_ACTIVE_CONNECTION_STATE_UNKNOWN = 0 NM_ACTIVE_CONNECTION_STATE_ACTIVATING = 1 NM_ACTIVE_CONNECTION_STATE_ACTIVATED = 2 NM_ACTIVE_CONNECTION_STATE_DEACTIVATING = 3 NM_ACTIVE_CONNECTION_STATE_DEACTIVATED = 4 class InfrastructureMode: '''Infrastructure mode As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_802_11_MODE ''' NM_802_11_MODE_UNKNOWN = 0 NM_802_11_MODE_ADHOC = 1 NM_802_11_MODE_INFRA = 2 NM_802_11_MODE_AP = 3 NAME_MAP = { NM_802_11_MODE_UNKNOWN: 'unknown', NM_802_11_MODE_ADHOC: 'adhoc', NM_802_11_MODE_INFRA: 'infrastructure', NM_802_11_MODE_AP: 'access-point', } class DeviceState: '''Device states As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_DEVICE_STATE ''' UNKNOWN = 0 UNMANAGED = 10 UNAVAILABLE = 20 DISCONNECTED = 30 PREPARE = 40 CONFIG = 50 NEED_AUTH = 60 IP_CONFIG = 70 IP_CHECK = 80 SECONDARIES = 90 ACTIVATED = 100 DEACTIVATING = 110 FAILED = 120 class NM80211ApSecurityFlags: '''Security flags As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_802_11_AP_SEC ''' NM_802_11_AP_SEC_NONE = 0x00000000 NM_802_11_AP_SEC_PAIR_WEP40 = 0x00000001 NM_802_11_AP_SEC_PAIR_WEP104 = 0x00000002 NM_802_11_AP_SEC_PAIR_TKIP = 0x00000004 NM_802_11_AP_SEC_PAIR_CCMP = 0x00000008 NM_802_11_AP_SEC_GROUP_WEP40 = 0x00000010 NM_802_11_AP_SEC_GROUP_WEP104 = 0x00000020 NM_802_11_AP_SEC_GROUP_TKIP = 0x00000040 NM_802_11_AP_SEC_GROUP_CCMP = 0x00000080 NM_802_11_AP_SEC_KEY_MGMT_PSK = 0x00000100 NM_802_11_AP_SEC_KEY_MGMT_802_1X = 0x00000200 NAME_MAP = { NM_802_11_AP_SEC_KEY_MGMT_PSK: { 'key-mgmt': 'wpa-psk', 'auth-alg': 'open' }, } class NM80211ApFlags: '''Device flags As per https://developer.gnome.org/NetworkManager/unstable/spec.html#type-NM_802_11_AP_FLAGS ''' NM_802_11_AP_FLAGS_NONE = 0x00000000 NM_802_11_AP_FLAGS_PRIVACY = 0x00000001 def activate_connection(self, conn, dev, ap): # find a new name count = 0 active_connections = dbusmock.get_object(MAIN_OBJ).Get(MAIN_IFACE, 'ActiveConnections') while True: path = dbus.ObjectPath('/org/freedesktop/NetworkManager/ActiveConnection/' + str(count)) if path not in active_connections: break count += 1 state = dbus.UInt32(NMActiveConnectionState.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) devices = [] if str(dev) != '/': devices.append(dev) active_conn = dbus.ObjectPath(AddActiveConnection(self, devices, conn, ap, str(count), state)) return active_conn def deactivate_connection(self, active_conn_path): NM = dbusmock.get_object(MAIN_OBJ) for dev_path in NM.GetDevices(): RemoveActiveConnection(self, dev_path, active_conn_path) def add_and_activate_connection(self, conn_conf, dev, ap): name = ap.rsplit('/', 1)[1] RemoveWifiConnection(self, dev, '/org/freedesktop/NetworkManager/Settings/' + name) raw_ssid = ''.join([chr(byte) for byte in conn_conf["802-11-wireless"]["ssid"]]) wifi_conn = dbus.ObjectPath(AddWiFiConnection(self, dev, name, raw_ssid, "")) active_conn = activate_connection(self, wifi_conn, dev, ap) return (wifi_conn, active_conn) def load(mock, parameters): mock.activate_connection = activate_connection mock.deactivate_connection = deactivate_connection mock.add_and_activate_connection = add_and_activate_connection mock.AddMethods(MAIN_IFACE, [ ('GetDevices', '', 'ao', 'ret = [k for k in objects.keys() if "/Devices" in k]'), ('GetPermissions', '', 'a{ss}', 'ret = {}'), ('state', '', 'u', "ret = self.Get('%s', 'State')" % MAIN_IFACE), ('CheckConnectivity', '', 'u', "ret = self.Get('%s', 'Connectivity')" % MAIN_IFACE), ('ActivateConnection', 'ooo', 'o', "ret = self.activate_connection(self, args[0], args[1], args[2])"), ('DeactivateConnection', 'o', '', "self.deactivate_connection(self, args[0])"), ('AddAndActivateConnection', 'a{sa{sv}}oo', 'oo', "ret = self.add_and_activate_connection(" "self, args[0], args[1], args[2])"), ]) mock.AddProperties('', { 'ActiveConnections': dbus.Array([], signature='o'), 'Devices': dbus.Array([], signature='o'), 'NetworkingEnabled': parameters.get('NetworkingEnabled', True), 'Connectivity': parameters.get('Connectivity', dbus.UInt32(NMConnectivityState.NM_CONNECTIVITY_FULL)), 'State': parameters.get('State', dbus.UInt32(NMState.NM_STATE_CONNECTED_GLOBAL)), 'Startup': False, 'Version': parameters.get('Version', '0.9.6.0'), 'WimaxEnabled': parameters.get('WimaxEnabled', True), 'WimaxHardwareEnabled': parameters.get('WimaxHardwareEnabled', True), 'WirelessEnabled': parameters.get('WirelessEnabled', True), 'WirelessHardwareEnabled': parameters.get('WirelessHardwareEnabled', True), 'WwanEnabled': parameters.get('WwanEnabled', False), 'WwanHardwareEnabled': parameters.get('WwanHardwareEnabled', True) }) settings_props = {'Hostname': 'hostname', 'CanModify': True, 'Connections': dbus.Array([], signature='o')} settings_methods = [('ListConnections', '', 'ao', "ret = self.Get('%s', 'Connections')" % SETTINGS_IFACE), ('GetConnectionByUuid', 's', 'o', ''), ('AddConnection', 'a{sa{sv}}', 'o', 'ret = self.SettingsAddConnection(args[0])'), ('SaveHostname', 's', '', '')] mock.AddObject(SETTINGS_OBJ, SETTINGS_IFACE, settings_props, settings_methods) @dbus.service.method(MOCK_IFACE, in_signature='sssv', out_signature='') def SetProperty(self, path, iface, name, value): obj = dbusmock.get_object(path) obj.Set(iface, name, value) obj.EmitSignal(iface, 'PropertiesChanged', 'a{sv}', [{name: value}]) @dbus.service.method(MOCK_IFACE, in_signature='u', out_signature='') def SetGlobalConnectionState(self, state): self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'State', dbus.UInt32(state, variant_level=1)) self.EmitSignal(MAIN_IFACE, 'StateChanged', 'u', [state]) @dbus.service.method(MOCK_IFACE, in_signature='u', out_signature='') def SetConnectivity(self, connectivity): self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'Connectivity', dbus.UInt32(connectivity, variant_level=1)) @dbus.service.method(MOCK_IFACE, in_signature='ss', out_signature='') def SetDeviceActive(self, device_path, active_connection_path): dev_obj = dbusmock.get_object(device_path) dev_obj.Set(DEVICE_IFACE, 'ActiveConnection', dbus.ObjectPath(active_connection_path)) old_state = dev_obj.Get(DEVICE_IFACE, 'State') dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.ACTIVATED)) dev_obj.EmitSignal(DEVICE_IFACE, 'StateChanged', 'uuu', [dbus.UInt32(DeviceState.ACTIVATED), old_state, dbus.UInt32(1)]) @dbus.service.method(MOCK_IFACE, in_signature='s', out_signature='') def SetDeviceDisconnected(self, device_path): dev_obj = dbusmock.get_object(device_path) dev_obj.Set(DEVICE_IFACE, 'ActiveConnection', dbus.ObjectPath('/')) old_state = dev_obj.Get(DEVICE_IFACE, 'State') dev_obj.Set(DEVICE_IFACE, 'State', dbus.UInt32(DeviceState.DISCONNECTED)) dev_obj.EmitSignal(DEVICE_IFACE, 'StateChanged', 'uuu', [dbus.UInt32(DeviceState.DISCONNECTED), old_state, dbus.UInt32(1)]) @dbus.service.method(MOCK_IFACE, in_signature='ssi', out_signature='s') def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = {'Carrier': False, 'HwAddress': dbus.String('78:DD:08:D2:3D:43'), 'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'), 'Speed': dbus.UInt32(0)} self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = {'DeviceType': dbus.UInt32(1), 'State': dbus.UInt32(state), 'Interface': iface_name, 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'IpInterface': ''} obj = dbusmock.get_object(path) obj.AddProperties(DEVICE_IFACE, props) devices = self.Get(MAIN_IFACE, 'Devices') devices.append(path) self.Set(MAIN_IFACE, 'Devices', devices) self.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path @dbus.service.method(MOCK_IFACE, in_signature='ssi', out_signature='s') def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, WIRELESS_DEVICE_IFACE, { 'HwAddress': dbus.String('11:22:33:44:55:66'), 'PermHwAddress': dbus.String('11:22:33:44:55:66'), 'Bitrate': dbus.UInt32(5400), 'Mode': dbus.UInt32(2), 'WirelessCapabilities': dbus.UInt32(255), 'AccessPoints': dbus.Array([], signature='o'), }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ('GetAllAccessPoints', '', 'ao', 'ret = self.access_points'), ('RequestScan', 'a{sv}', '', ''), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties(DEVICE_IFACE, { 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'DeviceType': dbus.UInt32(2), 'State': dbus.UInt32(state), 'Interface': iface_name, 'IpInterface': iface_name, }) devices = self.Get(MAIN_IFACE, 'Devices') devices.append(path) self.Set(MAIN_IFACE, 'Devices', devices) self.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path @dbus.service.method(MOCK_IFACE, in_signature='ssssuuuyu', out_signature='s') def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path]) return ap_path @dbus.service.method(MOCK_IFACE, in_signature='ssss', out_signature='s') def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access points. Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) connection_path = '/org/freedesktop/NetworkManager/Settings/' + connection_name connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() ssid = ssid_name.encode('UTF-8') # Find the access point by ssid access_point = None access_points = dev_obj.access_points for ap_path in access_points: ap = dbusmock.get_object(ap_path) if ap.Get(ACCESS_POINT_IFACE, 'Ssid') == ssid: access_point = ap break if not access_point: raise dbus.exceptions.DBusException( 'Access point with SSID [%s] could not be found' % (ssid_name), name=MAIN_IFACE + '.DoesNotExist') hw_address = access_point.Get(ACCESS_POINT_IFACE, 'HwAddress') mode = access_point.Get(ACCESS_POINT_IFACE, 'Mode') security = access_point.Get(ACCESS_POINT_IFACE, 'WpaFlags') if connection_path in connections or connection_path in main_connections: raise dbus.exceptions.DBusException( 'Connection %s on device %s already exists' % (connection_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') # Parse mac address string into byte array mac_bytes = binascii.unhexlify(hw_address.replace(':', '')) settings = { '802-11-wireless': { 'seen-bssids': [hw_address], 'ssid': dbus.ByteArray(ssid), 'mac-address': dbus.ByteArray(mac_bytes), 'mode': InfrastructureMode.NAME_MAP[mode] }, 'connection': { 'timestamp': dbus.UInt64(1374828522), 'type': '802-11-wireless', 'id': ssid_name, 'uuid': str(uuid.uuid4()) }, } if security != NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: settings['802-11-wireless']['security'] = '802-11-wireless-security' settings['802-11-wireless-security'] = NM80211ApSecurityFlags.NAME_MAP[security] self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate connections.append(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [ap_path]) return connection_path @dbus.service.method(MOCK_IFACE, in_signature='assssu', out_signature='s') def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path. ''' conn_obj = dbusmock.get_object(connection_device) settings = conn_obj.settings conn_uuid = settings['connection']['uuid'] conn_type = settings['connection']['type'] device_objects = [dbus.ObjectPath(dev) for dev in devices] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self.AddObject(active_connection_path, ACTIVE_CONNECTION_IFACE, { 'Devices': device_objects, 'Default6': False, 'Default': True, 'Type': conn_type, 'Vpn': (conn_type == 'vpn'), 'Connection': dbus.ObjectPath(connection_device), 'Master': dbus.ObjectPath('/'), 'SpecificObject': dbus.ObjectPath(specific_object), 'Uuid': conn_uuid, 'State': state, }, []) for dev_path in devices: self.SetDeviceActive(dev_path, active_connection_path) active_connections = self.Get(MAIN_IFACE, 'ActiveConnections') active_connections.append(dbus.ObjectPath(active_connection_path)) self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'ActiveConnections', active_connections) return active_connection_path @dbus.service.method(MOCK_IFACE, in_signature='ss', out_signature='') def RemoveAccessPoint(self, dev_path, ap_path): '''Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.remove(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.access_points.remove(ap_path) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointRemoved', 'o', [ap_path]) self.RemoveObject(ap_path) @dbus.service.method(MOCK_IFACE, in_signature='ss', out_signature='') def RemoveWifiConnection(self, dev_path, connection_path): '''Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) settings_obj = dbusmock.get_object(SETTINGS_OBJ) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') main_connections = settings_obj.ListConnections() if connection_path not in connections and connection_path not in main_connections: return connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.RemoveObject(connection_path) @dbus.service.method(MOCK_IFACE, in_signature='ss', out_signature='') def RemoveActiveConnection(self, dev_path, active_connection_path): '''Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ''' self.SetDeviceDisconnected(dev_path) active_connections = self.Get(MAIN_IFACE, 'ActiveConnections') if active_connection_path not in active_connections: return active_connections.remove(dbus.ObjectPath(active_connection_path)) self.SetProperty(MAIN_OBJ, MAIN_IFACE, 'ActiveConnections', active_connections) self.RemoveObject(active_connection_path) @dbus.service.method(SETTINGS_IFACE, in_signature='a{sa{sv}}', out_signature='o') def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'uuid' not in connection_settings['connection']: connection_settings['connection']['uuid'] = str(uuid.uuid4()) NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() # Mimic how NM names connections count = 0 while True: connection_obj_path = dbus.ObjectPath(SETTINGS_OBJ + '/' + str(count)) if connection_obj_path not in main_connections: break count += 1 connection_path = str(connection_obj_path) self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = connection_settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path]) auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MAIN_IFACE + '.DoesNotExist',) # Take care not to overwrite the secrets for setting_name in settings: setting = settings[setting_name] for k in setting: if setting_name not in self.settings: self.settings[setting_name] = {} self.settings[setting_name][k] = setting[k] self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path def ConnectionGetSettings(self): # Deep copy the settings with the secrets stripped # out. (NOTE: copy.deepcopy doesn't work with dbus # types). settings = {} for setting_name in self.settings: setting = self.settings[setting_name] for k in setting: if k != 'secrets': if setting_name not in settings: settings[setting_name] = {} settings[setting_name][k] = setting[k] return settings def ConnectionGetSecrets(self, setting): settings = self.settings[setting] if 'secrets' in settings: secrets = {setting: {'secrets': settings['secrets']}} else: secrets = {setting: {'secrets': {'no-secrets': True}}} return secrets def ConnectionDelete(self): '''Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If this was the only active connection, we change the global connection state. ''' connection_path = self.connection_path NM = dbusmock.get_object(MAIN_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) # Find the associated active connection(s). active_connections = NM.Get(MAIN_IFACE, 'ActiveConnections') associated_active_connections = [] for ac in active_connections: ac_obj = dbusmock.get_object(ac) ac_con = ac_obj.Get(ACTIVE_CONNECTION_IFACE, 'Connection') if ac_con == connection_path: associated_active_connections.append(ac) # We found that the connection we are deleting are associated to all # active connections and subsequently set the global state to # disconnected. if len(active_connections) == len(associated_active_connections): self.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTED) # Remove the connection from all associated devices. # We also remove all associated active connections. for dev_path in NM.GetDevices(): dev_obj = dbusmock.get_object(dev_path) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') for ac in associated_active_connections: NM.RemoveActiveConnection(dev_path, ac) if connection_path not in connections: continue connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) # Remove the connection from the settings interface main_connections = settings_obj.ListConnections() if connection_path not in main_connections: return main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) # Remove the connection from the mock connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.RemoveObject(connection_path) python-dbusmock-0.16.3/dbusmock/templates/notification_daemon.py0000664000175000017500000000336112605434671025742 0ustar martinmartin00000000000000'''notification-daemon mock template This creates the expected methods and properties of the notification-daemon services, but no devices. You can specify non-default capabilities in "parameters". ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' BUS_NAME = 'org.freedesktop.Notifications' MAIN_OBJ = '/org/freedesktop/Notifications' MAIN_IFACE = 'org.freedesktop.Notifications' SYSTEM_BUS = False # default capabilities, can be modified with "capabilities" parameter default_caps = ['body', 'body-markup', 'icon-static', 'image/svg+xml', 'private-synchronous', 'append', 'private-icon-only', 'truncation'] def load(mock, parameters): if 'capabilities' in parameters: caps = parameters['capabilities'].split() else: caps = default_caps # next notification ID mock.next_id = 1 mock.AddMethods(MAIN_IFACE, [ ('GetCapabilities', '', 'as', 'ret = %s' % repr(caps)), ('CloseNotification', 'i', '', 'if args[0] < self.next_id: self.EmitSignal(' '"", "NotificationClosed", "uu", [args[0], 1])'), ('GetServerInformation', '', 'ssss', 'ret = ("mock-notify", "test vendor", "1.0", "1.1")'), ('Notify', 'susssasa{sv}i', 'u', '''if args[1]: ret = args[1] else: ret = self.next_id self.next_id += 1 '''), ]) python-dbusmock-0.16.3/dbusmock/templates/ofono.py0000664000175000017500000004046212605434632023051 0ustar martinmartin00000000000000'''ofonod D-BUS mock template''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus import dbusmock BUS_NAME = 'org.ofono' MAIN_OBJ = '/' MAIN_IFACE = 'org.ofono.Manager' SYSTEM_BUS = True NOT_IMPLEMENTED = 'raise dbus.exceptions.DBusException("not implemented", name="org.ofono.Error.NotImplemented")' # interface org.ofono.Manager { # methods: # GetModems(out a(oa{sv}) modems); # signals: # ModemAdded(o path, # a{sv} properties); # ModemRemoved(o path); # }; _parameters = {} def load(mock, parameters): global _parameters mock.modems = [] # object paths _parameters = parameters mock.AddMethod(MAIN_IFACE, 'GetModems', '', 'a(oa{sv})', 'ret = [(m, objects[m].GetAll("org.ofono.Modem")) for m in self.modems]') if not parameters.get('no_modem', False): mock.AddModem(parameters.get('ModemName', 'ril_0'), {}) # interface org.ofono.Modem { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # signals: # PropertyChanged(s name, # v value); # }; @dbus.service.method(dbusmock.MOCK_IFACE, in_signature='sa{sv}', out_signature='s') def AddModem(self, name, properties): '''Convenience method to add a modem You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac". For future extensions you can specify a "properties" array, but no extra properties are supported for now. Returns the new object path. ''' path = '/' + name self.AddObject(path, 'org.ofono.Modem', { 'Online': dbus.Boolean(True, variant_level=1), 'Powered': dbus.Boolean(True, variant_level=1), 'Lockdown': dbus.Boolean(False, variant_level=1), 'Emergency': dbus.Boolean(False, variant_level=1), 'Manufacturer': dbus.String('Fakesys', variant_level=1), 'Model': dbus.String('Mock Modem', variant_level=1), 'Revision': dbus.String('0815.42', variant_level=1), 'Type': dbus.String('hardware', variant_level=1), 'Interfaces': ['org.ofono.CallVolume', 'org.ofono.VoiceCallManager', 'org.ofono.NetworkRegistration', 'org.ofono.SimManager', # 'org.ofono.MessageManager', 'org.ofono.ConnectionManager', # 'org.ofono.NetworkTime' ], # 'Features': ['sms', 'net', 'gprs', 'sim'] 'Features': ['gprs', 'net'], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.Modem")'), ('SetProperty', 'sv', '', 'self.Set("org.ofono.Modem", args[0], args[1]); ' 'self.EmitSignal("org.ofono.Modem", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ] ) obj = dbusmock.mockobject.objects[path] obj.name = name add_voice_call_api(obj) add_netreg_api(obj) add_simmanager_api(obj) add_connectionmanager_api(obj) self.modems.append(path) props = obj.GetAll('org.ofono.Modem', dbus_interface=dbus.PROPERTIES_IFACE) self.EmitSignal(MAIN_IFACE, 'ModemAdded', 'oa{sv}', [path, props]) return path # interface org.ofono.VoiceCallManager { # methods: # GetProperties(out a{sv} properties); # Dial(in s number, # in s hide_callerid, # out o path); # Transfer(); # SwapCalls(); # ReleaseAndAnswer(); # ReleaseAndSwap(); # HoldAndAnswer(); # HangupAll(); # PrivateChat(in o call, # out ao calls); # CreateMultiparty(out o calls); # HangupMultiparty(); # SendTones(in s SendTones); # GetCalls(out a(oa{sv}) calls_with_properties); # signals: # Forwarded(s type); # BarringActive(s type); # PropertyChanged(s name, # v value); # CallAdded(o path, # a{sv} properties); # CallRemoved(o path); # }; def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [] # object paths mock.AddMethods('org.ofono.VoiceCallManager', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.VoiceCallManager")'), ('Transfer', '', '', ''), ('SwapCalls', '', '', ''), ('ReleaseAndAnswer', '', '', ''), ('ReleaseAndSwap', '', '', ''), ('HoldAndAnswer', '', '', ''), ('SendTones', 's', '', ''), ('PrivateChat', 'o', 'ao', NOT_IMPLEMENTED), ('CreateMultiparty', '', 'o', NOT_IMPLEMENTED), ('HangupMultiparty', '', '', NOT_IMPLEMENTED), ('GetCalls', '', 'a(oa{sv})', 'ret = [(c, objects[c].GetAll("org.ofono.VoiceCall")) for c in self.calls]') ]) @dbus.service.method('org.ofono.VoiceCallManager', in_signature='ss', out_signature='s') def Dial(self, number, hide_callerid): path = self._object_path + '/voicecall%02i' % (len(self.calls) + 1) self.AddObject(path, 'org.ofono.VoiceCall', { 'State': dbus.String('dialing', variant_level=1), 'LineIdentification': dbus.String(number, variant_level=1), 'Name': dbus.String('', variant_level=1), 'Multiparty': dbus.Boolean(False, variant_level=1), 'Multiparty': dbus.Boolean(False, variant_level=1), 'RemoteHeld': dbus.Boolean(False, variant_level=1), 'RemoteMultiparty': dbus.Boolean(False, variant_level=1), 'Emergency': dbus.Boolean(False, variant_level=1), }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.VoiceCall")'), ('Deflect', 's', '', NOT_IMPLEMENTED), ('Hangup', '', '', 'self.parent.calls.remove(self._object_path);' 'self.parent.RemoveObject(self._object_path);' 'self.EmitSignal("org.ofono.VoiceCallManager", "CallRemoved", "o", [self._object_path])'), ('Answer', '', '', NOT_IMPLEMENTED), ] ) obj = dbusmock.mockobject.objects[path] obj.parent = self self.calls.append(path) self.EmitSignal('org.ofono.VoiceCallManager', 'CallAdded', 'oa{sv}', [path, obj.GetProperties()]) return path @dbus.service.method('org.ofono.VoiceCallManager', in_signature='', out_signature='') def HangupAll(self): print('XXX HangupAll', self.calls) for c in list(self.calls): # needs a copy dbusmock.mockobject.objects[c].Hangup() assert self.calls == [] # interface org.ofono.NetworkRegistration { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # Register(); # GetOperators(out a(oa{sv}) operators_with_properties); # Scan(out a(oa{sv}) operators_with_properties); # signals: # PropertyChanged(s name, # v value); # }; # # for //operator/: # interface org.ofono.NetworkOperator { # methods: # GetProperties(out a{sv} properties); # Register(); # signals: # PropertyChanged(s name, # v value); # properties: # }; def get_all_operators(mock): return 'ret = [(m, objects[m].GetAll("org.ofono.NetworkOperator")) ' \ 'for m in objects if "%s/operator/" in m]' % mock.name def add_netreg_api(mock): '''Add org.ofono.NetworkRegistration API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperties('org.ofono.NetworkRegistration', { 'Mode': 'auto', 'Status': 'registered', 'LocationAreaCode': _parameters.get('LocationAreaCode', 987), 'CellId': _parameters.get('CellId', 10203), 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technology': _parameters.get('Technology', 'gsm'), 'Name': _parameters.get('Name', 'fake.tel'), 'Strength': _parameters.get('Strength', dbus.Byte(80)), 'BaseStation': _parameters.get('BaseStation', ''), }) mock.AddObject('/%s/operator/op1' % mock.name, 'org.ofono.NetworkOperator', { 'Name': _parameters.get('Name', 'fake.tel'), 'Status': 'current', 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technologies': [_parameters.get('Technology', 'gsm')], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkOperator")'), ('Register', '', '', ''), ] # noqa: silly pep8 error here about hanging indent ) mock.AddMethods('org.ofono.NetworkRegistration', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkRegistration")'), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': 'org.ofono.NetworkRegistration'}), ('Register', '', '', ''), ('GetOperators', '', 'a(oa{sv})', get_all_operators(mock)), ('Scan', '', 'a(oa{sv})', get_all_operators(mock)), ]) # interface org.ofono.SimManager { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # ChangePin(in s type, # in s oldpin, # in s newpin); # EnterPin(in s type, # in s pin); # ResetPin(in s type, # in s puk, # in s newpin); # LockPin(in s type, # in s pin); # UnlockPin(in s type, # in s pin); # GetIcon(in y id, # out ay icon); # signals: # PropertyChanged(s name, # v value); # }; def add_simmanager_api(mock): '''Add org.ofono.SimManager API to a mock''' iface = 'org.ofono.SimManager' mock.AddProperties(iface, { 'CardIdentifier': _parameters.get('CardIdentifier', 12345), 'Present': _parameters.get('Present', dbus.Boolean(True)), 'Retries': _parameters.get('Retries', dbus.Dictionary([["pin", dbus.Byte(3)], ["puk", dbus.Byte(10)]])), 'PinRequired': _parameters.get('PinRequired', "none"), 'SubscriberNumbers': _parameters.get('SubscriberNumbers', ['123456789', '234567890']), 'SubscriberIdentity': _parameters.get('SubscriberIdentity', "23456"), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('ChangePin', 'sss', '', ''), ('EnterPin', 'ss', '', 'correctPin = "1234"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' newRetries["pin"] = dbus.Byte(newRetries["pin"] - 1)\n' 'elif args[0] == "pin":\n' ' newRetries["pin"] = dbus.Byte(3)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('ResetPin', 'sss', '', 'correctPuk = "12345678"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' newRetries["puk"] = dbus.Byte(newRetries["puk"] - 1)\n' 'elif args[0] == "puk":\n' ' newRetries["pin"] = dbus.Byte(3)\n' ' newRetries["puk"] = dbus.Byte(10)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('LockPin', 'ss', '', ''), ('UnlockPin', 'ss', '', ''), ]) # interface org.ofono.ConnectionManager { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # AddContext(in s type, # out o path); # RemoveContext(in o path); # DeactivateAll(); # GetContexts(out a(oa{sv}) contexts_with_properties); # signals: # PropertyChanged(s name, # v value); # ContextAdded(o path, # v properties); # ContextRemoved(o path); # }; def add_connectionmanager_api(mock): '''Add org.ofono.ConnectionManager API to a mock''' iface = 'org.ofono.ConnectionManager' mock.AddProperties(iface, { 'Attached': _parameters.get('Attached', True), 'Bearer': _parameters.get('Bearer', 'gprs'), 'RoamingAllowed': _parameters.get('RoamingAllowed', False), 'Powered': _parameters.get('ConnectionPowered', True), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('AddContext', 's', 'o', 'ret = "/"'), ('RemoveContext', 'o', '', ''), ('DeactivateAll', '', '', ''), ('GetContexts', '', 'a(oa{sv})', 'ret = dbus.Array([])'), ]) # unimplemented Modem object interfaces: # # interface org.ofono.NetworkTime { # methods: # GetNetworkTime(out a{sv} time); # signals: # NetworkTimeChanged(a{sv} time); # properties: # }; # interface org.ofono.MessageManager { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # SendMessage(in s to, # in s text, # out o path); # GetMessages(out a(oa{sv}) messages); # signals: # PropertyChanged(s name, # v value); # IncomingMessage(s message, # a{sv} info); # ImmediateMessage(s message, # a{sv} info); # MessageAdded(o path, # a{sv} properties); # MessageRemoved(o path); # }; # interface org.ofono.CallVolume { # methods: # GetProperties(out a{sv} properties); # SetProperty(in s property, # in v value); # signals: # PropertyChanged(s property, # v value); # }; python-dbusmock-0.16.3/dbusmock/templates/polkitd.py0000664000175000017500000000405112264500431023361 0ustar martinmartin00000000000000'''polkitd mock template This creates the expected methods and properties of the main org.freedesktop.PolicyKit1 object. By default, all actions are rejected. You can call AllowUnknown() and SetAllowed() on the mock D-BUS interface to control which actions are allowed. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus from dbusmock import MOCK_IFACE BUS_NAME = 'org.freedesktop.PolicyKit1' MAIN_OBJ = '/org/freedesktop/PolicyKit1/Authority' MAIN_IFACE = 'org.freedesktop.PolicyKit1.Authority' SYSTEM_BUS = True def load(mock, parameters): mock.AddMethod(MAIN_IFACE, 'CheckAuthorization', '(sa{sv})sa{ss}us', '(bba{ss})', '''ret = (args[1] in self.allowed or self.allow_unknown, False, {'test': 'test'})''') mock.AddProperties(MAIN_IFACE, dbus.Dictionary({ 'BackendName': 'local', 'BackendVersion': '0.8.15', 'BackendFeatures': dbus.UInt32(1, variant_level=1), }, signature='sv')) # default state mock.allow_unknown = False mock.allowed = [] @dbus.service.method(MOCK_IFACE, in_signature='b', out_signature='') def AllowUnknown(self, default): '''Control whether unknown actions are allowed This controls the return value of CheckAuthorization for actions which were not explicitly allowed by SetAllowed(). ''' self.allow_unknown = default @dbus.service.method(MOCK_IFACE, in_signature='as', out_signature='') def SetAllowed(self, actions): '''Set allowed actions''' self.allowed = actions python-dbusmock-0.16.3/dbusmock/templates/timedated.py0000664000175000017500000000340412536263500023661 0ustar martinmartin00000000000000'''systemd timedated mock template This creates the expected methods and properties of the main org.freedesktop.timedate object. You can specify D-BUS property values like "Timezone" or "NTP" in "parameters". ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Iain Lane' __email__ = 'iain.lane@canonical.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus BUS_NAME = 'org.freedesktop.timedate1' MAIN_OBJ = '/org/freedesktop/timedate1' MAIN_IFACE = 'org.freedesktop.timedate1' SYSTEM_BUS = True def setProperty(prop): return 'self.Set("%s", "%s", args[0])' % (MAIN_IFACE, prop) def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [ # There's nothing this can usefully do, but provide it for compatibility ('SetTime', 'xbb', '', ''), ('SetTimezone', 'sb', '', setProperty('Timezone')), ('SetLocalRTC', 'bbb', '', setProperty('LocalRTC')), ('SetNTP', 'bb', '', setProperty('NTP') + '; ' + setProperty('NTPSynchronized')) ]) mock.AddProperties(MAIN_IFACE, dbus.Dictionary({ 'Timezone': parameters.get('Timezone', 'Etc/Utc'), 'LocalRTC': parameters.get('LocalRTC', False), 'NTP': parameters.get('NTP', True), 'NTPSynchronized': parameters.get('NTP', True), 'CanNTP': parameters.get('CanNTP', True) }, signature='sv')) python-dbusmock-0.16.3/dbusmock/templates/upower.py0000664000175000017500000002506112506211460023240 0ustar martinmartin00000000000000'''upowerd mock template This creates the expected methods and properties of the main org.freedesktop.UPower object, but no devices. You can specify any property such as 'OnLowBattery' or the return value of 'SuspendAllowed', 'HibernateAllowed', and 'GetCriticalAction' in "parameters". This provides the 0.9 D-BUS API of upower by default, but if the DaemonVersion property (in parameters) is set to >= 0.99 it will provide the 1.0 D-BUS API instead. ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012, 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import dbus from dbusmock import MOCK_IFACE, mockobject import dbusmock BUS_NAME = 'org.freedesktop.UPower' MAIN_OBJ = '/org/freedesktop/UPower' MAIN_IFACE = 'org.freedesktop.UPower' SYSTEM_BUS = True DEVICE_IFACE = 'org.freedesktop.UPower.Device' def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [ ('EnumerateDevices', '', 'ao', 'ret = [k for k in objects.keys() ' 'if "/devices" in k and not k.endswith("/DisplayDevice")]'), ]) props = dbus.Dictionary({ 'DaemonVersion': parameters.get('DaemonVersion', '0.9'), 'OnBattery': parameters.get('OnBattery', False), 'LidIsPresent': parameters.get('LidIsPresent', True), 'LidIsClosed': parameters.get('LidIsClosed', False), 'LidForceSleep': parameters.get('LidForceSleep', True), 'IsDocked': parameters.get('IsDocked', False), }, signature='sv') mock.api1 = props['DaemonVersion'] >= '0.99' if mock.api1: mock.AddMethods(MAIN_IFACE, [ ('GetCriticalAction', '', 's', 'ret = "%s"' % parameters.get('GetCriticalAction', 'HybridSleep')), ('GetDisplayDevice', '', 'o', 'ret = "/org/freedesktop/UPower/devices/DisplayDevice"') ]) mock.p_display_dev = '/org/freedesktop/UPower/devices/DisplayDevice' # add Display device; for defined properties, see # http://cgit.freedesktop.org/upower/tree/src/org.freedesktop.UPower.xml mock.AddObject(mock.p_display_dev, DEVICE_IFACE, { 'Type': dbus.UInt32(0, variant_level=1), 'State': dbus.UInt32(0, variant_level=1), 'Percentage': dbus.Double(0.0, variant_level=1), 'Energy': dbus.Double(0.0, variant_level=1), 'EnergyFull': dbus.Double(0.0, variant_level=1), 'EnergyRate': dbus.Double(0.0, variant_level=1), 'TimeToEmpty': dbus.Int64(0, variant_level=1), 'TimeToFull': dbus.Int64(0, variant_level=1), 'IsPresent': dbus.Boolean(False, variant_level=1), 'IconName': dbus.String('', variant_level=1), # LEVEL_NONE 'WarningLevel': dbus.UInt32(1, variant_level=1), }, [ ('Refresh', '', '', ''), ]) mock.device_sig_type = 'o' else: props['CanSuspend'] = parameters.get('CanSuspend', True) props['CanHibernate'] = parameters.get('CanHibernate', True) props['OnLowBattery'] = parameters.get('OnLowBattery', True) mock.AddMethods(MAIN_IFACE, [ ('Suspend', '', '', ''), ('SuspendAllowed', '', 'b', 'ret = %s' % parameters.get('SuspendAllowed', True)), ('HibernateAllowed', '', 'b', 'ret = %s' % parameters.get('HibernateAllowed', True)), ]) mock.device_sig_type = 's' mock.AddProperties(MAIN_IFACE, props) @dbus.service.method(MOCK_IFACE, in_signature='ss', out_signature='s') def AddAC(self, device_name, model_name): '''Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Online': dbus.Boolean(True, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path @dbus.service.method(MOCK_IFACE, in_signature='ssdx', out_signature='s') def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): '''Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Percentage': dbus.Double(percentage, variant_level=1), 'TimeToEmpty': dbus.Int64(seconds_to_empty, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(percentage, variant_level=1), # UP_DEVICE_STATE_DISCHARGING 'State': dbus.UInt32(2, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path @dbus.service.method(MOCK_IFACE, in_signature='ssdx', out_signature='s') def AddChargingBattery(self, device_name, model_name, percentage, seconds_to_full): '''Convenience method to add a charging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is full. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Percentage': dbus.Double(percentage, variant_level=1), 'TimeToFull': dbus.Int64(seconds_to_full, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(percentage, variant_level=1), # UP_DEVICE_STATE_CHARGING 'State': dbus.UInt32(1, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path @dbus.service.method(MOCK_IFACE, in_signature='uuddddxxbsu', out_signature='') def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): '''Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API. ''' if not self.api1: raise dbus.exceptions.DBusException( 'SetupDisplayDevice() can only be used with the 1.0 API', name=MOCK_IFACE + '.APIVersion') display_props = mockobject.objects[self.p_display_dev] display_props.Set(DEVICE_IFACE, 'Type', dbus.UInt32(type)) display_props.Set(DEVICE_IFACE, 'State', dbus.UInt32(state)) display_props.Set(DEVICE_IFACE, 'Percentage', percentage) display_props.Set(DEVICE_IFACE, 'Energy', energy) display_props.Set(DEVICE_IFACE, 'EnergyFull', energy_full) display_props.Set(DEVICE_IFACE, 'EnergyRate', energy_rate) display_props.Set(DEVICE_IFACE, 'TimeToEmpty', dbus.Int64(time_to_empty)) display_props.Set(DEVICE_IFACE, 'TimeToFull', dbus.Int64(time_to_full)) display_props.Set(DEVICE_IFACE, 'IsPresent', is_present) display_props.Set(DEVICE_IFACE, 'IconName', icon_name) display_props.Set(DEVICE_IFACE, 'WarningLevel', dbus.UInt32(warning_level)) @dbus.service.method(MOCK_IFACE, in_signature='oa{sv}', out_signature='') def SetDeviceProperties(self, object_path, properties): '''Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; otherwise, the older org.freedesktop.UPower DeviceChanged signal will be emitted. ''' device = dbusmock.get_object(object_path) # set the properties for key, value in properties.items(): device.Set(DEVICE_IFACE, key, value) # notify the listeners if not self.api1: self.EmitSignal(MAIN_IFACE, 'DeviceChanged', 's', [object_path]) python-dbusmock-0.16.3/dbusmock/templates/urfkill.py0000664000175000017500000000717512506211460023375 0ustar martinmartin00000000000000'''urfkill mock template This creates the expected methods and properties of the main urfkill object, but no devices. You can specify any property such as urfkill in "parameters". ''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Jussi Pakkanen' __email__ = 'jussi.pakkanen@canonical.com' __copyright__ = '(C) 2015 Canonical ltd' __license__ = 'LGPL 3+' import dbus import dbusmock SYSTEM_BUS = True BUS_NAME = 'org.freedesktop.URfkill' MAIN_OBJ = '/org/freedesktop/URfkill' MAIN_IFACE = 'org.freedesktop.URfkill' individual_objects = ['BLUETOOTH', 'FM', 'GPS', 'NFC', 'UWB', 'WIMAX', 'WLAN', 'WWAN'] type2objectname = { 1: 'WLAN', 2: 'BLUETOOTH', 3: 'UWB', 4: 'WIMAX', 5: 'WWAN', 6: 'GPS', 7: 'FM', } KS_NOTAVAILABLE = -1 KS_UNBLOCKED = 0 KS_SOFTBLOCKED = 1 KS_HARDBLOCKED = 2 def toggle_flight_mode(self, new_block_state): new_block_state = bool(new_block_state) if self.flight_mode == new_block_state: return True self.flight_mode = new_block_state for i in individual_objects: old_value = self.internal_states[i] if old_value == 1: continue # It was already blocked so we don't need to do anything path = '/org/freedesktop/URfkill/' + i obj = dbusmock.get_object(path) if new_block_state: obj.Set('org.freedesktop.URfkill.Killswitch', 'state', 1) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) else: obj.Set('org.freedesktop.URfkill.Killswitch', 'state', 0) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) self.EmitSignal(MAIN_IFACE, 'FlightModeChanged', 'b', [self.flight_mode]) return True def block(self, index, should_block): should_block = bool(should_block) if index not in type2objectname: return False objname = type2objectname[index] if should_block: new_block_state = 1 else: new_block_state = 0 if self.internal_states[objname] != new_block_state: path = '/org/freedesktop/URfkill/' + objname obj = dbusmock.get_object(path) self.internal_states[objname] = new_block_state obj.Set('org.freedesktop.URfkill.Killswitch', 'state', new_block_state) obj.EmitSignal('org.freedesktop.URfkill.Killswitch', 'StateChanged', '', []) return True def load(mock, parameters): mock.toggle_flight_mode = toggle_flight_mode mock.block = block mock.flight_mode = False mock.internal_states = {} for oname in individual_objects: mock.internal_states[oname] = KS_UNBLOCKED # First we create the main urfkill object. mock.AddMethods(MAIN_IFACE, [ ('IsFlightMode', '', 'b', 'ret = self.flight_mode'), ('FlightMode', 'b', 'b', 'ret = self.toggle_flight_mode(self, args[0])'), ('Block', 'ub', 'b', 'ret = self.block(self, args[0], args[1])'), ]) mock.AddProperties(MAIN_IFACE, dbus.Dictionary({ 'DaemonVersion': parameters.get('DaemonVersion', '0.6.0'), 'KeyControl': parameters.get('KeyControl', True) }, signature='sv')) for i in individual_objects: path = '/org/freedesktop/URfkill/' + i mock.AddObject(path, 'org.freedesktop.URfkill.Killswitch', {'state': mock.internal_states[i]}, []) python-dbusmock-0.16.3/dbusmock/__init__.py0000664000175000017500000000153012633532730021462 0ustar martinmartin00000000000000# coding: UTF-8 '''Mock D-BUS objects for test suites.''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' __version__ = '0.16.3' from dbusmock.mockobject import (DBusMockObject, MOCK_IFACE, OBJECT_MANAGER_IFACE, get_object, get_objects) from dbusmock.testcase import DBusTestCase __all__ = ['DBusMockObject', 'MOCK_IFACE', 'OBJECT_MANAGER_IFACE', 'DBusTestCase', 'get_object', 'get_objects'] python-dbusmock-0.16.3/dbusmock/__main__.py0000664000175000017500000001066512605433114021447 0ustar martinmartin00000000000000# coding: UTF-8 '''Main entry point for running mock server.''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import argparse import dbus.service import dbusmock.mockobject import dbusmock.testcase import json import sys def parse_args(): parser = argparse.ArgumentParser(description='mock D-BUS object') parser.add_argument('-s', '--system', action='store_true', help='put object(s) on system bus (default: session bus)') parser.add_argument('-l', '--logfile', metavar='PATH', help='path of log file') parser.add_argument('-t', '--template', metavar='NAME', help='template to load (instead of specifying name, path, interface)') parser.add_argument('name', metavar='NAME', nargs='?', help='D-BUS name to claim (e. g. "com.example.MyService") (if not using -t)') parser.add_argument('path', metavar='PATH', nargs='?', help='D-BUS object path for initial/main object (if not using -t)') parser.add_argument('interface', metavar='INTERFACE', nargs='?', help='main D-BUS interface name for initial object (if not using -t)') parser.add_argument('-m', '--is-object-manager', action='store_true', help='automatically implement the org.freedesktop.DBus.ObjectManager interface') parser.add_argument('-p', '--parameters', help='JSON dictionary of parameters to pass to the template') args = parser.parse_args() if args.template: if args.name or args.path or args.interface: parser.error('--template and specifying NAME/PATH/INTERFACE are mutually exclusive') else: if not args.name or not args.path or not args.interface: parser.error('Not using a template, you must specify NAME, PATH, and INTERFACE') return args if __name__ == '__main__': import dbus.mainloop.glib from gi.repository import GLib args = parse_args() dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) if args.template: module = dbusmock.mockobject.load_module(args.template) args.name = module.BUS_NAME args.path = module.MAIN_OBJ args.system = module.SYSTEM_BUS if hasattr(module, 'IS_OBJECT_MANAGER'): args.is_object_manager = module.IS_OBJECT_MANAGER else: args.is_object_manager = False if args.is_object_manager and not hasattr(module, 'MAIN_IFACE'): args.interface = dbusmock.mockobject.OBJECT_MANAGER_IFACE else: args.interface = module.MAIN_IFACE main_loop = GLib.MainLoop() bus = dbusmock.testcase.DBusTestCase.get_dbus(args.system) # quit mock when the bus is going down bus.add_signal_receiver(main_loop.quit, signal_name='Disconnected', path='/org/freedesktop/DBus/Local', dbus_interface='org.freedesktop.DBus.Local') bus_name = dbus.service.BusName(args.name, bus, allow_replacement=True, replace_existing=True, do_not_queue=True) main_object = dbusmock.mockobject.DBusMockObject(bus_name, args.path, args.interface, {}, args.logfile, args.is_object_manager) parameters = None if args.parameters: try: parameters = json.loads(args.parameters) except ValueError as detail: sys.stderr.write('Malformed JSON given for parameters: %s\n' % detail) sys.exit(2) if not isinstance(parameters, dict): sys.stderr.write('JSON parameters must be a dictionary\n') sys.exit(2) if args.template: main_object.AddTemplate(args.template, parameters) dbusmock.mockobject.objects[args.path] = main_object main_loop.run() python-dbusmock-0.16.3/dbusmock/mockobject.py0000664000175000017500000006655212531036130022050 0ustar martinmartin00000000000000# coding: UTF-8 '''Mock D-BUS objects for test suites.''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import copy import time import sys import types import importlib import imp from xml.etree import ElementTree # we do not use this ourselves, but mock methods often want to use this import os os # pyflakes import dbus import dbus.service # global path -> DBusMockObject mapping objects = {} MOCK_IFACE = 'org.freedesktop.DBus.Mock' OBJECT_MANAGER_IFACE = 'org.freedesktop.DBus.ObjectManager' # stubs to keep code compatible with Python 2 and 3 if sys.version_info[0] >= 3: long = int unicode = str def load_module(name): if os.path.exists(name) and os.path.splitext(name)[1] == '.py': mod = imp.new_module(os.path.splitext(os.path.basename(name))[0]) with open(name) as f: exec(f.read(), mod.__dict__, mod.__dict__) return mod return importlib.import_module('dbusmock.templates.' + name) class DBusMockObject(dbus.service.Object): '''Mock D-Bus object This can be configured to have arbitrary methods (including code execution) and properties via methods on the org.freedesktop.DBus.Mock interface, so that you can control the mock from any programming language. ''' def __init__(self, bus_name, path, interface, props, logfile=None, is_object_manager=False): '''Create a new DBusMockObject bus_name: A dbus.service.BusName instance where the object will be put on path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) props: A property_name (string) → property (Variant) map with initial properties on "interface" logfile: When given, method calls will be logged into that file name; if None, logging will be written to stdout. Note that you can also query the called methods over D-BUS with GetCalls() and GetMethodCalls(). is_object_manager: If True, the GetManagedObjects method will automatically be implemented on the object, returning all objects which have this one’s path as a prefix of theirs. Note that the InterfacesAdded and InterfacesRemoved signals will not be automatically emitted. ''' dbus.service.Object.__init__(self, bus_name, path) self.bus_name = bus_name self.path = path self.interface = interface self.is_object_manager = is_object_manager self._template = None self._template_parameters = None if logfile: self.logfile = open(logfile, 'w') else: self.logfile = None self.is_logfile_owner = True self.call_log = [] if props is None: props = {} self._reset(props) def __del__(self): if self.logfile and self.is_logfile_owner: self.logfile.close() def _set_up_object_manager(self): '''Set up this mock object as a D-Bus ObjectManager.''' if self.path == '/': cond = 'k != \'/\'' else: cond = 'k.startswith(\'%s/\')' % self.path self.AddMethod(OBJECT_MANAGER_IFACE, 'GetManagedObjects', '', 'a{oa{sa{sv}}}', 'ret = {dbus.ObjectPath(k): objects[k].props ' + ' for k in objects.keys() if ' + cond + '}') def _reset(self, props): # interface -> name -> value self.props = {self.interface: props} # interface -> name -> (in_signature, out_signature, code, dbus_wrapper_fn) self.methods = {self.interface: {}} if self.is_object_manager: self._set_up_object_manager() @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v') def Get(self, interface_name, property_name): '''Standard D-Bus API for getting a property value''' self.log('Get %s.%s' % (interface_name, property_name)) if not interface_name: interface_name = self.interface try: return self.GetAll(interface_name)[property_name] except KeyError: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty') @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}') def GetAll(self, interface_name, *args, **kwargs): '''Standard D-Bus API for getting all property values''' self.log('GetAll ' + interface_name) if not interface_name: interface_name = self.interface try: return self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface') @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv', out_signature='') def Set(self, interface_name, property_name, value, *args, **kwargs): '''Standard D-Bus API for setting a property value''' self.log('Set %s.%s%s' % (interface_name, property_name, self.format_args((value,)))) try: iface_props = self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface') if property_name not in iface_props: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty') iface_props[property_name] = value self.EmitSignal('org.freedesktop.DBus.Properties', 'PropertiesChanged', 'sa{sv}as', [interface_name, dbus.Dictionary({property_name: value}, signature='sv'), dbus.Array([], signature='s') ]) @dbus.service.method(MOCK_IFACE, in_signature='ssa{sv}a(ssss)', out_signature='') def AddObject(self, path, interface, properties, methods): '''Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ]) ''' if path in objects: raise dbus.exceptions.DBusException( 'object %s already exists' % path, name='org.freedesktop.DBus.Mock.NameError') obj = DBusMockObject(self.bus_name, path, interface, properties) # make sure created objects inherit the log file stream obj.logfile = self.logfile obj.is_logfile_owner = False obj.AddMethods(interface, methods) objects[path] = obj @dbus.service.method(MOCK_IFACE, in_signature='s', out_signature='') def RemoveObject(self, path): '''Remove a D-Bus object from the mock As with AddObject, this will *not* emit the InterfacesRemoved signal if it’s an ObjectManager instance. ''' try: objects[path].remove_from_connection() del objects[path] except KeyError: raise dbus.exceptions.DBusException( 'object %s does not exist' % path, name='org.freedesktop.DBus.Mock.NameError') @dbus.service.method(MOCK_IFACE, in_signature='', out_signature='') def Reset(self): '''Reset the mock object state. Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemplate over D-Bus), it will be re-instantiated with that template. ''' # Clear other existing objects. for obj_name, obj in objects.items(): if obj_name != self.path: obj.remove_from_connection() objects.clear() # Reinitialise our state. Carefully remove new methods from our dict; # they don't not actually exist if they are a statically defined # template function for method_name in self.methods[self.interface]: try: delattr(self.__class__, method_name) except AttributeError: pass self._reset({}) if self._template is not None: self.AddTemplate(self._template, self._template_parameters) objects[self.path] = self @dbus.service.method(MOCK_IFACE, in_signature='sssss', out_signature='') def AddMethod(self, interface, name, in_sig, out_sig, code): '''Add a method to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the method in_sig: Signature of input arguments; for example "ias" for a method that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures out_sig: Signature of output arguments; for example "s" for a method that returns a string; use '' for methods that do not return anything. code: Python 3 code to run in the method call; you have access to the arguments through the "args" list, and can set the return value by assigning a value to the "ret" variable. You can also read the global "objects" variable, which is a dictionary mapping object paths to DBusMockObject instances. For keeping state across method calls, you are free to use normal Python members of the "self" object, which will be persistant for the whole mock's life time. E. g. you can have a method with "self.my_state = True", and another method that returns it with "ret = self.my_state". When specifying '', the method will not do anything (except logging) and return None. ''' if not interface: interface = self.interface n_args = len(dbus.Signature(in_sig)) # we need to have separate methods for dbus-python, so clone # mock_method(); using message_keyword with this dynamic approach fails # because inspect cannot handle those, so pass on interface and method # name as first positional arguments method = lambda self, *args, **kwargs: DBusMockObject.mock_method( self, interface, name, in_sig, *args, **kwargs) # we cannot specify in_signature here, as that trips over a consistency # check in dbus-python; we need to set it manually instead dbus_method = dbus.service.method(interface, out_signature=out_sig)(method) dbus_method.__name__ = str(name) dbus_method._dbus_in_signature = in_sig dbus_method._dbus_args = ['arg%i' % i for i in range(1, n_args + 1)] # for convenience, add mocked methods on the primary interface as # callable methods if interface == self.interface: setattr(self.__class__, name, dbus_method) self.methods.setdefault(interface, {})[str(name)] = (in_sig, out_sig, code, dbus_method) @dbus.service.method(MOCK_IFACE, in_signature='sa(ssss)', out_signature='') def AddMethods(self, interface, methods): '''Add several methods to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). methods: list of 4-tuples (name, in_sig, out_sig, code) describing one method each. See AddMethod() for details of the tuple values. ''' for method in methods: self.AddMethod(interface, *method) @dbus.service.method(MOCK_IFACE, in_signature='ssv', out_signature='') def AddProperty(self, interface, name, value): '''Add property to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). name: Property name. value: Property value. ''' if not interface: interface = self.interface try: self.props[interface][name] raise dbus.exceptions.DBusException( 'property %s already exists' % name, name=self.interface + '.PropertyExists') except KeyError: # this is what we expect pass # copy.copy removes one level of variant-ness, which means that the # types get exported in introspection data correctly, but we can't do # this for container types. if not (isinstance(value, dbus.Dictionary) or isinstance(value, dbus.Array)): value = copy.copy(value) self.props.setdefault(interface, {})[name] = value @dbus.service.method(MOCK_IFACE, in_signature='sa{sv}', out_signature='') def AddProperties(self, interface, properties): '''Add several properties to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). properties: A property_name (string) → value map ''' for k, v in properties.items(): self.AddProperty(interface, k, v) @dbus.service.method(MOCK_IFACE, in_signature='sa{sv}', out_signature='') def AddTemplate(self, template, parameters): '''Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of common properties, interfaces, and methods. template: Name of the template to load or the full path to a *.py file for custom templates. See "pydoc dbusmock.templates" for a list of available templates from python-dbusmock package, and "pydoc dbusmock.templates.NAME" for documentation about template NAME. parameters: A parameter (string) → value (variant) map, for parameterizing templates. Each template can define their own, see documentation of that particular template for details. ''' try: module = load_module(template) except ImportError as e: raise dbus.exceptions.DBusException('Cannot add template %s: %s' % (template, str(e)), name='org.freedesktop.DBus.Mock.TemplateError') # If the template specifies this is an ObjectManager, set that up if hasattr(module, 'IS_OBJECT_MANAGER') and module.IS_OBJECT_MANAGER: self._set_up_object_manager() # pick out all D-BUS service methods and add them to our interface for symbol in dir(module): fn = getattr(module, symbol) if ('_dbus_interface' in dir(fn) and ('_dbus_is_signal' not in dir(fn) or not fn._dbus_is_signal)): # for dbus-python compatibility, add methods as callables setattr(self.__class__, symbol, fn) self.methods.setdefault(fn._dbus_interface, {})[str(symbol)] = ( fn._dbus_in_signature, fn._dbus_out_signature, '', fn ) if parameters is None: parameters = {} module.load(self, parameters) # save the given template and parameters for re-instantiation on # Reset() self._template = template self._template_parameters = parameters @dbus.service.method(MOCK_IFACE, in_signature='sssav', out_signature='') def EmitSignal(self, interface, name, signature, args): '''Emit a signal from the object. interface: D-Bus interface to send the signal from. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the signal signature: Signature of input arguments; for example "ias" for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures args: variant array with signal arguments; must match order and type in "signature" ''' if not interface: interface = self.interface # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=signature, *args) args = m.get_args_list() fn = lambda self, *args: self.log('emit %s.%s%s' % (interface, name, self.format_args(args))) fn.__name__ = str(name) dbus_fn = dbus.service.signal(interface)(fn) dbus_fn._dbus_signature = signature dbus_fn._dbus_args = ['arg%i' % i for i in range(1, len(args) + 1)] dbus_fn(self, *args) @dbus.service.method(MOCK_IFACE, in_signature='', out_signature='a(tsav)') def GetCalls(self): '''List all the logged calls since the last call to ClearCalls(). Return a list of (timestamp, method_name, args_list) tuples. ''' return self.call_log @dbus.service.method(MOCK_IFACE, in_signature='s', out_signature='a(tav)') def GetMethodCalls(self, method): '''List all the logged calls of a particular method. Return a list of (timestamp, args_list) tuples. ''' return [(row[0], row[2]) for row in self.call_log if row[1] == method] @dbus.service.method(MOCK_IFACE, in_signature='', out_signature='') def ClearCalls(self): '''Empty the log of mock call signatures.''' self.call_log = [] @dbus.service.signal(MOCK_IFACE, signature='sav') def MethodCalled(self, name, args): '''Signal emitted for every called mock method. This is emitted for all mock method calls. This can be used to confirm that a particular method was called with particular arguments, as an alternative to reading the mock's log or GetCalls(). ''' pass def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs): '''Master mock method. This gets "instantiated" in AddMethod(). Execute the code snippet of the method and return the "ret" variable if it was set. ''' # print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr) # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if in_signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=in_signature, *args) args = m.get_args_list() self.log(dbus_method + self.format_args(args)) self.call_log.append((int(time.time()), str(dbus_method), args)) self.MethodCalled(dbus_method, args) # The code may be a Python 3 string to interpret, or may be a function # object (if AddMethod was called from within Python itself, rather than # over D-Bus). code = self.methods[interface][dbus_method][2] if code and isinstance(code, types.FunctionType): return code(self, *args) elif code: loc = locals().copy() exec(code, globals(), loc) if 'ret' in loc: return loc['ret'] def format_args(self, args): '''Format a D-BUS argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a, int) or isinstance(a, long): return str(a) if isinstance(a, str) or isinstance(a, unicode): return '"' + str(a) + '"' if isinstance(a, list): return '[' + ', '.join([format_arg(x) for x in a]) + ']' if isinstance(a, dict): fmta = '{' first = True for k, v in a.items(): if first: first = False else: fmta += ', ' fmta += format_arg(k) + ': ' + format_arg(v) return fmta + '}' # fallback return repr(a) s = '' for a in args: if s: s += ' ' s += format_arg(a) if s: s = ' ' + s return s def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile else: fd = sys.stdout fd.write('%.3f %s\n' % (time.time(), msg)) fd.flush() @dbus.service.method(dbus.INTROSPECTABLE_IFACE, in_signature='', out_signature='s', path_keyword='object_path', connection_keyword='connection') def Introspect(self, object_path, connection): '''Return XML description of this object's interfaces, methods and signals. This wraps dbus-python's Introspect() method to include the dynamic methods and properties. ''' # temporarily add our dynamic methods cls = self.__class__.__module__ + '.' + self.__class__.__name__ orig_interfaces = self._dbus_class_table[cls] mock_interfaces = orig_interfaces.copy() for interface, methods in self.methods.items(): for method in methods: mock_interfaces.setdefault(interface, {})[method] = self.methods[interface][method][3] self._dbus_class_table[cls] = mock_interfaces xml = dbus.service.Object.Introspect(self, object_path, connection) tree = ElementTree.fromstring(xml) for name in self.props: # We might have properties for new interfaces we don't know about # yet. Try to find an existing node named after our # interface to append to, and create one if we can't. interface = tree.find(".//interface[@name='%s']" % name) if interface is None: interface = ElementTree.Element("interface", {"name": name}) tree.append(interface) for prop, val in self.props[name].items(): if val is None: # can't guess type from None, skip continue elem = ElementTree.Element("property", { "name": prop, # We don't store the signature anywhere, so guess it. "type": dbus.lowlevel.Message.guess_signature(val), "access": "readwrite"}) interface.append(elem) xml = ElementTree.tostring(tree, encoding='utf8', method='xml').decode('utf8') # restore original class table self._dbus_class_table[cls] = orig_interfaces return xml # Overwrite dbus-python's _method_lookup(), as that offers no way to have the # same method name on different interfaces orig_method_lookup = dbus.service._method_lookup def _dbusmock_method_lookup(obj, method_name, dbus_interface): try: m = obj.methods[dbus_interface or obj.interface][method_name] return (m[3], m[3]) except KeyError: return orig_method_lookup(obj, method_name, dbus_interface) dbus.service._method_lookup = _dbusmock_method_lookup # # Helper API for templates # def get_objects(): '''Return all existing object paths''' return objects.keys() def get_object(path): '''Return object for a given object path''' return objects[path] python-dbusmock-0.16.3/dbusmock/testcase.py0000664000175000017500000002207212264500431021533 0ustar martinmartin00000000000000# coding: UTF-8 '''unittest.TestCase convenience methods for DBusMocks''' # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import time import sys import unittest import subprocess import signal import os import errno import tempfile import dbus from dbusmock.mockobject import MOCK_IFACE, OBJECT_MANAGER_IFACE, load_module class DBusTestCase(unittest.TestCase): '''Base class for D-BUS mock tests. This provides some convenience API to start/stop local D-Buses, so that you can run a private local session and/or system bus to run mocks on. This also provides a spawn_server() static method to run the D-Bus mock server in a separate process. ''' session_bus_pid = None system_bus_pid = None @classmethod def start_session_bus(klass): '''Set up a private local session bus This gets stopped automatically in tearDownClass(). ''' (DBusTestCase.session_bus_pid, addr) = klass.start_dbus() os.environ['DBUS_SESSION_BUS_ADDRESS'] = addr @classmethod def start_system_bus(klass): '''Set up a private local system bus This gets stopped automatically in tearDownClass(). ''' # create a temporary configuration which makes the fake bus actually # appear a type "system" with tempfile.NamedTemporaryFile(prefix='dbusmock_cfg') as c: c.write(b''' system unix:tmpdir=/tmp ''') c.flush() (DBusTestCase.system_bus_pid, addr) = klass.start_dbus(conf=c.name) os.environ['DBUS_SYSTEM_BUS_ADDRESS'] = addr @classmethod def tearDownClass(klass): '''Stop private session/system buses''' if DBusTestCase.session_bus_pid is not None: klass.stop_dbus(DBusTestCase.session_bus_pid) del os.environ['DBUS_SESSION_BUS_ADDRESS'] DBusTestCase.session_bus_pid = None if DBusTestCase.system_bus_pid is not None: klass.stop_dbus(DBusTestCase.system_bus_pid) del os.environ['DBUS_SYSTEM_BUS_ADDRESS'] DBusTestCase.system_bus_pid = None @classmethod def start_dbus(klass, conf=None): '''Start a D-BUS daemon Return (pid, address) pair. Normally you do not need to call this directly. Use start_system_bus() and start_session_bus() instead. ''' argv = ['dbus-launch'] if conf: argv.append('--config-file=' + conf) out = subprocess.check_output(argv, universal_newlines=True) variables = {} for line in out.splitlines(): (k, v) = line.split('=', 1) variables[k] = v return (int(variables['DBUS_SESSION_BUS_PID']), variables['DBUS_SESSION_BUS_ADDRESS']) @classmethod def stop_dbus(klass, pid): '''Stop a D-BUS daemon Normally you do not need to call this directly. When you use start_system_bus() and start_session_bus(), these buses are automatically stopped in tearDownClass(). ''' signal.signal(signal.SIGTERM, signal.SIG_IGN) timeout = 50 while timeout > 0: try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno == errno.ESRCH: break else: raise time.sleep(0.1) else: sys.stderr.write('ERROR: timed out waiting for bus process to terminate\n') os.kill(pid, signal.SIGKILL) time.sleep(0.5) signal.signal(signal.SIGTERM, signal.SIG_DFL) @classmethod def get_dbus(klass, system_bus=False): '''Get dbus.bus.BusConnection() object This is preferrable to dbus.SystemBus() and dbus.SessionBus() as those do not get along with multiple changing local test buses. ''' if system_bus: if os.environ.get('DBUS_SYSTEM_BUS_ADDRESS'): return dbus.bus.BusConnection(os.environ['DBUS_SYSTEM_BUS_ADDRESS']) else: return dbus.SystemBus() else: if os.environ.get('DBUS_SESSION_BUS_ADDRESS'): return dbus.bus.BusConnection(os.environ['DBUS_SESSION_BUS_ADDRESS']) else: return dbus.SessionBus() @classmethod def wait_for_bus_object(klass, dest, path, system_bus=False, timeout=50): '''Wait for an object to appear on D-BUS Raise an exception if object does not appear within 5 seconds. You can change the timeout with the "timeout" keyword argument which specifies deciseconds. ''' bus = klass.get_dbus(system_bus) last_exc = None # we check whether the name is owned first, to avoid race conditions # with service activation; once it's owned, wait until we can actually # call methods while timeout > 0: if bus.name_has_owner(dest): try: p = dbus.Interface(bus.get_object(dest, path), dbus_interface=dbus.INTROSPECTABLE_IFACE) p.Introspect() break except dbus.exceptions.DBusException as e: last_exc = e if '.UnknownInterface' in str(e): break pass timeout -= 1 time.sleep(0.1) if timeout <= 0: assert timeout > 0, 'timed out waiting for D-BUS object %s: %s' % (path, last_exc) @classmethod def spawn_server(klass, name, path, interface, system_bus=False, stdout=None): '''Run a DBusMockObject instance in a separate process The daemon will terminate automatically when the D-BUS that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually. This function blocks until the spawned DBusMockObject is ready and listening on the bus. Returns the Popen object of the spawned daemon. ''' argv = [sys.executable, '-m', 'dbusmock'] if system_bus: argv.append('--system') argv.append(name) argv.append(path) argv.append(interface) daemon = subprocess.Popen(argv, stdout=stdout) # wait for daemon to start up klass.wait_for_bus_object(name, path, system_bus) return daemon @classmethod def spawn_server_template(klass, template, parameters=None, stdout=None): '''Run a D-BUS mock template instance in a separate process This starts a D-BUS mock process and loads the given template with (optional) parameters into it. For details about templates see dbusmock.DBusMockObject.AddTemplate(). The daemon will terminate automatically when the D-BUS that it connects to goes down. If that does not happen (e. g. you test on the actual system/session bus), you need to kill it manually. This function blocks until the spawned DBusMockObject is ready and listening on the bus. Returns a pair (daemon Popen object, main dbus object). ''' # we need the bus address from the template module module = load_module(template) if hasattr(module, 'IS_OBJECT_MANAGER'): is_object_manager = module.IS_OBJECT_MANAGER else: is_object_manager = False if is_object_manager and not hasattr(module, 'MAIN_IFACE'): interface_name = OBJECT_MANAGER_IFACE else: interface_name = module.MAIN_IFACE daemon = klass.spawn_server(module.BUS_NAME, module.MAIN_OBJ, interface_name, module.SYSTEM_BUS, stdout) bus = klass.get_dbus(module.SYSTEM_BUS) obj = bus.get_object(module.BUS_NAME, module.MAIN_OBJ) if not parameters: parameters = dbus.Dictionary({}, signature='sv') obj.AddTemplate(template, parameters, dbus_interface=MOCK_IFACE) return (daemon, obj) # Python 2 backwards compatibility if sys.version_info[0] < 3: import re def assertRegex(self, value, pattern): if not re.search(pattern, value): raise self.failureException('%r not found in %s' % (pattern, value)) DBusTestCase.assertRegex = assertRegex python-dbusmock-0.16.3/python_dbusmock.egg-info/0000775000175000017500000000000012633533065022447 5ustar martinmartin00000000000000python-dbusmock-0.16.3/python_dbusmock.egg-info/PKG-INFO0000664000175000017500000003501312633533065023546 0ustar martinmartin00000000000000Metadata-Version: 1.1 Name: python-dbusmock Version: 0.16.3 Summary: Mock D-Bus objects Home-page: https://launchpad.net/python-dbusmock Author: Martin Pitt Author-email: martin.pitt@ubuntu.com License: LGPL 3+ Download-URL: https://launchpad.net/python-dbusmock/+download Description: python-dbusmock =============== Purpose ------- With this program/Python library you can easily create mock objects on D-Bus. This is useful for writing tests for software which talks to D-Bus services such as upower, systemd, ConsoleKit, gnome-session or others, and it is hard (or impossible without root privileges) to set the state of the real services to what you expect in your tests. Suppose you want to write tests for gnome-settings-daemon's power plugin, or another program that talks to upower. You want to verify that after the configured idle time the program suspends the machine. So your program calls ``org.freedesktop.UPower.Suspend()`` on the system D-Bus. Now, your test suite should not really talk to the actual system D-Bus and the real upower; a ``make check`` that suspends your machine will not be considered very friendly by most people, and if you want to run this in continuous integration test servers or package build environments, chances are that your process does not have the privilege to suspend, or there is no system bus or upower to begin with. Likewise, there is no way for an user process to forcefully set the system/seat idle flag in systemd or ConsoleKit, so your tests cannot set up the expected test environment on the real daemon. That's where mock objects come into play: They look like the real API (or at least the parts that you actually need), but they do not actually do anything (or only some action that you specify yourself). You can configure their state, behaviour and responses as you like in your test, without making any assumptions about the real system status. When using a local system/session bus, you can do unit or integration testing without needing root privileges or disturbing a running system. The Python API offers some convenience functions like ``start_session_bus()`` and ``start_system_bus()`` for this, in a ``DBusTestCase`` class (subclass of the standard ``unittest.TestCase``). You can use this with any programming language, as you can run the mocker as a normal program. The actual setup of the mock (adding objects, methods, properties, and signals) all happen via D-Bus methods on the ``org.freedesktop.DBus.Mock`` interface. You just don't have the convenience D-Bus launch API that way. Simple example in Python ------------------------ Picking up the above example about mocking upower's ``Suspend()`` method, this is how you would set up a mock upower in your test case: :: import dbus import dbusmock class TestMyProgram(dbusmock.DBusTestCase): @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(system_bus=True) def setUp(self): self.p_mock = self.spawn_server('org.freedesktop.UPower', '/org/freedesktop/UPower', 'org.freedesktop.UPower', system_bus=True, stdout=subprocess.PIPE) # Get a proxy for the UPower object's Mock interface self.dbus_upower_mock = dbus.Interface(self.dbus_con.get_object( 'org.freedesktop.UPower', '/org/freedesktop/UPower'), dbusmock.MOCK_IFACE) self.dbus_upower_mock.AddMethod('', 'Suspend', '', '', '') def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_suspend_on_idle(self): # run your program in a way that should trigger one suspend call # now check the log that we got one Suspend() call self.assertRegex(self.p_mock.stdout.readline(), b'^[0-9.]+ Suspend$') Let's walk through: - We derive our tests from ``dbusmock.DBusTestCase`` instead of ``unittest.TestCase`` directly, to make use of the convenience API to start a local system bus. - ``setUpClass()`` starts a local system bus, and makes a connection to it available to all methods as ``dbus_con``. ``True`` means that we connect to the system bus, not the session bus. We can use the same bus for all tests, so doing this once in ``setUpClass()`` instead of ``setUp()`` is enough. - ``setUp()`` spawns the mock D-Bus server process for an initial ``/org/freedesktop/UPower`` object with an ``org.freedesktop.UPower`` D-Bus interface on the system bus. We capture its stdout to be able to verify that methods were called. We then call ``org.freedesktop.DBus.Mock.AddMethod()`` to add a ``Suspend()`` method to our new object to the default D-Bus interface. This will not do anything (except log its call to stdout). It takes no input arguments, returns nothing, and does not run any custom code. - ``tearDown()`` stops our mock D-Bus server again. We do this so that each test case has a fresh and clean upower instance, but of course you can also set up everything in ``setUpClass()`` if tests do not interfere with each other on setting up the mock. - ``test_suspend_on_idle()`` is the actual test case. It needs to run your program in a way that should trigger one suspend call. Your program will try to call ``Suspend()``, but as that's now being served by our mock instead of upower, there will not be any actual machine suspend. Our mock process will log the method call together with a time stamp; you can use the latter for doing timing related tests, but we just ignore it here. Simple example from shell ------------------------- We use the actual session bus for this example. You can use ``dbus-launch`` to start a private one as well if you want, but that is not part of the actual mocking. So let's start a mock at the D-Bus name ``com.example.Foo`` with an initial "main" object on path /, with the main D-Bus interface ``com.example.Foo.Manager``: :: python3 -m dbusmock com.example.Foo / com.example.Foo.Manager On another terminal, let's first see what it does: :: gdbus introspect --session -d com.example.Foo -o / You'll see that it supports the standard D-Bus ``Introspectable`` and ``Properties`` interfaces, as well as the ``org.freedesktop.DBus.Mock`` interface for controlling the mock, but no "real" functionality yet. So let's add a method: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod '' Ping '' '' '' Now you can see the new method in ``introspect``, and call it: :: gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Ping The mock process in the other terminal will log the method call with a time stamp, and you'll see something like ``1348832614.970 Ping``. Now add another method with two int arguments and a return value and call it: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod \ '' Add 'ii' 'i' 'ret = args[0] + args[1]' gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Add 2 3 This will print ``(5,)`` as expected (remember that the return value is always a tuple), and again the mock process will log the Add method call. You can do the same operations in e. g. d-feet or any other D-Bus language binding. Logging ------- Usually you want to verify which methods have been called on the mock with which arguments. There are three ways to do that: - By default, the mock process writes the call log to stdout. - You can call the mock process with the ``-l``/``--logfile`` argument, or specify a log file object in the ``spawn_server()`` method if you are using Python. - You can use the ``GetCalls()``, ``GetMethodCalls()`` and ``ClearCalls()`` methods on the ``org.freedesktop.DBus.Mock`` D-BUS interface to get an array of tuples describing the calls. Templates --------- Some D-BUS services are commonly used in test suites, such as UPower or NetworkManager. python-dbusmock provides "templates" which set up the common structure of these services (their main objects, properties, and methods) so that you do not need to carry around this common code, and only need to set up the particular properties and specific D-BUS objects that you need. These templates can be parameterized for common customizations, and they can provide additional convenience methods on the ``org.freedesktop.DBus.Mock`` interface to provide more abstract functionality like "add a battery". For example, for starting a server with the "upower" template in Python you can run :: (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', {'OnBattery': True}, stdout=subprocess.PIPE) or load a template into an already running server with the ``AddTemplate()`` method; this is particularly useful if you are not using Python: :: python3 -m dbusmock --system org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower gdbus call --system -d org.freedesktop.UPower -o /org/freedesktop/UPower -m org.freedesktop.DBus.Mock.AddTemplate 'upower' '{"OnBattery": }' This creates all expected properties such as ``DaemonVersion``, and changes the default for one of them (``OnBattery``) through the (optional) parameters dict. If you do not need to specify parameters, you can do this in a simpler way with :: python3 -m dbusmock --template upower The template does not create any devices by default. You can add some with the template's convenience methods like :: ac_path = self.dbusmock.AddAC('mock_AC', 'Mock AC') bt_path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200) or calling ``AddObject()`` yourself with the desired properties, of course. If you want to contribute a template, look at dbusmock/templates/upower.py for a real-life implementation. You can copy dbusmock/templates/SKELETON to your new template file name and replace "CHANGEME" with the actual code/values. More Examples ------------- Have a look at the test suite for two real-live use cases: - ``tests/test_upower.py`` simulates upowerd, in a more complete way than in above example and using the ``upower`` template. It verifies that ``upower --dump`` is convinced that it's talking to upower. - ``tests/test_consolekit.py`` simulates ConsoleKit and verifies that ``ck-list-sessions`` works with the mock. - ``tests/test_api.py`` runs a mock on the session bus and exercises all available functionality, such as adding additional objects, properties, multiple methods, input arguments, return values, code in methods, raising signals, and introspection. Documentation ------------- The ``dbusmock`` module has extensive documentation built in, which you can read with e. g. ``pydoc3 dbusmock``. ``pydoc3 dbusmock.DBusMockObject`` shows the D-Bus API of the mock object, i. e. methods like ``AddObject()``, ``AddMethod()`` etc. which are used to set up your mock object. ``pydoc3 dbusmock.DBusTestCase`` shows the convenience Python API for writing test cases with local private session/system buses and launching the server. ``pydoc3 dbusmock.templates`` shows all available templates. ``pydoc3 dbusmock.templates.NAME`` shows the documentation and available parameters for the ``NAME`` template. ``python3 -m dbusmock --help`` shows the arguments and options for running the mock server as a program. Development ----------- python-dbusmock is hosted on github: https://github.com/martinpitt/python-dbusmock Feedback -------- For feature requests and bugs, please file reports at one of: https://github.com/martinpitt/python-dbusmock/issues https://bugs.launchpad.net/python-dbusmock Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Other Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: POSIX :: BSD Classifier: Operating System :: Unix Classifier: Topic :: Software Development :: Quality Assurance Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries :: Python Modules python-dbusmock-0.16.3/python_dbusmock.egg-info/SOURCES.txt0000664000175000017500000000203512633533065024333 0ustar martinmartin00000000000000COPYING MANIFEST.in NEWS README.rst setup.py dbusmock/__init__.py dbusmock/__main__.py dbusmock/mockobject.py dbusmock/testcase.py dbusmock/templates/__init__.py dbusmock/templates/bluez4.py dbusmock/templates/bluez5-obex.py dbusmock/templates/bluez5.py dbusmock/templates/gnome_screensaver.py dbusmock/templates/logind.py dbusmock/templates/networkmanager.py dbusmock/templates/notification_daemon.py dbusmock/templates/ofono.py dbusmock/templates/polkitd.py dbusmock/templates/timedated.py dbusmock/templates/upower.py dbusmock/templates/urfkill.py python_dbusmock.egg-info/PKG-INFO python_dbusmock.egg-info/SOURCES.txt python_dbusmock.egg-info/dependency_links.txt python_dbusmock.egg-info/top_level.txt tests/test_api.py tests/test_bluez4.py tests/test_bluez5.py tests/test_cli.py tests/test_code.py tests/test_consolekit.py tests/test_gnome_screensaver.py tests/test_logind.py tests/test_networkmanager.py tests/test_notification_daemon.py tests/test_ofono.py tests/test_polkitd.py tests/test_timedated.py tests/test_upower.py tests/test_urfkill.pypython-dbusmock-0.16.3/python_dbusmock.egg-info/dependency_links.txt0000664000175000017500000000000112633533065026515 0ustar martinmartin00000000000000 python-dbusmock-0.16.3/python_dbusmock.egg-info/top_level.txt0000664000175000017500000000001112633533065025171 0ustar martinmartin00000000000000dbusmock python-dbusmock-0.16.3/tests/0000775000175000017500000000000012633533065016707 5ustar martinmartin00000000000000python-dbusmock-0.16.3/tests/test_api.py0000644000175000017500000007644112524067507021105 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import os import tempfile import subprocess import time import dbus import dbus.mainloop.glib import dbusmock from gi.repository import GLib dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) class TestAPI(dbusmock.DBusTestCase): '''Test dbus-mock API''' @classmethod def setUpClass(klass): klass.start_session_bus() klass.dbus_con = klass.get_dbus() def setUp(self): self.mock_log = tempfile.NamedTemporaryFile() self.p_mock = self.spawn_server('org.freedesktop.Test', '/', 'org.freedesktop.Test.Main', stdout=self.mock_log) self.obj_test = self.dbus_con.get_object('org.freedesktop.Test', '/') self.dbus_test = dbus.Interface(self.obj_test, 'org.freedesktop.Test.Main') self.dbus_mock = dbus.Interface(self.obj_test, dbusmock.MOCK_IFACE) self.dbus_props = dbus.Interface(self.obj_test, dbus.PROPERTIES_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_noarg_noret(self): '''no arguments, no return value''' self.dbus_mock.AddMethod('', 'Do', '', '', '') self.assertEqual(self.dbus_test.Do(), None) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do$') def test_onearg_noret(self): '''one argument, no return value''' self.dbus_mock.AddMethod('', 'Do', 's', '', '') self.assertEqual(self.dbus_test.Do('Hello'), None) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do "Hello"$') def test_onearg_ret(self): '''one argument, code for return value''' self.dbus_mock.AddMethod('', 'Do', 's', 's', 'ret = args[0]') self.assertEqual(self.dbus_test.Do('Hello'), 'Hello') def test_twoarg_ret(self): '''two arguments, code for return value''' self.dbus_mock.AddMethod('', 'Do', 'si', 's', 'ret = args[0] * args[1]') self.assertEqual(self.dbus_test.Do('foo', 3), 'foofoofoo') # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do "foo" 3$') def test_array_arg(self): '''array argument''' self.dbus_mock.AddMethod('', 'Do', 'iaou', '', '''assert len(args) == 3 assert args[0] == -1; assert args[1] == ['/foo'] assert type(args[1]) == dbus.Array assert type(args[1][0]) == dbus.ObjectPath assert args[2] == 5 ''') self.assertEqual(self.dbus_test.Do(-1, ['/foo'], 5), None) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do -1 \["/foo"\] 5$') def test_dict_arg(self): '''dictionary argument''' self.dbus_mock.AddMethod('', 'Do', 'ia{si}u', '', '''assert len(args) == 3 assert args[0] == -1; assert args[1] == {'foo': 42} assert type(args[1]) == dbus.Dictionary assert args[2] == 5 ''') self.assertEqual(self.dbus_test.Do(-1, {'foo': 42}, 5), None) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do -1 {"foo": 42} 5$') def test_methods_on_other_interfaces(self): '''methods on other interfaces''' self.dbus_mock.AddMethod('org.freedesktop.Test.Other', 'OtherDo', '', '', '') self.dbus_mock.AddMethods('org.freedesktop.Test.Other', [('OtherDo2', '', '', ''), ('OtherDo3', 'i', 'i', 'ret = args[0]')]) # should not be on the main interface self.assertRaises(dbus.exceptions.DBusException, self.dbus_test.OtherDo) # should be on the other interface self.assertEqual(self.obj_test.OtherDo(dbus_interface='org.freedesktop.Test.Other'), None) self.assertEqual(self.obj_test.OtherDo2(dbus_interface='org.freedesktop.Test.Other'), None) self.assertEqual(self.obj_test.OtherDo3(42, dbus_interface='org.freedesktop.Test.Other'), 42) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ OtherDo\n[0-9.]+ OtherDo2\n[0-9.]+ OtherDo3 42$') def test_methods_same_name(self): '''methods with same name on different interfaces''' self.dbus_mock.AddMethod('org.iface1', 'Do', 'i', 'i', 'ret = args[0] + 2') self.dbus_mock.AddMethod('org.iface2', 'Do', 'i', 'i', 'ret = args[0] + 3') # should not be on the main interface self.assertRaises(dbus.exceptions.DBusException, self.dbus_test.Do) # should be on the other interface self.assertEqual(self.obj_test.Do(10, dbus_interface='org.iface1'), 12) self.assertEqual(self.obj_test.Do(11, dbus_interface='org.iface2'), 14) # check that it's logged correctly with open(self.mock_log.name) as f: self.assertRegex(f.read(), '^[0-9.]+ Do 10\n[0-9.]+ Do 11$') # now add it to the primary interface, too self.dbus_mock.AddMethod('', 'Do', 'i', 'i', 'ret = args[0] + 1') self.assertEqual(self.obj_test.Do(9, dbus_interface='org.freedesktop.Test.Main'), 10) self.assertEqual(self.obj_test.Do(10, dbus_interface='org.iface1'), 12) self.assertEqual(self.obj_test.Do(11, dbus_interface='org.iface2'), 14) def test_methods_type_mismatch(self): '''calling methods with wrong arguments''' def check(signature, args, err): self.dbus_mock.AddMethod('', 'Do', signature, '', '') try: self.dbus_test.Do(*args) self.fail('method call did not raise an error for signature "%s" and arguments %s' % (signature, args)) except dbus.exceptions.DBusException as e: self.assertTrue(err in str(e), e) # not enough arguments check('i', [], 'TypeError: More items found') check('is', [1], 'TypeError: More items found') # too many arguments check('', [1], 'TypeError: Fewer items found') check('i', [1, 'hello'], 'TypeError: Fewer items found') # type mismatch check('u', [-1], 'convert negative value to unsigned') check('i', ['hello'], 'TypeError: an integer is required') check('s', [1], 'TypeError: Expected a string') def test_add_object(self): '''add a new object''' self.dbus_mock.AddObject('/obj1', 'org.freedesktop.Test.Sub', { 'state': dbus.String('online', variant_level=1), 'cute': dbus.Boolean(True, variant_level=1), }, []) obj1 = self.dbus_con.get_object('org.freedesktop.Test', '/obj1') dbus_sub = dbus.Interface(obj1, 'org.freedesktop.Test.Sub') dbus_props = dbus.Interface(obj1, dbus.PROPERTIES_IFACE) # check properties self.assertEqual(dbus_props.Get('org.freedesktop.Test.Sub', 'state'), 'online') self.assertEqual(dbus_props.Get('org.freedesktop.Test.Sub', 'cute'), True) self.assertEqual(dbus_props.GetAll('org.freedesktop.Test.Sub'), {'state': 'online', 'cute': True}) # add new method obj1.AddMethod('', 'Do', '', 's', 'ret = "hello"', dbus_interface=dbusmock.MOCK_IFACE) self.assertEqual(dbus_sub.Do(), 'hello') def test_add_object_existing(self): '''try to add an existing object''' self.dbus_mock.AddObject('/obj1', 'org.freedesktop.Test.Sub', {}, []) self.assertRaises(dbus.exceptions.DBusException, self.dbus_mock.AddObject, '/obj1', 'org.freedesktop.Test.Sub', {}, []) # try to add the main object again self.assertRaises(dbus.exceptions.DBusException, self.dbus_mock.AddObject, '/', 'org.freedesktop.Test.Other', {}, []) def test_add_object_with_methods(self): '''add a new object with methods''' self.dbus_mock.AddObject('/obj1', 'org.freedesktop.Test.Sub', { 'state': dbus.String('online', variant_level=1), 'cute': dbus.Boolean(True, variant_level=1), }, [ ('Do0', '', 'i', 'ret = 42'), ('Do1', 'i', 'i', 'ret = 31337'), ]) obj1 = self.dbus_con.get_object('org.freedesktop.Test', '/obj1') self.assertEqual(obj1.Do0(), 42) self.assertEqual(obj1.Do1(1), 31337) self.assertRaises(dbus.exceptions.DBusException, obj1.Do2, 31337) def test_properties(self): '''add and change properties''' # no properties by default self.assertEqual(self.dbus_props.GetAll('org.freedesktop.Test.Main'), {}) # no such property with self.assertRaises(dbus.exceptions.DBusException) as ctx: self.dbus_props.Get('org.freedesktop.Test.Main', 'version') self.assertEqual(ctx.exception.get_dbus_name(), 'org.freedesktop.Test.Main.UnknownProperty') self.assertEqual(ctx.exception.get_dbus_message(), 'no such property version') self.assertRaises(dbus.exceptions.DBusException, self.dbus_props.Set, 'org.freedesktop.Test.Main', 'version', dbus.Int32(2, variant_level=1)) self.dbus_mock.AddProperty('org.freedesktop.Test.Main', 'version', dbus.Int32(2, variant_level=1)) # once again on default interface self.dbus_mock.AddProperty('', 'connected', dbus.Boolean(True, variant_level=1)) self.assertEqual(self.dbus_props.Get('org.freedesktop.Test.Main', 'version'), 2) self.assertEqual(self.dbus_props.Get('org.freedesktop.Test.Main', 'connected'), True) self.assertEqual(self.dbus_props.GetAll('org.freedesktop.Test.Main'), {'version': 2, 'connected': True}) with self.assertRaises(dbus.exceptions.DBusException) as ctx: self.dbus_props.GetAll('org.freedesktop.Test.Bogus') self.assertEqual(ctx.exception.get_dbus_name(), 'org.freedesktop.Test.Main.UnknownInterface') self.assertEqual(ctx.exception.get_dbus_message(), 'no such interface org.freedesktop.Test.Bogus') # change property self.dbus_props.Set('org.freedesktop.Test.Main', 'version', dbus.Int32(4, variant_level=1)) self.assertEqual(self.dbus_props.Get('org.freedesktop.Test.Main', 'version'), 4) # check that the Get/Set calls get logged with open(self.mock_log.name) as f: contents = f.read() self.assertRegex(contents, '\n[0-9.]+ Get org.freedesktop.Test.Main.version\n') self.assertRegex(contents, '\n[0-9.]+ Get org.freedesktop.Test.Main.connected\n') self.assertRegex(contents, '\n[0-9.]+ GetAll org.freedesktop.Test.Main\n') self.assertRegex(contents, '\n[0-9.]+ Set org.freedesktop.Test.Main.version 4\n') # add property to different interface self.dbus_mock.AddProperty('org.freedesktop.Test.Other', 'color', dbus.String('yellow', variant_level=1)) self.assertEqual(self.dbus_props.GetAll('org.freedesktop.Test.Main'), {'version': 4, 'connected': True}) self.assertEqual(self.dbus_props.GetAll('org.freedesktop.Test.Other'), {'color': 'yellow'}) self.assertEqual(self.dbus_props.Get('org.freedesktop.Test.Other', 'color'), 'yellow') def test_introspection_methods(self): '''dynamically added methods appear in introspection''' dbus_introspect = dbus.Interface(self.obj_test, dbus.INTROSPECTABLE_IFACE) xml_empty = dbus_introspect.Introspect() self.assertTrue('' in xml_empty, xml_empty) self.assertTrue('' in xml_empty, xml_empty) self.dbus_mock.AddMethod('', 'Do', 'saiv', 'i', 'ret = 42') xml_method = dbus_introspect.Introspect() self.assertFalse(xml_empty == xml_method, 'No change from empty XML') self.assertTrue('' in xml_method, xml_method) self.assertTrue(''' ''' in xml_method, xml_method) # properties in introspection are not supported by dbus-python right now def test_introspection_properties(self): '''dynamically added properties appear in introspection''' self.dbus_mock.AddProperty('', 'Color', 'yellow') self.dbus_mock.AddProperty('org.freedesktop.Test.Sub', 'Count', 5) xml = self.obj_test.Introspect() self.assertTrue('' in xml, xml) self.assertTrue('' in xml, xml) self.assertTrue('' in xml, xml) self.assertTrue('' in xml, xml) def test_objects_map(self): '''access global objects map''' self.dbus_mock.AddMethod('', 'EnumObjs', '', 'ao', 'ret = objects.keys()') self.assertEqual(self.dbus_test.EnumObjs(), ['/']) self.dbus_mock.AddObject('/obj1', 'org.freedesktop.Test.Sub', {}, []) self.assertEqual(set(self.dbus_test.EnumObjs()), {'/', '/obj1'}) def test_signals(self): '''emitting signals''' def do_emit(): self.dbus_mock.EmitSignal('', 'SigNoArgs', '', []) self.dbus_mock.EmitSignal('org.freedesktop.Test.Sub', 'SigTwoArgs', 'su', ['hello', 42]) self.dbus_mock.EmitSignal('org.freedesktop.Test.Sub', 'SigTypeTest', 'iuvao', [-42, 42, dbus.String('hello', variant_level=1), ['/a', '/b']]) caught = [] ml = GLib.MainLoop() def catch(*args, **kwargs): if kwargs['interface'].startswith('org.freedesktop.Test'): caught.append((args, kwargs)) if len(caught) == 3: # we caught everything there is to catch, don't wait for the # timeout ml.quit() self.dbus_con.add_signal_receiver(catch, interface_keyword='interface', path_keyword='path', member_keyword='member') GLib.timeout_add(200, do_emit) # ensure that the loop quits even when we catch fewer than 2 signals GLib.timeout_add(3000, ml.quit) ml.run() # check SigNoArgs self.assertEqual(caught[0][0], ()) self.assertEqual(caught[0][1]['member'], 'SigNoArgs') self.assertEqual(caught[0][1]['path'], '/') self.assertEqual(caught[0][1]['interface'], 'org.freedesktop.Test.Main') # check SigTwoArgs self.assertEqual(caught[1][0], ('hello', 42)) self.assertEqual(caught[1][1]['member'], 'SigTwoArgs') self.assertEqual(caught[1][1]['path'], '/') self.assertEqual(caught[1][1]['interface'], 'org.freedesktop.Test.Sub') # check data types in SigTypeTest self.assertEqual(caught[2][1]['member'], 'SigTypeTest') self.assertEqual(caught[2][1]['path'], '/') args = caught[2][0] self.assertEqual(args[0], -42) self.assertEqual(type(args[0]), dbus.Int32) self.assertEqual(args[0].variant_level, 0) self.assertEqual(args[1], 42) self.assertEqual(type(args[1]), dbus.UInt32) self.assertEqual(args[1].variant_level, 0) self.assertEqual(args[2], 'hello') self.assertEqual(type(args[2]), dbus.String) self.assertEqual(args[2].variant_level, 1) self.assertEqual(args[3], ['/a', '/b']) self.assertEqual(type(args[3]), dbus.Array) self.assertEqual(args[3].variant_level, 0) self.assertEqual(type(args[3][0]), dbus.ObjectPath) self.assertEqual(args[3][0].variant_level, 0) # check correct logging with open(self.mock_log.name) as f: log = f.read() self.assertRegex(log, '[0-9.]+ emit org.freedesktop.Test.Main.SigNoArgs\n') self.assertRegex(log, '[0-9.]+ emit org.freedesktop.Test.Sub.SigTwoArgs "hello" 42\n') self.assertRegex(log, '[0-9.]+ emit org.freedesktop.Test.Sub.SigTypeTest -42 42') self.assertRegex(log, '[0-9.]+ emit org.freedesktop.Test.Sub.SigTypeTest -42 42 "hello" \["/a", "/b"\]\n') def test_signals_type_mismatch(self): '''emitting signals with wrong arguments''' def check(signature, args, err): try: self.dbus_mock.EmitSignal('', 's', signature, args) self.fail('EmitSignal did not raise an error for signature "%s" and arguments %s' % (signature, args)) except dbus.exceptions.DBusException as e: self.assertTrue(err in str(e), e) # not enough arguments check('i', [], 'TypeError: More items found') check('is', [1], 'TypeError: More items found') # too many arguments check('', [1], 'TypeError: Fewer items found') check('i', [1, 'hello'], 'TypeError: Fewer items found') # type mismatch check('u', [-1], 'convert negative value to unsigned') check('i', ['hello'], 'TypeError: an integer is required') check('s', [1], 'TypeError: Expected a string') def test_dbus_get_log(self): '''query call logs over D-BUS''' self.assertEqual(self.dbus_mock.ClearCalls(), None) self.assertEqual(self.dbus_mock.GetCalls(), dbus.Array([])) self.dbus_mock.AddMethod('', 'Do', '', '', '') self.assertEqual(self.dbus_test.Do(), None) mock_log = self.dbus_mock.GetCalls() self.assertEqual(len(mock_log), 1) self.assertGreater(mock_log[0][0], 10000) # timestamp self.assertEqual(mock_log[0][1], 'Do') self.assertEqual(mock_log[0][2], []) self.assertEqual(self.dbus_mock.ClearCalls(), None) self.assertEqual(self.dbus_mock.GetCalls(), dbus.Array([])) self.dbus_mock.AddMethod('', 'Wop', 's', 's', 'ret="hello"') self.assertEqual(self.dbus_test.Wop('foo'), 'hello') self.assertEqual(self.dbus_test.Wop('bar'), 'hello') mock_log = self.dbus_mock.GetCalls() self.assertEqual(len(mock_log), 2) self.assertGreater(mock_log[0][0], 10000) # timestamp self.assertEqual(mock_log[0][1], 'Wop') self.assertEqual(mock_log[0][2], ['foo']) self.assertEqual(mock_log[1][1], 'Wop') self.assertEqual(mock_log[1][2], ['bar']) self.assertEqual(self.dbus_mock.ClearCalls(), None) self.assertEqual(self.dbus_mock.GetCalls(), dbus.Array([])) def test_dbus_get_method_calls(self): '''query method call logs over D-BUS''' self.dbus_mock.AddMethod('', 'Do', '', '', '') self.assertEqual(self.dbus_test.Do(), None) self.assertEqual(self.dbus_test.Do(), None) self.dbus_mock.AddMethod('', 'Wop', 's', 's', 'ret="hello"') self.assertEqual(self.dbus_test.Wop('foo'), 'hello') self.assertEqual(self.dbus_test.Wop('bar'), 'hello') mock_calls = self.dbus_mock.GetMethodCalls('Do') self.assertEqual(len(mock_calls), 2) self.assertEqual(mock_calls[0][1], []) self.assertEqual(mock_calls[1][1], []) mock_calls = self.dbus_mock.GetMethodCalls('Wop') self.assertEqual(len(mock_calls), 2) self.assertGreater(mock_calls[0][0], 10000) # timestamp self.assertEqual(mock_calls[0][1], ['foo']) self.assertGreater(mock_calls[1][0], 10000) # timestamp self.assertEqual(mock_calls[1][1], ['bar']) def test_dbus_method_called(self): '''subscribe to MethodCalled signal''' loop = GLib.MainLoop() caught_signals = [] def method_called(method, args, **kwargs): caught_signals.append((method, args)) loop.quit() self.dbus_mock.AddMethod('', 'Do', 's', '', '') self.dbus_mock.connect_to_signal('MethodCalled', method_called) self.assertEqual(self.dbus_test.Do('foo'), None) GLib.timeout_add(5000, loop.quit) loop.run() self.assertEqual(len(caught_signals), 1) method, args = caught_signals[0] self.assertEqual(method, 'Do') self.assertEqual(len(args), 1) self.assertEqual(args[0], 'foo') def test_reset(self): '''resetting to pristine state''' self.dbus_mock.AddMethod('', 'Do', '', '', '') self.dbus_mock.AddProperty('', 'propone', True) self.dbus_mock.AddProperty('org.Test.Other', 'proptwo', 1) self.dbus_mock.AddObject('/obj1', '', {}, []) self.dbus_mock.Reset() # resets properties and keeps the initial object self.assertEqual(self.dbus_props.GetAll(''), {}) # resets methods self.assertRaises(dbus.exceptions.DBusException, self.dbus_test.Do) # resets other objects obj1 = self.dbus_con.get_object('org.freedesktop.Test', '/obj1') self.assertRaises(dbus.exceptions.DBusException, obj1.GetAll, '') class TestTemplates(dbusmock.DBusTestCase): '''Test template API''' @classmethod def setUpClass(klass): klass.start_session_bus() klass.start_system_bus() def test_local(self): '''Load a local template *.py file''' with tempfile.NamedTemporaryFile(prefix='answer_', suffix='.py') as my_template: my_template.write(b'''import dbus BUS_NAME = 'universe.Ultimate' MAIN_OBJ = '/' MAIN_IFACE = 'universe.Ultimate' SYSTEM_BUS = False def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [('Answer', '', 'i', 'ret = 42')]) ''') my_template.flush() (p_mock, dbus_ultimate) = self.spawn_server_template( my_template.name, stdout=subprocess.PIPE) self.addCleanup(p_mock.wait) self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) # ensure that we don't use/write any .pyc files, they are dangerous # in a world-writable directory like /tmp self.assertFalse(os.path.exists(my_template.name + 'c')) try: from importlib.util import cache_from_source self.assertFalse(os.path.exists(cache_from_source(my_template.name))) except ImportError: # python < 3.4 pass self.assertEqual(dbus_ultimate.Answer(), 42) # should appear in introspection xml = dbus_ultimate.Introspect() self.assertIn('', xml) self.assertIn('', xml) # should not have ObjectManager API by default self.assertRaises(dbus.exceptions.DBusException, dbus_ultimate.GetManagedObjects) def test_static_method(self): '''Static method in a template''' with tempfile.NamedTemporaryFile(prefix='answer_', suffix='.py') as my_template: my_template.write(b'''import dbus BUS_NAME = 'universe.Ultimate' MAIN_OBJ = '/' MAIN_IFACE = 'universe.Ultimate' SYSTEM_BUS = False def load(mock, parameters): pass @dbus.service.method(MAIN_IFACE, in_signature='', out_signature='i') def Answer(self): return 42 ''') my_template.flush() (p_mock, dbus_ultimate) = self.spawn_server_template( my_template.name, stdout=subprocess.PIPE) self.addCleanup(p_mock.wait) self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) self.assertEqual(dbus_ultimate.Answer(), 42) # should appear in introspection xml = dbus_ultimate.Introspect() self.assertIn('', xml) self.assertIn('', xml) def test_local_nonexisting(self): self.assertRaises(ImportError, self.spawn_server_template, '/non/existing.py') def test_object_manager(self): '''Template with ObjectManager API''' with tempfile.NamedTemporaryFile(prefix='objmgr_', suffix='.py') as my_template: my_template.write(b'''import dbus BUS_NAME = 'org.test.Things' MAIN_OBJ = '/org/test/Things' IS_OBJECT_MANAGER = True SYSTEM_BUS = False def load(mock, parameters): mock.AddObject('/org/test/Things/Thing1', 'org.test.Do', {'name': 'one'}, []) mock.AddObject('/org/test/Things/Thing2', 'org.test.Do', {'name': 'two'}, []) mock.AddObject('/org/test/Peer', 'org.test.Do', {'name': 'peer'}, []) ''') my_template.flush() (p_mock, dbus_objmgr) = self.spawn_server_template( my_template.name, stdout=subprocess.PIPE) self.addCleanup(p_mock.wait) self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) # should have the two Things, but not the Peer self.assertEqual(dbus_objmgr.GetManagedObjects(), {'/org/test/Things/Thing1': {'org.test.Do': {'name': 'one'}}, '/org/test/Things/Thing2': {'org.test.Do': {'name': 'two'}}}) # should appear in introspection xml = dbus_objmgr.Introspect() self.assertIn('', xml) self.assertIn('', xml) self.assertIn('', xml) self.assertIn('', xml) def test_reset(self): '''Reset() puts the template back to pristine state''' (p_mock, obj_logind) = self.spawn_server_template( 'logind', stdout=subprocess.PIPE) self.addCleanup(p_mock.wait) self.addCleanup(p_mock.terminate) self.addCleanup(p_mock.stdout.close) # do some property, method, and object changes obj_logind.Set('org.freedesktop.login1.Manager', 'IdleAction', 'frob') mock_logind = dbus.Interface(obj_logind, dbusmock.MOCK_IFACE) mock_logind.AddProperty('org.Test.Other', 'walk', 'silly') mock_logind.AddMethod('', 'DoWalk', '', '', '') mock_logind.AddObject('/obj1', '', {}, []) mock_logind.Reset() # keeps the objects from the template dbus_con = self.get_dbus(system_bus=True) obj_logind = dbus_con.get_object('org.freedesktop.login1', '/org/freedesktop/login1') self.assertEqual(obj_logind.CanSuspend(), 'yes') # resets properties self.assertRaises(dbus.exceptions.DBusException, obj_logind.GetAll, 'org.Test.Other') self.assertEqual( obj_logind.Get('org.freedesktop.login1.Manager', 'IdleAction'), 'ignore') # resets methods self.assertRaises(dbus.exceptions.DBusException, obj_logind.DoWalk) # resets other objects obj1 = dbus_con.get_object('org.freedesktop.login1', '/obj1') self.assertRaises(dbus.exceptions.DBusException, obj1.GetAll, '') class TestCleanup(dbusmock.DBusTestCase): '''Test cleanup of resources''' def test_mock_terminates_with_bus(self): '''Spawned mock processes exit when bus goes down''' self.start_session_bus() p_mock = self.spawn_server('org.freedesktop.Test', '/', 'org.freedesktop.Test.Main') self.stop_dbus(self.session_bus_pid) # give the mock 2 seconds to terminate timeout = 20 while timeout > 0: if p_mock.poll() is not None: break timeout -= 1 time.sleep(0.1) if p_mock.poll() is None: # clean up manually p_mock.terminate() p_mock.wait() self.fail('mock process did not terminate after 2 seconds') self.assertEqual(p_mock.wait(), 0) class TestSubclass(dbusmock.DBusTestCase): '''Test subclassing DBusMockObject''' @classmethod def setUpClass(klass): klass.start_session_bus() def test_ctor(self): '''Override DBusMockObject constructor''' class MyMock(dbusmock.mockobject.DBusMockObject): def __init__(self): bus_name = dbus.service.BusName('org.test.MyMock', dbusmock.testcase.DBusTestCase.get_dbus()) dbusmock.mockobject.DBusMockObject.__init__( self, bus_name, '/', 'org.test.A', {}, os.devnull) self.AddMethod('', 'Ping', '', 'i', 'ret = 42') m = MyMock() self.assertEqual(m.Ping(), 42) def test_none_props(self): '''object with None properties argument''' class MyMock(dbusmock.mockobject.DBusMockObject): def __init__(self): bus_name = dbus.service.BusName('org.test.MyMock', dbusmock.testcase.DBusTestCase.get_dbus()) dbusmock.mockobject.DBusMockObject.__init__( self, bus_name, '/mymock', 'org.test.MyMockI', None, os.devnull) self.AddMethod('', 'Ping', '', 'i', 'ret = 42') m = MyMock() self.assertEqual(m.Ping(), 42) self.assertEqual(m.GetAll('org.test.MyMockI'), {}) m.AddProperty('org.test.MyMockI', 'blurb', 5) self.assertEqual(m.GetAll('org.test.MyMockI'), {'blurb': 5}) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_bluez4.py0000664000175000017500000001613212506173111021517 0ustar martinmartin00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __authors__ = ['Mathieu Trudel-Lapierre ', 'Philip Withnall '] __copyright__ = '(c) 2013 Collabora Ltd.' __copyright__ = '(c) 2014 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbus import dbus.mainloop.glib import dbusmock dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) p = subprocess.Popen(['which', 'bluez-test-adapter'], stdout=subprocess.PIPE) p.communicate() have_test_adapter = (p.returncode == 0) p = subprocess.Popen(['which', 'bluez-test-device'], stdout=subprocess.PIPE) p.communicate() have_test_device = (p.returncode == 0) def _run_test_command(prog, command): '''Run bluez-test command with the given command. Return its output as a list of lines. If bluez-test-adapter returns a non-zero exit code, raise an Exception. ''' cmd = [] cmd.append(prog) if type(command) is str: cmd.append(command) else: cmd.extend(command) process = subprocess.Popen(cmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out, err = process.communicate() lines = out.split('\n') lines = filter(lambda l: l != '', lines) lines = list(lines) errlines = err.split('\n') errlines = filter(lambda l: l != '', errlines) errlines = list(errlines) return (lines, errlines) @unittest.skipUnless(have_test_adapter and have_test_device, 'bluez 4 not installed') class TestBlueZ4(dbusmock.DBusTestCase): '''Test mocking bluetoothd''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) (klass.p_mock, klass.obj_bluez) = klass.spawn_server_template( 'bluez4', {}, stdout=subprocess.PIPE) def setUp(self): self.obj_bluez.Reset() self.dbusmock = dbus.Interface(self.obj_bluez, dbusmock.MOCK_IFACE) self.dbusmock_bluez = dbus.Interface(self.obj_bluez, 'org.bluez.Mock') def test_no_adapters(self): # Check for adapters. out, err = _run_test_command('bluez-test-adapter', 'list') expected = "dbus.exceptions.DBusException: " \ + "org.bluez.Error.NoSuchAdapter: No such adapter." self.assertIn(expected, err) def test_one_adapter(self): # Chosen parameters. adapter_name = 'hci0' system_name = 'my-computer' # Add an adapter path = self.dbusmock_bluez.AddAdapter(adapter_name, system_name) self.assertEqual(path, '/org/bluez/' + adapter_name) adapter = self.dbus_con.get_object('org.bluez', path) address = adapter.Get('org.bluez.Adapter', 'Address') self.assertEqual(str(address), '00:01:02:03:04:05') # Check for the adapter. out, err = _run_test_command('bluez-test-adapter', 'list') self.assertIn(' Name = ' + system_name, out) self.assertIn(' Alias = ' + system_name, out) self.assertIn(' Powered = 1', out) self.assertIn(' Pairable = 1', out) self.assertIn(' Discovering = 0', out) def test_no_devices(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Check for devices. out, err = _run_test_command('bluez-test-device', 'list') self.assertListEqual([], out) def test_one_device(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Add a device. address = '11:22:33:44:55:66' alias = 'My Phone' path = self.dbusmock_bluez.AddDevice(adapter_name, address, alias) self.assertEqual(path, '/org/bluez/' + adapter_name + '/dev_' + address.replace(':', '_')) # Check for the device. out, err = _run_test_command('bluez-test-device', 'list') self.assertIn(address + ' ' + alias, out) out, err = _run_test_command('bluez-test-device', ['name', address]) self.assertIn(alias, out) device = self.dbus_con.get_object('org.bluez', path) dev_name = device.Get('org.bluez.Device', 'Name') self.assertEqual(str(dev_name), alias) dev_address = device.Get('org.bluez.Device', 'Address') self.assertEqual(str(dev_address), address) dev_class = device.Get('org.bluez.Device', 'Class') self.assertNotEqual(dev_class, 0) dev_conn = device.Get('org.bluez.Device', 'Connected') self.assertEqual(dev_conn, 0) def test_connect_disconnect(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Add a device. address = '11:22:33:44:55:66' alias = 'My Phone' path = self.dbusmock_bluez.AddDevice(adapter_name, address, alias) self.assertEqual(path, '/org/bluez/' + adapter_name + '/dev_' + address.replace(':', '_')) # Force a service discovery so the audio interface appears. device = self.dbus_con.get_object('org.bluez', path) bluez_dev = dbus.Interface(device, 'org.bluez.Device') bluez_dev.DiscoverServices("") # Test the connection prior dev_state = device.Get('org.bluez.Audio', 'State') self.assertEqual(str(dev_state), "disconnected") dev_conn = device.Get('org.bluez.Device', 'Connected') self.assertEqual(dev_conn, 0) # Connect the audio interface. bluez_audio = dbus.Interface(device, 'org.bluez.Audio') bluez_audio.Connect() # Test the connection after connecting dev_state = device.Get('org.bluez.Audio', 'State') self.assertEqual(str(dev_state), "connected") dev_conn = device.Get('org.bluez.Device', 'Connected') self.assertEqual(dev_conn, 1) # Disconnect audio bluez_audio.Disconnect() # Test the connection after connecting dev_state = device.Get('org.bluez.Audio', 'State') self.assertEqual(str(dev_state), "disconnected") dev_conn = device.Get('org.bluez.Device', 'Connected') self.assertEqual(dev_conn, 0) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_bluez5.py0000644000175000017500000002644612631747004021536 0ustar martinmartin00000000000000#!/usr/bin/python3 # -*- coding: utf-8 -*- # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Philip Withnall' __email__ = 'philip.withnall@collabora.co.uk' __copyright__ = '(c) 2013 Collabora Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import time import os import dbus import dbus.mainloop.glib import dbusmock from gi.repository import GLib dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) p = subprocess.Popen(['which', 'bluetoothctl'], stdout=subprocess.PIPE) p.communicate() have_bluetoothctl = (p.returncode == 0) p = subprocess.Popen(['which', 'pbap-client'], stdout=subprocess.PIPE) p.communicate() have_pbap_client = (p.returncode == 0) def _run_bluetoothctl(command): '''Run bluetoothctl with the given command. Return its output as a list of lines, with the command prompt removed from each, and empty lines eliminated. If bluetoothctl returns a non-zero exit code, raise an Exception. ''' process = subprocess.Popen(['bluetoothctl'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr, universal_newlines=True) time.sleep(0.5) # give it time to query the bus out, err = process.communicate(input='list\n' + command + '\nquit\n') # Ignore output on stderr unless bluetoothctl dies. if process.returncode != 0: raise Exception('bluetoothctl died with status ' + str(process.returncode) + ' and errors: ' + (err or "")) # Strip the prompt from the start of every line, then remove empty # lines. # # The prompt looks like ‘[bluetooth]# ’, potentially containing command # line colour control codes. Split at the first space. # # Sometimes we end up with the final line being ‘\x1b[K’ (partial # control code), which we need to ignore. def remove_prefix(line): if line.startswith('[bluetooth]#') or line.startswith('\x1b'): parts = line.split(' ', 1) try: return parts[1].strip() except IndexError: return '' return line.strip() lines = out.split('\n') lines = map(remove_prefix, lines) lines = filter(lambda l: l != '', lines) # Filter out the echoed commands. (bluetoothctl uses readline.) lines = filter(lambda l: l not in ['list', command, 'quit'], lines) lines = list(lines) return lines @unittest.skipUnless(have_bluetoothctl, 'bluetoothctl not installed') class TestBlueZ5(dbusmock.DBusTestCase): '''Test mocking bluetoothd''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) (klass.p_mock, klass.obj_bluez) = klass.spawn_server_template( 'bluez5', {}, stdout=subprocess.PIPE) def setUp(self): self.obj_bluez.Reset() self.dbusmock = dbus.Interface(self.obj_bluez, dbusmock.MOCK_IFACE) self.dbusmock_bluez = dbus.Interface(self.obj_bluez, 'org.bluez.Mock') def test_no_adapters(self): # Check for adapters. out = _run_bluetoothctl('list') self.assertEqual(out, []) def test_one_adapter(self): # Chosen parameters. adapter_name = 'hci0' system_name = 'my-computer' # Add an adapter path = self.dbusmock_bluez.AddAdapter(adapter_name, system_name) self.assertEqual(path, '/org/bluez/' + adapter_name) adapter = self.dbus_con.get_object('org.bluez', path) address = adapter.Get('org.bluez.Adapter1', 'Address') # Check for the adapter. out = _run_bluetoothctl('list') self.assertIn('Controller ' + address + ' ' + system_name + ' [default]', out) out = _run_bluetoothctl('show ' + address) self.assertIn('Controller ' + address, out) self.assertIn('Name: ' + system_name, out) self.assertIn('Alias: ' + system_name, out) self.assertIn('Powered: yes', out) self.assertIn('Discoverable: yes', out) self.assertIn('Pairable: yes', out) self.assertIn('Discovering: yes', out) def test_no_devices(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Check for devices. out = _run_bluetoothctl('devices') self.assertIn('Controller 00:01:02:03:04:05 my-computer [default]', out) @unittest.skip('flaky test') def test_one_device(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Add a device. address = '11:22:33:44:55:66' alias = 'My Phone' path = self.dbusmock_bluez.AddDevice(adapter_name, address, alias) self.assertEqual(path, '/org/bluez/' + adapter_name + '/dev_' + address.replace(':', '_')) # Check for the device. out = _run_bluetoothctl('devices') self.assertIn('Device ' + address + ' ' + alias, out) # Check the device’s properties. out = '\n'.join(_run_bluetoothctl('info ' + address)) self.assertIn('Device ' + address, out) self.assertIn('Name: ' + alias, out) self.assertIn('Alias: ' + alias, out) self.assertIn('Paired: no', out) self.assertIn('Trusted: no', out) self.assertIn('Blocked: no', out) self.assertIn('Connected: no', out) @unittest.skip('flaky test') def test_pairing_device(self): # Add an adapter. adapter_name = 'hci0' path = self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.assertEqual(path, '/org/bluez/' + adapter_name) # Add a device. address = '11:22:33:44:55:66' alias = 'My Phone' path = self.dbusmock_bluez.AddDevice(adapter_name, address, alias) self.assertEqual(path, '/org/bluez/' + adapter_name + '/dev_' + address.replace(':', '_')) # Pair with the device. self.dbusmock_bluez.PairDevice(adapter_name, address) # Check the device’s properties. out = '\n'.join(_run_bluetoothctl('info ' + address)) self.assertIn('Device ' + address, out) self.assertIn('Paired: yes', out) @unittest.skipUnless(have_pbap_client, 'pbap-client not installed (copy it from bluez/test)') class TestBlueZObex(dbusmock.DBusTestCase): '''Test mocking obexd''' @classmethod def setUpClass(klass): klass.start_session_bus() klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): # bluetoothd (self.p_mock, self.obj_bluez) = self.spawn_server_template( 'bluez5', {}, stdout=subprocess.PIPE) self.dbusmock_bluez = dbus.Interface(self.obj_bluez, 'org.bluez.Mock') # obexd (self.p_mock, self.obj_obex) = self.spawn_server_template( 'bluez5-obex', {}, stdout=subprocess.PIPE) self.dbusmock = dbus.Interface(self.obj_obex, dbusmock.MOCK_IFACE) self.dbusmock_obex = dbus.Interface(self.obj_obex, 'org.bluez.obex.Mock') def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_everything(self): # Set up an adapter and device. adapter_name = 'hci0' device_address = '11:22:33:44:55:66' device_alias = 'My Phone' ml = GLib.MainLoop() self.dbusmock_bluez.AddAdapter(adapter_name, 'my-computer') self.dbusmock_bluez.AddDevice(adapter_name, device_address, device_alias) self.dbusmock_bluez.PairDevice(adapter_name, device_address) transferred_files = [] def _transfer_created_cb(path, params, transfer_filename): bus = self.get_dbus(False) obj = bus.get_object('org.bluez.obex', path) transfer = dbus.Interface(obj, 'org.bluez.obex.transfer1.Mock') with open(transfer_filename, 'w') as f: f.write( 'BEGIN:VCARD\r\n' + 'VERSION:3.0\r\n' + 'FN:Forrest Gump\r\n' + 'TEL;TYPE=WORK,VOICE:(111) 555-1212\r\n' + 'TEL;TYPE=HOME,VOICE:(404) 555-1212\r\n' + 'EMAIL;TYPE=PREF,INTERNET:forrestgump@example.com\r\n' + 'EMAIL:test@example.com\r\n' + 'URL;TYPE=HOME:http://example.com/\r\n' + 'URL:http://forest.com/\r\n' + 'URL:https://test.com/\r\n' + 'END:VCARD\r\n' ) transfer.UpdateStatus(True) transferred_files.append(transfer_filename) self.dbusmock_obex.connect_to_signal('TransferCreated', _transfer_created_cb) # Run pbap-client, then run the GLib main loop. The main loop will quit # after a timeout, at which point the code handles output from # pbap-client and waits for it to terminate. Integrating # process.communicate() with the GLib main loop to avoid the timeout is # too difficult. process = subprocess.Popen(['pbap-client', device_address], stdout=subprocess.PIPE, stderr=sys.stderr, universal_newlines=True) GLib.timeout_add(5000, ml.quit) ml.run() out, err = process.communicate() lines = out.split('\n') lines = filter(lambda l: l != '', lines) lines = list(lines) # Clean up the transferred files. for f in transferred_files: try: os.remove(f) except: pass # See what pbap-client sees. self.assertIn('Creating Session', lines) self.assertIn('--- Select Phonebook PB ---', lines) self.assertIn('--- GetSize ---', lines) self.assertIn('Size = 0', lines) self.assertIn('--- List vCard ---', lines) self.assertIn( 'Transfer /org/bluez/obex/client/session0/transfer0 complete', lines) self.assertIn( 'Transfer /org/bluez/obex/client/session0/transfer1 complete', lines) self.assertIn( 'Transfer /org/bluez/obex/client/session0/transfer2 complete', lines) self.assertIn( 'Transfer /org/bluez/obex/client/session0/transfer3 complete', lines) self.assertIn('FINISHED', lines) self.assertNotIn('ERROR', lines) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_cli.py0000664000175000017500000001447412605433373021101 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbus import dbusmock p = subprocess.Popen(['which', 'upower'], stdout=subprocess.PIPE) p.communicate() have_upower = (p.returncode == 0) class TestCLI(dbusmock.DBusTestCase): '''Test running dbusmock from the command line''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.start_session_bus() klass.system_con = klass.get_dbus(True) klass.session_con = klass.get_dbus() def setUp(self): self.p_mock = None def tearDown(self): if self.p_mock: if self.p_mock.stdout: self.p_mock.stdout.close() if self.p_mock.stderr: self.p_mock.stdout.close() self.p_mock.terminate() self.p_mock.wait() self.p_mock = None def test_session_bus(self): self.p_mock = subprocess.Popen([sys.executable, '-m', 'dbusmock', 'com.example.Test', '/', 'TestIface']) self.wait_for_bus_object('com.example.Test', '/') def test_system_bus(self): self.p_mock = subprocess.Popen([sys.executable, '-m', 'dbusmock', '--system', 'com.example.Test', '/', 'TestIface']) self.wait_for_bus_object('com.example.Test', '/', True) def test_template_system(self): self.p_mock = subprocess.Popen([sys.executable, '-m', 'dbusmock', '--system', '-t', 'upower'], stdout=subprocess.PIPE, universal_newlines=True) self.wait_for_bus_object('org.freedesktop.UPower', '/org/freedesktop/UPower', True) # check that it actually ran the template, if we have upower if have_upower: out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'on-battery:\s+no') mock_out = self.p_mock.stdout.readline() self.assertTrue('EnumerateDevices' in mock_out or 'GetAll' in mock_out, mock_out) def test_template_parameters(self): self.p_mock = subprocess.Popen([sys.executable, '-m', 'dbusmock', '--system', '-t', 'upower', '-p', '{"DaemonVersion": "0.99.0", "OnBattery": true}'], stdout=subprocess.PIPE, universal_newlines=True) self.wait_for_bus_object('org.freedesktop.UPower', '/org/freedesktop/UPower', True) # check that it actually ran the template, if we have upower if have_upower: out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'daemon-version:\s+0\\.99\\.0') self.assertRegex(out, 'on-battery:\s+yes') def test_template_parameters_malformed_json(self): with self.assertRaises(subprocess.CalledProcessError) as cm: subprocess.check_output([sys.executable, '-m', 'dbusmock', '--system', '-t', 'upower', '-p', '{"DaemonVersion: "0.99.0"}'], stderr=subprocess.STDOUT, universal_newlines=True) err = cm.exception self.assertEqual(err.returncode, 2) self.assertRegex(err.output, 'Malformed JSON given for parameters:.* delimiter') def test_template_parameters_not_dict(self): with self.assertRaises(subprocess.CalledProcessError) as cm: subprocess.check_output([sys.executable, '-m', 'dbusmock', '--system', '-t', 'upower', '-p', '"banana"'], stderr=subprocess.STDOUT, universal_newlines=True) err = cm.exception self.assertEqual(err.returncode, 2) self.assertEqual(err.output, 'JSON parameters must be a dictionary\n') def test_object_manager(self): self.p_mock = subprocess.Popen([sys.executable, '-m', 'dbusmock', '-m', 'com.example.Test', '/', 'TestIface'], stdout=subprocess.PIPE) self.wait_for_bus_object('com.example.Test', '/') obj = self.session_con.get_object('com.example.Test', '/') if_om = dbus.Interface(obj, dbusmock.OBJECT_MANAGER_IFACE) self.assertEqual(if_om.GetManagedObjects(), {}) # add a new object, should appear obj.AddObject('/a/b', 'org.Test', {'name': 'foo'}, dbus.Array([], signature='(ssss)')) self.assertEqual(if_om.GetManagedObjects(), {'/a/b': {'org.Test': {'name': 'foo'}}}) def test_no_args(self): p = subprocess.Popen([sys.executable, '-m', 'dbusmock'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) (out, err) = p.communicate() self.assertEqual(out, '') self.assertTrue('must specify NAME' in err, err) self.assertNotEqual(p.returncode, 0) def test_help(self): p = subprocess.Popen([sys.executable, '-m', 'dbusmock', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) (out, err) = p.communicate() self.assertEqual(err, '') self.assertTrue('INTERFACE' in out, out) self.assertTrue('--system' in out, out) self.assertEqual(p.returncode, 0) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_code.py0000664000175000017500000000312712605435032021227 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import sys import unittest import subprocess class StaticCodeTests(unittest.TestCase): @unittest.skipIf(subprocess.call(['which', 'pyflakes'], stdout=subprocess.PIPE) != 0, 'pyflakes not installed') def test_pyflakes(self): pyflakes = subprocess.Popen(['pyflakes', '.'], stdout=subprocess.PIPE, universal_newlines=True) (out, err) = pyflakes.communicate() self.assertEqual(pyflakes.returncode, 0, out) @unittest.skipIf(subprocess.call(['which', 'pep8'], stdout=subprocess.PIPE) != 0, 'pep8 not installed') def test_pep8(self): pep8 = subprocess.Popen(['pep8', '--max-line-length=130', '--ignore=E124,E402,E731', '.'], stdout=subprocess.PIPE, universal_newlines=True) (out, err) = pep8.communicate() self.assertEqual(pep8.returncode, 0, out) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_consolekit.py0000644000175000017500000000757712264500431022477 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import os.path import dbus import dbusmock @unittest.skipUnless(os.path.exists('/usr/bin/ck-list-sessions'), 'ck-list-sessions not installed') class TestConsoleKit(dbusmock.DBusTestCase): @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): self.p_mock = self.spawn_server('org.freedesktop.ConsoleKit', '/org/freedesktop/ConsoleKit/Manager', 'org.freedesktop.ConsoleKit.Manager', system_bus=True, stdout=subprocess.PIPE) self.dbusmock = dbus.Interface(self.dbus_con.get_object( 'org.freedesktop.ConsoleKit', '/org/freedesktop/ConsoleKit/Manager'), dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_one_active_session(self): self.dbusmock.AddMethods('', ( ('GetSessions', '', 'ao', 'ret = ["/org/freedesktop/ConsoleKit/MockSession"]'), ('GetCurrentSession', '', 'o', 'ret = "/org/freedesktop/ConsoleKit/MockSession"'), ('GetSeats', '', 'ao', 'ret = ["/org/freedesktop/ConsoleKit/MockSeat"]'), )) self.dbusmock.AddObject('/org/freedesktop/ConsoleKit/MockSeat', 'org.freedesktop.ConsoleKit.Seat', {}, [ ('GetSessions', '', 'ao', 'ret = ["/org/freedesktop/ConsoleKit/MockSession"]'), ]) self.dbusmock.AddObject('/org/freedesktop/ConsoleKit/MockSession', 'org.freedesktop.ConsoleKit.Session', {}, [ ('GetSeatId', '', 'o', 'ret = "/org/freedesktop/ConsoleKit/MockSeat"'), ('GetUnixUser', '', 'u', 'ret = os.geteuid()'), ('GetCreationTime', '', 's', 'ret = "2012-01-01T01:23:45.600000Z"'), ('GetIdleSinceHint', '', 's', 'ret = "2012-01-01T02:23:45.600000Z"'), ('IsLocal', '', 'b', 'ret = True'), ('IsActive', '', 'b', 'ret = True'), ('GetDisplayDevice', '', 's', 'ret = ""'), ('GetX11DisplayDevice', '', 's', 'ret = "/dev/tty7"'), ('GetX11Display', '', 's', 'ret = os.environ.get("DISPLAY", "95:0")'), ('GetRemoteHostName', '', 's', 'ret = ""'), ('GetSessionType', '', 's', 'ret = ""'), ('GetLoginSessionId', '', 's', 'ret = "12345"'), ]) out = subprocess.check_output(['ck-list-sessions'], universal_newlines=True) self.assertRegex(out, '^MockSession:') self.assertRegex(out, 'is-local = TRUE') self.assertRegex(out, "login-session-id = '12345'") if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_gnome_screensaver.py0000664000175000017500000000436712264500431024026 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import os import sys import subprocess import fcntl import dbusmock class TestGnomeScreensaver(dbusmock.DBusTestCase): '''Test mocking gnome-screensaver''' @classmethod def setUpClass(klass): klass.start_session_bus() klass.dbus_con = klass.get_dbus(False) def setUp(self): (self.p_mock, self.obj_ss) = self.spawn_server_template( 'gnome_screensaver', {}, stdout=subprocess.PIPE) # set log to nonblocking flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL) fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_default_state(self): '''Not locked by default''' self.assertEqual(self.obj_ss.GetActive(), False) def test_lock(self): '''Lock()''' self.obj_ss.Lock() self.assertEqual(self.obj_ss.GetActive(), True) self.assertGreater(self.obj_ss.GetActiveTime(), 0) self.assertRegex(self.p_mock.stdout.read(), b'emit org.gnome.ScreenSaver.ActiveChanged True\n') def test_set_active(self): '''SetActive()''' self.obj_ss.SetActive(True) self.assertEqual(self.obj_ss.GetActive(), True) self.assertRegex(self.p_mock.stdout.read(), b'emit org.gnome.ScreenSaver.ActiveChanged True\n') self.obj_ss.SetActive(False) self.assertEqual(self.obj_ss.GetActive(), False) self.assertRegex(self.p_mock.stdout.read(), b'emit org.gnome.ScreenSaver.ActiveChanged False\n') if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_logind.py0000644000175000017500000001060612406750515021574 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbusmock p = subprocess.Popen(['which', 'loginctl'], stdout=subprocess.PIPE) p.communicate() have_loginctl = (p.returncode == 0) @unittest.skipUnless(have_loginctl, 'loginctl not installed') class TestLogind(dbusmock.DBusTestCase): '''Test mocking logind''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) if have_loginctl: out = subprocess.check_output(['loginctl', '--version'], universal_newlines=True) klass.version = out.splitlines()[0].split()[-1] def setUp(self): self.p_mock = None def tearDown(self): if self.p_mock: self.p_mock.terminate() self.p_mock.wait() def test_empty(self): (self.p_mock, _) = self.spawn_server_template('logind', {}, stdout=subprocess.PIPE) cmd = ['loginctl'] if self.version >= '209': cmd.append('--no-legend') out = subprocess.check_output(cmd + ['list-sessions'], universal_newlines=True) self.assertEqual(out, '') out = subprocess.check_output(cmd + ['list-seats'], universal_newlines=True) self.assertEqual(out, '') out = subprocess.check_output(cmd + ['list-users'], universal_newlines=True) self.assertEqual(out, '') def test_session(self): (self.p_mock, obj_logind) = self.spawn_server_template('logind', {}, stdout=subprocess.PIPE) obj_logind.AddSession('c1', 'seat0', 500, 'joe', True) out = subprocess.check_output(['loginctl', 'list-seats'], universal_newlines=True) self.assertRegex(out, '(^|\n)seat0\s+') out = subprocess.check_output(['loginctl', 'show-seat', 'seat0'], universal_newlines=True) self.assertRegex(out, 'Id=seat0') if self.version <= '208': self.assertRegex(out, 'ActiveSession=c1') self.assertRegex(out, 'Sessions=c1') out = subprocess.check_output(['loginctl', 'list-users'], universal_newlines=True) self.assertRegex(out, '(^|\n) +500 +joe +($|\n)') # note, this does an actual getpwnam() in the client, so we cannot call # this with hardcoded user names; get from actual user in the system # out = subprocess.check_output(['loginctl', 'show-user', 'joe'], # universal_newlines=True) # self.assertRegex(out, 'UID=500') # self.assertRegex(out, 'GID=500') # self.assertRegex(out, 'Name=joe') # self.assertRegex(out, 'Sessions=c1') # self.assertRegex(out, 'State=active') out = subprocess.check_output(['loginctl', 'list-sessions'], universal_newlines=True) self.assertRegex(out, 'c1 +500 +joe +seat0') out = subprocess.check_output(['loginctl', 'show-session', 'c1'], universal_newlines=True) self.assertRegex(out, 'Id=c1') self.assertRegex(out, 'Class=user') self.assertRegex(out, 'Active=yes') self.assertRegex(out, 'State=active') self.assertRegex(out, 'Name=joe') def test_properties(self): (self.p_mock, obj_logind) = self.spawn_server_template('logind', {}, stdout=subprocess.PIPE) props = obj_logind.GetAll('org.freedesktop.login1.Manager', interface='org.freedesktop.DBus.Properties') self.assertEqual(props['PreparingForSleep'], False) self.assertEqual(props['IdleSinceHint'], 0) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_networkmanager.py0000664000175000017500000005406012633532515023350 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Iftikhar Ahmad' __email__ = 'iftikhar.ahmad@canonical.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbus import dbus.mainloop.glib import dbusmock import os import re from gi.repository import GLib from dbusmock.templates.networkmanager import DeviceState from dbusmock.templates.networkmanager import NM80211ApSecurityFlags from dbusmock.templates.networkmanager import InfrastructureMode from dbusmock.templates.networkmanager import NMActiveConnectionState from dbusmock.templates.networkmanager import NMState from dbusmock.templates.networkmanager import NMConnectivityState from dbusmock.templates.networkmanager import (CSETTINGS_IFACE, MAIN_IFACE, SETTINGS_OBJ, SETTINGS_IFACE) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) p = subprocess.Popen(['which', 'nmcli'], stdout=subprocess.PIPE) p.communicate() have_nmcli = (p.returncode == 0) @unittest.skipUnless(have_nmcli, 'nmcli not installed') class TestNetworkManager(dbusmock.DBusTestCase): '''Test mocking NetworkManager''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) # prepare environment which avoids translations klass.lang_env = os.environ.copy() try: del klass.lang_env['LANG'] except KeyError: pass try: del klass.lang_env['LANGUAGE'] except KeyError: pass klass.lang_env['LC_MESSAGES'] = 'C' def setUp(self): (self.p_mock, self.obj_networkmanager) = self.spawn_server_template( 'networkmanager', {'NetworkingEnabled': True, 'WwanEnabled': False}, stdout=subprocess.PIPE) self.dbusmock = dbus.Interface(self.obj_networkmanager, dbusmock.MOCK_IFACE) self.settings = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, SETTINGS_OBJ), SETTINGS_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def read_general(self): return subprocess.check_output(['nmcli', '--nocheck', 'general'], env=self.lang_env, universal_newlines=True) def read_connection(self): return subprocess.check_output(['nmcli', '--nocheck', 'connection'], env=self.lang_env, universal_newlines=True) def read_active_connection(self): return subprocess.check_output(['nmcli', '--nocheck', 'connection', 'show', '--active'], env=self.lang_env, universal_newlines=True) def read_device(self): return subprocess.check_output(['nmcli', '--nocheck', 'dev'], env=self.lang_env, universal_newlines=True) def read_device_wifi(self): return subprocess.check_output(['nmcli', '--nocheck', 'dev', 'wifi'], env=self.lang_env, universal_newlines=True) def test_one_eth_disconnected(self): self.dbusmock.AddEthernetDevice('mock_Ethernet1', 'eth0', DeviceState.DISCONNECTED) out = self.read_device() self.assertRegex(out, 'eth0.*\sdisconnected') def test_one_eth_connected(self): self.dbusmock.AddEthernetDevice('mock_Ethernet1', 'eth0', DeviceState.ACTIVATED) out = self.read_device() self.assertRegex(out, 'eth0.*\sconnected') def test_two_eth(self): # test with numeric state value self.dbusmock.AddEthernetDevice('mock_Ethernet1', 'eth0', 30) self.dbusmock.AddEthernetDevice('mock_Ethernet2', 'eth1', DeviceState.ACTIVATED) out = self.read_device() self.assertRegex(out, 'eth0.*\sdisconnected') self.assertRegex(out, 'eth1.*\sconnected') def test_wifi_without_access_points(self): self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) out = self.read_device() self.assertRegex(out, 'wlan0.*\sconnected') def test_eth_and_wifi(self): self.dbusmock.AddEthernetDevice('mock_Ethernet1', 'eth0', DeviceState.DISCONNECTED) self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) out = self.read_device() self.assertRegex(out, 'eth0.*\sdisconnected') self.assertRegex(out, 'wlan0.*\sconnected') def test_one_wifi_with_accesspoints(self): wifi = self.dbusmock.AddWiFiDevice('mock_WiFi2', 'wlan0', DeviceState.ACTIVATED) self.dbusmock.AddAccessPoint(wifi, 'Mock_AP1', 'AP_1', '00:23:F8:7E:12:BB', InfrastructureMode.NM_802_11_MODE_ADHOC, 2425, 5400, 82, NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_PSK) self.dbusmock.AddAccessPoint(wifi, 'Mock_AP3', 'AP_3', '00:23:F8:7E:12:BC', InfrastructureMode.NM_802_11_MODE_INFRA, 2425, 5400, 82, 0x400) out = self.read_device() aps = self.read_device_wifi() self.assertRegex(out, 'wlan0.*\sconnected') self.assertRegex(aps, 'AP_1.*\sAd-Hoc') self.assertRegex(aps, 'AP_3.*\sInfra') def test_two_wifi_with_accesspoints(self): wifi1 = self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) wifi2 = self.dbusmock.AddWiFiDevice('mock_WiFi2', 'wlan1', DeviceState.UNAVAILABLE) self.dbusmock.AddAccessPoint(wifi1, 'Mock_AP0', 'AP_0', '00:23:F8:7E:12:BA', InfrastructureMode.NM_802_11_MODE_UNKNOWN, 2425, 5400, 82, 0x400) self.dbusmock.AddAccessPoint(wifi2, 'Mock_AP1', 'AP_1', '00:23:F8:7E:12:BB', InfrastructureMode.NM_802_11_MODE_ADHOC, 2425, 5400, 82, NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_PSK) self.dbusmock.AddAccessPoint(wifi2, 'Mock_AP3', 'AP_2', '00:23:F8:7E:12:BC', InfrastructureMode.NM_802_11_MODE_INFRA, 2425, 5400, 82, 0x400) out = self.read_device() aps = self.read_device_wifi() self.assertRegex(out, 'wlan0.*\sconnected') self.assertRegex(out, 'wlan1.*\sunavailable') self.assertRegex(aps, 'AP_0.*\s(Unknown|N/A)') self.assertRegex(aps, 'AP_1.*\sAd-Hoc') self.assertRegex(aps, 'AP_2.*\sInfra') def test_wifi_with_connection(self): wifi1 = self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) ap1 = self.dbusmock.AddAccessPoint( wifi1, 'Mock_AP1', 'The_SSID', '00:23:F8:7E:12:BB', InfrastructureMode.NM_802_11_MODE_ADHOC, 2425, 5400, 82, NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_PSK) con1 = self.dbusmock.AddWiFiConnection(wifi1, 'Mock_Con1', 'The_SSID', 'wpa-psk') self.assertRegex(self.read_connection(), 'The_SSID.*\s802-11-wireless') self.assertEqual(ap1, '/org/freedesktop/NetworkManager/AccessPoint/Mock_AP1') self.assertEqual(con1, '/org/freedesktop/NetworkManager/Settings/Mock_Con1') def test_global_state(self): self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_CONNECTED_GLOBAL) self.assertRegex(self.read_general(), 'connected.*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_CONNECTED_SITE) self.assertRegex(self.read_general(), 'connected \(site only\).*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_CONNECTED_LOCAL) self.assertRegex(self.read_general(), 'connected \(local only\).*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_CONNECTING) self.assertRegex(self.read_general(), 'connecting.*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTING) self.assertRegex(self.read_general(), 'disconnecting.*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTED) self.assertRegex(self.read_general(), 'disconnected.*\sfull') self.dbusmock.SetGlobalConnectionState(NMState.NM_STATE_ASLEEP) self.assertRegex(self.read_general(), 'asleep.*\sfull') def test_connectivity_state(self): self.dbusmock.SetConnectivity(NMConnectivityState.NM_CONNECTIVITY_FULL) self.assertRegex(self.read_general(), 'connected.*\sfull') self.dbusmock.SetConnectivity(NMConnectivityState.NM_CONNECTIVITY_LIMITED) self.assertRegex(self.read_general(), 'connected.*\slimited') self.dbusmock.SetConnectivity(NMConnectivityState.NM_CONNECTIVITY_PORTAL) self.assertRegex(self.read_general(), 'connected.*\sportal') self.dbusmock.SetConnectivity(NMConnectivityState.NM_CONNECTIVITY_NONE) self.assertRegex(self.read_general(), 'connected.*\snone') def test_wifi_with_active_connection(self): wifi1 = self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) ap1 = self.dbusmock.AddAccessPoint( wifi1, 'Mock_AP1', 'The_SSID', '00:23:F8:7E:12:BB', InfrastructureMode.NM_802_11_MODE_INFRA, 2425, 5400, 82, NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_PSK) con1 = self.dbusmock.AddWiFiConnection(wifi1, 'Mock_Con1', 'The_SSID', '') active_con1 = self.dbusmock.AddActiveConnection( [wifi1], con1, ap1, 'Mock_Active1', NMActiveConnectionState.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) self.assertEqual(ap1, '/org/freedesktop/NetworkManager/AccessPoint/Mock_AP1') self.assertEqual(con1, '/org/freedesktop/NetworkManager/Settings/Mock_Con1') self.assertEqual(active_con1, '/org/freedesktop/NetworkManager/ActiveConnection/Mock_Active1') self.assertRegex(self.read_general(), 'connected.*\sfull') self.assertRegex(self.read_connection(), 'The_SSID.*\s802-11-wireless') self.assertRegex(self.read_active_connection(), 'The_SSID.*\s802-11-wireless') self.assertRegex(self.read_device_wifi(), 'The_SSID') self.dbusmock.RemoveActiveConnection(wifi1, active_con1) self.assertRegex(self.read_connection(), 'The_SSID.*\s802-11-wireless') self.assertFalse(re.compile('The_SSID.*\s802-11-wireless').search(self.read_active_connection())) self.assertRegex(self.read_device_wifi(), 'The_SSID') self.dbusmock.RemoveWifiConnection(wifi1, con1) self.assertFalse(re.compile('The_SSID.*\s802-11-wireless').search(self.read_connection())) self.assertRegex(self.read_device_wifi(), 'The_SSID') self.dbusmock.RemoveAccessPoint(wifi1, ap1) self.assertFalse(re.compile('The_SSID').search(self.read_device_wifi())) def test_add_connection(self): self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) uuid = '11111111-1111-1111-1111-111111111111' settings = dbus.Dictionary({ 'connection': dbus.Dictionary({ 'id': 'test connection', 'uuid': uuid, 'type': '802-11-wireless'}, signature='sv'), '802-11-wireless': dbus.Dictionary({ 'ssid': dbus.ByteArray('The_SSID'.encode('UTF-8'))}, signature='sv') }, signature='sa{sv}') con1 = self.settings.AddConnection(settings) self.assertEqual(con1, '/org/freedesktop/NetworkManager/Settings/0') self.assertRegex(self.read_connection(), '%s.*\s802-11-wireless' % uuid) # Use the same settings, but this one will autoconnect. uuid2 = '22222222-2222-2222-2222-222222222222' settings['connection']['autoconnect'] = dbus.Boolean( True, variant_level=1) settings['connection']['uuid'] = uuid2 con2 = self.settings.AddConnection(settings) self.assertEqual(con2, '/org/freedesktop/NetworkManager/Settings/1') self.assertRegex(self.read_general(), 'connected.*\sfull') self.assertRegex(self.read_connection(), '%s.*\s802-11-wireless' % uuid2) self.assertRegex(self.read_active_connection(), '%s.*\s802-11-wireless' % uuid2) def test_update_connection(self): uuid = '133d8eb9-6de6-444f-8b37-f40bf9e33226' settings = dbus.Dictionary({ 'connection': dbus.Dictionary({ 'id': 'test wireless', 'uuid': uuid, 'type': '802-11-wireless'}, signature='sv'), '802-11-wireless': dbus.Dictionary({ 'ssid': dbus.ByteArray('The_SSID'.encode('UTF-8'))}, signature='sv') }, signature='sa{sv}') con1 = self.settings.AddConnection(settings) con1_iface = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, con1), CSETTINGS_IFACE) self.assertEqual(con1, '/org/freedesktop/NetworkManager/Settings/0') self.assertRegex(self.read_connection(), '%s.*\s802-11-wireless' % uuid) new_settings = dbus.Dictionary({ 'connection': dbus.Dictionary({ 'id': 'test wired', 'type': '802-3-ethernet'}, signature='sv'), '802-3-ethernet': dbus.Dictionary({ 'name': '802-3-ethernet' }, signature='sv')}, signature='sa{sv}') con1_iface.Update(new_settings) self.assertRegex(self.read_connection(), '%s.*\s802-3-ethernet' % uuid) def test_remove_connection(self): wifi1 = self.dbusmock.AddWiFiDevice('mock_WiFi1', 'wlan0', DeviceState.ACTIVATED) ap1 = self.dbusmock.AddAccessPoint( wifi1, 'Mock_AP1', 'The_SSID', '00:23:F8:7E:12:BB', InfrastructureMode.NM_802_11_MODE_INFRA, 2425, 5400, 82, NM80211ApSecurityFlags.NM_802_11_AP_SEC_KEY_MGMT_PSK) con1 = self.dbusmock.AddWiFiConnection(wifi1, 'Mock_Con1', 'The_SSID', '') self.dbusmock.AddActiveConnection( [wifi1], con1, ap1, 'Mock_Active1', NMActiveConnectionState.NM_ACTIVE_CONNECTION_STATE_ACTIVATED) con1_i = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, con1), CSETTINGS_IFACE) con1_i.Delete() self.assertRegex(self.read_general(), 'disconnected.*\sfull') self.assertFalse(re.compile('The_SSID.*\s802-11-wireless').search(self.read_active_connection())) self.assertRegex(self.read_device(), 'wlan0.*\sdisconnected') def test_add_remove_settings(self): connection = { 'connection': { 'timestamp': 1441979296, 'type': 'vpn', 'id': 'a', 'uuid': '11111111-1111-1111-1111-111111111111' }, 'vpn': { 'service-type': 'org.freedesktop.NetworkManager.openvpn', 'data': { 'connection-type': 'tls' } }, 'ipv4': { 'routes': dbus.Array([], signature='o'), 'never-default': True, 'addresses': dbus.Array([], signature='o'), 'dns': dbus.Array([], signature='o'), 'method': 'auto' }, 'ipv6': { 'addresses': dbus.Array([], signature='o'), 'ip6-privacy': 0, 'dns': dbus.Array([], signature='o'), 'never-default': True, 'routes': dbus.Array([], signature='o'), 'method': 'auto' } } connectionA = self.settings.AddConnection(connection) connection['connection']['id'] = 'b' connection['connection']['uuid'] = '11111111-1111-1111-1111-111111111112' connectionB = self.settings.AddConnection(connection) self.assertEqual(self.settings.ListConnections(), [connectionA, connectionB]) connectionA_i = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, connectionA), CSETTINGS_IFACE) connectionA_i.Delete() self.assertEqual(self.settings.ListConnections(), [connectionB]) connection['connection']['id'] = 'c' connection['connection']['uuid'] = '11111111-1111-1111-1111-111111111113' connectionC = self.settings.AddConnection(connection) self.assertEqual(self.settings.ListConnections(), [connectionB, connectionC]) def test_add_update_settings(self): connection = { 'connection': { 'timestamp': 1441979296, 'type': 'vpn', 'id': 'a', 'uuid': '11111111-1111-1111-1111-111111111111' }, 'vpn': { 'service-type': 'org.freedesktop.NetworkManager.openvpn', 'data': dbus.Dictionary({ 'connection-type': 'tls' }, signature='ss') }, 'ipv4': { 'routes': dbus.Array([], signature='o'), 'never-default': True, 'addresses': dbus.Array([], signature='o'), 'dns': dbus.Array([], signature='o'), 'method': 'auto' }, 'ipv6': { 'addresses': dbus.Array([], signature='o'), 'ip6-privacy': 0, 'dns': dbus.Array([], signature='o'), 'never-default': True, 'routes': dbus.Array([], signature='o'), 'method': 'auto' } } connectionA = self.settings.AddConnection(connection) self.assertEqual(self.settings.ListConnections(), [connectionA]) connectionA_i = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, connectionA), CSETTINGS_IFACE) connection['connection']['id'] = 'b' def do_update(): connectionA_i.Update(connection) caught = [] ml = GLib.MainLoop() def catch(*args, **kwargs): if (kwargs['interface'] == 'org.freedesktop.NetworkManager.Settings.Connection' and kwargs['member'] == 'Updated'): caught.append(kwargs['path']) ml.quit() self.dbus_con.add_signal_receiver(catch, interface_keyword='interface', path_keyword='path', member_keyword='member') GLib.timeout_add(200, do_update) # ensure that the loop quits even when we don't catch anything GLib.timeout_add(3000, ml.quit) ml.run() self.assertEqual(connectionA_i.GetSettings(), connection) self.assertEqual(caught, [connectionA]) def test_settings_secrets(self): secrets = dbus.Dictionary({ 'cert-pass': 'certificate password', 'password': 'the password', }, signature='ss') connection = { 'connection': { 'timestamp': 1441979296, 'type': 'vpn', 'id': 'a', 'uuid': '11111111-1111-1111-1111-111111111111' }, 'vpn': { 'service-type': 'org.freedesktop.NetworkManager.openvpn', 'data': dbus.Dictionary({ 'connection-type': 'password-tls', 'remote': 'remotey', 'ca': '/my/ca.crt', 'cert': '/my/cert.crt', 'cert-pass-flags': '1', 'key': '/my/key.key', 'password-flags': "1", }, signature='ss'), 'secrets': secrets }, 'ipv4': { 'routes': dbus.Array([], signature='o'), 'never-default': True, 'addresses': dbus.Array([], signature='o'), 'dns': dbus.Array([], signature='o'), 'method': 'auto' }, 'ipv6': { 'addresses': dbus.Array([], signature='o'), 'ip6-privacy': 0, 'dns': dbus.Array([], signature='o'), 'never-default': True, 'routes': dbus.Array([], signature='o'), 'method': 'auto' } } connectionPath = self.settings.AddConnection(connection) self.assertEqual(self.settings.ListConnections(), [connectionPath]) connection_i = dbus.Interface( self.dbus_con.get_object(MAIN_IFACE, connectionPath), CSETTINGS_IFACE) # We expect there to be no secrets in the normal settings dict del connection['vpn']['secrets'] self.assertEqual(connection_i.GetSettings(), connection) # Secrets request should contain just vpn section with the secrets in self.assertEqual(connection_i.GetSecrets('vpn'), {'vpn': {'secrets': secrets}}) if __name__ == '__main__': unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_notification_daemon.py0000664000175000017500000001017712264500431024326 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import fcntl import os import dbus import dbusmock try: notify_send_version = subprocess.check_output(['notify-send', '--version'], universal_newlines=True) notify_send_version = notify_send_version.split()[-1] except (OSError, subprocess.CalledProcessError): notify_send_version = '' @unittest.skipUnless(notify_send_version, 'notify-send not installed') class TestNotificationDaemon(dbusmock.DBusTestCase): '''Test mocking notification-daemon''' @classmethod def setUpClass(klass): klass.start_session_bus() klass.dbus_con = klass.get_dbus(False) def setUp(self): (self.p_mock, self.obj_daemon) = self.spawn_server_template( 'notification_daemon', {}, stdout=subprocess.PIPE) # set log to nonblocking flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL) fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_no_options(self): '''notify-send with no options''' subprocess.check_call(['notify-send', 'title', 'my text']) log = self.p_mock.stdout.read() self.assertRegex(log, b'[0-9.]+ Notify "notify-send" 0 "" "title" "my text" \[\]') @unittest.skipIf(notify_send_version < '0.7.5', 'this requires libnotify >= 0.7.5') def test_options(self): '''notify-send with some options''' subprocess.check_call(['notify-send', '-t', '27', '-a', 'fooApp', '-i', 'warning_icon', 'title', 'my text']) log = self.p_mock.stdout.read() self.assertRegex(log, b'[0-9.]+ Notify "fooApp" 0 "warning_icon" "title" "my text" \[\] {"urgency": 1} 27\n') def test_id(self): '''ID handling''' notify_proxy = dbus.Interface( self.dbus_con.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications'), 'org.freedesktop.Notifications') # with input ID 0 it should generate new IDs id = notify_proxy.Notify('test', 0, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 1) id = notify_proxy.Notify('test', 0, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 2) # an existing ID should just be bounced back id = notify_proxy.Notify('test', 4, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 4) id = notify_proxy.Notify('test', 1, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 1) # the previous doesn't forget the counter id = notify_proxy.Notify('test', 0, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 3) def test_close(self): '''CloseNotification() and NotificationClosed() signal''' notify_proxy = dbus.Interface( self.dbus_con.get_object('org.freedesktop.Notifications', '/org/freedesktop/Notifications'), 'org.freedesktop.Notifications') id = notify_proxy.Notify('test', 0, '', 'summary', 'body', [], {}, -1) self.assertEqual(id, 1) # known notification, should send a signal notify_proxy.CloseNotification(id) log = self.p_mock.stdout.read() self.assertRegex(log, b'[0-9.]+ emit .*NotificationClosed 1 1\n') # unknown notification, don't send a signal notify_proxy.CloseNotification(id + 1) log = self.p_mock.stdout.read() self.assertNotIn(b'NotificationClosed', log) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_ofono.py0000664000175000017500000001334012532052161021430 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import os import dbus import dbusmock script_dir = os.environ.get('OFONO_SCRIPT_DIR', '/usr/share/ofono/scripts') have_scripts = os.access(os.path.join(script_dir, 'list-modems'), os.X_OK) @unittest.skipUnless(have_scripts, 'ofono scripts not available, set $OFONO_SCRIPT_DIR') class TestOfono(dbusmock.DBusTestCase): '''Test mocking ofonod''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) (klass.p_mock, klass.obj_ofono) = klass.spawn_server_template( 'ofono', {}, stdout=subprocess.PIPE) def setUp(self): self.obj_ofono.Reset() def test_list_modems(self): '''Manager.GetModems()''' out = subprocess.check_output([os.path.join(script_dir, 'list-modems')]) self.assertTrue(out.startswith(b'[ /ril_0 ]'), out) self.assertIn(b'Powered = 1', out) self.assertIn(b'Online = 1', out) self.assertIn(b'Model = Mock Modem', out) self.assertIn(b'[ org.ofono.NetworkRegistration ]', out) self.assertIn(b'Status = registered', out) self.assertIn(b'Name = fake.tel', out) self.assertIn(b'Technology = gsm', out) self.assertIn(b'[ org.ofono.SimManager ]', out) self.assertIn(b'PinRequired = none', out) self.assertIn(b'Present = 1', out) def test_outgoing_call(self): '''outgoing voice call''' # no calls by default out = subprocess.check_output([os.path.join(script_dir, 'list-calls')]) self.assertEqual(out, b'[ /ril_0 ]\n') # start call out = subprocess.check_output([os.path.join(script_dir, 'dial-number'), '12345']) self.assertEqual(out, b'Using modem /ril_0\n/ril_0/voicecall01\n') out = subprocess.check_output([os.path.join(script_dir, 'list-calls')]) self.assertIn(b'/ril_0/voicecall01', out) self.assertIn(b'LineIdentification = 12345', out) self.assertIn(b'State = dialing', out) out = subprocess.check_output([os.path.join(script_dir, 'hangup-call'), '/ril_0/voicecall01']) self.assertEqual(out, b'') # no active calls any more out = subprocess.check_output([os.path.join(script_dir, 'list-calls')]) self.assertEqual(out, b'[ /ril_0 ]\n') def test_hangup_all(self): '''multiple outgoing voice calls''' out = subprocess.check_output([os.path.join(script_dir, 'dial-number'), '12345']) self.assertEqual(out, b'Using modem /ril_0\n/ril_0/voicecall01\n') out = subprocess.check_output([os.path.join(script_dir, 'dial-number'), '54321']) self.assertEqual(out, b'Using modem /ril_0\n/ril_0/voicecall02\n') out = subprocess.check_output([os.path.join(script_dir, 'list-calls')]) self.assertIn(b'/ril_0/voicecall01', out) self.assertIn(b'/ril_0/voicecall02', out) self.assertIn(b'LineIdentification = 12345', out) self.assertIn(b'LineIdentification = 54321', out) out = subprocess.check_output([os.path.join(script_dir, 'hangup-all')]) out = subprocess.check_output([os.path.join(script_dir, 'list-calls')]) self.assertEqual(out, b'[ /ril_0 ]\n') def test_list_operators(self): '''list operators''' out = subprocess.check_output([os.path.join(script_dir, 'list-operators')], universal_newlines=True) self.assertTrue(out.startswith('[ /ril_0 ]'), out) self.assertIn('[ /ril_0/operator/op1 ]', out) self.assertIn('Status = current', out) self.assertIn('Technologies = gsm', out) self.assertIn('MobileNetworkCode = 11', out) self.assertIn('MobileCountryCode = 777', out) self.assertIn('Name = fake.tel', out) def test_get_operators_for_two_modems(self): '''Add second modem, list operators on both''' iface = 'org.ofono.NetworkRegistration' # add second modem self.obj_ofono.AddModem('sim2', {'Powered': True}) # get modem proxy, get netreg interface modem_0 = self.dbus_con.get_object('org.ofono', '/ril_0') modem_0_netreg = dbus.Interface( modem_0, dbus_interface=iface) modem_0_ops = modem_0_netreg.GetOperators() # get modem proxy, get netreg interface modem_1 = self.dbus_con.get_object('org.ofono', '/sim2') modem_1_netreg = dbus.Interface( modem_1, dbus_interface=iface) modem_1_ops = modem_1_netreg.GetOperators() self.assertIn('/ril_0/operator/op1', str(modem_0_ops)) self.assertNotIn('/sim2', str(modem_0_ops)) self.assertIn('/sim2/operator/op1', str(modem_1_ops)) self.assertNotIn('/ril_0', str(modem_1_ops)) def test_second_modem(self): '''Add a second modem''' self.obj_ofono.AddModem('sim2', {'Powered': True}) out = subprocess.check_output([os.path.join(script_dir, 'list-modems')]) self.assertTrue(out.startswith(b'[ /ril_0 ]'), out) self.assertIn(b'[ /sim2 ]', out) self.assertIn(b'Powered = 1', out) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_polkitd.py0000664000175000017500000000517512264500431021765 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbus import dbusmock p = subprocess.Popen(['which', 'pkcheck'], stdout=subprocess.PIPE) p.communicate() have_pkcheck = (p.returncode == 0) @unittest.skipUnless(have_pkcheck, 'pkcheck not installed') class TestPolkit(dbusmock.DBusTestCase): '''Test mocking polkitd''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, self.obj_polkitd) = self.spawn_server_template( 'polkitd', {}, stdout=subprocess.PIPE) self.dbusmock = dbus.Interface(self.obj_polkitd, dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_default(self): self.check_action('org.freedesktop.test.frobnicate', False) def test_allow_unknown(self): self.dbusmock.AllowUnknown(True) self.check_action('org.freedesktop.test.frobnicate', True) self.dbusmock.AllowUnknown(False) self.check_action('org.freedesktop.test.frobnicate', False) def test_set_allowed(self): self.dbusmock.SetAllowed(['org.freedesktop.test.frobnicate', 'org.freedesktop.test.slap']) self.check_action('org.freedesktop.test.frobnicate', True) self.check_action('org.freedesktop.test.slap', True) self.check_action('org.freedesktop.test.wobble', False) def check_action(self, action, expect_allow): pkcheck = subprocess.Popen(['pkcheck', '--action-id', action, '--process', '123'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) out = pkcheck.communicate()[0] if expect_allow: self.assertEqual(pkcheck.returncode, 0) self.assertEqual(out, 'test=test\n') else: self.assertNotEqual(pkcheck.returncode, 0) self.assertEqual(out, 'test=test\nNot authorized.\n') if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_timedated.py0000664000175000017500000000544512536263131022264 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Iain Lane' __email__ = 'iain.lane@canonical.com' __copyright__ = '(c) 2013 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import dbusmock p = subprocess.Popen(['which', 'timedatectl'], stdout=subprocess.PIPE) p.communicate() have_timedatectl = (p.returncode == 0) @unittest.skipUnless(have_timedatectl, 'timedatectl not installed') class TestTimedated(dbusmock.DBusTestCase): '''Test mocking timedated''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, _) = self.spawn_server_template( 'timedated', {}, stdout=subprocess.PIPE) self.obj_timedated = self.dbus_con.get_object( 'org.freedesktop.timedate1', '/org/freedesktop/timedate1') def tearDown(self): if self.p_mock: self.p_mock.terminate() self.p_mock.wait() def run_timedatectl(self): return subprocess.check_output(['timedatectl'], universal_newlines=True) def test_default_timezone(self): out = self.run_timedatectl() # timedatectl doesn't get the timezone offset information over dbus so # we can't mock that. self.assertRegex(out, 'Time *zone: Etc/Utc') def test_changing_timezone(self): self.obj_timedated.SetTimezone('Africa/Johannesburg', False) out = self.run_timedatectl() # timedatectl doesn't get the timezone offset information over dbus so # we can't mock that. self.assertRegex(out, 'Time *zone: Africa/Johannesburg') def test_default_ntp(self): out = self.run_timedatectl() self.assertRegex(out, 'NTP (enabled|synchronized): yes') def test_changing_ntp(self): self.obj_timedated.SetNTP(False, False) out = self.run_timedatectl() self.assertRegex(out, 'NTP (enabled|synchronized): no') def test_default_local_rtc(self): out = self.run_timedatectl() self.assertRegex(out, 'RTC in local TZ: no') def test_changing_local_rtc(self): self.obj_timedated.SetLocalRTC(True, False, False) out = self.run_timedatectl() self.assertRegex(out, 'RTC in local TZ: yes') if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner( stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_upower.py0000664000175000017500000003071112456426345021650 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Martin Pitt' __email__ = 'martin.pitt@ubuntu.com' __copyright__ = '(c) 2012 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import time import os import fcntl import dbus import dbusmock UP_DEVICE_LEVEL_UNKNOWN = 0 UP_DEVICE_LEVEL_NONE = 1 p = subprocess.Popen(['which', 'upower'], stdout=subprocess.PIPE) p.communicate() have_upower = (p.returncode == 0) if have_upower: p = subprocess.Popen(['upower', '--version'], stdout=subprocess.PIPE, universal_newlines=True) out = p.communicate()[0] try: upower_client_version = out.splitlines()[0].split()[-1] assert p.returncode == 0 except IndexError: # FIXME: this happens in environments without a system D-BUS; upower # 0.9 still prints the client version, 0.99 just crashes upower_client_version = '0.99' else: upower_client_version = 0 @unittest.skipUnless(have_upower, 'upower not installed') class TestUPower(dbusmock.DBusTestCase): '''Test mocking upowerd''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', { 'OnBattery': True, 'HibernateAllowed': False, 'DaemonVersion': upower_client_version }, stdout=subprocess.PIPE) # set log to nonblocking flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL) fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) self.dbusmock = dbus.Interface(self.obj_upower, dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_no_devices(self): out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) # upower 1.0 has a "DisplayDevice" which is always there, ignore that # one for line in out.splitlines(): if line.endswith('/DisplayDevice'): continue self.assertFalse('Device' in line, out) self.assertRegex(out, 'on-battery:\s+yes') self.assertRegex(out, 'lid-is-present:\s+yes') def test_one_ac(self): path = self.dbusmock.AddAC('mock_AC', 'Mock AC') self.assertEqual(path, '/org/freedesktop/UPower/devices/mock_AC') self.assertRegex(self.p_mock.stdout.read(), b'emit org.freedesktop.UPower.DeviceAdded ' b'"/org/freedesktop/UPower/devices/mock_AC"\n') out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'Device: ' + path) # note, Add* is not magic: this just adds an object, not change # properties self.assertRegex(out, 'on-battery:\s+yes') self.assertRegex(out, 'lid-is-present:\s+yes') # print('--------- out --------\n%s\n------------' % out) mon = subprocess.Popen(['upower', '--monitor-detail'], stdout=subprocess.PIPE, universal_newlines=True) time.sleep(0.3) self.dbusmock.SetDeviceProperties(path, { 'PowerSupply': dbus.Boolean(True, variant_level=1) }) time.sleep(0.2) mon.terminate() out = mon.communicate()[0] self.assertRegex(out, 'device changed:\s+' + path) # print('--------- monitor out --------\n%s\n------------' % out) def test_discharging_battery(self): path = self.dbusmock.AddDischargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200) self.assertEqual(path, '/org/freedesktop/UPower/devices/mock_BAT') self.assertRegex(self.p_mock.stdout.read(), b'emit org.freedesktop.UPower.DeviceAdded ' b'"/org/freedesktop/UPower/devices/mock_BAT"\n') out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'Device: ' + path) # note, Add* is not magic: this just adds an object, not change # properties self.assertRegex(out, 'on-battery:\s+yes') self.assertRegex(out, 'lid-is-present:\s+yes') self.assertRegex(out, ' present:\s+yes') self.assertRegex(out, ' percentage:\s+30%') self.assertRegex(out, ' time to empty:\s+20.0 min') self.assertRegex(out, ' state:\s+discharging') def test_charging_battery(self): path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200) self.assertEqual(path, '/org/freedesktop/UPower/devices/mock_BAT') self.assertRegex(self.p_mock.stdout.read(), b'emit org.freedesktop.UPower.DeviceAdded ' b'"/org/freedesktop/UPower/devices/mock_BAT"\n') out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'Device: ' + path) # note, Add* is not magic: this just adds an object, not change # properties self.assertRegex(out, 'on-battery:\s+yes') self.assertRegex(out, 'lid-is-present:\s+yes') self.assertRegex(out, ' present:\s+yes') self.assertRegex(out, ' percentage:\s+30%') self.assertRegex(out, ' time to full:\s+20.0 min') self.assertRegex(out, ' state:\s+charging') @unittest.skipUnless(have_upower, 'upower not installed') @unittest.skipUnless(upower_client_version <= '0.99', 'pre-0.99 client API specific test') class TestUPower0(dbusmock.DBusTestCase): '''Test mocking upowerd with 0.x API''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', { 'OnBattery': True, 'HibernateAllowed': False, 'DaemonVersion': '0.9' }, stdout=subprocess.PIPE) # set log to nonblocking flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL) fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) self.dbusmock = dbus.Interface(self.obj_upower, dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_suspend(self): '''0.9 API specific Suspend signal''' self.obj_upower.Suspend(dbus_interface='org.freedesktop.UPower') self.assertRegex(self.p_mock.stdout.readline(), b'^[0-9.]+ Suspend$') def test_09_properties(self): '''0.9 API specific properties''' out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'daemon-version:\s+0.9') self.assertRegex(out, 'can-suspend:\s+yes') self.assertRegex(out, 'can-hibernate:?\s+no') self.assertNotIn('critical-action:', out) def test_no_display_device(self): '''0.9 API has no display device''' self.assertRaises(dbus.exceptions.DBusException, self.obj_upower.GetDisplayDevice) self.assertRaises(dbus.exceptions.DBusException, self.dbusmock.SetupDisplayDevice, 2, 1, 50.0, 40.0, 80.0, 2.5, 3600, 1800, True, 'half-battery', 3) display_dev = self.dbus_con.get_object( 'org.freedesktop.UPower', '/org/freedesktop/UPower/devices/DisplayDevice') self.assertRaises(dbus.exceptions.DBusException, display_dev.GetAll, '') @unittest.skipUnless(have_upower, 'upower not installed') @unittest.skipUnless(upower_client_version >= '0.99', '1.0 client API specific test') class TestUPower1(dbusmock.DBusTestCase): '''Test mocking upowerd with 1.0 API''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', {'OnBattery': True, 'DaemonVersion': '1.0', 'GetCriticalAction': 'Suspend'}, stdout=subprocess.PIPE) self.dbusmock = dbus.Interface(self.obj_upower, dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_no_devices(self): out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertIn('/DisplayDevice\n', out) # should not have any other device for line in out.splitlines(): if line.endswith('/DisplayDevice'): continue self.assertFalse('Device' in line, out) self.assertRegex(out, 'on-battery:\s+yes') self.assertRegex(out, 'lid-is-present:\s+yes') def test_properties(self): '''1.0 API specific properties''' out = subprocess.check_output(['upower', '--dump'], universal_newlines=True) self.assertRegex(out, 'daemon-version:\s+1.0') self.assertRegex(out, 'critical-action:\s+Suspend') self.assertNotIn('can-suspend', out) def test_enumerate(self): self.dbusmock.AddAC('mock_AC', 'Mock AC') self.assertEqual(self.obj_upower.EnumerateDevices(), ['/org/freedesktop/UPower/devices/mock_AC']) def test_display_device_default(self): path = self.obj_upower.GetDisplayDevice() self.assertEqual(path, '/org/freedesktop/UPower/devices/DisplayDevice') display_dev = self.dbus_con.get_object('org.freedesktop.UPower', path) props = display_dev.GetAll('org.freedesktop.UPower.Device') # http://cgit.freedesktop.org/upower/tree/src/org.freedesktop.UPower.xml # defines the properties which are defined self.assertEqual( set(props.keys()), set(['Type', 'State', 'Percentage', 'Energy', 'EnergyFull', 'EnergyRate', 'TimeToEmpty', 'TimeToFull', 'IsPresent', 'IconName', 'WarningLevel'])) # not set up by default, so should not present self.assertEqual(props['IsPresent'], False) self.assertEqual(props['IconName'], '') self.assertEqual(props['WarningLevel'], UP_DEVICE_LEVEL_NONE) def test_setup_display_device(self): self.dbusmock.SetupDisplayDevice(2, 1, 50.0, 40.0, 80.0, 2.5, 3600, 1800, True, 'half-battery', 3) path = self.obj_upower.GetDisplayDevice() display_dev = self.dbus_con.get_object('org.freedesktop.UPower', path) props = display_dev.GetAll('org.freedesktop.UPower.Device') # just some spot-checks, check all the values from upower -d self.assertEqual(props['Type'], 2) self.assertEqual(props['Percentage'], 50.0) self.assertEqual(props['WarningLevel'], 3) env = os.environ.copy() env['LC_ALL'] = 'C' try: del env['LANGUAGE'] except KeyError: pass out = subprocess.check_output(['upower', '--dump'], universal_newlines=True, env=env) self.assertIn('/DisplayDevice\n', out) self.assertIn(' battery\n', out) # type self.assertRegex(out, 'state:\s+charging') self.assertRegex(out, 'percentage:\s+50%') self.assertRegex(out, 'energy:\s+40 Wh') self.assertRegex(out, 'energy-full:\s+80 Wh') self.assertRegex(out, 'energy-rate:\s+2.5 W') self.assertRegex(out, 'time to empty:\s+1\.0 hours') self.assertRegex(out, 'time to full:\s+30\.0 minutes') self.assertRegex(out, 'present:\s+yes') self.assertRegex(out, "icon-name:\s+'half-battery'") self.assertRegex(out, 'warning-level:\s+low') if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/tests/test_urfkill.py0000664000175000017500000001203612500336743021767 0ustar martinmartin00000000000000#!/usr/bin/python3 # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) any # later version. See http://www.gnu.org/copyleft/lgpl.html for the full text # of the license. __author__ = 'Jussi Pakkanen' __email__ = 'jussi.pakkanen@canonical.com' __copyright__ = '(c) 2015 Canonical Ltd.' __license__ = 'LGPL 3+' import unittest import sys import subprocess import os import fcntl import dbus import dbusmock class TestURfkill(dbusmock.DBusTestCase): '''Test mocked URfkill''' @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(True) def setUp(self): (self.p_mock, self.obj_urfkill) = self.spawn_server_template( 'urfkill', {}, stdout=subprocess.PIPE) # set log to nonblocking flags = fcntl.fcntl(self.p_mock.stdout, fcntl.F_GETFL) fcntl.fcntl(self.p_mock.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK) self.dbusmock = dbus.Interface(self.obj_urfkill, dbusmock.MOCK_IFACE) def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def get_urfkill_objects(self): bus = dbus.SystemBus() remote_object = bus.get_object('org.freedesktop.URfkill', '/org/freedesktop/URfkill') iface = dbus.Interface(remote_object, 'org.freedesktop.URfkill') return (remote_object, iface) def test_mainobject(self): (remote_object, iface) = self.get_urfkill_objects() self.assertFalse(iface.IsFlightMode()) propiface = dbus.Interface(remote_object, 'org.freedesktop.DBus.Properties') version = propiface.Get('org.freedesktop.URfkill', 'DaemonVersion') self.assertEqual(version, '0.6.0') def test_subobjects(self): bus = dbus.SystemBus() individual_objects = ['BLUETOOTH', 'FM', 'GPS', 'NFC', 'UWB', 'WIMAX', 'WLAN', 'WWAN'] for i in individual_objects: path = '/org/freedesktop/URfkill/' + i remote_object = bus.get_object('org.freedesktop.URfkill', path) propiface = dbus.Interface(remote_object, 'org.freedesktop.DBus.Properties') state = propiface.Get('org.freedesktop.URfkill.Killswitch', 'state') self.assertEqual(state, 0) def test_block(self): bus = dbus.SystemBus() (remote_object, iface) = self.get_urfkill_objects() property_object = bus.get_object('org.freedesktop.URfkill', '/org/freedesktop/URfkill/WLAN') propiface = dbus.Interface(property_object, 'org.freedesktop.DBus.Properties') self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 0) self.assertTrue(iface.Block(1, True)) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 1) self.assertTrue(iface.Block(1, False)) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 0) # 99 is an unknown type to the mock, so it should return false. self.assertFalse(iface.Block(99, False)) def test_flightmode(self): bus = dbus.SystemBus() (remote_object, iface) = self.get_urfkill_objects() property_object = bus.get_object('org.freedesktop.URfkill', '/org/freedesktop/URfkill/WLAN') propiface = dbus.Interface(property_object, 'org.freedesktop.DBus.Properties') self.assertFalse(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 0) iface.FlightMode(True) self.assertTrue(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 1) iface.FlightMode(False) self.assertFalse(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 0) def test_flightmode_restore(self): # An interface that was blocked remains blocked once flightmode is removed. bus = dbus.SystemBus() (remote_object, iface) = self.get_urfkill_objects() property_object = bus.get_object('org.freedesktop.URfkill', '/org/freedesktop/URfkill/WLAN') propiface = dbus.Interface(property_object, 'org.freedesktop.DBus.Properties') self.assertFalse(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 0) iface.Block(1, True) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 1) iface.FlightMode(True) self.assertTrue(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 1) iface.FlightMode(False) self.assertFalse(iface.IsFlightMode()) self.assertEqual(propiface.Get('org.freedesktop.URfkill.Killswitch', 'state'), 1) if __name__ == '__main__': # avoid writing to stderr unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) python-dbusmock-0.16.3/COPYING0000644000175000017500000001674312264500431016600 0ustar martinmartin00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. python-dbusmock-0.16.3/MANIFEST.in0000664000175000017500000000006112264500431017267 0ustar martinmartin00000000000000include tests/*.py include COPYING* include NEWS python-dbusmock-0.16.3/NEWS0000664000175000017500000003773712633532730016263 0ustar martinmartin000000000000000.16.3 (2015-12-14) - NetworkManager template test: Make the test run standalone. Thanks Pete Woods. 0.16.2 (2015-12-09) ------------------- - NetworkManager template: Fix connection settings Updated signal emitted by wrong object. - NetworkManager template: Handle empty device at connection activation. - NetworkManager template: Implement secrets management in settings. 0.16.1 (2015-10-22) ------------------- - NetworkManager template: Fix indexing bug in SettingsAddConnection. Thanks Pete Woods. 0.16 (2015-10-08) ----------------- - NetworkManager template: Generate a new unused name in connection activation instead of just using the access point name. Thanks Pete Woods for the original patch! - Allow the passing of template parameters via the command-line as JSON strings. Thanks Pete Woods. 0.15.3 (2015-09-16) ------------------- - NetworkManager template: Add missing properties to ethernet device and active connection. Thanks Pete Woods. - Quiesce irrelevant PEP-8 errors with pep8 1.6. 0.15.2 (2015-06-11) ------------------- - test_ofono: Test fields which don't get obfuscated with Ubuntu's latest ofono (See LP #1459983). Thanks Iain Lane. - timedated template: Add NTPSynchronized property and set it in SetNTP(), to also work with systemd 220. 0.15.1 (2015-05-12) ------------------- - SECURITY FIX: When loading a template from an arbitrary file through the AddTemplate() D-Bus method call or DBusTestCase.spawn_server_template() Python method, don't create or use Python's *.pyc cached files. By tricking a user into loading a template from a world-writable directory like /tmp, an attacker could run arbitrary code with the user's privileges by putting a crafted .pyc file into that directory. Note that this is highly unlikely to actually appear in practice as custom dbusmock templates are usually shipped in project directories, not directly in world-writable directories. Thanks to Simon McVittie for discovering this! (LP: #1453815, CVE-2015-1326) 0.15 (2015-05-08) ------------------- - NetworkManager template: Restore nm-specific PropertiesChanged signal - NetworkManager template: Add DeactivateConnection(), Settings.AddConnection(), Settings.Connection.Update(), and Settings.Connection.Delete() methods. Also allow Connections with autoconnect, added using AddConnection, to be automatically connected by the first found device, roughly like NetworkManager itself does. Thanks Jonas Grønås Drange! - NetworkManager template: Fix broken exception in AddWiFiConnection. - NetworkManager template: Set RsnFlags to have the same value as WpaFlags. Thanks Pete Woods! 0.14 (2015-03-30) ----------------- - Move project hosting to github, update README.rst. - urfkill template: Return boolean from block() method, as the original urfkill does. Thanks Jonas Grønås Drange! - Correctly instantiate DBusExceptions so that they get a proper name and message (issue #3) - ofono template: Fix SubscriberIdentity property type - Emit PropertiesChanged signal when Set()ing properties. - urfkill template: Return boolean from Block() and FlightMode() methods - ofono template: Add ConnectionManager interface. - NetworkManager template: Much more complete support for mocking access points and connections. 0.13 (2015-02-27) ----------------- - Add urfkill template. Thanks Jussi Pakkanen! 0.12 (2015-01-17) ----------------- - upower template: Add SetDeviceProperties() convenience method for changing upower device properties. Thanks Charles Kerr! 0.11.4 (2014-09-22) ------------------- - upower template: Go back to using type 's' for Device* signal arguments for upower 0.9. The older library does not get along with 'o'. (Regression in 0.11.2) 0.11.3 (2014-09-19) ------------------- - Fix test suite crash if loginctl is not installed. 0.11.2 (2014-09-19) ------------------- - upower template: Fix type of Device* signal arguments to be 'o', not 's'. Thanks Iain Lane. - ofono template: Add org.ofono.SimManager interface. Thanks Jonas Grønås Drange. - bluez5 template: Fix the type of the 'Transferred' property. Thanks Philip Withnall. - networkmanager template: Fix the "FAILED" state value to be 120, not 12. Thanks Jonas Grønås Drange. - bluez5 tests: Accept devices in state "not available" (or other states) as well. - timedated and logind tests: Adjust to also accept output format of systemd 215. 0.11.1 (2014-08-08) ------------------- - Rename bluez test classes to TestBlueZ4 and TestBlueZ5, to tell them apart in the output. - logind template: Fix type of IdleSinceHint property, and add IdleSinceHintMonotonic and IdleActionUSec properties. (LP: #1348437) - bluez4 template: Fix settings properties in StartDiscovery/StopDiscovery. Thanks to Mathieu Trudel-Lapierre. - NetworkManager template: Add "Devices" and "AccessPoints" properties of NetworkManager 0.9.10. (LP: #1328579) - NetworkManager template: Fix the types of the AccessPoint properties, and add some more properties. - Adjust NetworkManager template tests for changed strings in NM 0.9.10. 0.11 (2014-07-24) ----------------- - ofono: Fix GetOperators() to only apply to its own modem, not all modems. Thanks to Jonas Grønås Drange. - Add template for BlueZ 4. Thanks to Mathieu Trudel-Lapierre! 0.10.3 (2014-07-16) ------------------- - Fix upower tests to work for upower 0.99 in environments without a system D-BUS. 0.10.2 (2014-07-16) ------------------- - ofono: Make Scan() do the same as GetOperators(). Thanks Iain Lane. - README.rst: Clarify that the "True" argument to get_dbus() means the system bus. - Fix code to be compliant with pep8 1.5. - Fix TestCLI.test_template_system test with upower 0.99. (LP: #1330037) - ofono template: Support adding a second modem with AddModem(). (LP: #1340590) 0.10.1 (2014-01-30) ------------------- - Move code from bzr to git, adjust README.rst, do-release, and other files accordingly. - timedated template: Emit PropertiesChanged when setting properties. Thanks Iain Lane. 0.10 (2013-12-18) ----------------- - Add dynamic properties to introspection XML, to make mocked properties work with Qt's property support, d-feet, and other tools. Thanks Iain Lane! - Fix frequent KeyError() when calling static methods from a template. Regression from 0.9. - Support having the same method name on different D-BUS interfaces. - Add ofono template with support for the Manager, VoiceCallManager, and NetworkRegistration/NetworkOperator interfaces. - Add template for systemd's timedated. Thanks Iain Lane! 0.9.2 (2013-12-13) ------------------ - upower template: Emit DeviceAdded when adding new a new AC adapter or battery. Thanks Iain Lane! - Fix ResourceWarnings in test suite. 0.9.1 (2013-12-10) ------------------ - Fix UnicodeDecodeError in NEWS parsing when trying to build with a C locale. Thanks Dmitry Shachnev. 0.9 (2013-11-29) ---------------- - Make static template methods appear in introspection. Thanks Philip Whitnall! (LP: #1250096) - Add support for the D-Bus ObjectManager interface. This can now be enabled in templates (IS_OBJECT_MANAGER = True) or the CLI (--is-object-manager/-m). Thanks Philip Whitnall! - Add Reset() mock interface method to reset that object’s state (including removing all its sub-objects) as if the object or template had been destroyed and re-created. This is intended for use at the end of test cases to reset state before the next test case is run, as an alternative to killing python-dbusmock and re-starting it. Thanks Philip Whitnall! - logind template: Fix return value of CanSuspend() and related methods, calling them previously caused a crash. - Don't close the log file multiple times if it is shared between objects. Thanks Philip Whitnall! - Log calls to Get(), GetAll(), and Set(). - Add templates for BlueZ 5 and BlueZ-OBEX. These templates are moderately well featured, though currently targeted exclusively at testing OBEX vCard transfers from phones to computers. Thanks Philip Whitnall! 0.8.1 (2013-11-11) ------------------ - Fix test failure if the "upower" tool is not installed. - Fix bad upower test which assumed a locale with a comma decimal separator. 0.8 (2013-11-08) ---------------- - upower template: Change default daemon version to "0.9", and fix tests to work with both upower 0.9 and 1.0 client tool. - upower template: Provide 1.0 API if DaemonVersion property/template parameter gets set to >= "0.99". (LP: #1245955) - upower template: Add SetupDisplayDevice() method on the mock interface to conveniently configure all defined properties of the DisplayDevice. Only available when using the 1.0 API. (LP: #1245955) 0.7.2 (2013-08-30) ------------------ - Add optional "timeout" argument to DBusTestCase.wait_for_bus_object(). (LP: #1218318) - DBusTestCase.start_system_bus(): Make the fake bus look more like a real system bus by specifying a configuration file with type "system". 0.7.1 (2013-08-02) ------------------ - Handle the "Disconnected" signal only if it comes from the D-BUS object, to avoid accidentally reacting to other signals (like from BlueZ). Thanks Lucas De Marchi. 0.7 (2013-07-30) ---------------- - Accept *.py files for the --template command line option, similar to AddTemplate(). Thanks Emanuele Aina. - Pass log file to objects created with AddObject(). Thanks Emanuele Aina. - NetworkManager template: Add new method AddWiFiConnection(), to simulate a connection associated to a previously added device (with AddWiFiDevice()). Thanks Pete Woods. 0.6.3 (2013-06-13) ------------------ - Drop "can-suspend" and "can-hibernate" checks from upower template test. upower 1.0 deprecates this functionality, and defaults to not building it. 0.6.2 (2013-06-13) ------------------ - Fix test_api.TestSubclass test to work without an existing session D-BUS. 0.6.1 (2013-06-13) ------------------ - Add dbusmock.__version__ attribute, as per PEP-0396. - Fix not being able to inherit from DBusMockObject. Thanks Lucas De Marchi! - Allow subclassed DBusMockObject constructors to specify props arguments as None. - Fix failing notification-daemon tests for too old libnotify. (LP: #1190208) - notification_daemon template: Generate new IDs for Notify() calls with an input ID of 0. (LP: #1190209 part 1) - notification_daemon template: Send NotificationClosed signal in CloseNotification() method for valid IDs. (LP: #1190209 part 2) 0.6 (2013-03-20) ---------------- - Emit MethodCalled() signal on the DBusMock interface, as an alternative way of verifying method calls. Thanks Lars Uebernickel. - DBusMockObject.AddTemplate() and DBusTestCase.spawn_server_template() can now load local templates by specifying a path to a *.py file as template name. Thanks Lucas De Marchi. - Quit mock process if the D-BUS it connected to goes down. (LP: #1156561) - Support Get() and GetAll() with empty interface names, default to main interface in this case. - Add template for systemd's logind. 0.5 (2013-02-03) ---------------- - upower template: Change LidIsClosed property default value to False. - Add polkitd template. (LP: #1112551) 0.4.0 (2013-01-21) ------------------ - Add GetCalls(), GetMethodCalls() and ClearCalls() methods on the mock D-BUS interface to query the call log, for cases where parsing stdout is inconvenient. Thanks to Robert Bruce Park for the patch! (LP: #1099483) - Document how to keep internal state in AddMethod(). - Add template for gnome-screensaver. Thanks to Bastien Nocera! - Fix logging of signal arguments to have the same format as method call arguments. 0.3.1 (2013-01-07) ------------------ - upower template: Set Energy and EnergyFull properties. 0.3 (2012-12-19) ---------------- - In the logging of mock method calls, log the arguments as well. - Fix race condition in waiting for mock to get online on the bus, by avoiding triggering D-BUS service activation with system-installed services. - Add "notification_daemon" mock template. 0.2.2 (2012-11-27) ------------------ - tests: Suppress "nmcli and NetworkManager versions don't match" warning. - networkmanager template: Add DeviceState enum for easier specification of states. Thanks Alberto Ruiz. - Fix deprecation warnings with PyGObject 3.7.x. 0.2.1 (2012-11-15) ------------------ - Fix tests to skip instead of fail if NetworkManager or upower are not installed. 0.2.0 (2012-11-15) ------------------ - Turn dbusmock from a module into a package. This is transparent for API users, but necessary for adding future subpackages and also makes the code more maintainable. - Run pyflakes and pep8 during test suite, if available. - Add support for templates: You can now call AddTemplate() on the org.freedesktop.DBus.Mock interface to load a template into the mock, or in Python, start a server process with loading a template with DBusTestCase.spawn_server_template(). Templates set up the common structure of these services (their main objects, properties, and methods) so that you do not need to carry around this common code, and only need to set up the particular properties and specific D-BUS objects that you need. These templates can be parameterized for common customizations, and they can provide additional convenience methods on the org.freedesktop.DBus.Mock interface to provide more abstract functionality like "add a battery". - Add a first simple "upower" template with convenience methods to add AC and battery objects, and change tests/test_upower.py to use it. - Add a first "networkmanager" template with convenience methods to add Ethernet/WiFi devices and access points. Thanks Iftikhar Ahmad! - Add symbol dbusmock.MOCK_IFACE for 'org.freedesktop.DBus.Mock'. - Add test cases for command line invocation (python3 -m dbusmock ...). 0.1.3 (2012-11-03) ------------------ - Ship NEWS in release tarballs. 0.1.2 (2012-10-10) ------------------ - dbusmock.py, EmitSignal(): Convert arguments to the right data types according to the signature. - dbusmock.py, method calls: Convert arguments to the right data types according to the signature. - tests/test_api.py: Check proper handling of signature vs. argument list length and/or type mismatch. (LP: #1064836) - tests/test_upower.py: Add test for handling "DeviceChanged" signal. - setup.py: Get version from NEWS file. 0.1.1 (2012-10-04) ------------------ - setup.py: Use README.rst as long description. - setup.py: Add download URL. - tests/test_consolekit.py: Skip test if ck-list-sessions is not installed. - setup.py: Import "multiprocessing" to work around "'NoneType' object is not callable" error when running "setup.py test" with python 2.7. 0.1 (2012-10-04) ---------------- - tests/test_api.py: Add tests for adding existing objects. - dbusmock.py: Also put first (main) object into the global objects map. - dbusmock.py: Document global objects map in AddMethod(). - tests/test_upower.py: Silence "No ... property" warnings; the test does not create them all. - dbusmock.py: Fix stopping of local D-Bus daemons for test subclasses. - dbusmock.py, stop_dbus(): Wait for local D-Bus to be killed, and avoid getting SIGTERMed ourselves. - dbusmock.py: Add AddProperties() method to conveniently add several properties to one interface at once. Update upower test case to use this. - dbusmock.py: Add EmitSignal() method to emit an arbitrary signal on any interface. - Make code compatible with Python 2.7 as well. (LP: #1060278) 0.0.3 (2012-10-01) ------------------ - tests/test_api.py: Add tests for GetAll() - wait_for_bus_object(): Poll for Introspect() instead of GetAll(), as some services such as gnome-session don't implement GetAll() properly. - Rename "dbus_mock" module to "dbusmock", to be more consistent with the project name and Python module name conventions. - Support adding properties to different interfaces. - Support adding methods to different interfaces. 0.0.2 (2012-10-01) ------------------ - setup.py: Add categories. 0.0.1 (2012-09-28) ------------------ Initial release. python-dbusmock-0.16.3/README.rst0000664000175000017500000002645512500336606017243 0ustar martinmartin00000000000000python-dbusmock =============== Purpose ------- With this program/Python library you can easily create mock objects on D-Bus. This is useful for writing tests for software which talks to D-Bus services such as upower, systemd, ConsoleKit, gnome-session or others, and it is hard (or impossible without root privileges) to set the state of the real services to what you expect in your tests. Suppose you want to write tests for gnome-settings-daemon's power plugin, or another program that talks to upower. You want to verify that after the configured idle time the program suspends the machine. So your program calls ``org.freedesktop.UPower.Suspend()`` on the system D-Bus. Now, your test suite should not really talk to the actual system D-Bus and the real upower; a ``make check`` that suspends your machine will not be considered very friendly by most people, and if you want to run this in continuous integration test servers or package build environments, chances are that your process does not have the privilege to suspend, or there is no system bus or upower to begin with. Likewise, there is no way for an user process to forcefully set the system/seat idle flag in systemd or ConsoleKit, so your tests cannot set up the expected test environment on the real daemon. That's where mock objects come into play: They look like the real API (or at least the parts that you actually need), but they do not actually do anything (or only some action that you specify yourself). You can configure their state, behaviour and responses as you like in your test, without making any assumptions about the real system status. When using a local system/session bus, you can do unit or integration testing without needing root privileges or disturbing a running system. The Python API offers some convenience functions like ``start_session_bus()`` and ``start_system_bus()`` for this, in a ``DBusTestCase`` class (subclass of the standard ``unittest.TestCase``). You can use this with any programming language, as you can run the mocker as a normal program. The actual setup of the mock (adding objects, methods, properties, and signals) all happen via D-Bus methods on the ``org.freedesktop.DBus.Mock`` interface. You just don't have the convenience D-Bus launch API that way. Simple example in Python ------------------------ Picking up the above example about mocking upower's ``Suspend()`` method, this is how you would set up a mock upower in your test case: :: import dbus import dbusmock class TestMyProgram(dbusmock.DBusTestCase): @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(system_bus=True) def setUp(self): self.p_mock = self.spawn_server('org.freedesktop.UPower', '/org/freedesktop/UPower', 'org.freedesktop.UPower', system_bus=True, stdout=subprocess.PIPE) # Get a proxy for the UPower object's Mock interface self.dbus_upower_mock = dbus.Interface(self.dbus_con.get_object( 'org.freedesktop.UPower', '/org/freedesktop/UPower'), dbusmock.MOCK_IFACE) self.dbus_upower_mock.AddMethod('', 'Suspend', '', '', '') def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_suspend_on_idle(self): # run your program in a way that should trigger one suspend call # now check the log that we got one Suspend() call self.assertRegex(self.p_mock.stdout.readline(), b'^[0-9.]+ Suspend$') Let's walk through: - We derive our tests from ``dbusmock.DBusTestCase`` instead of ``unittest.TestCase`` directly, to make use of the convenience API to start a local system bus. - ``setUpClass()`` starts a local system bus, and makes a connection to it available to all methods as ``dbus_con``. ``True`` means that we connect to the system bus, not the session bus. We can use the same bus for all tests, so doing this once in ``setUpClass()`` instead of ``setUp()`` is enough. - ``setUp()`` spawns the mock D-Bus server process for an initial ``/org/freedesktop/UPower`` object with an ``org.freedesktop.UPower`` D-Bus interface on the system bus. We capture its stdout to be able to verify that methods were called. We then call ``org.freedesktop.DBus.Mock.AddMethod()`` to add a ``Suspend()`` method to our new object to the default D-Bus interface. This will not do anything (except log its call to stdout). It takes no input arguments, returns nothing, and does not run any custom code. - ``tearDown()`` stops our mock D-Bus server again. We do this so that each test case has a fresh and clean upower instance, but of course you can also set up everything in ``setUpClass()`` if tests do not interfere with each other on setting up the mock. - ``test_suspend_on_idle()`` is the actual test case. It needs to run your program in a way that should trigger one suspend call. Your program will try to call ``Suspend()``, but as that's now being served by our mock instead of upower, there will not be any actual machine suspend. Our mock process will log the method call together with a time stamp; you can use the latter for doing timing related tests, but we just ignore it here. Simple example from shell ------------------------- We use the actual session bus for this example. You can use ``dbus-launch`` to start a private one as well if you want, but that is not part of the actual mocking. So let's start a mock at the D-Bus name ``com.example.Foo`` with an initial "main" object on path /, with the main D-Bus interface ``com.example.Foo.Manager``: :: python3 -m dbusmock com.example.Foo / com.example.Foo.Manager On another terminal, let's first see what it does: :: gdbus introspect --session -d com.example.Foo -o / You'll see that it supports the standard D-Bus ``Introspectable`` and ``Properties`` interfaces, as well as the ``org.freedesktop.DBus.Mock`` interface for controlling the mock, but no "real" functionality yet. So let's add a method: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod '' Ping '' '' '' Now you can see the new method in ``introspect``, and call it: :: gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Ping The mock process in the other terminal will log the method call with a time stamp, and you'll see something like ``1348832614.970 Ping``. Now add another method with two int arguments and a return value and call it: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod \ '' Add 'ii' 'i' 'ret = args[0] + args[1]' gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Add 2 3 This will print ``(5,)`` as expected (remember that the return value is always a tuple), and again the mock process will log the Add method call. You can do the same operations in e. g. d-feet or any other D-Bus language binding. Logging ------- Usually you want to verify which methods have been called on the mock with which arguments. There are three ways to do that: - By default, the mock process writes the call log to stdout. - You can call the mock process with the ``-l``/``--logfile`` argument, or specify a log file object in the ``spawn_server()`` method if you are using Python. - You can use the ``GetCalls()``, ``GetMethodCalls()`` and ``ClearCalls()`` methods on the ``org.freedesktop.DBus.Mock`` D-BUS interface to get an array of tuples describing the calls. Templates --------- Some D-BUS services are commonly used in test suites, such as UPower or NetworkManager. python-dbusmock provides "templates" which set up the common structure of these services (their main objects, properties, and methods) so that you do not need to carry around this common code, and only need to set up the particular properties and specific D-BUS objects that you need. These templates can be parameterized for common customizations, and they can provide additional convenience methods on the ``org.freedesktop.DBus.Mock`` interface to provide more abstract functionality like "add a battery". For example, for starting a server with the "upower" template in Python you can run :: (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', {'OnBattery': True}, stdout=subprocess.PIPE) or load a template into an already running server with the ``AddTemplate()`` method; this is particularly useful if you are not using Python: :: python3 -m dbusmock --system org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower gdbus call --system -d org.freedesktop.UPower -o /org/freedesktop/UPower -m org.freedesktop.DBus.Mock.AddTemplate 'upower' '{"OnBattery": }' This creates all expected properties such as ``DaemonVersion``, and changes the default for one of them (``OnBattery``) through the (optional) parameters dict. If you do not need to specify parameters, you can do this in a simpler way with :: python3 -m dbusmock --template upower The template does not create any devices by default. You can add some with the template's convenience methods like :: ac_path = self.dbusmock.AddAC('mock_AC', 'Mock AC') bt_path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200) or calling ``AddObject()`` yourself with the desired properties, of course. If you want to contribute a template, look at dbusmock/templates/upower.py for a real-life implementation. You can copy dbusmock/templates/SKELETON to your new template file name and replace "CHANGEME" with the actual code/values. More Examples ------------- Have a look at the test suite for two real-live use cases: - ``tests/test_upower.py`` simulates upowerd, in a more complete way than in above example and using the ``upower`` template. It verifies that ``upower --dump`` is convinced that it's talking to upower. - ``tests/test_consolekit.py`` simulates ConsoleKit and verifies that ``ck-list-sessions`` works with the mock. - ``tests/test_api.py`` runs a mock on the session bus and exercises all available functionality, such as adding additional objects, properties, multiple methods, input arguments, return values, code in methods, raising signals, and introspection. Documentation ------------- The ``dbusmock`` module has extensive documentation built in, which you can read with e. g. ``pydoc3 dbusmock``. ``pydoc3 dbusmock.DBusMockObject`` shows the D-Bus API of the mock object, i. e. methods like ``AddObject()``, ``AddMethod()`` etc. which are used to set up your mock object. ``pydoc3 dbusmock.DBusTestCase`` shows the convenience Python API for writing test cases with local private session/system buses and launching the server. ``pydoc3 dbusmock.templates`` shows all available templates. ``pydoc3 dbusmock.templates.NAME`` shows the documentation and available parameters for the ``NAME`` template. ``python3 -m dbusmock --help`` shows the arguments and options for running the mock server as a program. Development ----------- python-dbusmock is hosted on github: https://github.com/martinpitt/python-dbusmock Feedback -------- For feature requests and bugs, please file reports at one of: https://github.com/martinpitt/python-dbusmock/issues https://bugs.launchpad.net/python-dbusmock python-dbusmock-0.16.3/setup.py0000755000175000017500000000273712264500431017260 0ustar martinmartin00000000000000#!/usr/bin/python3 import setuptools # Work around "TypeError: 'NoneType' object is not callable" # during `python setup.py test` # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html import multiprocessing multiprocessing # pyflakes with open('README.rst') as f: readme = f.read() with open('NEWS', 'rb') as f: version = f.readline().split()[0].decode() setuptools.setup( name='python-dbusmock', version=version, description='Mock D-Bus objects', long_description=readme, author='Martin Pitt', author_email='martin.pitt@ubuntu.com', url='https://launchpad.net/python-dbusmock', download_url='https://launchpad.net/python-dbusmock/+download', license='LGPL 3+', packages=['dbusmock', 'dbusmock.templates'], test_suite='nose.collector', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', 'Development Status :: 3 - Alpha', 'Environment :: Other Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: BSD', 'Operating System :: Unix', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) python-dbusmock-0.16.3/PKG-INFO0000664000175000017500000003501312633533065016644 0ustar martinmartin00000000000000Metadata-Version: 1.1 Name: python-dbusmock Version: 0.16.3 Summary: Mock D-Bus objects Home-page: https://launchpad.net/python-dbusmock Author: Martin Pitt Author-email: martin.pitt@ubuntu.com License: LGPL 3+ Download-URL: https://launchpad.net/python-dbusmock/+download Description: python-dbusmock =============== Purpose ------- With this program/Python library you can easily create mock objects on D-Bus. This is useful for writing tests for software which talks to D-Bus services such as upower, systemd, ConsoleKit, gnome-session or others, and it is hard (or impossible without root privileges) to set the state of the real services to what you expect in your tests. Suppose you want to write tests for gnome-settings-daemon's power plugin, or another program that talks to upower. You want to verify that after the configured idle time the program suspends the machine. So your program calls ``org.freedesktop.UPower.Suspend()`` on the system D-Bus. Now, your test suite should not really talk to the actual system D-Bus and the real upower; a ``make check`` that suspends your machine will not be considered very friendly by most people, and if you want to run this in continuous integration test servers or package build environments, chances are that your process does not have the privilege to suspend, or there is no system bus or upower to begin with. Likewise, there is no way for an user process to forcefully set the system/seat idle flag in systemd or ConsoleKit, so your tests cannot set up the expected test environment on the real daemon. That's where mock objects come into play: They look like the real API (or at least the parts that you actually need), but they do not actually do anything (or only some action that you specify yourself). You can configure their state, behaviour and responses as you like in your test, without making any assumptions about the real system status. When using a local system/session bus, you can do unit or integration testing without needing root privileges or disturbing a running system. The Python API offers some convenience functions like ``start_session_bus()`` and ``start_system_bus()`` for this, in a ``DBusTestCase`` class (subclass of the standard ``unittest.TestCase``). You can use this with any programming language, as you can run the mocker as a normal program. The actual setup of the mock (adding objects, methods, properties, and signals) all happen via D-Bus methods on the ``org.freedesktop.DBus.Mock`` interface. You just don't have the convenience D-Bus launch API that way. Simple example in Python ------------------------ Picking up the above example about mocking upower's ``Suspend()`` method, this is how you would set up a mock upower in your test case: :: import dbus import dbusmock class TestMyProgram(dbusmock.DBusTestCase): @classmethod def setUpClass(klass): klass.start_system_bus() klass.dbus_con = klass.get_dbus(system_bus=True) def setUp(self): self.p_mock = self.spawn_server('org.freedesktop.UPower', '/org/freedesktop/UPower', 'org.freedesktop.UPower', system_bus=True, stdout=subprocess.PIPE) # Get a proxy for the UPower object's Mock interface self.dbus_upower_mock = dbus.Interface(self.dbus_con.get_object( 'org.freedesktop.UPower', '/org/freedesktop/UPower'), dbusmock.MOCK_IFACE) self.dbus_upower_mock.AddMethod('', 'Suspend', '', '', '') def tearDown(self): self.p_mock.terminate() self.p_mock.wait() def test_suspend_on_idle(self): # run your program in a way that should trigger one suspend call # now check the log that we got one Suspend() call self.assertRegex(self.p_mock.stdout.readline(), b'^[0-9.]+ Suspend$') Let's walk through: - We derive our tests from ``dbusmock.DBusTestCase`` instead of ``unittest.TestCase`` directly, to make use of the convenience API to start a local system bus. - ``setUpClass()`` starts a local system bus, and makes a connection to it available to all methods as ``dbus_con``. ``True`` means that we connect to the system bus, not the session bus. We can use the same bus for all tests, so doing this once in ``setUpClass()`` instead of ``setUp()`` is enough. - ``setUp()`` spawns the mock D-Bus server process for an initial ``/org/freedesktop/UPower`` object with an ``org.freedesktop.UPower`` D-Bus interface on the system bus. We capture its stdout to be able to verify that methods were called. We then call ``org.freedesktop.DBus.Mock.AddMethod()`` to add a ``Suspend()`` method to our new object to the default D-Bus interface. This will not do anything (except log its call to stdout). It takes no input arguments, returns nothing, and does not run any custom code. - ``tearDown()`` stops our mock D-Bus server again. We do this so that each test case has a fresh and clean upower instance, but of course you can also set up everything in ``setUpClass()`` if tests do not interfere with each other on setting up the mock. - ``test_suspend_on_idle()`` is the actual test case. It needs to run your program in a way that should trigger one suspend call. Your program will try to call ``Suspend()``, but as that's now being served by our mock instead of upower, there will not be any actual machine suspend. Our mock process will log the method call together with a time stamp; you can use the latter for doing timing related tests, but we just ignore it here. Simple example from shell ------------------------- We use the actual session bus for this example. You can use ``dbus-launch`` to start a private one as well if you want, but that is not part of the actual mocking. So let's start a mock at the D-Bus name ``com.example.Foo`` with an initial "main" object on path /, with the main D-Bus interface ``com.example.Foo.Manager``: :: python3 -m dbusmock com.example.Foo / com.example.Foo.Manager On another terminal, let's first see what it does: :: gdbus introspect --session -d com.example.Foo -o / You'll see that it supports the standard D-Bus ``Introspectable`` and ``Properties`` interfaces, as well as the ``org.freedesktop.DBus.Mock`` interface for controlling the mock, but no "real" functionality yet. So let's add a method: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod '' Ping '' '' '' Now you can see the new method in ``introspect``, and call it: :: gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Ping The mock process in the other terminal will log the method call with a time stamp, and you'll see something like ``1348832614.970 Ping``. Now add another method with two int arguments and a return value and call it: :: gdbus call --session -d com.example.Foo -o / -m org.freedesktop.DBus.Mock.AddMethod \ '' Add 'ii' 'i' 'ret = args[0] + args[1]' gdbus call --session -d com.example.Foo -o / -m com.example.Foo.Manager.Add 2 3 This will print ``(5,)`` as expected (remember that the return value is always a tuple), and again the mock process will log the Add method call. You can do the same operations in e. g. d-feet or any other D-Bus language binding. Logging ------- Usually you want to verify which methods have been called on the mock with which arguments. There are three ways to do that: - By default, the mock process writes the call log to stdout. - You can call the mock process with the ``-l``/``--logfile`` argument, or specify a log file object in the ``spawn_server()`` method if you are using Python. - You can use the ``GetCalls()``, ``GetMethodCalls()`` and ``ClearCalls()`` methods on the ``org.freedesktop.DBus.Mock`` D-BUS interface to get an array of tuples describing the calls. Templates --------- Some D-BUS services are commonly used in test suites, such as UPower or NetworkManager. python-dbusmock provides "templates" which set up the common structure of these services (their main objects, properties, and methods) so that you do not need to carry around this common code, and only need to set up the particular properties and specific D-BUS objects that you need. These templates can be parameterized for common customizations, and they can provide additional convenience methods on the ``org.freedesktop.DBus.Mock`` interface to provide more abstract functionality like "add a battery". For example, for starting a server with the "upower" template in Python you can run :: (self.p_mock, self.obj_upower) = self.spawn_server_template( 'upower', {'OnBattery': True}, stdout=subprocess.PIPE) or load a template into an already running server with the ``AddTemplate()`` method; this is particularly useful if you are not using Python: :: python3 -m dbusmock --system org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower gdbus call --system -d org.freedesktop.UPower -o /org/freedesktop/UPower -m org.freedesktop.DBus.Mock.AddTemplate 'upower' '{"OnBattery": }' This creates all expected properties such as ``DaemonVersion``, and changes the default for one of them (``OnBattery``) through the (optional) parameters dict. If you do not need to specify parameters, you can do this in a simpler way with :: python3 -m dbusmock --template upower The template does not create any devices by default. You can add some with the template's convenience methods like :: ac_path = self.dbusmock.AddAC('mock_AC', 'Mock AC') bt_path = self.dbusmock.AddChargingBattery('mock_BAT', 'Mock Battery', 30.0, 1200) or calling ``AddObject()`` yourself with the desired properties, of course. If you want to contribute a template, look at dbusmock/templates/upower.py for a real-life implementation. You can copy dbusmock/templates/SKELETON to your new template file name and replace "CHANGEME" with the actual code/values. More Examples ------------- Have a look at the test suite for two real-live use cases: - ``tests/test_upower.py`` simulates upowerd, in a more complete way than in above example and using the ``upower`` template. It verifies that ``upower --dump`` is convinced that it's talking to upower. - ``tests/test_consolekit.py`` simulates ConsoleKit and verifies that ``ck-list-sessions`` works with the mock. - ``tests/test_api.py`` runs a mock on the session bus and exercises all available functionality, such as adding additional objects, properties, multiple methods, input arguments, return values, code in methods, raising signals, and introspection. Documentation ------------- The ``dbusmock`` module has extensive documentation built in, which you can read with e. g. ``pydoc3 dbusmock``. ``pydoc3 dbusmock.DBusMockObject`` shows the D-Bus API of the mock object, i. e. methods like ``AddObject()``, ``AddMethod()`` etc. which are used to set up your mock object. ``pydoc3 dbusmock.DBusTestCase`` shows the convenience Python API for writing test cases with local private session/system buses and launching the server. ``pydoc3 dbusmock.templates`` shows all available templates. ``pydoc3 dbusmock.templates.NAME`` shows the documentation and available parameters for the ``NAME`` template. ``python3 -m dbusmock --help`` shows the arguments and options for running the mock server as a program. Development ----------- python-dbusmock is hosted on github: https://github.com/martinpitt/python-dbusmock Feedback -------- For feature requests and bugs, please file reports at one of: https://github.com/martinpitt/python-dbusmock/issues https://bugs.launchpad.net/python-dbusmock Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 3 Classifier: Development Status :: 3 - Alpha Classifier: Environment :: Other Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+) Classifier: Operating System :: POSIX :: Linux Classifier: Operating System :: POSIX :: BSD Classifier: Operating System :: Unix Classifier: Topic :: Software Development :: Quality Assurance Classifier: Topic :: Software Development :: Testing Classifier: Topic :: Software Development :: Libraries :: Python Modules python-dbusmock-0.16.3/setup.cfg0000664000175000017500000000007312633533065017366 0ustar martinmartin00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0