id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
25,700 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | ListAdapters | 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) | python | 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) | [
"def",
"ListAdapters",
"(",
"self",
")",
":",
"adapters",
"=",
"[",
"]",
"for",
"obj",
"in",
"mockobject",
".",
"objects",
".",
"keys",
"(",
")",
":",
"if",
"obj",
".",
"startswith",
"(",
"'/org/bluez/'",
")",
"and",
"'dev_'",
"not",
"in",
"obj",
":"... | List all known adapters | [
"List",
"all",
"known",
"adapters"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L173-L182 |
25,701 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | CreateDevice | 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) | python | 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) | [
"def",
"CreateDevice",
"(",
"self",
",",
"device_address",
")",
":",
"device_name",
"=",
"'dev_'",
"+",
"device_address",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
".",
"upper",
"(",
")",
"adapter_path",
"=",
"self",
".",
"path",
"path",
"=",
"adapter... | Create a new device | [
"Create",
"a",
"new",
"device"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L187-L202 |
25,702 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | AddDevice | 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 | python | 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 | [
"def",
"AddDevice",
"(",
"self",
",",
"adapter_device_name",
",",
"device_address",
",",
"alias",
")",
":",
"device_name",
"=",
"'dev_'",
"+",
"device_address",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
".",
"upper",
"(",
")",
"adapter_path",
"=",
"'/or... | 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. | [
"Convenience",
"method",
"to",
"add",
"a",
"Bluetooth",
"device"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L207-L269 |
25,703 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | ListDevices | 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) | python | 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) | [
"def",
"ListDevices",
"(",
"self",
")",
":",
"devices",
"=",
"[",
"]",
"for",
"obj",
"in",
"mockobject",
".",
"objects",
".",
"keys",
"(",
")",
":",
"if",
"obj",
".",
"startswith",
"(",
"'/org/bluez/'",
")",
"and",
"'dev_'",
"in",
"obj",
":",
"device... | List all known devices | [
"List",
"all",
"known",
"devices"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L274-L283 |
25,704 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | FindDevice | 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') | python | 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') | [
"def",
"FindDevice",
"(",
"self",
",",
"address",
")",
":",
"for",
"obj",
"in",
"mockobject",
".",
"objects",
".",
"keys",
"(",
")",
":",
"if",
"obj",
".",
"startswith",
"(",
"'/org/bluez/'",
")",
"and",
"'dev_'",
"in",
"obj",
":",
"o",
"=",
"mockobj... | Find a specific device by bluetooth address. | [
"Find",
"a",
"specific",
"device",
"by",
"bluetooth",
"address",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L288-L299 |
25,705 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | Connect | 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),
]) | python | 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),
]) | [
"def",
"Connect",
"(",
"self",
")",
":",
"device_path",
"=",
"self",
".",
"path",
"if",
"device_path",
"not",
"in",
"mockobject",
".",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'No such device.'",
",",
"name",
"=",
"'o... | Connect a device | [
"Connect",
"a",
"device"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L376-L396 |
25,706 | martinpitt/python-dbusmock | dbusmock/templates/bluez4.py | Disconnect | 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),
]) | python | 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),
]) | [
"def",
"Disconnect",
"(",
"self",
")",
":",
"device_path",
"=",
"self",
".",
"path",
"if",
"device_path",
"not",
"in",
"mockobject",
".",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'No such device.'",
",",
"name",
"=",
... | Disconnect a device | [
"Disconnect",
"a",
"device"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L401-L425 |
25,707 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | AddEthernetDevice | 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)
self.object_manager_emit_added(path)
NM = dbusmock.get_object(MANAGER_OBJ)
devices = NM.Get(MANAGER_IFACE, 'Devices')
devices.append(path)
NM.Set(MANAGER_IFACE, 'Devices', devices)
NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path])
return path | python | 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)
self.object_manager_emit_added(path)
NM = dbusmock.get_object(MANAGER_OBJ)
devices = NM.Get(MANAGER_IFACE, 'Devices')
devices.append(path)
NM.Set(MANAGER_IFACE, 'Devices', devices)
NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path])
return path | [
"def",
"AddEthernetDevice",
"(",
"self",
",",
"device_name",
",",
"iface_name",
",",
"state",
")",
":",
"path",
"=",
"'/org/freedesktop/NetworkManager/Devices/'",
"+",
"device_name",
"wired_props",
"=",
"{",
"'Carrier'",
":",
"False",
",",
"'HwAddress'",
":",
"dbu... | 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. | [
"Add",
"an",
"ethernet",
"device",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L299-L343 |
25,708 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | AddWiFiDevice | 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,
})
self.object_manager_emit_added(path)
NM = dbusmock.get_object(MANAGER_OBJ)
devices = NM.Get(MANAGER_IFACE, 'Devices')
devices.append(path)
NM.Set(MANAGER_IFACE, 'Devices', devices)
NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path])
return path | python | 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,
})
self.object_manager_emit_added(path)
NM = dbusmock.get_object(MANAGER_OBJ)
devices = NM.Get(MANAGER_IFACE, 'Devices')
devices.append(path)
NM.Set(MANAGER_IFACE, 'Devices', devices)
NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path])
return path | [
"def",
"AddWiFiDevice",
"(",
"self",
",",
"device_name",
",",
"iface_name",
",",
"state",
")",
":",
"path",
"=",
"'/org/freedesktop/NetworkManager/Devices/'",
"+",
"device_name",
"self",
".",
"AddObject",
"(",
"path",
",",
"WIRELESS_DEVICE_IFACE",
",",
"{",
"'HwAd... | 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. | [
"Add",
"a",
"WiFi",
"Device",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L348-L404 |
25,709 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | AddAccessPoint | 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=MANAGER_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)},
[])
self.object_manager_emit_added(ap_path)
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 | python | 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=MANAGER_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)},
[])
self.object_manager_emit_added(ap_path)
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 | [
"def",
"AddAccessPoint",
"(",
"self",
",",
"dev_path",
",",
"ap_name",
",",
"ssid",
",",
"hw_address",
",",
"mode",
",",
"frequency",
",",
"rate",
",",
"strength",
",",
"security",
")",
":",
"dev_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"dev_path",
... | 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. | [
"Add",
"an",
"access",
"point",
"to",
"an",
"existing",
"WiFi",
"device",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L409-L456 |
25,710 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | AddWiFiConnection | 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=MANAGER_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=MANAGER_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])'),
])
self.object_manager_emit_added(connection_path)
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 | python | 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=MANAGER_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=MANAGER_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])'),
])
self.object_manager_emit_added(connection_path)
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 | [
"def",
"AddWiFiConnection",
"(",
"self",
",",
"dev_path",
",",
"connection_name",
",",
"ssid_name",
",",
"key_mgmt",
")",
":",
"dev_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"dev_path",
")",
"connection_path",
"=",
"'/org/freedesktop/NetworkManager/Settings/'",
... | 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. | [
"Add",
"an",
"available",
"connection",
"to",
"an",
"existing",
"WiFi",
"device",
"and",
"access",
"point",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L461-L557 |
25,711 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | AddActiveConnection | 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': dbus.Array(device_objects, signature='o'),
'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': dbus.UInt32(state),
},
[])
for dev_path in devices:
self.SetDeviceActive(dev_path, active_connection_path)
self.object_manager_emit_added(active_connection_path)
NM = dbusmock.get_object(MANAGER_OBJ)
active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections')
active_connections.append(dbus.ObjectPath(active_connection_path))
NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections)
return active_connection_path | python | 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': dbus.Array(device_objects, signature='o'),
'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': dbus.UInt32(state),
},
[])
for dev_path in devices:
self.SetDeviceActive(dev_path, active_connection_path)
self.object_manager_emit_added(active_connection_path)
NM = dbusmock.get_object(MANAGER_OBJ)
active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections')
active_connections.append(dbus.ObjectPath(active_connection_path))
NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections)
return active_connection_path | [
"def",
"AddActiveConnection",
"(",
"self",
",",
"devices",
",",
"connection_device",
",",
"specific_object",
",",
"name",
",",
"state",
")",
":",
"conn_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"connection_device",
")",
"settings",
"=",
"conn_obj",
".",
"... | 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. | [
"Add",
"an",
"active",
"connection",
"to",
"an",
"existing",
"WiFi",
"device",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L562-L608 |
25,712 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | RemoveAccessPoint | 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.object_manager_emit_removed(ap_path)
self.RemoveObject(ap_path) | python | 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.object_manager_emit_removed(ap_path)
self.RemoveObject(ap_path) | [
"def",
"RemoveAccessPoint",
"(",
"self",
",",
"dev_path",
",",
"ap_path",
")",
":",
"dev_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"dev_path",
")",
"aps",
"=",
"dev_obj",
".",
"Get",
"(",
"WIRELESS_DEVICE_IFACE",
",",
"'AccessPoints'",
")",
"aps",
".",
... | 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. | [
"Remove",
"the",
"specified",
"access",
"point",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L613-L633 |
25,713 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | RemoveWifiConnection | 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.object_manager_emit_removed(connection_path)
self.RemoveObject(connection_path) | python | 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.object_manager_emit_removed(connection_path)
self.RemoveObject(connection_path) | [
"def",
"RemoveWifiConnection",
"(",
"self",
",",
"dev_path",
",",
"connection_path",
")",
":",
"dev_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"dev_path",
")",
"settings_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"SETTINGS_OBJ",
")",
"connections",
"=",
... | 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. | [
"Remove",
"the",
"specified",
"WiFi",
"connection",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L638-L668 |
25,714 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | RemoveActiveConnection | 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)
NM = dbusmock.get_object(MANAGER_OBJ)
active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections')
if active_connection_path not in active_connections:
return
active_connections.remove(dbus.ObjectPath(active_connection_path))
NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections)
self.object_manager_emit_removed(active_connection_path)
self.RemoveObject(active_connection_path) | python | 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)
NM = dbusmock.get_object(MANAGER_OBJ)
active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections')
if active_connection_path not in active_connections:
return
active_connections.remove(dbus.ObjectPath(active_connection_path))
NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections)
self.object_manager_emit_removed(active_connection_path)
self.RemoveObject(active_connection_path) | [
"def",
"RemoveActiveConnection",
"(",
"self",
",",
"dev_path",
",",
"active_connection_path",
")",
":",
"self",
".",
"SetDeviceDisconnected",
"(",
"dev_path",
")",
"NM",
"=",
"dbusmock",
".",
"get_object",
"(",
"MANAGER_OBJ",
")",
"active_connections",
"=",
"NM",
... | 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. | [
"Remove",
"the",
"specified",
"ActiveConnection",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L673-L693 |
25,715 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | SettingsAddConnection | 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(MANAGER_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])'),
])
self.object_manager_emit_added(connection_path)
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 | python | 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(MANAGER_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])'),
])
self.object_manager_emit_added(connection_path)
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",
"SettingsAddConnection",
"(",
"self",
",",
"connection_settings",
")",
":",
"if",
"'uuid'",
"not",
"in",
"connection_settings",
"[",
"'connection'",
"]",
":",
"connection_settings",
"[",
"'connection'",
"]",
"[",
"'uuid'",
"]",
"=",
"str",
"(",
"uuid",
... | 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. | [
"Add",
"a",
"connection",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L698-L765 |
25,716 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | ConnectionUpdate | 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(MANAGER_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=MANAGER_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 | python | 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(MANAGER_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=MANAGER_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",
"ConnectionUpdate",
"(",
"self",
",",
"settings",
")",
":",
"connection_path",
"=",
"self",
".",
"connection_path",
"NM",
"=",
"dbusmock",
".",
"get_object",
"(",
"MANAGER_OBJ",
")",
"settings_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"SETTINGS_OBJ",... | 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 | [
"Update",
"settings",
"on",
"a",
"connection",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L779-L823 |
25,717 | martinpitt/python-dbusmock | dbusmock/templates/networkmanager.py | ConnectionDelete | 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(MANAGER_OBJ)
settings_obj = dbusmock.get_object(SETTINGS_OBJ)
# Find the associated active connection(s).
active_connections = NM.Get(MANAGER_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.object_manager_emit_removed(connection_path)
self.RemoveObject(connection_path) | python | 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(MANAGER_OBJ)
settings_obj = dbusmock.get_object(SETTINGS_OBJ)
# Find the associated active connection(s).
active_connections = NM.Get(MANAGER_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.object_manager_emit_removed(connection_path)
self.RemoveObject(connection_path) | [
"def",
"ConnectionDelete",
"(",
"self",
")",
":",
"connection_path",
"=",
"self",
".",
"connection_path",
"NM",
"=",
"dbusmock",
".",
"get_object",
"(",
"MANAGER_OBJ",
")",
"settings_obj",
"=",
"dbusmock",
".",
"get_object",
"(",
"SETTINGS_OBJ",
")",
"# Find the... | 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. | [
"Deletes",
"a",
"connection",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L853-L913 |
25,718 | martinpitt/python-dbusmock | dbusmock/templates/upower.py | AddAC | 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 | python | 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 | [
"def",
"AddAC",
"(",
"self",
",",
"device_name",
",",
"model_name",
")",
":",
"path",
"=",
"'/org/freedesktop/UPower/devices/'",
"+",
"device_name",
"self",
".",
"AddObject",
"(",
"path",
",",
"DEVICE_IFACE",
",",
"{",
"'PowerSupply'",
":",
"dbus",
".",
"Boole... | 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. | [
"Convenience",
"method",
"to",
"add",
"an",
"AC",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L101-L122 |
25,719 | martinpitt/python-dbusmock | dbusmock/templates/upower.py | AddDischargingBattery | 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 | python | 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 | [
"def",
"AddDischargingBattery",
"(",
"self",
",",
"device_name",
",",
"model_name",
",",
"percentage",
",",
"seconds_to_empty",
")",
":",
"path",
"=",
"'/org/freedesktop/UPower/devices/'",
"+",
"device_name",
"self",
".",
"AddObject",
"(",
"path",
",",
"DEVICE_IFACE... | 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. | [
"Convenience",
"method",
"to",
"add",
"a",
"discharging",
"battery",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L127-L157 |
25,720 | martinpitt/python-dbusmock | dbusmock/templates/upower.py | SetupDisplayDevice | 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)) | python | 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)) | [
"def",
"SetupDisplayDevice",
"(",
"self",
",",
"type",
",",
"state",
",",
"percentage",
",",
"energy",
",",
"energy_full",
",",
"energy_rate",
",",
"time_to_empty",
",",
"time_to_full",
",",
"is_present",
",",
"icon_name",
",",
"warning_level",
")",
":",
"if",... | 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. | [
"Convenience",
"method",
"to",
"configure",
"DisplayDevice",
"properties"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L197-L234 |
25,721 | martinpitt/python-dbusmock | dbusmock/templates/upower.py | SetDeviceProperties | 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 | 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]) | [
"def",
"SetDeviceProperties",
"(",
"self",
",",
"object_path",
",",
"properties",
")",
":",
"device",
"=",
"dbusmock",
".",
"get_object",
"(",
"object_path",
")",
"# set the properties",
"for",
"key",
",",
"value",
"in",
"properties",
".",
"items",
"(",
")",
... | 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. | [
"Convenience",
"method",
"to",
"Set",
"a",
"device",
"s",
"properties",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L238-L256 |
25,722 | martinpitt/python-dbusmock | dbusmock/templates/logind.py | AddSeat | 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 | python | 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 | [
"def",
"AddSeat",
"(",
"self",
",",
"seat",
")",
":",
"seat_path",
"=",
"'/org/freedesktop/login1/seat/'",
"+",
"seat",
"if",
"seat_path",
"in",
"mockobject",
".",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'Seat %s already e... | Convenience method to add a seat.
Return the object path of the new seat. | [
"Convenience",
"method",
"to",
"add",
"a",
"seat",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L117-L145 |
25,723 | martinpitt/python-dbusmock | dbusmock/templates/logind.py | AddUser | 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 | python | 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 | [
"def",
"AddUser",
"(",
"self",
",",
"uid",
",",
"username",
",",
"active",
")",
":",
"user_path",
"=",
"'/org/freedesktop/login1/user/%i'",
"%",
"uid",
"if",
"user_path",
"in",
"mockobject",
".",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBus... | Convenience method to add a user.
Return the object path of the new user. | [
"Convenience",
"method",
"to",
"add",
"a",
"user",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L150-L183 |
25,724 | martinpitt/python-dbusmock | dbusmock/templates/logind.py | AddSession | 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 | 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 | [
"def",
"AddSession",
"(",
"self",
",",
"session_id",
",",
"seat",
",",
"uid",
",",
"username",
",",
"active",
")",
":",
"seat_path",
"=",
"dbus",
".",
"ObjectPath",
"(",
"'/org/freedesktop/login1/seat/'",
"+",
"seat",
")",
"if",
"seat_path",
"not",
"in",
"... | 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. | [
"Convenience",
"method",
"to",
"add",
"a",
"session",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L188-L260 |
25,725 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject._set_up_object_manager | 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 + '}')
self.object_manager = self | python | 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 + '}')
self.object_manager = self | [
"def",
"_set_up_object_manager",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
"==",
"'/'",
":",
"cond",
"=",
"'k != \\'/\\''",
"else",
":",
"cond",
"=",
"'k.startswith(\\'%s/\\')'",
"%",
"self",
".",
"path",
"self",
".",
"AddMethod",
"(",
"OBJECT_MANAGE... | Set up this mock object as a D-Bus ObjectManager. | [
"Set",
"up",
"this",
"mock",
"object",
"as",
"a",
"D",
"-",
"Bus",
"ObjectManager",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L108-L119 |
25,726 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.Get | 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') | python | 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') | [
"def",
"Get",
"(",
"self",
",",
"interface_name",
",",
"property_name",
")",
":",
"self",
".",
"log",
"(",
"'Get %s.%s'",
"%",
"(",
"interface_name",
",",
"property_name",
")",
")",
"if",
"not",
"interface_name",
":",
"interface_name",
"=",
"self",
".",
"i... | Standard D-Bus API for getting a property value | [
"Standard",
"D",
"-",
"Bus",
"API",
"for",
"getting",
"a",
"property",
"value"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L133-L145 |
25,727 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.GetAll | 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') | python | 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') | [
"def",
"GetAll",
"(",
"self",
",",
"interface_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"'GetAll '",
"+",
"interface_name",
")",
"if",
"not",
"interface_name",
":",
"interface_name",
"=",
"self",
".",
"interface... | Standard D-Bus API for getting all property values | [
"Standard",
"D",
"-",
"Bus",
"API",
"for",
"getting",
"all",
"property",
"values"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L149-L161 |
25,728 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.Set | 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')
]) | python | 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')
]) | [
"def",
"Set",
"(",
"self",
",",
"interface_name",
",",
"property_name",
",",
"value",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"log",
"(",
"'Set %s.%s%s'",
"%",
"(",
"interface_name",
",",
"property_name",
",",
"self",
".",
"fo... | Standard D-Bus API for setting a property value | [
"Standard",
"D",
"-",
"Bus",
"API",
"for",
"setting",
"a",
"property",
"value"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L165-L192 |
25,729 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddObject | 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.object_manager = self.object_manager
obj.is_logfile_owner = False
obj.AddMethods(interface, methods)
objects[path] = obj | python | 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.object_manager = self.object_manager
obj.is_logfile_owner = False
obj.AddMethods(interface, methods)
objects[path] = obj | [
"def",
"AddObject",
"(",
"self",
",",
"path",
",",
"interface",
",",
"properties",
",",
"methods",
")",
":",
"if",
"path",
"in",
"objects",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'object %s already exists'",
"%",
"path",
",",
... | 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"]'),
]) | [
"Add",
"a",
"new",
"D",
"-",
"Bus",
"object",
"to",
"the",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L197-L241 |
25,730 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.RemoveObject | 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') | python | 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') | [
"def",
"RemoveObject",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"objects",
"[",
"path",
"]",
".",
"remove_from_connection",
"(",
")",
"del",
"objects",
"[",
"path",
"]",
"except",
"KeyError",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusExce... | Remove a D-Bus object from the mock
As with AddObject, this will *not* emit the InterfacesRemoved signal if
it’s an ObjectManager instance. | [
"Remove",
"a",
"D",
"-",
"Bus",
"object",
"from",
"the",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L246-L258 |
25,731 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.Reset | 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 | python | 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 | [
"def",
"Reset",
"(",
"self",
")",
":",
"# Clear other existing objects.",
"for",
"obj_name",
",",
"obj",
"in",
"objects",
".",
"items",
"(",
")",
":",
"if",
"obj_name",
"!=",
"self",
".",
"path",
":",
"obj",
".",
"remove_from_connection",
"(",
")",
"object... | 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. | [
"Reset",
"the",
"mock",
"object",
"state",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L262-L291 |
25,732 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddMethod | 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 persistent 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) | python | 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 persistent 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) | [
"def",
"AddMethod",
"(",
"self",
",",
"interface",
",",
"name",
",",
"in_sig",
",",
"out_sig",
",",
"code",
")",
":",
"if",
"not",
"interface",
":",
"interface",
"=",
"self",
".",
"interface",
"n_args",
"=",
"len",
"(",
"dbus",
".",
"Signature",
"(",
... | 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 persistent 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. | [
"Add",
"a",
"method",
"to",
"this",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L296-L348 |
25,733 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddMethods | 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) | python | 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) | [
"def",
"AddMethods",
"(",
"self",
",",
"interface",
",",
"methods",
")",
":",
"for",
"method",
"in",
"methods",
":",
"self",
".",
"AddMethod",
"(",
"interface",
",",
"*",
"method",
")"
] | 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. | [
"Add",
"several",
"methods",
"to",
"this",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L353-L363 |
25,734 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddProperty | 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 | python | 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 | [
"def",
"AddProperty",
"(",
"self",
",",
"interface",
",",
"name",
",",
"value",
")",
":",
"if",
"not",
"interface",
":",
"interface",
"=",
"self",
".",
"interface",
"try",
":",
"self",
".",
"props",
"[",
"interface",
"]",
"[",
"name",
"]",
"raise",
"... | 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. | [
"Add",
"property",
"to",
"this",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L368-L394 |
25,735 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddProperties | 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) | python | 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) | [
"def",
"AddProperties",
"(",
"self",
",",
"interface",
",",
"properties",
")",
":",
"for",
"k",
",",
"v",
"in",
"properties",
".",
"items",
"(",
")",
":",
"self",
".",
"AddProperty",
"(",
"interface",
",",
"k",
",",
"v",
")"
] | 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 | [
"Add",
"several",
"properties",
"to",
"this",
"object"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L399-L408 |
25,736 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.AddTemplate | 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 | python | 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 | [
"def",
"AddTemplate",
"(",
"self",
",",
"template",
",",
"parameters",
")",
":",
"try",
":",
"module",
"=",
"load_module",
"(",
"template",
")",
"except",
"ImportError",
"as",
"e",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusException",
"(",
"'Canno... | 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. | [
"Load",
"a",
"template",
"into",
"the",
"mock",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L413-L460 |
25,737 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.EmitSignal | 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) | python | 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) | [
"def",
"EmitSignal",
"(",
"self",
",",
"interface",
",",
"name",
",",
"signature",
",",
"args",
")",
":",
"if",
"not",
"interface",
":",
"interface",
"=",
"self",
".",
"interface",
"# convert types of arguments according to signature, using",
"# MethodCallMessage.appe... | 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" | [
"Emit",
"a",
"signal",
"from",
"the",
"object",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L465-L496 |
25,738 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.GetMethodCalls | 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] | python | 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] | [
"def",
"GetMethodCalls",
"(",
"self",
",",
"method",
")",
":",
"return",
"[",
"(",
"row",
"[",
"0",
"]",
",",
"row",
"[",
"2",
"]",
")",
"for",
"row",
"in",
"self",
".",
"call_log",
"if",
"row",
"[",
"1",
"]",
"==",
"method",
"]"
] | List all the logged calls of a particular method.
Return a list of (timestamp, args_list) tuples. | [
"List",
"all",
"the",
"logged",
"calls",
"of",
"a",
"particular",
"method",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L511-L516 |
25,739 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.mock_method | 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'] | python | 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",
"mock_method",
"(",
"self",
",",
"interface",
",",
"dbus_method",
",",
"in_signature",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr)",
"# convert types of arguments according... | Master mock method.
This gets "instantiated" in AddMethod(). Execute the code snippet of
the method and return the "ret" variable if it was set. | [
"Master",
"mock",
"method",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L548-L579 |
25,740 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.format_args | 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):
return '"' + str(a) + '"'
if isinstance(a, unicode): # Python 2 only
return '"' + repr(a.encode('UTF-8'))[1:-1] + '"'
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 | python | 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):
return '"' + str(a) + '"'
if isinstance(a, unicode): # Python 2 only
return '"' + repr(a.encode('UTF-8'))[1:-1] + '"'
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",
"format_args",
"(",
"self",
",",
"args",
")",
":",
"def",
"format_arg",
"(",
"a",
")",
":",
"if",
"isinstance",
"(",
"a",
",",
"dbus",
".",
"Boolean",
")",
":",
"return",
"str",
"(",
"bool",
"(",
"a",
")",
")",
"if",
"isinstance",
"(",
"a"... | Format a D-Bus argument tuple into an appropriate logging string. | [
"Format",
"a",
"D",
"-",
"Bus",
"argument",
"tuple",
"into",
"an",
"appropriate",
"logging",
"string",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L581-L618 |
25,741 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.log | 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.fileno()
else:
fd = sys.stdout.fileno()
os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8')) | python | 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.fileno()
else:
fd = sys.stdout.fileno()
os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8')) | [
"def",
"log",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"logfile",
":",
"fd",
"=",
"self",
".",
"logfile",
".",
"fileno",
"(",
")",
"else",
":",
"fd",
"=",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
"os",
".",
"write",
"(",
"f... | 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. | [
"Log",
"a",
"message",
"prefixed",
"with",
"a",
"timestamp",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L620-L631 |
25,742 | martinpitt/python-dbusmock | dbusmock/mockobject.py | DBusMockObject.Introspect | 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 <interface> 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 | python | 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 <interface> 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 | [
"def",
"Introspect",
"(",
"self",
",",
"object_path",
",",
"connection",
")",
":",
"# temporarily add our dynamic methods",
"cls",
"=",
"self",
".",
"__class__",
".",
"__module__",
"+",
"'.'",
"+",
"self",
".",
"__class__",
".",
"__name__",
"orig_interfaces",
"=... | 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. | [
"Return",
"XML",
"description",
"of",
"this",
"object",
"s",
"interfaces",
"methods",
"and",
"signals",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L638-L684 |
25,743 | martinpitt/python-dbusmock | dbusmock/templates/bluez5-obex.py | CreateSession | 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 | python | 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 | [
"def",
"CreateSession",
"(",
"self",
",",
"destination",
",",
"args",
")",
":",
"if",
"'Target'",
"not",
"in",
"args",
"or",
"args",
"[",
"'Target'",
"]",
".",
"upper",
"(",
")",
"!=",
"'PBAP'",
":",
"raise",
"dbus",
".",
"exceptions",
".",
"DBusExcept... | 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. | [
"OBEX",
"method",
"to",
"create",
"a",
"new",
"transfer",
"session",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L58-L118 |
25,744 | martinpitt/python-dbusmock | dbusmock/templates/bluez5-obex.py | RemoveSession | 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],
]) | python | 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],
]) | [
"def",
"RemoveSession",
"(",
"self",
",",
"session_path",
")",
":",
"manager",
"=",
"mockobject",
".",
"objects",
"[",
"'/'",
"]",
"# Remove all the session's transfers.",
"transfer_id",
"=",
"0",
"while",
"session_path",
"+",
"'/transfer'",
"+",
"str",
"(",
"tr... | OBEX method to remove an existing transfer session.
This takes the path of the transfer Session object and removes it. | [
"OBEX",
"method",
"to",
"remove",
"an",
"existing",
"transfer",
"session",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L123-L152 |
25,745 | martinpitt/python-dbusmock | dbusmock/templates/bluez5-obex.py | PullAll | 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) | python | 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) | [
"def",
"PullAll",
"(",
"self",
",",
"target_file",
",",
"filters",
")",
":",
"# Find the first unused session ID.",
"session_path",
"=",
"self",
".",
"path",
"transfer_id",
"=",
"0",
"while",
"session_path",
"+",
"'/transfer'",
"+",
"str",
"(",
"transfer_id",
")... | 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. | [
"OBEX",
"method",
"to",
"start",
"a",
"pull",
"transfer",
"of",
"a",
"phone",
"book",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L157-L228 |
25,746 | martinpitt/python-dbusmock | dbusmock/templates/bluez5-obex.py | UpdateStatus | 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 | 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),
},
[],
]) | [
"def",
"UpdateStatus",
"(",
"self",
",",
"is_complete",
")",
":",
"status",
"=",
"'complete'",
"if",
"is_complete",
"else",
"'active'",
"transferred",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"self",
".",
"props",
"[",
"TRANSFER_IFACE",
"]",
"[",
"'Fil... | 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). | [
"Mock",
"method",
"to",
"update",
"the",
"transfer",
"status",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L261-L285 |
25,747 | martinpitt/python-dbusmock | dbusmock/templates/ofono.py | AddModem | 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),
'Serial': dbus.String(new_modem_serial(self), 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(self, 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 | python | 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),
'Serial': dbus.String(new_modem_serial(self), 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(self, 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 | [
"def",
"AddModem",
"(",
"self",
",",
"name",
",",
"properties",
")",
":",
"path",
"=",
"'/'",
"+",
"name",
"self",
".",
"AddObject",
"(",
"path",
",",
"'org.ofono.Modem'",
",",
"{",
"'Online'",
":",
"dbus",
".",
"Boolean",
"(",
"True",
",",
"variant_le... | 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. | [
"Convenience",
"method",
"to",
"add",
"a",
"modem"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L65-L114 |
25,748 | martinpitt/python-dbusmock | dbusmock/templates/ofono.py | add_voice_call_api | 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]')
]) | python | 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]')
]) | [
"def",
"add_voice_call_api",
"(",
"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'",
",",
"[",
"'91... | Add org.ofono.VoiceCallManager API to a mock | [
"Add",
"org",
".",
"ofono",
".",
"VoiceCallManager",
"API",
"to",
"a",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L169-L190 |
25,749 | martinpitt/python-dbusmock | dbusmock/templates/ofono.py | add_netreg_api | 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)),
]) | python | 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)),
]) | [
"def",
"add_netreg_api",
"(",
"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'",
","... | Add org.ofono.NetworkRegistration API to a mock | [
"Add",
"org",
".",
"ofono",
".",
"NetworkRegistration",
"API",
"to",
"a",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L262-L302 |
25,750 | martinpitt/python-dbusmock | dbusmock/templates/ofono.py | add_simmanager_api | def add_simmanager_api(self, mock):
'''Add org.ofono.SimManager API to a mock'''
iface = 'org.ofono.SimManager'
mock.AddProperties(iface, {
'BarredDialing': _parameters.get('BarredDialing', False),
'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)),
'FixedDialing': _parameters.get('FixedDialing', False),
'LockedPins': _parameters.get('LockedPins', dbus.Array([], signature='s')),
'MobileCountryCode': _parameters.get('MobileCountryCode', '310'),
'MobileNetworkCode': _parameters.get('MobileNetworkCode', '150'),
'PreferredLanguages': _parameters.get('PreferredLanguages', ['en']),
'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', new_imsi(self)),
})
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', '', ''),
]) | python | def add_simmanager_api(self, mock):
'''Add org.ofono.SimManager API to a mock'''
iface = 'org.ofono.SimManager'
mock.AddProperties(iface, {
'BarredDialing': _parameters.get('BarredDialing', False),
'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)),
'FixedDialing': _parameters.get('FixedDialing', False),
'LockedPins': _parameters.get('LockedPins', dbus.Array([], signature='s')),
'MobileCountryCode': _parameters.get('MobileCountryCode', '310'),
'MobileNetworkCode': _parameters.get('MobileNetworkCode', '150'),
'PreferredLanguages': _parameters.get('PreferredLanguages', ['en']),
'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', new_imsi(self)),
})
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', '', ''),
]) | [
"def",
"add_simmanager_api",
"(",
"self",
",",
"mock",
")",
":",
"iface",
"=",
"'org.ofono.SimManager'",
"mock",
".",
"AddProperties",
"(",
"iface",
",",
"{",
"'BarredDialing'",
":",
"_parameters",
".",
"get",
"(",
"'BarredDialing'",
",",
"False",
")",
",",
... | Add org.ofono.SimManager API to a mock | [
"Add",
"org",
".",
"ofono",
".",
"SimManager",
"API",
"to",
"a",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L329-L388 |
25,751 | martinpitt/python-dbusmock | dbusmock/templates/ofono.py | add_connectionmanager_api | 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([])'),
]) | python | 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([])'),
]) | [
"def",
"add_connectionmanager_api",
"(",
"mock",
")",
":",
"iface",
"=",
"'org.ofono.ConnectionManager'",
"mock",
".",
"AddProperties",
"(",
"iface",
",",
"{",
"'Attached'",
":",
"_parameters",
".",
"get",
"(",
"'Attached'",
",",
"True",
")",
",",
"'Bearer'",
... | Add org.ofono.ConnectionManager API to a mock | [
"Add",
"org",
".",
"ofono",
".",
"ConnectionManager",
"API",
"to",
"a",
"mock"
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L408-L426 |
25,752 | martinpitt/python-dbusmock | dbusmock/templates/bluez5.py | BlockDevice | 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),
},
[],
]) | python | 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),
},
[],
]) | [
"def",
"BlockDevice",
"(",
"self",
",",
"adapter_device_name",
",",
"device_address",
")",
":",
"device_name",
"=",
"'dev_'",
"+",
"device_address",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
".",
"upper",
"(",
")",
"adapter_path",
"=",
"'/org/bluez/'",
"+... | 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. | [
"Convenience",
"method",
"to",
"mark",
"an",
"existing",
"device",
"as",
"blocked",
"."
] | 26f65f78bc0ed347233f699a8d6ee0e6880e7eb0 | https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5.py#L268-L308 |
25,753 | briancappello/flask-unchained | flask_unchained/bundles/api/model_resource.py | ModelResource.create | def create(self, instance, errors):
"""
Create an instance of a model.
:param instance: The created model instance.
:param errors: Any errors.
:return: The created model instance, or a dictionary of errors.
"""
if errors:
return self.errors(errors)
return self.created(instance) | python | def create(self, instance, errors):
if errors:
return self.errors(errors)
return self.created(instance) | [
"def",
"create",
"(",
"self",
",",
"instance",
",",
"errors",
")",
":",
"if",
"errors",
":",
"return",
"self",
".",
"errors",
"(",
"errors",
")",
"return",
"self",
".",
"created",
"(",
"instance",
")"
] | Create an instance of a model.
:param instance: The created model instance.
:param errors: Any errors.
:return: The created model instance, or a dictionary of errors. | [
"Create",
"an",
"instance",
"of",
"a",
"model",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L300-L310 |
25,754 | briancappello/flask-unchained | flask_unchained/bundles/api/model_resource.py | ModelResource.patch | def patch(self, instance, errors):
"""
Partially update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors.
"""
if errors:
return self.errors(errors)
return self.updated(instance) | python | def patch(self, instance, errors):
if errors:
return self.errors(errors)
return self.updated(instance) | [
"def",
"patch",
"(",
"self",
",",
"instance",
",",
"errors",
")",
":",
"if",
"errors",
":",
"return",
"self",
".",
"errors",
"(",
"errors",
")",
"return",
"self",
".",
"updated",
"(",
"instance",
")"
] | Partially update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors. | [
"Partially",
"update",
"a",
"model",
"instance",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L323-L333 |
25,755 | briancappello/flask-unchained | flask_unchained/bundles/api/model_resource.py | ModelResource.put | def put(self, instance, errors):
"""
Update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors.
"""
if errors:
return self.errors(errors)
return self.updated(instance) | python | def put(self, instance, errors):
if errors:
return self.errors(errors)
return self.updated(instance) | [
"def",
"put",
"(",
"self",
",",
"instance",
",",
"errors",
")",
":",
"if",
"errors",
":",
"return",
"self",
".",
"errors",
"(",
"errors",
")",
"return",
"self",
".",
"updated",
"(",
"instance",
")"
] | Update a model instance.
:param instance: The model instance.
:param errors: Any errors.
:return: The updated model instance, or a dictionary of errors. | [
"Update",
"a",
"model",
"instance",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L336-L346 |
25,756 | briancappello/flask-unchained | flask_unchained/bundles/controller/__init__.py | ControllerBundle.before_init_app | def before_init_app(self, app: FlaskUnchained):
"""
Configure the Jinja environment and template loader.
"""
from .templates import (UnchainedJinjaEnvironment,
UnchainedJinjaLoader)
app.jinja_environment = UnchainedJinjaEnvironment
app.jinja_options = {**app.jinja_options,
'loader': UnchainedJinjaLoader(app)}
app.jinja_env.globals['url_for'] = url_for
for name in ['string', 'str']:
app.url_map.converters[name] = StringConverter | python | def before_init_app(self, app: FlaskUnchained):
from .templates import (UnchainedJinjaEnvironment,
UnchainedJinjaLoader)
app.jinja_environment = UnchainedJinjaEnvironment
app.jinja_options = {**app.jinja_options,
'loader': UnchainedJinjaLoader(app)}
app.jinja_env.globals['url_for'] = url_for
for name in ['string', 'str']:
app.url_map.converters[name] = StringConverter | [
"def",
"before_init_app",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
")",
":",
"from",
".",
"templates",
"import",
"(",
"UnchainedJinjaEnvironment",
",",
"UnchainedJinjaLoader",
")",
"app",
".",
"jinja_environment",
"=",
"UnchainedJinjaEnvironment",
"app",
".",... | Configure the Jinja environment and template loader. | [
"Configure",
"the",
"Jinja",
"environment",
"and",
"template",
"loader",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/__init__.py#L43-L55 |
25,757 | briancappello/flask-unchained | flask_unchained/bundles/controller/__init__.py | ControllerBundle.after_init_app | def after_init_app(self, app: FlaskUnchained):
"""
Configure an after request hook to set the ``csrf_token`` in the cookie.
"""
from flask_wtf.csrf import generate_csrf
# send CSRF token in the cookie
@app.after_request
def set_csrf_cookie(response):
if response:
response.set_cookie('csrf_token', generate_csrf())
return response | python | def after_init_app(self, app: FlaskUnchained):
from flask_wtf.csrf import generate_csrf
# send CSRF token in the cookie
@app.after_request
def set_csrf_cookie(response):
if response:
response.set_cookie('csrf_token', generate_csrf())
return response | [
"def",
"after_init_app",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
")",
":",
"from",
"flask_wtf",
".",
"csrf",
"import",
"generate_csrf",
"# send CSRF token in the cookie",
"@",
"app",
".",
"after_request",
"def",
"set_csrf_cookie",
"(",
"response",
")",
":"... | Configure an after request hook to set the ``csrf_token`` in the cookie. | [
"Configure",
"an",
"after",
"request",
"hook",
"to",
"set",
"the",
"csrf_token",
"in",
"the",
"cookie",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/__init__.py#L57-L69 |
25,758 | briancappello/flask-unchained | flask_unchained/commands/shell.py | shell | def shell():
"""
Runs a shell in the app context. If ``IPython`` is installed, it will
be used, otherwise the default Python shell is used.
"""
ctx = _get_shell_ctx()
try:
import IPython
IPython.embed(header=_get_shell_banner(), user_ns=ctx)
except ImportError:
import code
code.interact(banner=_get_shell_banner(verbose=True), local=ctx) | python | def shell():
ctx = _get_shell_ctx()
try:
import IPython
IPython.embed(header=_get_shell_banner(), user_ns=ctx)
except ImportError:
import code
code.interact(banner=_get_shell_banner(verbose=True), local=ctx) | [
"def",
"shell",
"(",
")",
":",
"ctx",
"=",
"_get_shell_ctx",
"(",
")",
"try",
":",
"import",
"IPython",
"IPython",
".",
"embed",
"(",
"header",
"=",
"_get_shell_banner",
"(",
")",
",",
"user_ns",
"=",
"ctx",
")",
"except",
"ImportError",
":",
"import",
... | Runs a shell in the app context. If ``IPython`` is installed, it will
be used, otherwise the default Python shell is used. | [
"Runs",
"a",
"shell",
"in",
"the",
"app",
"context",
".",
"If",
"IPython",
"is",
"installed",
"it",
"will",
"be",
"used",
"otherwise",
"the",
"default",
"Python",
"shell",
"is",
"used",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/shell.py#L10-L21 |
25,759 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.login | def login(self):
"""
View function to log a user in. Supports html and json requests.
"""
form = self._get_form('SECURITY_LOGIN_FORM')
if form.validate_on_submit():
try:
self.security_service.login_user(form.user, form.remember.data)
except AuthenticationError as e:
form._errors = {'_error': [str(e)]}
else:
self.after_this_request(self._commit)
if request.is_json:
return self.jsonify({'token': form.user.get_auth_token(),
'user': form.user})
self.flash(_('flask_unchained.bundles.security:flash.login'),
category='success')
return self.redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
else:
# FIXME-identity
identity_attrs = app.config.SECURITY_USER_IDENTITY_ATTRIBUTES
msg = f"Invalid {', '.join(identity_attrs)} and/or password."
# we just want a single top-level form error
form._errors = {'_error': [msg]}
for field in form._fields.values():
field.errors = None
if form.errors and request.is_json:
return self.jsonify({'error': form.errors.get('_error')[0]},
code=HTTPStatus.UNAUTHORIZED)
return self.render('login',
login_user_form=form,
**self.security.run_ctx_processor('login')) | python | def login(self):
form = self._get_form('SECURITY_LOGIN_FORM')
if form.validate_on_submit():
try:
self.security_service.login_user(form.user, form.remember.data)
except AuthenticationError as e:
form._errors = {'_error': [str(e)]}
else:
self.after_this_request(self._commit)
if request.is_json:
return self.jsonify({'token': form.user.get_auth_token(),
'user': form.user})
self.flash(_('flask_unchained.bundles.security:flash.login'),
category='success')
return self.redirect('SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
else:
# FIXME-identity
identity_attrs = app.config.SECURITY_USER_IDENTITY_ATTRIBUTES
msg = f"Invalid {', '.join(identity_attrs)} and/or password."
# we just want a single top-level form error
form._errors = {'_error': [msg]}
for field in form._fields.values():
field.errors = None
if form.errors and request.is_json:
return self.jsonify({'error': form.errors.get('_error')[0]},
code=HTTPStatus.UNAUTHORIZED)
return self.render('login',
login_user_form=form,
**self.security.run_ctx_processor('login')) | [
"def",
"login",
"(",
"self",
")",
":",
"form",
"=",
"self",
".",
"_get_form",
"(",
"'SECURITY_LOGIN_FORM'",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"try",
":",
"self",
".",
"security_service",
".",
"login_user",
"(",
"form",
".",
"us... | View function to log a user in. Supports html and json requests. | [
"View",
"function",
"to",
"log",
"a",
"user",
"in",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L39-L73 |
25,760 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.logout | def logout(self):
"""
View function to log a user out. Supports html and json requests.
"""
if current_user.is_authenticated:
self.security_service.logout_user()
if request.is_json:
return '', HTTPStatus.NO_CONTENT
self.flash(_('flask_unchained.bundles.security:flash.logout'),
category='success')
return self.redirect('SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT') | python | def logout(self):
if current_user.is_authenticated:
self.security_service.logout_user()
if request.is_json:
return '', HTTPStatus.NO_CONTENT
self.flash(_('flask_unchained.bundles.security:flash.logout'),
category='success')
return self.redirect('SECURITY_POST_LOGOUT_REDIRECT_ENDPOINT') | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"current_user",
".",
"is_authenticated",
":",
"self",
".",
"security_service",
".",
"logout_user",
"(",
")",
"if",
"request",
".",
"is_json",
":",
"return",
"''",
",",
"HTTPStatus",
".",
"NO_CONTENT",
"self",
"... | View function to log a user out. Supports html and json requests. | [
"View",
"function",
"to",
"log",
"a",
"user",
"out",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L76-L88 |
25,761 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.register | def register(self):
"""
View function to register user. Supports html and json requests.
"""
form = self._get_form('SECURITY_REGISTER_FORM')
if form.validate_on_submit():
user = self.security_service.user_manager.create(**form.to_dict())
self.security_service.register_user(user)
return self.redirect('SECURITY_POST_REGISTER_REDIRECT_ENDPOINT')
return self.render('register',
register_user_form=form,
**self.security.run_ctx_processor('register')) | python | def register(self):
form = self._get_form('SECURITY_REGISTER_FORM')
if form.validate_on_submit():
user = self.security_service.user_manager.create(**form.to_dict())
self.security_service.register_user(user)
return self.redirect('SECURITY_POST_REGISTER_REDIRECT_ENDPOINT')
return self.render('register',
register_user_form=form,
**self.security.run_ctx_processor('register')) | [
"def",
"register",
"(",
"self",
")",
":",
"form",
"=",
"self",
".",
"_get_form",
"(",
"'SECURITY_REGISTER_FORM'",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"user",
"=",
"self",
".",
"security_service",
".",
"user_manager",
".",
"create",
... | View function to register user. Supports html and json requests. | [
"View",
"function",
"to",
"register",
"user",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L93-L105 |
25,762 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.send_confirmation_email | def send_confirmation_email(self):
"""
View function which sends confirmation token and instructions to a user.
"""
form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM')
if form.validate_on_submit():
self.security_service.send_email_confirmation_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_request',
email=form.user.email), category='info')
if request.is_json:
return '', HTTPStatus.NO_CONTENT
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('send_confirmation_email',
send_confirmation_form=form,
**self.security.run_ctx_processor('send_confirmation_email')) | python | def send_confirmation_email(self):
form = self._get_form('SECURITY_SEND_CONFIRMATION_FORM')
if form.validate_on_submit():
self.security_service.send_email_confirmation_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_request',
email=form.user.email), category='info')
if request.is_json:
return '', HTTPStatus.NO_CONTENT
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('send_confirmation_email',
send_confirmation_form=form,
**self.security.run_ctx_processor('send_confirmation_email')) | [
"def",
"send_confirmation_email",
"(",
"self",
")",
":",
"form",
"=",
"self",
".",
"_get_form",
"(",
"'SECURITY_SEND_CONFIRMATION_FORM'",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"self",
".",
"security_service",
".",
"send_email_confirmation_inst... | View function which sends confirmation token and instructions to a user. | [
"View",
"function",
"which",
"sends",
"confirmation",
"token",
"and",
"instructions",
"to",
"a",
"user",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L109-L126 |
25,763 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.confirm_email | def confirm_email(self, token):
"""
View function to confirm a user's token from the confirmation email send to them.
Supports html and json requests.
"""
expired, invalid, user = \
self.security_utils_service.confirm_email_token_status(token)
if not user or invalid:
invalid = True
self.flash(
_('flask_unchained.bundles.security:flash.invalid_confirmation_token'),
category='error')
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
self.security_service.send_email_confirmation_instructions(user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_expired',
email=user.email,
within=app.config.SECURITY_CONFIRM_EMAIL_WITHIN),
category='error')
if invalid or (expired and not already_confirmed):
return self.redirect('SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT',
'security_controller.send_confirmation_email')
if self.security_service.confirm_user(user):
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.email_confirmed'),
category='success')
else:
self.flash(_('flask_unchained.bundles.security:flash.already_confirmed'),
category='info')
if user != current_user:
self.security_service.logout_user()
self.security_service.login_user(user)
return self.redirect('SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT') | python | def confirm_email(self, token):
expired, invalid, user = \
self.security_utils_service.confirm_email_token_status(token)
if not user or invalid:
invalid = True
self.flash(
_('flask_unchained.bundles.security:flash.invalid_confirmation_token'),
category='error')
already_confirmed = user is not None and user.confirmed_at is not None
if expired and not already_confirmed:
self.security_service.send_email_confirmation_instructions(user)
self.flash(_('flask_unchained.bundles.security:flash.confirmation_expired',
email=user.email,
within=app.config.SECURITY_CONFIRM_EMAIL_WITHIN),
category='error')
if invalid or (expired and not already_confirmed):
return self.redirect('SECURITY_CONFIRM_ERROR_REDIRECT_ENDPOINT',
'security_controller.send_confirmation_email')
if self.security_service.confirm_user(user):
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.email_confirmed'),
category='success')
else:
self.flash(_('flask_unchained.bundles.security:flash.already_confirmed'),
category='info')
if user != current_user:
self.security_service.logout_user()
self.security_service.login_user(user)
return self.redirect('SECURITY_POST_CONFIRM_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT') | [
"def",
"confirm_email",
"(",
"self",
",",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"self",
".",
"security_utils_service",
".",
"confirm_email_token_status",
"(",
"token",
")",
"if",
"not",
"user",
"or",
"invalid",
":",
"invalid",
"=",
... | View function to confirm a user's token from the confirmation email send to them.
Supports html and json requests. | [
"View",
"function",
"to",
"confirm",
"a",
"user",
"s",
"token",
"from",
"the",
"confirmation",
"email",
"send",
"to",
"them",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L130-L168 |
25,764 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.forgot_password | def forgot_password(self):
"""
View function to request a password recovery email with a reset token.
Supports html and json requests.
"""
form = self._get_form('SECURITY_FORGOT_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.send_reset_password_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.password_reset_request',
email=form.user.email),
category='info')
if request.is_json:
return '', HTTPStatus.NO_CONTENT
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('forgot_password',
forgot_password_form=form,
**self.security.run_ctx_processor('forgot_password')) | python | def forgot_password(self):
form = self._get_form('SECURITY_FORGOT_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.send_reset_password_instructions(form.user)
self.flash(_('flask_unchained.bundles.security:flash.password_reset_request',
email=form.user.email),
category='info')
if request.is_json:
return '', HTTPStatus.NO_CONTENT
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('forgot_password',
forgot_password_form=form,
**self.security.run_ctx_processor('forgot_password')) | [
"def",
"forgot_password",
"(",
"self",
")",
":",
"form",
"=",
"self",
".",
"_get_form",
"(",
"'SECURITY_FORGOT_PASSWORD_FORM'",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"self",
".",
"security_service",
".",
"send_reset_password_instructions",
"... | View function to request a password recovery email with a reset token.
Supports html and json requests. | [
"View",
"function",
"to",
"request",
"a",
"password",
"recovery",
"email",
"with",
"a",
"reset",
"token",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L174-L193 |
25,765 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.reset_password | def reset_password(self, token):
"""
View function verify a users reset password token from the email we sent to them.
It also handles the form for them to set a new password.
Supports html and json requests.
"""
expired, invalid, user = \
self.security_utils_service.reset_password_token_status(token)
if invalid:
self.flash(
_('flask_unchained.bundles.security:flash.invalid_reset_password_token'),
category='error')
return self.redirect('SECURITY_INVALID_RESET_TOKEN_REDIRECT')
elif expired:
self.security_service.send_reset_password_instructions(user)
self.flash(_('flask_unchained.bundles.security:flash.password_reset_expired',
email=user.email,
within=app.config.SECURITY_RESET_PASSWORD_WITHIN),
category='error')
return self.redirect('SECURITY_EXPIRED_RESET_TOKEN_REDIRECT')
spa_redirect = app.config.SECURITY_API_RESET_PASSWORD_HTTP_GET_REDIRECT
if request.method == 'GET' and spa_redirect:
return self.redirect(spa_redirect, token=token, _external=True)
form = self._get_form('SECURITY_RESET_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.reset_password(user, form.password.data)
self.security_service.login_user(user)
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.password_reset'),
category='success')
if request.is_json:
return self.jsonify({'token': user.get_auth_token(),
'user': user})
return self.redirect('SECURITY_POST_RESET_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('reset_password',
reset_password_form=form,
reset_password_token=token,
**self.security.run_ctx_processor('reset_password')) | python | def reset_password(self, token):
expired, invalid, user = \
self.security_utils_service.reset_password_token_status(token)
if invalid:
self.flash(
_('flask_unchained.bundles.security:flash.invalid_reset_password_token'),
category='error')
return self.redirect('SECURITY_INVALID_RESET_TOKEN_REDIRECT')
elif expired:
self.security_service.send_reset_password_instructions(user)
self.flash(_('flask_unchained.bundles.security:flash.password_reset_expired',
email=user.email,
within=app.config.SECURITY_RESET_PASSWORD_WITHIN),
category='error')
return self.redirect('SECURITY_EXPIRED_RESET_TOKEN_REDIRECT')
spa_redirect = app.config.SECURITY_API_RESET_PASSWORD_HTTP_GET_REDIRECT
if request.method == 'GET' and spa_redirect:
return self.redirect(spa_redirect, token=token, _external=True)
form = self._get_form('SECURITY_RESET_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.reset_password(user, form.password.data)
self.security_service.login_user(user)
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.password_reset'),
category='success')
if request.is_json:
return self.jsonify({'token': user.get_auth_token(),
'user': user})
return self.redirect('SECURITY_POST_RESET_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('reset_password',
reset_password_form=form,
reset_password_token=token,
**self.security.run_ctx_processor('reset_password')) | [
"def",
"reset_password",
"(",
"self",
",",
"token",
")",
":",
"expired",
",",
"invalid",
",",
"user",
"=",
"self",
".",
"security_utils_service",
".",
"reset_password_token_status",
"(",
"token",
")",
"if",
"invalid",
":",
"self",
".",
"flash",
"(",
"_",
"... | View function verify a users reset password token from the email we sent to them.
It also handles the form for them to set a new password.
Supports html and json requests. | [
"View",
"function",
"verify",
"a",
"users",
"reset",
"password",
"token",
"from",
"the",
"email",
"we",
"sent",
"to",
"them",
".",
"It",
"also",
"handles",
"the",
"form",
"for",
"them",
"to",
"set",
"a",
"new",
"password",
".",
"Supports",
"html",
"and",... | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L198-L242 |
25,766 | briancappello/flask-unchained | flask_unchained/bundles/security/views/security_controller.py | SecurityController.change_password | def change_password(self):
"""
View function for a user to change their password.
Supports html and json requests.
"""
form = self._get_form('SECURITY_CHANGE_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.change_password(
current_user._get_current_object(),
form.new_password.data)
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.password_change'),
category='success')
if request.is_json:
return self.jsonify({'token': current_user.get_auth_token()})
return self.redirect('SECURITY_POST_CHANGE_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('change_password',
change_password_form=form,
**self.security.run_ctx_processor('change_password')) | python | def change_password(self):
form = self._get_form('SECURITY_CHANGE_PASSWORD_FORM')
if form.validate_on_submit():
self.security_service.change_password(
current_user._get_current_object(),
form.new_password.data)
self.after_this_request(self._commit)
self.flash(_('flask_unchained.bundles.security:flash.password_change'),
category='success')
if request.is_json:
return self.jsonify({'token': current_user.get_auth_token()})
return self.redirect('SECURITY_POST_CHANGE_REDIRECT_ENDPOINT',
'SECURITY_POST_LOGIN_REDIRECT_ENDPOINT')
elif form.errors and request.is_json:
return self.errors(form.errors)
return self.render('change_password',
change_password_form=form,
**self.security.run_ctx_processor('change_password')) | [
"def",
"change_password",
"(",
"self",
")",
":",
"form",
"=",
"self",
".",
"_get_form",
"(",
"'SECURITY_CHANGE_PASSWORD_FORM'",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"self",
".",
"security_service",
".",
"change_password",
"(",
"current_us... | View function for a user to change their password.
Supports html and json requests. | [
"View",
"function",
"for",
"a",
"user",
"to",
"change",
"their",
"password",
".",
"Supports",
"html",
"and",
"json",
"requests",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/views/security_controller.py#L247-L270 |
25,767 | briancappello/flask-unchained | flask_unchained/bundles/security/extensions/security.py | Security._get_pwd_context | def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext:
"""
Get the password hashing context.
"""
pw_hash = app.config.SECURITY_PASSWORD_HASH
schemes = app.config.SECURITY_PASSWORD_SCHEMES
if pw_hash not in schemes:
allowed = (', '.join(schemes[:-1]) + ' and ' + schemes[-1])
raise ValueError(f'Invalid password hashing scheme {pw_hash}. '
f'Allowed values are {allowed}.')
return CryptContext(schemes=schemes, default=pw_hash,
deprecated=app.config.SECURITY_DEPRECATED_PASSWORD_SCHEMES) | python | def _get_pwd_context(self, app: FlaskUnchained) -> CryptContext:
pw_hash = app.config.SECURITY_PASSWORD_HASH
schemes = app.config.SECURITY_PASSWORD_SCHEMES
if pw_hash not in schemes:
allowed = (', '.join(schemes[:-1]) + ' and ' + schemes[-1])
raise ValueError(f'Invalid password hashing scheme {pw_hash}. '
f'Allowed values are {allowed}.')
return CryptContext(schemes=schemes, default=pw_hash,
deprecated=app.config.SECURITY_DEPRECATED_PASSWORD_SCHEMES) | [
"def",
"_get_pwd_context",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
")",
"->",
"CryptContext",
":",
"pw_hash",
"=",
"app",
".",
"config",
".",
"SECURITY_PASSWORD_HASH",
"schemes",
"=",
"app",
".",
"config",
".",
"SECURITY_PASSWORD_SCHEMES",
"if",
"pw_hash... | Get the password hashing context. | [
"Get",
"the",
"password",
"hashing",
"context",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L215-L226 |
25,768 | briancappello/flask-unchained | flask_unchained/bundles/security/extensions/security.py | Security._get_serializer | def _get_serializer(self, app: FlaskUnchained, name: str) -> URLSafeTimedSerializer:
"""
Get a URLSafeTimedSerializer for the given serialization context name.
:param app: the :class:`FlaskUnchained` instance
:param name: Serialization context. One of ``confirm``, ``login``,
``remember``, or ``reset``
:return: URLSafeTimedSerializer
"""
salt = app.config.get('SECURITY_%s_SALT' % name.upper())
return URLSafeTimedSerializer(secret_key=app.config.SECRET_KEY, salt=salt) | python | def _get_serializer(self, app: FlaskUnchained, name: str) -> URLSafeTimedSerializer:
salt = app.config.get('SECURITY_%s_SALT' % name.upper())
return URLSafeTimedSerializer(secret_key=app.config.SECRET_KEY, salt=salt) | [
"def",
"_get_serializer",
"(",
"self",
",",
"app",
":",
"FlaskUnchained",
",",
"name",
":",
"str",
")",
"->",
"URLSafeTimedSerializer",
":",
"salt",
"=",
"app",
".",
"config",
".",
"get",
"(",
"'SECURITY_%s_SALT'",
"%",
"name",
".",
"upper",
"(",
")",
")... | Get a URLSafeTimedSerializer for the given serialization context name.
:param app: the :class:`FlaskUnchained` instance
:param name: Serialization context. One of ``confirm``, ``login``,
``remember``, or ``reset``
:return: URLSafeTimedSerializer | [
"Get",
"a",
"URLSafeTimedSerializer",
"for",
"the",
"given",
"serialization",
"context",
"name",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L228-L238 |
25,769 | briancappello/flask-unchained | flask_unchained/bundles/security/extensions/security.py | Security._request_loader | def _request_loader(self, request: Request) -> Union[User, AnonymousUser]:
"""
Attempt to load the user from the request token.
"""
header_key = self.token_authentication_header
args_key = self.token_authentication_key
token = request.args.get(args_key, request.headers.get(header_key, None))
if request.is_json:
data = request.get_json(silent=True) or {}
token = data.get(args_key, token)
try:
data = self.remember_token_serializer.loads(token, max_age=self.token_max_age)
user = self.user_manager.get(data[0])
if user and self.security_utils_service.verify_hash(data[1], user.password):
return user
except:
pass
return self.login_manager.anonymous_user() | python | def _request_loader(self, request: Request) -> Union[User, AnonymousUser]:
header_key = self.token_authentication_header
args_key = self.token_authentication_key
token = request.args.get(args_key, request.headers.get(header_key, None))
if request.is_json:
data = request.get_json(silent=True) or {}
token = data.get(args_key, token)
try:
data = self.remember_token_serializer.loads(token, max_age=self.token_max_age)
user = self.user_manager.get(data[0])
if user and self.security_utils_service.verify_hash(data[1], user.password):
return user
except:
pass
return self.login_manager.anonymous_user() | [
"def",
"_request_loader",
"(",
"self",
",",
"request",
":",
"Request",
")",
"->",
"Union",
"[",
"User",
",",
"AnonymousUser",
"]",
":",
"header_key",
"=",
"self",
".",
"token_authentication_header",
"args_key",
"=",
"self",
".",
"token_authentication_key",
"toke... | Attempt to load the user from the request token. | [
"Attempt",
"to",
"load",
"the",
"user",
"from",
"the",
"request",
"token",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/security/extensions/security.py#L260-L279 |
25,770 | briancappello/flask-unchained | flask_unchained/commands/unchained.py | bundles | def bundles(ctx):
"""
List discovered bundles.
"""
bundles = _get_bundles(ctx.obj.data['env'])
print_table(('Name', 'Location'),
[(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}')
for bundle in bundles]) | python | def bundles(ctx):
bundles = _get_bundles(ctx.obj.data['env'])
print_table(('Name', 'Location'),
[(bundle.name, f'{bundle.__module__}.{bundle.__class__.__name__}')
for bundle in bundles]) | [
"def",
"bundles",
"(",
"ctx",
")",
":",
"bundles",
"=",
"_get_bundles",
"(",
"ctx",
".",
"obj",
".",
"data",
"[",
"'env'",
"]",
")",
"print_table",
"(",
"(",
"'Name'",
",",
"'Location'",
")",
",",
"[",
"(",
"bundle",
".",
"name",
",",
"f'{bundle.__mo... | List discovered bundles. | [
"List",
"discovered",
"bundles",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/unchained.py#L16-L23 |
25,771 | briancappello/flask-unchained | flask_unchained/click.py | argument | def argument(*param_decls, cls=None, **attrs):
"""
Arguments are positional parameters to a command. They generally
provide fewer features than options but can have infinite ``nargs``
and are required by default.
:param param_decls: the parameter declarations for this option or
argument. This is a list of flags or argument
names.
:param type: the type that should be used. Either a :class:`ParamType`
or a Python type. The later is converted into the former
automatically if supported.
:param required: controls if this is optional or not.
:param default: the default value if omitted. This can also be a callable,
in which case it's invoked when the default is needed
without any arguments.
:param callback: a callback that should be executed after the parameter
was matched. This is called as ``fn(ctx, param,
value)`` and needs to return the value. Before Click
2.0, the signature was ``(ctx, value)``.
:param nargs: the number of arguments to match. If not ``1`` the return
value is a tuple instead of single value. The default for
nargs is ``1`` (except if the type is a tuple, then it's
the arity of the tuple).
:param metavar: how the value is represented in the help page.
:param expose_value: if this is `True` then the value is passed onwards
to the command callback and stored on the context,
otherwise it's skipped.
:param is_eager: eager values are processed before non eager ones. This
should not be set for arguments or it will inverse the
order of processing.
:param envvar: a string or list of strings that are environment variables
that should be checked.
:param help: the help string.
:param hidden: hide this option from help outputs.
Default is True, unless help is given.
"""
return click.argument(*param_decls, cls=cls or Argument, **attrs) | python | def argument(*param_decls, cls=None, **attrs):
return click.argument(*param_decls, cls=cls or Argument, **attrs) | [
"def",
"argument",
"(",
"*",
"param_decls",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"click",
".",
"argument",
"(",
"*",
"param_decls",
",",
"cls",
"=",
"cls",
"or",
"Argument",
",",
"*",
"*",
"attrs",
")"
] | Arguments are positional parameters to a command. They generally
provide fewer features than options but can have infinite ``nargs``
and are required by default.
:param param_decls: the parameter declarations for this option or
argument. This is a list of flags or argument
names.
:param type: the type that should be used. Either a :class:`ParamType`
or a Python type. The later is converted into the former
automatically if supported.
:param required: controls if this is optional or not.
:param default: the default value if omitted. This can also be a callable,
in which case it's invoked when the default is needed
without any arguments.
:param callback: a callback that should be executed after the parameter
was matched. This is called as ``fn(ctx, param,
value)`` and needs to return the value. Before Click
2.0, the signature was ``(ctx, value)``.
:param nargs: the number of arguments to match. If not ``1`` the return
value is a tuple instead of single value. The default for
nargs is ``1`` (except if the type is a tuple, then it's
the arity of the tuple).
:param metavar: how the value is represented in the help page.
:param expose_value: if this is `True` then the value is passed onwards
to the command callback and stored on the context,
otherwise it's skipped.
:param is_eager: eager values are processed before non eager ones. This
should not be set for arguments or it will inverse the
order of processing.
:param envvar: a string or list of strings that are environment variables
that should be checked.
:param help: the help string.
:param hidden: hide this option from help outputs.
Default is True, unless help is given. | [
"Arguments",
"are",
"positional",
"parameters",
"to",
"a",
"command",
".",
"They",
"generally",
"provide",
"fewer",
"features",
"than",
"options",
"but",
"can",
"have",
"infinite",
"nargs",
"and",
"are",
"required",
"by",
"default",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/click.py#L390-L427 |
25,772 | briancappello/flask-unchained | flask_unchained/click.py | option | def option(*param_decls, cls=None, **attrs):
"""
Options are usually optional values on the command line and
have some extra features that arguments don't have.
:param param_decls: the parameter declarations for this option or
argument. This is a list of flags or argument
names.
:param show_default: controls if the default value should be shown on the
help page. Normally, defaults are not shown.
:param prompt: if set to `True` or a non empty string then the user will
be prompted for input if not set. If set to `True` the
prompt will be the option name capitalized.
:param confirmation_prompt: if set then the value will need to be confirmed
if it was prompted for.
:param hide_input: if this is `True` then the input on the prompt will be
hidden from the user. This is useful for password
input.
:param is_flag: forces this option to act as a flag. The default is
auto detection.
:param flag_value: which value should be used for this flag if it's
enabled. This is set to a boolean automatically if
the option string contains a slash to mark two options.
:param multiple: if this is set to `True` then the argument is accepted
multiple times and recorded. This is similar to ``nargs``
in how it works but supports arbitrary number of
arguments.
:param count: this flag makes an option increment an integer.
:param allow_from_autoenv: if this is enabled then the value of this
parameter will be pulled from an environment
variable in case a prefix is defined on the
context.
:param help: the help string.
"""
return click.option(*param_decls, cls=cls or Option, **attrs) | python | def option(*param_decls, cls=None, **attrs):
return click.option(*param_decls, cls=cls or Option, **attrs) | [
"def",
"option",
"(",
"*",
"param_decls",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"return",
"click",
".",
"option",
"(",
"*",
"param_decls",
",",
"cls",
"=",
"cls",
"or",
"Option",
",",
"*",
"*",
"attrs",
")"
] | Options are usually optional values on the command line and
have some extra features that arguments don't have.
:param param_decls: the parameter declarations for this option or
argument. This is a list of flags or argument
names.
:param show_default: controls if the default value should be shown on the
help page. Normally, defaults are not shown.
:param prompt: if set to `True` or a non empty string then the user will
be prompted for input if not set. If set to `True` the
prompt will be the option name capitalized.
:param confirmation_prompt: if set then the value will need to be confirmed
if it was prompted for.
:param hide_input: if this is `True` then the input on the prompt will be
hidden from the user. This is useful for password
input.
:param is_flag: forces this option to act as a flag. The default is
auto detection.
:param flag_value: which value should be used for this flag if it's
enabled. This is set to a boolean automatically if
the option string contains a slash to mark two options.
:param multiple: if this is set to `True` then the argument is accepted
multiple times and recorded. This is similar to ``nargs``
in how it works but supports arbitrary number of
arguments.
:param count: this flag makes an option increment an integer.
:param allow_from_autoenv: if this is enabled then the value of this
parameter will be pulled from an environment
variable in case a prefix is defined on the
context.
:param help: the help string. | [
"Options",
"are",
"usually",
"optional",
"values",
"on",
"the",
"command",
"line",
"and",
"have",
"some",
"extra",
"features",
"that",
"arguments",
"don",
"t",
"have",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/click.py#L430-L464 |
25,773 | briancappello/flask-unchained | flask_unchained/bundles/api/apispec.py | APISpec._openapi_json | def _openapi_json(self):
"""Serve JSON spec file"""
# We don't use Flask.jsonify here as it would sort the keys
# alphabetically while we want to preserve the order.
from pprint import pprint
pprint(self.to_dict())
return current_app.response_class(json.dumps(self.to_dict(), indent=4),
mimetype='application/json') | python | def _openapi_json(self):
# We don't use Flask.jsonify here as it would sort the keys
# alphabetically while we want to preserve the order.
from pprint import pprint
pprint(self.to_dict())
return current_app.response_class(json.dumps(self.to_dict(), indent=4),
mimetype='application/json') | [
"def",
"_openapi_json",
"(",
"self",
")",
":",
"# We don't use Flask.jsonify here as it would sort the keys",
"# alphabetically while we want to preserve the order.",
"from",
"pprint",
"import",
"pprint",
"pprint",
"(",
"self",
".",
"to_dict",
"(",
")",
")",
"return",
"curr... | Serve JSON spec file | [
"Serve",
"JSON",
"spec",
"file"
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L59-L66 |
25,774 | briancappello/flask-unchained | flask_unchained/bundles/api/apispec.py | APISpec._openapi_redoc | def _openapi_redoc(self):
"""
Expose OpenAPI spec with ReDoc
The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL``
"""
return render_template('openapi/redoc.html',
title=self.app.config.API_TITLE or self.app.name,
redoc_url=self.app.config.API_REDOC_SOURCE_URL) | python | def _openapi_redoc(self):
return render_template('openapi/redoc.html',
title=self.app.config.API_TITLE or self.app.name,
redoc_url=self.app.config.API_REDOC_SOURCE_URL) | [
"def",
"_openapi_redoc",
"(",
"self",
")",
":",
"return",
"render_template",
"(",
"'openapi/redoc.html'",
",",
"title",
"=",
"self",
".",
"app",
".",
"config",
".",
"API_TITLE",
"or",
"self",
".",
"app",
".",
"name",
",",
"redoc_url",
"=",
"self",
".",
"... | Expose OpenAPI spec with ReDoc
The ReDoc script URL can be specified as ``API_REDOC_SOURCE_URL`` | [
"Expose",
"OpenAPI",
"spec",
"with",
"ReDoc"
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L68-L76 |
25,775 | briancappello/flask-unchained | flask_unchained/bundles/api/apispec.py | APISpec.register_converter | def register_converter(self, converter, conv_type, conv_format=None):
"""
Register custom path parameter converter
:param BaseConverter converter: Converter.
Subclass of werkzeug's BaseConverter
:param str conv_type: Parameter type
:param str conv_format: Parameter format (optional)
"""
self.flask_plugin.register_converter(converter, conv_type, conv_format) | python | def register_converter(self, converter, conv_type, conv_format=None):
self.flask_plugin.register_converter(converter, conv_type, conv_format) | [
"def",
"register_converter",
"(",
"self",
",",
"converter",
",",
"conv_type",
",",
"conv_format",
"=",
"None",
")",
":",
"self",
".",
"flask_plugin",
".",
"register_converter",
"(",
"converter",
",",
"conv_type",
",",
"conv_format",
")"
] | Register custom path parameter converter
:param BaseConverter converter: Converter.
Subclass of werkzeug's BaseConverter
:param str conv_type: Parameter type
:param str conv_format: Parameter format (optional) | [
"Register",
"custom",
"path",
"parameter",
"converter"
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/apispec.py#L78-L87 |
25,776 | briancappello/flask-unchained | flask_unchained/bundles/api/decorators.py | list_loader | def list_loader(*decorator_args, model):
"""
Decorator to automatically query the database for all records of a model.
:param model: The model class to query
"""
def wrapped(fn):
@wraps(fn)
def decorated(*args, **kwargs):
return fn(model.query.all())
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapped(decorator_args[0])
return wrapped | python | def list_loader(*decorator_args, model):
def wrapped(fn):
@wraps(fn)
def decorated(*args, **kwargs):
return fn(model.query.all())
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapped(decorator_args[0])
return wrapped | [
"def",
"list_loader",
"(",
"*",
"decorator_args",
",",
"model",
")",
":",
"def",
"wrapped",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"fn",
"(",
"model",
... | Decorator to automatically query the database for all records of a model.
:param model: The model class to query | [
"Decorator",
"to",
"automatically",
"query",
"the",
"database",
"for",
"all",
"records",
"of",
"a",
"model",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/decorators.py#L7-L21 |
25,777 | briancappello/flask-unchained | flask_unchained/bundles/api/decorators.py | post_loader | def post_loader(*decorator_args, serializer):
"""
Decorator to automatically instantiate a model from json request data
:param serializer: The ModelSerializer to use to load data from the request
"""
def wrapped(fn):
@wraps(fn)
def decorated(*args, **kwargs):
return fn(*serializer.load(request.get_json()))
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapped(decorator_args[0])
return wrapped | python | def post_loader(*decorator_args, serializer):
def wrapped(fn):
@wraps(fn)
def decorated(*args, **kwargs):
return fn(*serializer.load(request.get_json()))
return decorated
if decorator_args and callable(decorator_args[0]):
return wrapped(decorator_args[0])
return wrapped | [
"def",
"post_loader",
"(",
"*",
"decorator_args",
",",
"serializer",
")",
":",
"def",
"wrapped",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"fn",
"(",
"*",
... | Decorator to automatically instantiate a model from json request data
:param serializer: The ModelSerializer to use to load data from the request | [
"Decorator",
"to",
"automatically",
"instantiate",
"a",
"model",
"from",
"json",
"request",
"data"
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/decorators.py#L68-L82 |
25,778 | briancappello/flask-unchained | flask_unchained/bundles/sqlalchemy/commands.py | reset_command | def reset_command(force):
"""Drop database tables and run migrations."""
if not force:
exit('Cancelled.')
click.echo('Dropping DB tables.')
drop_all()
click.echo('Running DB migrations.')
alembic.upgrade(migrate.get_config(None), 'head')
click.echo('Done.') | python | def reset_command(force):
if not force:
exit('Cancelled.')
click.echo('Dropping DB tables.')
drop_all()
click.echo('Running DB migrations.')
alembic.upgrade(migrate.get_config(None), 'head')
click.echo('Done.') | [
"def",
"reset_command",
"(",
"force",
")",
":",
"if",
"not",
"force",
":",
"exit",
"(",
"'Cancelled.'",
")",
"click",
".",
"echo",
"(",
"'Dropping DB tables.'",
")",
"drop_all",
"(",
")",
"click",
".",
"echo",
"(",
"'Running DB migrations.'",
")",
"alembic",... | Drop database tables and run migrations. | [
"Drop",
"database",
"tables",
"and",
"run",
"migrations",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/sqlalchemy/commands.py#L43-L54 |
25,779 | tanbro/pyyaml-include | src/yamlinclude/constructor.py | YamlIncludeConstructor.load | def load(self, loader, pathname, recursive=False, encoding=None):
"""Once add the constructor to PyYAML loader class,
Loader will use this function to include other YAML fils
on parsing ``"!include"`` tag
:param loader: Instance of PyYAML's loader class
:param str pathname: pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards
:param bool recursive: If recursive is true, the pattern ``"**"`` will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.
Note:
Using the ``"**"`` pattern in large directory trees may consume an inordinate amount of time.
:param str encoding: YAML file encoding
:default: ``None``: Attribute :attr:`encoding` or constant :attr:`DEFAULT_ENCODING` will be used to open it
:return: included YAML file, in Python data type
.. warning:: It's called by :mod:`yaml`. Do NOT call it yourself.
"""
if not encoding:
encoding = self._encoding or self.DEFAULT_ENCODING
if self._base_dir:
pathname = os.path.join(self._base_dir, pathname)
if re.match(WILDCARDS_REGEX, pathname):
result = []
if PYTHON_MAYOR_MINOR >= '3.5':
iterator = iglob(pathname, recursive=recursive)
else:
iterator = iglob(pathname)
for path in iterator:
if os.path.isfile(path):
with io.open(path, encoding=encoding) as fp: # pylint:disable=invalid-name
result.append(yaml.load(fp, type(loader)))
return result
with io.open(pathname, encoding=encoding) as fp: # pylint:disable=invalid-name
return yaml.load(fp, type(loader)) | python | def load(self, loader, pathname, recursive=False, encoding=None):
if not encoding:
encoding = self._encoding or self.DEFAULT_ENCODING
if self._base_dir:
pathname = os.path.join(self._base_dir, pathname)
if re.match(WILDCARDS_REGEX, pathname):
result = []
if PYTHON_MAYOR_MINOR >= '3.5':
iterator = iglob(pathname, recursive=recursive)
else:
iterator = iglob(pathname)
for path in iterator:
if os.path.isfile(path):
with io.open(path, encoding=encoding) as fp: # pylint:disable=invalid-name
result.append(yaml.load(fp, type(loader)))
return result
with io.open(pathname, encoding=encoding) as fp: # pylint:disable=invalid-name
return yaml.load(fp, type(loader)) | [
"def",
"load",
"(",
"self",
",",
"loader",
",",
"pathname",
",",
"recursive",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"if",
"not",
"encoding",
":",
"encoding",
"=",
"self",
".",
"_encoding",
"or",
"self",
".",
"DEFAULT_ENCODING",
"if",
"s... | Once add the constructor to PyYAML loader class,
Loader will use this function to include other YAML fils
on parsing ``"!include"`` tag
:param loader: Instance of PyYAML's loader class
:param str pathname: pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards
:param bool recursive: If recursive is true, the pattern ``"**"`` will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.
Note:
Using the ``"**"`` pattern in large directory trees may consume an inordinate amount of time.
:param str encoding: YAML file encoding
:default: ``None``: Attribute :attr:`encoding` or constant :attr:`DEFAULT_ENCODING` will be used to open it
:return: included YAML file, in Python data type
.. warning:: It's called by :mod:`yaml`. Do NOT call it yourself. | [
"Once",
"add",
"the",
"constructor",
"to",
"PyYAML",
"loader",
"class",
"Loader",
"will",
"use",
"this",
"function",
"to",
"include",
"other",
"YAML",
"fils",
"on",
"parsing",
"!include",
"tag"
] | f0e6490399aaf7c02321000fe5cdccfa8f63cf66 | https://github.com/tanbro/pyyaml-include/blob/f0e6490399aaf7c02321000fe5cdccfa8f63cf66/src/yamlinclude/constructor.py#L96-L133 |
25,780 | tanbro/pyyaml-include | src/yamlinclude/constructor.py | YamlIncludeConstructor.add_to_loader_class | def add_to_loader_class(cls, loader_class=None, tag=None, **kwargs):
# type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor
"""
Create an instance of the constructor, and add it to the YAML `Loader` class
:param loader_class: The `Loader` class add constructor to.
.. attention:: This parameter **SHOULD** be a **class type**, **NOT** object.
It's one of following:
- :class:`yaml.BaseLoader`
- :class:`yaml.UnSafeLoader`
- :class:`yaml.SafeLoader`
- :class:`yaml.Loader`
- :class:`yaml.FullLoader`
- :class:`yaml.CBaseLoader`
- :class:`yaml.CUnSafeLoader`
- :class:`yaml.CSafeLoader`
- :class:`yaml.CLoader`
- :class:`yaml.CFullLoader`
:default: ``None``:
- When :mod:`pyyaml` 3.*: Add to PyYAML's default `Loader`
- When :mod:`pyyaml` 5.*: Add to `FullLoader`
:type loader_class: type
:param str tag: Tag's name of the include constructor.
:default: ``""``: Use :attr:`DEFAULT_TAG_NAME` as tag name.
:param kwargs: Arguments passed to construct function
:return: New created object
:rtype: YamlIncludeConstructor
"""
if tag is None:
tag = ''
tag = tag.strip()
if not tag:
tag = cls.DEFAULT_TAG_NAME
if not tag.startswith('!'):
raise ValueError('`tag` argument should start with character "!"')
instance = cls(**kwargs)
if loader_class is None:
if FullLoader:
yaml.add_constructor(tag, instance, FullLoader)
else:
yaml.add_constructor(tag, instance)
else:
yaml.add_constructor(tag, instance, loader_class)
return instance | python | def add_to_loader_class(cls, loader_class=None, tag=None, **kwargs):
# type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor
if tag is None:
tag = ''
tag = tag.strip()
if not tag:
tag = cls.DEFAULT_TAG_NAME
if not tag.startswith('!'):
raise ValueError('`tag` argument should start with character "!"')
instance = cls(**kwargs)
if loader_class is None:
if FullLoader:
yaml.add_constructor(tag, instance, FullLoader)
else:
yaml.add_constructor(tag, instance)
else:
yaml.add_constructor(tag, instance, loader_class)
return instance | [
"def",
"add_to_loader_class",
"(",
"cls",
",",
"loader_class",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (type(yaml.Loader), str, **str)-> YamlIncludeConstructor",
"if",
"tag",
"is",
"None",
":",
"tag",
"=",
"''",
"tag",
... | Create an instance of the constructor, and add it to the YAML `Loader` class
:param loader_class: The `Loader` class add constructor to.
.. attention:: This parameter **SHOULD** be a **class type**, **NOT** object.
It's one of following:
- :class:`yaml.BaseLoader`
- :class:`yaml.UnSafeLoader`
- :class:`yaml.SafeLoader`
- :class:`yaml.Loader`
- :class:`yaml.FullLoader`
- :class:`yaml.CBaseLoader`
- :class:`yaml.CUnSafeLoader`
- :class:`yaml.CSafeLoader`
- :class:`yaml.CLoader`
- :class:`yaml.CFullLoader`
:default: ``None``:
- When :mod:`pyyaml` 3.*: Add to PyYAML's default `Loader`
- When :mod:`pyyaml` 5.*: Add to `FullLoader`
:type loader_class: type
:param str tag: Tag's name of the include constructor.
:default: ``""``: Use :attr:`DEFAULT_TAG_NAME` as tag name.
:param kwargs: Arguments passed to construct function
:return: New created object
:rtype: YamlIncludeConstructor | [
"Create",
"an",
"instance",
"of",
"the",
"constructor",
"and",
"add",
"it",
"to",
"the",
"YAML",
"Loader",
"class"
] | f0e6490399aaf7c02321000fe5cdccfa8f63cf66 | https://github.com/tanbro/pyyaml-include/blob/f0e6490399aaf7c02321000fe5cdccfa8f63cf66/src/yamlinclude/constructor.py#L136-L189 |
25,781 | briancappello/flask-unchained | flask_unchained/commands/utils.py | print_table | def print_table(column_names: IterableOfStrings,
rows: IterableOfTuples,
column_alignments: Optional[IterableOfStrings] = None,
primary_column_idx: int = 0,
) -> None:
"""
Prints a table of information to the console. Automatically determines if the
console is wide enough, and if not, displays the information in list form.
:param column_names: The heading labels
:param rows: A list of lists
:param column_alignments: An optional list of strings, using either '<' or '>'
to specify left or right alignment respectively
:param primary_column_idx: Used when displaying information in list form,
to determine which label should be the top-most one. Defaults to the first
label in ``column_names``.
"""
header_template = ''
row_template = ''
table_width = 0
type_formatters = {int: 'd', float: 'f', str: 's'}
types = [type_formatters.get(type(x), 'r') for x in rows[0]]
alignments = {int: '>', float: '>'}
column_alignments = (column_alignments or
[alignments.get(type(x), '<') for x in rows[0]])
def get_column_width(idx):
header_length = len(column_names[idx])
content_length = max(len(str(row[idx])) for row in rows)
return (content_length if content_length > header_length
else header_length)
for i in range(0, len(column_names)):
col_width = get_column_width(i)
header_col_template = f'{{:{col_width}}}'
col_template = f'{{:{column_alignments[i]}{col_width}{types[i]}}}'
if i == 0:
header_template += header_col_template
row_template += col_template
table_width += col_width
else:
header_template += ' ' + header_col_template
row_template += ' ' + col_template
table_width += 2 + col_width
# check if we can format the table horizontally
if table_width < get_terminal_width():
click.echo(header_template.format(*column_names))
click.echo('-' * table_width)
for row in rows:
try:
click.echo(row_template.format(*row))
except TypeError as e:
raise TypeError(f'{e}: {row!r}')
# otherwise format it vertically
else:
max_label_width = max(*[len(label) for label in column_names])
non_primary_columns = [(i, col) for i, col in enumerate(column_names)
if i != primary_column_idx]
for row in rows:
type_ = types[primary_column_idx]
row_template = f'{{:>{max_label_width}s}}: {{:{type_}}}'
click.echo(row_template.format(column_names[primary_column_idx],
row[primary_column_idx]))
for i, label in non_primary_columns:
row_template = f'{{:>{max_label_width}s}}: {{:{types[i]}}}'
click.echo(row_template.format(label, row[i]))
click.echo() | python | def print_table(column_names: IterableOfStrings,
rows: IterableOfTuples,
column_alignments: Optional[IterableOfStrings] = None,
primary_column_idx: int = 0,
) -> None:
header_template = ''
row_template = ''
table_width = 0
type_formatters = {int: 'd', float: 'f', str: 's'}
types = [type_formatters.get(type(x), 'r') for x in rows[0]]
alignments = {int: '>', float: '>'}
column_alignments = (column_alignments or
[alignments.get(type(x), '<') for x in rows[0]])
def get_column_width(idx):
header_length = len(column_names[idx])
content_length = max(len(str(row[idx])) for row in rows)
return (content_length if content_length > header_length
else header_length)
for i in range(0, len(column_names)):
col_width = get_column_width(i)
header_col_template = f'{{:{col_width}}}'
col_template = f'{{:{column_alignments[i]}{col_width}{types[i]}}}'
if i == 0:
header_template += header_col_template
row_template += col_template
table_width += col_width
else:
header_template += ' ' + header_col_template
row_template += ' ' + col_template
table_width += 2 + col_width
# check if we can format the table horizontally
if table_width < get_terminal_width():
click.echo(header_template.format(*column_names))
click.echo('-' * table_width)
for row in rows:
try:
click.echo(row_template.format(*row))
except TypeError as e:
raise TypeError(f'{e}: {row!r}')
# otherwise format it vertically
else:
max_label_width = max(*[len(label) for label in column_names])
non_primary_columns = [(i, col) for i, col in enumerate(column_names)
if i != primary_column_idx]
for row in rows:
type_ = types[primary_column_idx]
row_template = f'{{:>{max_label_width}s}}: {{:{type_}}}'
click.echo(row_template.format(column_names[primary_column_idx],
row[primary_column_idx]))
for i, label in non_primary_columns:
row_template = f'{{:>{max_label_width}s}}: {{:{types[i]}}}'
click.echo(row_template.format(label, row[i]))
click.echo() | [
"def",
"print_table",
"(",
"column_names",
":",
"IterableOfStrings",
",",
"rows",
":",
"IterableOfTuples",
",",
"column_alignments",
":",
"Optional",
"[",
"IterableOfStrings",
"]",
"=",
"None",
",",
"primary_column_idx",
":",
"int",
"=",
"0",
",",
")",
"->",
"... | Prints a table of information to the console. Automatically determines if the
console is wide enough, and if not, displays the information in list form.
:param column_names: The heading labels
:param rows: A list of lists
:param column_alignments: An optional list of strings, using either '<' or '>'
to specify left or right alignment respectively
:param primary_column_idx: Used when displaying information in list form,
to determine which label should be the top-most one. Defaults to the first
label in ``column_names``. | [
"Prints",
"a",
"table",
"of",
"information",
"to",
"the",
"console",
".",
"Automatically",
"determines",
"if",
"the",
"console",
"is",
"wide",
"enough",
"and",
"if",
"not",
"displays",
"the",
"information",
"in",
"list",
"form",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/commands/utils.py#L10-L80 |
25,782 | briancappello/flask-unchained | flask_mail.py | Connection.send | def send(self, message, envelope_from=None):
"""Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command.
"""
assert message.send_to, "No recipients have been added"
assert message.sender, (
"The message does not specify a sender and a default sender "
"has not been configured")
if message.has_bad_headers():
raise BadHeaderError
if message.date is None:
message.date = time.time()
ret = None
if self.host:
ret = self.host.sendmail(
sanitize_address(envelope_from or message.sender),
list(sanitize_addresses(message.send_to)),
message.as_bytes() if PY3 else message.as_string(),
message.mail_options,
message.rcpt_options
)
email_dispatched.send(message, app=current_app._get_current_object())
self.num_emails += 1
if self.num_emails == self.mail.max_emails:
self.num_emails = 0
if self.host:
self.host.quit()
self.host = self.configure_host()
return ret | python | def send(self, message, envelope_from=None):
assert message.send_to, "No recipients have been added"
assert message.sender, (
"The message does not specify a sender and a default sender "
"has not been configured")
if message.has_bad_headers():
raise BadHeaderError
if message.date is None:
message.date = time.time()
ret = None
if self.host:
ret = self.host.sendmail(
sanitize_address(envelope_from or message.sender),
list(sanitize_addresses(message.send_to)),
message.as_bytes() if PY3 else message.as_string(),
message.mail_options,
message.rcpt_options
)
email_dispatched.send(message, app=current_app._get_current_object())
self.num_emails += 1
if self.num_emails == self.mail.max_emails:
self.num_emails = 0
if self.host:
self.host.quit()
self.host = self.configure_host()
return ret | [
"def",
"send",
"(",
"self",
",",
"message",
",",
"envelope_from",
"=",
"None",
")",
":",
"assert",
"message",
".",
"send_to",
",",
"\"No recipients have been added\"",
"assert",
"message",
".",
"sender",
",",
"(",
"\"The message does not specify a sender and a default... | Verifies and sends message.
:param message: Message instance.
:param envelope_from: Email address to be used in MAIL FROM command. | [
"Verifies",
"and",
"sends",
"message",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L228-L266 |
25,783 | briancappello/flask-unchained | flask_mail.py | _MailMixin.connect | def connect(self):
"""
Opens a connection to the mail host.
"""
app = getattr(self, "app", None) or current_app
try:
return Connection(app.extensions['mail'])
except KeyError:
raise RuntimeError("The curent application was"
" not configured with Flask-Mail") | python | def connect(self):
app = getattr(self, "app", None) or current_app
try:
return Connection(app.extensions['mail'])
except KeyError:
raise RuntimeError("The curent application was"
" not configured with Flask-Mail") | [
"def",
"connect",
"(",
"self",
")",
":",
"app",
"=",
"getattr",
"(",
"self",
",",
"\"app\"",
",",
"None",
")",
"or",
"current_app",
"try",
":",
"return",
"Connection",
"(",
"app",
".",
"extensions",
"[",
"'mail'",
"]",
")",
"except",
"KeyError",
":",
... | Opens a connection to the mail host. | [
"Opens",
"a",
"connection",
"to",
"the",
"mail",
"host",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L633-L642 |
25,784 | briancappello/flask-unchained | flask_mail.py | Mail.init_app | def init_app(self, app):
"""Initializes your mail settings from the application settings.
You can use this if you want to set up your Mail instance
at configuration time.
:param app: Flask application instance
"""
state = self.init_mail(app.config, app.debug, app.testing)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['mail'] = state
return state | python | def init_app(self, app):
state = self.init_mail(app.config, app.debug, app.testing)
# register extension with app
app.extensions = getattr(app, 'extensions', {})
app.extensions['mail'] = state
return state | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"state",
"=",
"self",
".",
"init_mail",
"(",
"app",
".",
"config",
",",
"app",
".",
"debug",
",",
"app",
".",
"testing",
")",
"# register extension with app",
"app",
".",
"extensions",
"=",
"getattr",... | Initializes your mail settings from the application settings.
You can use this if you want to set up your Mail instance
at configuration time.
:param app: Flask application instance | [
"Initializes",
"your",
"mail",
"settings",
"from",
"the",
"application",
"settings",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_mail.py#L691-L704 |
25,785 | briancappello/flask-unchained | flask_unchained/bundle.py | _DeferredBundleFunctions.url_defaults | def url_defaults(self, fn):
"""
Callback function for URL defaults for this bundle. It's called
with the endpoint and values and should update the values passed
in place.
"""
self._defer(lambda bp: bp.url_defaults(fn))
return fn | python | def url_defaults(self, fn):
self._defer(lambda bp: bp.url_defaults(fn))
return fn | [
"def",
"url_defaults",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"bp",
":",
"bp",
".",
"url_defaults",
"(",
"fn",
")",
")",
"return",
"fn"
] | Callback function for URL defaults for this bundle. It's called
with the endpoint and values and should update the values passed
in place. | [
"Callback",
"function",
"for",
"URL",
"defaults",
"for",
"this",
"bundle",
".",
"It",
"s",
"called",
"with",
"the",
"endpoint",
"and",
"values",
"and",
"should",
"update",
"the",
"values",
"passed",
"in",
"place",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L113-L120 |
25,786 | briancappello/flask-unchained | flask_unchained/bundle.py | _DeferredBundleFunctions.url_value_preprocessor | def url_value_preprocessor(self, fn):
"""
Registers a function as URL value preprocessor for this
bundle. It's called before the view functions are called and
can modify the url values provided.
"""
self._defer(lambda bp: bp.url_value_preprocessor(fn))
return fn | python | def url_value_preprocessor(self, fn):
self._defer(lambda bp: bp.url_value_preprocessor(fn))
return fn | [
"def",
"url_value_preprocessor",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"bp",
":",
"bp",
".",
"url_value_preprocessor",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a function as URL value preprocessor for this
bundle. It's called before the view functions are called and
can modify the url values provided. | [
"Registers",
"a",
"function",
"as",
"URL",
"value",
"preprocessor",
"for",
"this",
"bundle",
".",
"It",
"s",
"called",
"before",
"the",
"view",
"functions",
"are",
"called",
"and",
"can",
"modify",
"the",
"url",
"values",
"provided",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L122-L129 |
25,787 | briancappello/flask-unchained | flask_unchained/bundle.py | _DeferredBundleFunctions.errorhandler | def errorhandler(self, code_or_exception):
"""
Registers an error handler that becomes active for this bundle
only. Please be aware that routing does not happen local to a
bundle so an error handler for 404 usually is not handled by
a bundle unless it is caused inside a view function. Another
special case is the 500 internal server error which is always looked
up from the application.
Otherwise works as the :meth:`flask.Blueprint.errorhandler` decorator.
"""
def decorator(fn):
self._defer(lambda bp: bp.register_error_handler(code_or_exception, fn))
return fn
return decorator | python | def errorhandler(self, code_or_exception):
def decorator(fn):
self._defer(lambda bp: bp.register_error_handler(code_or_exception, fn))
return fn
return decorator | [
"def",
"errorhandler",
"(",
"self",
",",
"code_or_exception",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"bp",
":",
"bp",
".",
"register_error_handler",
"(",
"code_or_exception",
",",
"fn",
")",
")",
"return",
... | Registers an error handler that becomes active for this bundle
only. Please be aware that routing does not happen local to a
bundle so an error handler for 404 usually is not handled by
a bundle unless it is caused inside a view function. Another
special case is the 500 internal server error which is always looked
up from the application.
Otherwise works as the :meth:`flask.Blueprint.errorhandler` decorator. | [
"Registers",
"an",
"error",
"handler",
"that",
"becomes",
"active",
"for",
"this",
"bundle",
"only",
".",
"Please",
"be",
"aware",
"that",
"routing",
"does",
"not",
"happen",
"local",
"to",
"a",
"bundle",
"so",
"an",
"error",
"handler",
"for",
"404",
"usua... | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundle.py#L131-L145 |
25,788 | briancappello/flask-unchained | flask_unchained/bundles/controller/routes.py | controller | def controller(url_prefix_or_controller_cls: Union[str, Type[Controller]],
controller_cls: Optional[Type[Controller]] = None,
*,
rules: Optional[Iterable[Union[Route, RouteGenerator]]] = None,
) -> RouteGenerator:
"""
This function is used to register a controller class's routes.
Example usage::
routes = lambda: [
controller(SiteController),
]
Or with the optional prefix argument::
routes = lambda: [
controller('/products', ProductController),
]
Specify ``rules`` to only include those routes from the controller::
routes = lambda: [
controller(SecurityController, rules=[
rule('/login', SecurityController.login),
rule('/logout', SecurityController.logout),
rule('/sign-up', SecurityController.register),
]),
]
:param url_prefix_or_controller_cls: The controller class, or a url prefix for
all of the rules from the controller class
passed as the second argument
:param controller_cls: If a url prefix was given as the first argument, then
the controller class must be passed as the second argument
:param rules: An optional list of rules to limit/customize the routes included
from the controller
"""
url_prefix, controller_cls = _normalize_args(
url_prefix_or_controller_cls, controller_cls, _is_controller_cls)
url_prefix = url_prefix or controller_cls.Meta.url_prefix
routes = []
controller_routes = getattr(controller_cls, CONTROLLER_ROUTES_ATTR)
if rules is None:
routes = controller_routes.values()
else:
for route in _reduce_routes(rules):
existing = controller_routes.get(route.method_name)
if existing:
routes.append(_inherit_route_options(route, existing[0]))
else:
routes.append(route)
yield from _normalize_controller_routes(routes, controller_cls,
url_prefix=url_prefix) | python | def controller(url_prefix_or_controller_cls: Union[str, Type[Controller]],
controller_cls: Optional[Type[Controller]] = None,
*,
rules: Optional[Iterable[Union[Route, RouteGenerator]]] = None,
) -> RouteGenerator:
url_prefix, controller_cls = _normalize_args(
url_prefix_or_controller_cls, controller_cls, _is_controller_cls)
url_prefix = url_prefix or controller_cls.Meta.url_prefix
routes = []
controller_routes = getattr(controller_cls, CONTROLLER_ROUTES_ATTR)
if rules is None:
routes = controller_routes.values()
else:
for route in _reduce_routes(rules):
existing = controller_routes.get(route.method_name)
if existing:
routes.append(_inherit_route_options(route, existing[0]))
else:
routes.append(route)
yield from _normalize_controller_routes(routes, controller_cls,
url_prefix=url_prefix) | [
"def",
"controller",
"(",
"url_prefix_or_controller_cls",
":",
"Union",
"[",
"str",
",",
"Type",
"[",
"Controller",
"]",
"]",
",",
"controller_cls",
":",
"Optional",
"[",
"Type",
"[",
"Controller",
"]",
"]",
"=",
"None",
",",
"*",
",",
"rules",
":",
"Opt... | This function is used to register a controller class's routes.
Example usage::
routes = lambda: [
controller(SiteController),
]
Or with the optional prefix argument::
routes = lambda: [
controller('/products', ProductController),
]
Specify ``rules`` to only include those routes from the controller::
routes = lambda: [
controller(SecurityController, rules=[
rule('/login', SecurityController.login),
rule('/logout', SecurityController.logout),
rule('/sign-up', SecurityController.register),
]),
]
:param url_prefix_or_controller_cls: The controller class, or a url prefix for
all of the rules from the controller class
passed as the second argument
:param controller_cls: If a url prefix was given as the first argument, then
the controller class must be passed as the second argument
:param rules: An optional list of rules to limit/customize the routes included
from the controller | [
"This",
"function",
"is",
"used",
"to",
"register",
"a",
"controller",
"class",
"s",
"routes",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/routes.py#L20-L75 |
25,789 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.service | def service(self, name: str = None):
"""
Decorator to mark something as a service.
"""
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return lambda x: x
def wrapper(service):
self.register_service(name, service)
return service
return wrapper | python | def service(self, name: str = None):
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return lambda x: x
def wrapper(service):
self.register_service(name, service)
return service
return wrapper | [
"def",
"service",
"(",
"self",
",",
"name",
":",
"str",
"=",
"None",
")",
":",
"if",
"self",
".",
"_services_initialized",
":",
"from",
"warnings",
"import",
"warn",
"warn",
"(",
"'Services have already been initialized. Please register '",
"f'{name} sooner.'",
")",... | Decorator to mark something as a service. | [
"Decorator",
"to",
"mark",
"something",
"as",
"a",
"service",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L127-L140 |
25,790 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.register_service | def register_service(self, name: str, service: Any):
"""
Method to register a service.
"""
if not isinstance(service, type):
if hasattr(service, '__class__'):
_ensure_service_name(service.__class__, name)
self.services[name] = service
return
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return
self._services_registry[_ensure_service_name(service, name)] = service | python | def register_service(self, name: str, service: Any):
if not isinstance(service, type):
if hasattr(service, '__class__'):
_ensure_service_name(service.__class__, name)
self.services[name] = service
return
if self._services_initialized:
from warnings import warn
warn('Services have already been initialized. Please register '
f'{name} sooner.')
return
self._services_registry[_ensure_service_name(service, name)] = service | [
"def",
"register_service",
"(",
"self",
",",
"name",
":",
"str",
",",
"service",
":",
"Any",
")",
":",
"if",
"not",
"isinstance",
"(",
"service",
",",
"type",
")",
":",
"if",
"hasattr",
"(",
"service",
",",
"'__class__'",
")",
":",
"_ensure_service_name"... | Method to register a service. | [
"Method",
"to",
"register",
"a",
"service",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L142-L158 |
25,791 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.before_request | def before_request(self, fn):
"""
Registers a function to run before each request.
For example, this can be used to open a database connection, or to load
the logged in user from the session.
The function will be called without any arguments. If it returns a
non-None value, the value is handled as if it was the return value from
the view, and further request handling is stopped.
"""
self._defer(lambda app: app.before_request(fn))
return fn | python | def before_request(self, fn):
self._defer(lambda app: app.before_request(fn))
return fn | [
"def",
"before_request",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"before_request",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a function to run before each request.
For example, this can be used to open a database connection, or to load
the logged in user from the session.
The function will be called without any arguments. If it returns a
non-None value, the value is handled as if it was the return value from
the view, and further request handling is stopped. | [
"Registers",
"a",
"function",
"to",
"run",
"before",
"each",
"request",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L346-L358 |
25,792 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.before_first_request | def before_first_request(self, fn):
"""
Registers a function to be run before the first request to this
instance of the application.
The function will be called without any arguments and its return
value is ignored.
"""
self._defer(lambda app: app.before_first_request(fn))
return fn | python | def before_first_request(self, fn):
self._defer(lambda app: app.before_first_request(fn))
return fn | [
"def",
"before_first_request",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"before_first_request",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a function to be run before the first request to this
instance of the application.
The function will be called without any arguments and its return
value is ignored. | [
"Registers",
"a",
"function",
"to",
"be",
"run",
"before",
"the",
"first",
"request",
"to",
"this",
"instance",
"of",
"the",
"application",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L360-L369 |
25,793 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.after_request | def after_request(self, fn):
"""
Register a function to be run after each request.
Your function must take one parameter, an instance of
:attr:`response_class` and return a new response object or the
same (see :meth:`process_response`).
As of Flask 0.7 this function might not be executed at the end of the
request in case an unhandled exception occurred.
"""
self._defer(lambda app: app.after_request(fn))
return fn | python | def after_request(self, fn):
self._defer(lambda app: app.after_request(fn))
return fn | [
"def",
"after_request",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"after_request",
"(",
"fn",
")",
")",
"return",
"fn"
] | Register a function to be run after each request.
Your function must take one parameter, an instance of
:attr:`response_class` and return a new response object or the
same (see :meth:`process_response`).
As of Flask 0.7 this function might not be executed at the end of the
request in case an unhandled exception occurred. | [
"Register",
"a",
"function",
"to",
"be",
"run",
"after",
"each",
"request",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L371-L383 |
25,794 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.teardown_request | def teardown_request(self, fn):
"""
Register a function to be run at the end of each request,
regardless of whether there was an exception or not. These functions
are executed when the request context is popped, even if not an
actual request was performed.
Example::
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the request context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Generally teardown functions must take every necessary step to avoid
that they will fail. If they do execute code that might fail they
will have to surround the execution of these code by try/except
statements and log occurring errors.
When a teardown function was called because of an exception it will
be passed an error object.
The return values of teardown functions are ignored.
.. admonition:: Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead it will keep it alive so that the interactive
debugger can still access it. This behavior can be controlled
by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.
"""
self._defer(lambda app: app.teardown_request(fn))
return fn | python | def teardown_request(self, fn):
self._defer(lambda app: app.teardown_request(fn))
return fn | [
"def",
"teardown_request",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"teardown_request",
"(",
"fn",
")",
")",
"return",
"fn"
] | Register a function to be run at the end of each request,
regardless of whether there was an exception or not. These functions
are executed when the request context is popped, even if not an
actual request was performed.
Example::
ctx = app.test_request_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the request context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Generally teardown functions must take every necessary step to avoid
that they will fail. If they do execute code that might fail they
will have to surround the execution of these code by try/except
statements and log occurring errors.
When a teardown function was called because of an exception it will
be passed an error object.
The return values of teardown functions are ignored.
.. admonition:: Debug Note
In debug mode Flask will not tear down a request on an exception
immediately. Instead it will keep it alive so that the interactive
debugger can still access it. This behavior can be controlled
by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable. | [
"Register",
"a",
"function",
"to",
"be",
"run",
"at",
"the",
"end",
"of",
"each",
"request",
"regardless",
"of",
"whether",
"there",
"was",
"an",
"exception",
"or",
"not",
".",
"These",
"functions",
"are",
"executed",
"when",
"the",
"request",
"context",
"... | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L385-L422 |
25,795 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.teardown_appcontext | def teardown_appcontext(self, fn):
"""
Registers a function to be called when the application context
ends. These functions are typically also called when the request
context is popped.
Example::
ctx = app.app_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the app context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Since a request context typically also manages an application
context it would also be called when you pop a request context.
When a teardown function was called because of an unhandled exception
it will be passed an error object. If an :meth:`errorhandler` is
registered, it will handle the exception and the teardown will not
receive it.
The return values of teardown functions are ignored.
"""
self._defer(lambda app: app.teardown_appcontext(fn))
return fn | python | def teardown_appcontext(self, fn):
self._defer(lambda app: app.teardown_appcontext(fn))
return fn | [
"def",
"teardown_appcontext",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"teardown_appcontext",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a function to be called when the application context
ends. These functions are typically also called when the request
context is popped.
Example::
ctx = app.app_context()
ctx.push()
...
ctx.pop()
When ``ctx.pop()`` is executed in the above example, the teardown
functions are called just before the app context moves from the
stack of active contexts. This becomes relevant if you are using
such constructs in tests.
Since a request context typically also manages an application
context it would also be called when you pop a request context.
When a teardown function was called because of an unhandled exception
it will be passed an error object. If an :meth:`errorhandler` is
registered, it will handle the exception and the teardown will not
receive it.
The return values of teardown functions are ignored. | [
"Registers",
"a",
"function",
"to",
"be",
"called",
"when",
"the",
"application",
"context",
"ends",
".",
"These",
"functions",
"are",
"typically",
"also",
"called",
"when",
"the",
"request",
"context",
"is",
"popped",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L424-L453 |
25,796 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.context_processor | def context_processor(self, fn):
"""
Registers a template context processor function.
"""
self._defer(lambda app: app.context_processor(fn))
return fn | python | def context_processor(self, fn):
self._defer(lambda app: app.context_processor(fn))
return fn | [
"def",
"context_processor",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"context_processor",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a template context processor function. | [
"Registers",
"a",
"template",
"context",
"processor",
"function",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L455-L460 |
25,797 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.shell_context_processor | def shell_context_processor(self, fn):
"""
Registers a shell context processor function.
"""
self._defer(lambda app: app.shell_context_processor(fn))
return fn | python | def shell_context_processor(self, fn):
self._defer(lambda app: app.shell_context_processor(fn))
return fn | [
"def",
"shell_context_processor",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"shell_context_processor",
"(",
"fn",
")",
")",
"return",
"fn"
] | Registers a shell context processor function. | [
"Registers",
"a",
"shell",
"context",
"processor",
"function",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L462-L467 |
25,798 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.url_defaults | def url_defaults(self, fn):
"""
Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place.
"""
self._defer(lambda app: app.url_defaults(fn))
return fn | python | def url_defaults(self, fn):
self._defer(lambda app: app.url_defaults(fn))
return fn | [
"def",
"url_defaults",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"url_defaults",
"(",
"fn",
")",
")",
"return",
"fn"
] | Callback function for URL defaults for all view functions of the
application. It's called with the endpoint and values and should
update the values passed in place. | [
"Callback",
"function",
"for",
"URL",
"defaults",
"for",
"all",
"view",
"functions",
"of",
"the",
"application",
".",
"It",
"s",
"called",
"with",
"the",
"endpoint",
"and",
"values",
"and",
"should",
"update",
"the",
"values",
"passed",
"in",
"place",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L486-L493 |
25,799 | briancappello/flask-unchained | flask_unchained/unchained.py | Unchained.errorhandler | def errorhandler(self, code_or_exception):
"""
Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an
error code. Example::
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions::
@app.errorhandler(DatabaseError)
def special_exception_handler(error):
return 'Database connection failed', 500
:param code_or_exception: the code as integer for the handler, or
an arbitrary exception
"""
def decorator(fn):
self._defer(lambda app: app.register_error_handler(code_or_exception, fn))
return fn
return decorator | python | def errorhandler(self, code_or_exception):
def decorator(fn):
self._defer(lambda app: app.register_error_handler(code_or_exception, fn))
return fn
return decorator | [
"def",
"errorhandler",
"(",
"self",
",",
"code_or_exception",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"self",
".",
"_defer",
"(",
"lambda",
"app",
":",
"app",
".",
"register_error_handler",
"(",
"code_or_exception",
",",
"fn",
")",
")",
"return"... | Register a function to handle errors by code or exception class.
A decorator that is used to register a function given an
error code. Example::
@app.errorhandler(404)
def page_not_found(error):
return 'This page does not exist', 404
You can also register handlers for arbitrary exceptions::
@app.errorhandler(DatabaseError)
def special_exception_handler(error):
return 'Database connection failed', 500
:param code_or_exception: the code as integer for the handler, or
an arbitrary exception | [
"Register",
"a",
"function",
"to",
"handle",
"errors",
"by",
"code",
"or",
"exception",
"class",
"."
] | 4d536cb90e2cc4829c1c05f2c74d3e22901a1399 | https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/unchained.py#L495-L518 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.