idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
24,200 | def get_repo_info ( loader , sha , prov_g ) : user_repo = loader . getFullName ( ) repo_title = loader . getRepoTitle ( ) contact_name = loader . getContactName ( ) contact_url = loader . getContactUrl ( ) commit_list = loader . getCommitList ( ) licence_url = loader . getLicenceURL ( ) if prov_g : prov_g . add_used_entity ( loader . getRepoURI ( ) ) prev_commit = None next_commit = None version = sha if sha else commit_list [ 0 ] if commit_list . index ( version ) < len ( commit_list ) - 1 : prev_commit = commit_list [ commit_list . index ( version ) + 1 ] if commit_list . index ( version ) > 0 : next_commit = commit_list [ commit_list . index ( version ) - 1 ] info = { 'version' : version , 'title' : repo_title , 'contact' : { 'name' : contact_name , 'url' : contact_url } , 'license' : { 'name' : 'License' , 'url' : licence_url } } basePath = '/api/' + user_repo + '/' basePath += ( 'commit/' + sha + '/' ) if sha else '' return prev_commit , next_commit , info , basePath | Generate swagger information from the repo being used . |
24,201 | def buildPaginationHeader ( resultCount , resultsPerPage , pageArg , url ) : lastPage = resultCount / resultsPerPage if pageArg : page = int ( pageArg ) next_url = re . sub ( "page=[0-9]+" , "page={}" . format ( page + 1 ) , url ) prev_url = re . sub ( "page=[0-9]+" , "page={}" . format ( page - 1 ) , url ) first_url = re . sub ( "page=[0-9]+" , "page=1" , url ) last_url = re . sub ( "page=[0-9]+" , "page={}" . format ( lastPage ) , url ) else : page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}" . format ( lastPage ) if page == 1 : headerLink = "<{}>; rel=next, <{}>; rel=last" . format ( next_url , last_url ) elif page == lastPage : headerLink = "<{}>; rel=prev, <{}>; rel=first" . format ( prev_url , first_url ) else : headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last" . format ( next_url , prev_url , first_url , last_url ) return headerLink | Build link header for result pagination |
24,202 | def format_directive ( module , package = None ) : directive = '.. automodule:: %s\n' % makename ( package , module ) for option in OPTIONS : directive += ' :%s:\n' % option return directive | Create the automodule directive and add the options . |
24,203 | def extract_summary ( obj ) : try : doc = inspect . getdoc ( obj ) . split ( "\n" ) except AttributeError : doc = '' while doc and not doc [ 0 ] . strip ( ) : doc . pop ( 0 ) for i , piece in enumerate ( doc ) : if not piece . strip ( ) : doc = doc [ : i ] break sentences = periods_re . split ( " " . join ( doc ) ) if len ( sentences ) == 1 : summary = sentences [ 0 ] . strip ( ) else : summary = '' state_machine = RSTStateMachine ( state_classes , 'Body' ) while sentences : summary += sentences . pop ( 0 ) + '.' node = new_document ( '' ) node . reporter = NullReporter ( '' , 999 , 4 ) node . settings . pep_references = None node . settings . rfc_references = None state_machine . run ( [ summary ] , node ) if not node . traverse ( nodes . system_message ) : break return summary | Extract summary from docstring . |
24,204 | def _get_member_ref_str ( name , obj , role = 'obj' , known_refs = None ) : if known_refs is not None : if name in known_refs : return known_refs [ name ] ref = _get_fullname ( name , obj ) return ":%s:`%s <%s>`" % ( role , name , ref ) | generate a ReST - formmated reference link to the given obj of type role using name as the link text |
24,205 | def _get_mod_ns ( name , fullname , includeprivate ) : ns = { 'name' : name , 'fullname' : fullname , 'members' : [ ] , 'functions' : [ ] , 'classes' : [ ] , 'exceptions' : [ ] , 'subpackages' : [ ] , 'submodules' : [ ] , 'doc' : None } p = 0 if includeprivate : p = 1 mod = importlib . import_module ( fullname ) ns [ 'members' ] = _get_members ( mod ) [ p ] ns [ 'functions' ] = _get_members ( mod , typ = 'function' ) [ p ] ns [ 'classes' ] = _get_members ( mod , typ = 'class' ) [ p ] ns [ 'exceptions' ] = _get_members ( mod , typ = 'exception' ) [ p ] ns [ 'data' ] = _get_members ( mod , typ = 'data' ) [ p ] ns [ 'doc' ] = mod . __doc__ return ns | Return the template context of module identified by fullname as a dict |
24,206 | def get_all_for ( self , key ) : if not isinstance ( key , _string_type ) : raise TypeError ( "Key needs to be a string." ) return [ self [ ( idx , key ) ] for idx in _range ( self . __kcount [ key ] ) ] | Returns all values of the given key |
24,207 | def remove_all_for ( self , key ) : if not isinstance ( key , _string_type ) : raise TypeError ( "Key need to be a string." ) for idx in _range ( self . __kcount [ key ] ) : super ( VDFDict , self ) . __delitem__ ( ( idx , key ) ) self . __omap = list ( filter ( lambda x : x [ 1 ] != key , self . __omap ) ) del self . __kcount [ key ] | Removes all items with the given key |
24,208 | def has_duplicates ( self ) : for n in getattr ( self . __kcount , _iter_values ) ( ) : if n != 1 : return True def dict_recurse ( obj ) : for v in getattr ( obj , _iter_values ) ( ) : if isinstance ( v , VDFDict ) and v . has_duplicates ( ) : return True elif isinstance ( v , dict ) : return dict_recurse ( v ) return False return dict_recurse ( self ) | Returns True if the dict contains keys with duplicates . Recurses through any all keys with value that is VDFDict . |
24,209 | def dumps ( obj , pretty = False , escaped = True ) : if not isinstance ( obj , dict ) : raise TypeError ( "Expected data to be an instance of``dict``" ) if not isinstance ( pretty , bool ) : raise TypeError ( "Expected pretty to be of type bool" ) if not isinstance ( escaped , bool ) : raise TypeError ( "Expected escaped to be of type bool" ) return '' . join ( _dump_gen ( obj , pretty , escaped ) ) | Serialize obj to a VDF formatted str . |
24,210 | def binary_dumps ( obj , alt_format = False ) : return b'' . join ( _binary_dump_gen ( obj , alt_format = alt_format ) ) | Serialize obj to a binary VDF formatted bytes . |
24,211 | def vbkv_loads ( s , mapper = dict , merge_duplicate_keys = True ) : if s [ : 4 ] != b'VBKV' : raise ValueError ( "Invalid header" ) checksum , = struct . unpack ( '<i' , s [ 4 : 8 ] ) if checksum != crc32 ( s [ 8 : ] ) : raise ValueError ( "Invalid checksum" ) return binary_loads ( s [ 8 : ] , mapper , merge_duplicate_keys , alt_format = True ) | Deserialize s ( bytes containing a VBKV to a Python object . |
24,212 | def vbkv_dumps ( obj ) : data = b'' . join ( _binary_dump_gen ( obj , alt_format = True ) ) checksum = crc32 ( data ) return b'VBKV' + struct . pack ( '<i' , checksum ) + data | Serialize obj to a VBKV formatted bytes . |
24,213 | def signature_validate ( signature , error = None ) : "is signature a valid sequence of zero or more complete types." error , my_error = _get_error ( error ) result = dbus . dbus_signature_validate ( signature . encode ( ) , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result | is signature a valid sequence of zero or more complete types . |
24,214 | def unparse_signature ( signature ) : "converts a signature from parsed form to string form." signature = parse_signature ( signature ) if not isinstance ( signature , ( tuple , list ) ) : signature = [ signature ] return DBUS . Signature ( "" . join ( t . signature for t in signature ) ) | converts a signature from parsed form to string form . |
24,215 | def signature_validate_single ( signature , error = None ) : "is signature a single valid type." error , my_error = _get_error ( error ) result = dbus . dbus_signature_validate_single ( signature . encode ( ) , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result | is signature a single valid type . |
24,216 | def split_path ( path ) : "convenience routine for splitting a path into a list of components." if isinstance ( path , ( tuple , list ) ) : result = path elif path == "/" : result = [ ] else : if not path . startswith ( "/" ) or path . endswith ( "/" ) : raise DBusError ( DBUS . ERROR_INVALID_ARGS , "invalid path %s" % repr ( path ) ) result = path . split ( "/" ) [ 1 : ] return result | convenience routine for splitting a path into a list of components . |
24,217 | def validate_utf8 ( alleged_utf8 , error = None ) : "alleged_utf8 must be null-terminated bytes." error , my_error = _get_error ( error ) result = dbus . dbus_validate_utf8 ( alleged_utf8 , error . _dbobj ) != 0 my_error . raise_if_set ( ) return result | alleged_utf8 must be null - terminated bytes . |
24,218 | def int_subtype ( i , bits , signed ) : "returns integer i after checking that it fits in the given number of bits." if not isinstance ( i , int ) : raise TypeError ( "value is not int: %s" % repr ( i ) ) if signed : lo = - 1 << bits - 1 hi = ( 1 << bits - 1 ) - 1 else : lo = 0 hi = ( 1 << bits ) - 1 if i < lo or i > hi : raise ValueError ( "%d not in range of %s %d-bit value" % ( i , ( "unsigned" , "signed" ) [ signed ] , bits ) ) return i | returns integer i after checking that it fits in the given number of bits . |
24,219 | def server_id ( self ) : "asks the server at the other end for its unique id." c_result = dbus . dbus_connection_get_server_id ( self . _dbobj ) result = ct . cast ( c_result , ct . c_char_p ) . value . decode ( ) dbus . dbus_free ( c_result ) return result | asks the server at the other end for its unique id . |
24,220 | def send ( self , message ) : "puts a message in the outgoing queue." if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) serial = ct . c_uint ( ) if not dbus . dbus_connection_send ( self . _dbobj , message . _dbobj , ct . byref ( serial ) ) : raise CallFailed ( "dbus_connection_send" ) return serial . value | puts a message in the outgoing queue . |
24,221 | def send_with_reply_and_block ( self , message , timeout = DBUS . TIMEOUT_USE_DEFAULT , error = None ) : "sends a message, blocks the thread until the reply is available, and returns it." if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) error , my_error = _get_error ( error ) reply = dbus . dbus_connection_send_with_reply_and_block ( self . _dbobj , message . _dbobj , _get_timeout ( timeout ) , error . _dbobj ) my_error . raise_if_set ( ) if reply != None : result = Message ( reply ) else : result = None return result | sends a message blocks the thread until the reply is available and returns it . |
24,222 | def list_registered ( self , parent_path ) : "lists all the object paths for which you have ObjectPathVTable handlers registered." child_entries = ct . POINTER ( ct . c_char_p ) ( ) if not dbus . dbus_connection_list_registered ( self . _dbobj , parent_path . encode ( ) , ct . byref ( child_entries ) ) : raise CallFailed ( "dbus_connection_list_registered" ) result = [ ] i = 0 while True : entry = child_entries [ i ] if entry == None : break result . append ( entry . decode ( ) ) i += 1 dbus . dbus_free_string_array ( child_entries ) return result | lists all the object paths for which you have ObjectPathVTable handlers registered . |
24,223 | def bus_get ( celf , type , private , error = None ) : "returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value." error , my_error = _get_error ( error ) result = ( dbus . dbus_bus_get , dbus . dbus_bus_get_private ) [ private ] ( type , error . _dbobj ) my_error . raise_if_set ( ) if result != None : result = celf ( result ) return result | returns a Connection to one of the predefined D - Bus buses ; type is a BUS_xxx value . |
24,224 | def become_monitor ( self , rules ) : "turns the connection into one that can only receive monitoring messages." message = Message . new_method_call ( destination = DBUS . SERVICE_DBUS , path = DBUS . PATH_DBUS , iface = DBUS . INTERFACE_MONITORING , method = "BecomeMonitor" ) message . append_objects ( "asu" , ( list ( format_rule ( rule ) for rule in rules ) ) , 0 ) self . send ( message ) | turns the connection into one that can only receive monitoring messages . |
24,225 | def send ( self , message ) : "alternative to Connection.send_preallocated." if not isinstance ( message , Message ) : raise TypeError ( "message must be a Message" ) assert not self . _sent , "preallocated has already been sent" serial = ct . c_uint ( ) dbus . dbus_connection_send_preallocated ( self . _parent . _dbobj , self . _dbobj , message . _dbobj , ct . byref ( serial ) ) self . _sent = True return serial . value | alternative to Connection . send_preallocated . |
24,226 | def new_error ( self , name , message ) : "creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message." result = dbus . dbus_message_new_error ( self . _dbobj , name . encode ( ) , ( lambda : None , lambda : message . encode ( ) ) [ message != None ] ( ) ) if result == None : raise CallFailed ( "dbus_message_new_error" ) return type ( self ) ( result ) | creates a new DBUS . MESSAGE_TYPE_ERROR message that is a reply to this Message . |
24,227 | def new_method_call ( celf , destination , path , iface , method ) : "creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message." result = dbus . dbus_message_new_method_call ( ( lambda : None , lambda : destination . encode ( ) ) [ destination != None ] ( ) , path . encode ( ) , ( lambda : None , lambda : iface . encode ( ) ) [ iface != None ] ( ) , method . encode ( ) , ) if result == None : raise CallFailed ( "dbus_message_new_method_call" ) return celf ( result ) | creates a new DBUS . MESSAGE_TYPE_METHOD_CALL message . |
24,228 | def new_method_return ( self ) : "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message." result = dbus . dbus_message_new_method_return ( self . _dbobj ) if result == None : raise CallFailed ( "dbus_message_new_method_return" ) return type ( self ) ( result ) | creates a new DBUS . MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message . |
24,229 | def new_signal ( celf , path , iface , name ) : "creates a new DBUS.MESSAGE_TYPE_SIGNAL message." result = dbus . dbus_message_new_signal ( path . encode ( ) , iface . encode ( ) , name . encode ( ) ) if result == None : raise CallFailed ( "dbus_message_new_signal" ) return celf ( result ) | creates a new DBUS . MESSAGE_TYPE_SIGNAL message . |
24,230 | def copy ( self ) : "creates a copy of this Message." result = dbus . dbus_message_copy ( self . _dbobj ) if result == None : raise CallFailed ( "dbus_message_copy" ) return type ( self ) ( result ) | creates a copy of this Message . |
24,231 | def iter_init ( self ) : "creates an iterator for extracting the arguments of the Message." iter = self . ExtractIter ( None ) if dbus . dbus_message_iter_init ( self . _dbobj , iter . _dbobj ) == 0 : iter . _nulliter = True return iter | creates an iterator for extracting the arguments of the Message . |
24,232 | def iter_init_append ( self ) : "creates a Message.AppendIter for appending arguments to the Message." iter = self . AppendIter ( None ) dbus . dbus_message_iter_init_append ( self . _dbobj , iter . _dbobj ) return iter | creates a Message . AppendIter for appending arguments to the Message . |
24,233 | def error_name ( self ) : "the error name for a DBUS.MESSAGE_TYPE_ERROR message." result = dbus . dbus_message_get_error_name ( self . _dbobj ) if result != None : result = result . decode ( ) return result | the error name for a DBUS . MESSAGE_TYPE_ERROR message . |
24,234 | def destination ( self ) : "the bus name that the message is to be sent to." result = dbus . dbus_message_get_destination ( self . _dbobj ) if result != None : result = result . decode ( ) return result | the bus name that the message is to be sent to . |
24,235 | def marshal ( self ) : "serializes this Message into the wire protocol format and returns a bytes object." buf = ct . POINTER ( ct . c_ubyte ) ( ) nr_bytes = ct . c_int ( ) if not dbus . dbus_message_marshal ( self . _dbobj , ct . byref ( buf ) , ct . byref ( nr_bytes ) ) : raise CallFailed ( "dbus_message_marshal" ) result = bytearray ( nr_bytes . value ) ct . memmove ( ct . addressof ( ( ct . c_ubyte * nr_bytes . value ) . from_buffer ( result ) ) , buf , nr_bytes . value ) dbus . dbus_free ( buf ) return result | serializes this Message into the wire protocol format and returns a bytes object . |
24,236 | def cancel ( self ) : "tells libdbus you no longer care about the pending incoming message." dbus . dbus_pending_call_cancel ( self . _dbobj ) if self . _awaiting != None : self . _awaiting . cancel ( ) | tells libdbus you no longer care about the pending incoming message . |
24,237 | def set ( self , name , msg ) : "fills in the error name and message." dbus . dbus_set_error ( self . _dbobj , name . encode ( ) , b"%s" , msg . encode ( ) ) | fills in the error name and message . |
24,238 | def parse ( celf , s ) : "generates an Introspection tree from the given XML string description." def from_string_elts ( celf , attrs , tree ) : elts = dict ( ( k , attrs [ k ] ) for k in attrs ) child_tags = dict ( ( childclass . tag_name , childclass ) for childclass in tuple ( celf . tag_elts . values ( ) ) + ( Introspection . Annotation , ) ) children = [ ] for child in tree : if child . tag not in child_tags : raise KeyError ( "unrecognized tag %s" % child . tag ) childclass = child_tags [ child . tag ] childattrs = { } for attrname in childclass . tag_attrs : if hasattr ( childclass , "tag_attrs_optional" ) and attrname in childclass . tag_attrs_optional : childattrs [ attrname ] = child . attrib . get ( attrname , None ) else : if attrname not in child . attrib : raise ValueError ( "missing %s attribute for %s tag" % ( attrname , child . tag ) ) childattrs [ attrname ] = child . attrib [ attrname ] if hasattr ( childclass , "attr_convert" ) : for attr in childclass . attr_convert : if attr in childattrs : childattrs [ attr ] = childclass . attr_convert [ attr ] ( childattrs [ attr ] ) children . append ( from_string_elts ( childclass , childattrs , child ) ) for child_tag , childclass in tuple ( celf . tag_elts . items ( ) ) + ( ( ) , ( ( "annotations" , Introspection . Annotation ) , ) ) [ tree . tag != "annotation" ] : for child in children : if isinstance ( child , childclass ) : if child_tag not in elts : elts [ child_tag ] = [ ] elts [ child_tag ] . append ( child ) return celf ( ** elts ) tree = XMLElementTree . fromstring ( s ) assert tree . tag == "node" , "root of introspection tree must be <node> tag" return from_string_elts ( Introspection , { } , tree ) | generates an Introspection tree from the given XML string description . |
24,239 | def unparse ( self , indent_step = 4 , max_linelen = 72 ) : "returns an XML string description of this Introspection tree." out = io . StringIO ( ) def to_string ( obj , indent ) : tag_name = obj . tag_name attrs = [ ] for attrname in obj . tag_attrs : attr = getattr ( obj , attrname ) if attr != None : if isinstance ( attr , enum . Enum ) : attr = attr . value elif isinstance ( attr , Type ) : attr = unparse_signature ( attr ) elif not isinstance ( attr , str ) : raise TypeError ( "unexpected attribute type %s for %s" % ( type ( attr ) . __name__ , repr ( attr ) ) ) attrs . append ( "%s=%s" % ( attrname , quote_xml_attr ( attr ) ) ) has_elts = ( sum ( len ( getattr ( obj , attrname ) ) for attrname in tuple ( obj . tag_elts . keys ( ) ) + ( ( ) , ( "annotations" , ) ) [ not isinstance ( obj , Introspection . Annotation ) ] ) != 0 ) out . write ( " " * indent + "<" + tag_name ) if ( max_linelen != None and indent + len ( tag_name ) + sum ( ( len ( s ) + 1 ) for s in attrs ) + 2 + int ( has_elts ) > max_linelen ) : out . write ( "\n" ) for attr in attrs : out . write ( " " * ( indent + indent_step ) ) out . write ( attr ) out . write ( "\n" ) out . write ( " " * indent ) else : for attr in attrs : out . write ( " " ) out . write ( attr ) if not has_elts : out . write ( "/" ) out . write ( ">\n" ) if has_elts : for attrname in sorted ( obj . tag_elts . keys ( ) ) + [ "annotations" ] : for elt in getattr ( obj , attrname ) : to_string ( elt , indent + indent_step ) out . write ( " " * indent + "</" + tag_name + ">\n" ) out . write ( DBUS . INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE ) out . write ( "<node" ) if self . name != None : out . write ( " name=%s" % quote_xml_attr ( self . name ) ) out . write ( ">\n" ) for elt in self . interfaces : to_string ( elt , indent_step ) for elt in self . nodes : to_string ( elt , indent_step ) out . write ( "</node>\n" ) return out . getvalue ( ) | returns an XML string description of this Introspection tree . |
24,240 | def as_error ( self ) : "fills in and returns an Error object that reports the specified error name and message." result = dbus . Error . init ( ) result . set ( self . args [ 0 ] , self . args [ 1 ] ) return result | fills in and returns an Error object that reports the specified error name and message . |
24,241 | async def release_name_async ( self , bus_name , error = None , timeout = DBUS . TIMEOUT_USE_DEFAULT ) : "releases a registered bus name." assert self . loop != None , "no event loop to attach coroutine to" return await self . connection . bus_release_name_async ( bus_name , error = error , timeout = timeout ) | releases a registered bus name . |
24,242 | def DefaultAdapter ( self ) : default_adapter = None for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' not in obj : default_adapter = obj if default_adapter : return dbus . ObjectPath ( default_adapter , variant_level = 1 ) else : raise dbus . exceptions . DBusException ( 'No such adapter.' , name = 'org.bluez.Error.NoSuchAdapter' ) | Retrieve the default adapter |
24,243 | def ListAdapters ( self ) : 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 ) | List all known adapters |
24,244 | def CreateDevice ( self , device_address ) : 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 ) | Create a new device |
24,245 | def AddDevice ( self , adapter_device_name , device_address , alias ) : 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 ) , '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 ) , 'Icon' : dbus . String ( 'audio-headset' , variant_level = 1 ) , } self . AddObject ( path , DEVICE_IFACE , properties , [ ( '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 | Convenience method to add a Bluetooth device |
24,246 | def ListDevices ( self ) : 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 ) | List all known devices |
24,247 | def FindDevice ( self , 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' ) | Find a specific device by bluetooth address . |
24,248 | def Connect ( self ) : 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 ) , ] ) | Connect a device |
24,249 | def Disconnect ( self ) : 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 ) , ] ) | Disconnect a device |
24,250 | def AddEthernetDevice ( self , device_name , iface_name , state ) : 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 | Add an ethernet device . |
24,251 | def AddWiFiDevice ( self , device_name , iface_name , state ) : 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 | Add a WiFi Device . |
24,252 | def AddAccessPoint ( self , dev_path , ap_name , ssid , hw_address , mode , frequency , rate , strength , security ) : 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 | Add an access point to an existing WiFi device . |
24,253 | def AddWiFiConnection ( self , dev_path , connection_name , ssid_name , key_mgmt ) : 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' ) 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' ) 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 | Add an available connection to an existing WiFi device and access point . |
24,254 | def AddActiveConnection ( self , devices , connection_device , specific_object , name , state ) : 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 | Add an active connection to an existing WiFi device . |
24,255 | def RemoveAccessPoint ( self , dev_path , ap_path ) : 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 ) | Remove the specified access point . |
24,256 | def RemoveWifiConnection ( self , dev_path , connection_path ) : 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 ) | Remove the specified WiFi connection . |
24,257 | def RemoveActiveConnection ( self , dev_path , active_connection_path ) : 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 ) | Remove the specified ActiveConnection . |
24,258 | def SettingsAddConnection ( self , connection_settings ) : 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 ( ) 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 ( ) if len ( devices ) > 0 : dev = devices [ 0 ] if dev : activate_connection ( NM , connection_path , dev , connection_path ) return connection_path | Add a connection . |
24,259 | def ConnectionUpdate ( self , settings ) : 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' , ) 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 ( ) if len ( devices ) > 0 : dev = devices [ 0 ] if dev : activate_connection ( NM , connection_path , dev , connection_path ) return connection_path | Update settings on a connection . |
24,260 | def ConnectionDelete ( self ) : connection_path = self . connection_path NM = dbusmock . get_object ( MANAGER_OBJ ) settings_obj = dbusmock . get_object ( SETTINGS_OBJ ) 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 ) if len ( active_connections ) == len ( associated_active_connections ) : self . SetGlobalConnectionState ( NMState . NM_STATE_DISCONNECTED ) 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 ) 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 ] ) connection_obj = dbusmock . get_object ( connection_path ) connection_obj . EmitSignal ( CSETTINGS_IFACE , 'Removed' , '' , [ ] ) self . object_manager_emit_removed ( connection_path ) self . RemoveObject ( connection_path ) | Deletes a connection . |
24,261 | def AddAC ( self , device_name , model_name ) : 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 | Convenience method to add an AC object |
24,262 | def AddDischargingBattery ( self , device_name , model_name , percentage , seconds_to_empty ) : 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 ) , 'State' : dbus . UInt32 ( 2 , variant_level = 1 ) , 'Type' : dbus . UInt32 ( 2 , variant_level = 1 ) , } , [ ] ) self . EmitSignal ( MAIN_IFACE , 'DeviceAdded' , self . device_sig_type , [ path ] ) return path | Convenience method to add a discharging battery object |
24,263 | def SetupDisplayDevice ( self , type , state , percentage , energy , energy_full , energy_rate , time_to_empty , time_to_full , is_present , icon_name , warning_level ) : 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 ) ) | Convenience method to configure DisplayDevice properties |
24,264 | def SetDeviceProperties ( self , object_path , properties ) : device = dbusmock . get_object ( object_path ) for key , value in properties . items ( ) : device . Set ( DEVICE_IFACE , key , value ) if not self . api1 : self . EmitSignal ( MAIN_IFACE , 'DeviceChanged' , 's' , [ object_path ] ) | Convenience method to Set a device s properties . |
24,265 | def AddSeat ( self , 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 | Convenience method to add a seat . |
24,266 | def AddUser ( self , uid , username , active ) : 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 | Convenience method to add a user . |
24,267 | def AddSession ( self , session_id , seat , uid , username , active ) : 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' , '' , '' , '' ) , ] ) 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 ) ) 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 | Convenience method to add a session . |
24,268 | def _set_up_object_manager ( self ) : 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 | Set up this mock object as a D - Bus ObjectManager . |
24,269 | def Get ( self , interface_name , property_name ) : 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' ) | Standard D - Bus API for getting a property value |
24,270 | def GetAll ( self , interface_name , * args , ** kwargs ) : 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' ) | Standard D - Bus API for getting all property values |
24,271 | def Set ( self , interface_name , property_name , value , * args , ** kwargs ) : 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' ) ] ) | Standard D - Bus API for setting a property value |
24,272 | def AddObject ( self , path , interface , properties , methods ) : 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 ) obj . logfile = self . logfile obj . object_manager = self . object_manager obj . is_logfile_owner = False obj . AddMethods ( interface , methods ) objects [ path ] = obj | Add a new D - Bus object to the mock |
24,273 | def RemoveObject ( self , path ) : 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' ) | Remove a D - Bus object from the mock |
24,274 | def Reset ( self ) : for obj_name , obj in objects . items ( ) : if obj_name != self . path : obj . remove_from_connection ( ) objects . clear ( ) 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 | Reset the mock object state . |
24,275 | def AddMethod ( self , interface , name , in_sig , out_sig , code ) : if not interface : interface = self . interface n_args = len ( dbus . Signature ( in_sig ) ) method = lambda self , * args , ** kwargs : DBusMockObject . mock_method ( self , interface , name , in_sig , * args , ** kwargs ) 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 ) ] if interface == self . interface : setattr ( self . __class__ , name , dbus_method ) self . methods . setdefault ( interface , { } ) [ str ( name ) ] = ( in_sig , out_sig , code , dbus_method ) | Add a method to this object |
24,276 | def AddMethods ( self , interface , methods ) : for method in methods : self . AddMethod ( interface , * method ) | Add several methods to this object |
24,277 | def AddProperty ( self , interface , name , 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 : pass if not ( isinstance ( value , dbus . Dictionary ) or isinstance ( value , dbus . Array ) ) : value = copy . copy ( value ) self . props . setdefault ( interface , { } ) [ name ] = value | Add property to this object |
24,278 | def AddProperties ( self , interface , properties ) : for k , v in properties . items ( ) : self . AddProperty ( interface , k , v ) | Add several properties to this object |
24,279 | def AddTemplate ( self , template , parameters ) : 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 hasattr ( module , 'IS_OBJECT_MANAGER' ) and module . IS_OBJECT_MANAGER : self . _set_up_object_manager ( ) 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 ) ) : 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 ) self . _template = template self . _template_parameters = parameters | Load a template into the mock . |
24,280 | def EmitSignal ( self , interface , name , signature , args ) : if not interface : interface = self . interface 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 ) | Emit a signal from the object . |
24,281 | 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 . |
24,282 | def mock_method ( self , interface , dbus_method , in_signature , * args , ** kwargs ) : 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 ) 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' ] | Master mock method . |
24,283 | def format_args ( self , args ) : 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 ) : 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 + '}' return repr ( a ) s = '' for a in args : if s : s += ' ' s += format_arg ( a ) if s : s = ' ' + s return s | Format a D - Bus argument tuple into an appropriate logging string . |
24,284 | def log ( self , msg ) : if self . logfile : fd = self . logfile . fileno ( ) else : fd = sys . stdout . fileno ( ) os . write ( fd , ( '%.3f %s\n' % ( time . time ( ) , msg ) ) . encode ( 'UTF-8' ) ) | Log a message prefixed with a timestamp . |
24,285 | def Introspect ( self , object_path , connection ) : 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 : 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 : continue elem = ElementTree . Element ( "property" , { "name" : prop , "type" : dbus . lowlevel . Message . guess_signature ( val ) , "access" : "readwrite" } ) interface . append ( elem ) xml = ElementTree . tostring ( tree , encoding = 'utf8' , method = 'xml' ) . decode ( 'utf8' ) self . _dbus_class_table [ cls ] = orig_interfaces return xml | Return XML description of this object s interfaces methods and signals . |
24,286 | def CreateSession ( self , destination , args ) : 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' ) 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 , [ ( 'GetCapabilities' , '' , 's' , '' ) , ] ) session = mockobject . objects [ path ] session . AddMethods ( PHONEBOOK_ACCESS_IFACE , [ ( 'Select' , 'ss' , '' , '' ) , ( 'List' , 'a{sv}' , 'a(ss)' , 'ret = dbus.Array(signature="(ss)")' ) , ( 'ListFilterFields' , '' , 'as' , 'ret = dbus.Array(signature="(s)")' ) , ( 'PullAll' , 'sa{sv}' , 'sa{sv}' , PullAll ) , ( 'GetSize' , '' , 'q' , 'ret = 0' ) , ] ) manager = mockobject . objects [ '/' ] manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesAdded' , 'oa{sa{sv}}' , [ dbus . ObjectPath ( path ) , { SESSION_IFACE : properties } , ] ) return path | OBEX method to create a new transfer session . |
24,287 | def RemoveSession ( self , session_path ) : manager = mockobject . objects [ '/' ] 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 ] , ] ) self . RemoveObject ( session_path ) manager . EmitSignal ( OBJECT_MANAGER_IFACE , 'InterfacesRemoved' , 'oas' , [ dbus . ObjectPath ( session_path ) , [ SESSION_IFACE , PHONEBOOK_ACCESS_IFACE ] , ] ) | OBEX method to remove an existing transfer session . |
24,288 | def PullAll ( self , target_file , filters ) : 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 ) 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 , props , [ ( 'Cancel' , '' , '' , '' ) , ] ) 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 } , ] ) manager . EmitSignal ( OBEX_MOCK_IFACE , 'TransferCreated' , 'sa{sv}s' , [ transfer_path , filters , filename ] ) return ( transfer_path , props ) | OBEX method to start a pull transfer of a phone book . |
24,289 | def UpdateStatus ( self , is_complete ) : 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 ) , } , [ ] , ] ) | Mock method to update the transfer status . |
24,290 | def AddModem ( self , name , properties ) : 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.ConnectionManager' , ] , '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 | Convenience method to add a modem |
24,291 | def add_voice_call_api ( mock ) : mock . AddProperty ( 'org.ofono.VoiceCallManager' , 'EmergencyNumbers' , [ '911' , '13373' ] ) mock . calls = [ ] 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]' ) ] ) | Add org . ofono . VoiceCallManager API to a mock |
24,292 | def add_netreg_api ( mock ) : 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' , '' , '' , '' ) , ] ) 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 ) ) , ] ) | Add org . ofono . NetworkRegistration API to a mock |
24,293 | def add_simmanager_api ( self , 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' , '' , '' ) , ] ) | Add org . ofono . SimManager API to a mock |
24,294 | def add_connectionmanager_api ( 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([])' ) , ] ) | Add org . ofono . ConnectionManager API to a mock |
24,295 | def BlockDevice ( self , adapter_device_name , device_address ) : 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 ) , } , [ ] , ] ) | Convenience method to mark an existing device as blocked . |
24,296 | def create ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . created ( instance ) | Create an instance of a model . |
24,297 | def patch ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . updated ( instance ) | Partially update a model instance . |
24,298 | def put ( self , instance , errors ) : if errors : return self . errors ( errors ) return self . updated ( instance ) | Update a model instance . |
24,299 | 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 | Configure the Jinja environment and template loader . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.