def test_delete(self): connection = Connection(MemoryStorage()) pd = PersistentDict((x, True) for x in range(10)) connection.root['x'] = pd connection.commit() del pd[1] assert pd._p_is_unsaved()
def test_copy(self): connection = Connection(MemoryStorage()) pd = PersistentDict((x, True) for x in range(10)) pd2 = pd.copy() assert pd == pd2 pd[1] = 34 assert pd != pd2
def delete(self): connection = Connection(MemoryStorage()) pd = PersistentDict((x, True) for x in range(10)) connection.root['x'] = pd connection.commit() del pd[1] assert pd._p_is_unsaved()
def test_iter(self): pd = PersistentDict((x, True) for x in range(10)) if hasattr({}, 'iteritems'): assert list(pd.iteritems()) == list(zip(pd.iterkeys(), pd.itervalues())) else: assert list(pd.items()) == list(zip(pd.keys(), pd.values())) assert list(pd.items()) == list(zip(pd.keys(), pd.values()))
def copy(self): connection = Connection(MemoryStorage()) pd = PersistentDict((x, True) for x in range(10)) pd2 = pd.copy() assert pd == pd2 pd[1] = 34 assert pd != pd2
def __init__(self, name): super(NetworkDevice, self).__init__() self.name = self.hostname = str(name) self.INTERFACEMAP = PersistentDict() self._interfaces = PersistentDict() self.data_interfaces = PersistentList() self.admin_interface = None self.initialize() # subclass interface
def __init__(self): self._conn = Connection(FileStorage(PROJECTS_DATA_PATH)) self._data = self._conn.get_root() if not len(self._data.keys()): self._data["Default"] = PersistentDict( autocomplete=PersistentDict()) self.sync()
def __init__(self, subnet=None, subnetname=None): super(Network, self).__init__() self.name = None self.mask = None self._subnets = PersistentList() self.nodes = PersistentDict() # actually, Interface objects self._gatways = PersistentList() if subnet: self.add_subnet(subnet, subnetname)
class CUser(Persistent): def __init__(self, jid): self.jid = jid self.items_pending = PersistentList() # [CItem, ...] self.config = PersistentDict() self.feeds = PersistentDict() # {CFeed: send first notification?} def __len__(self): return len(self.feeds) def subs_feed(self, feeditem, sendFirstNoti=False): """Add a feed item in 'feeds' dict.""" if not self.has_feed(feeditem): self.feeds[feeditem] = sendFirstNoti return True return False def unsubs_feed(self, feeditem): """Delete a feed item from 'feeds' dict.""" if self.has_feed(feeditem): del self.feeds[feeditem] return True return False def has_feed(self, feeditem): """Search the url feed in 'feeds' dict""" for x in self.feeds.keys(): if x.url == feeditem.url: return True return False def enableNotifications(self, feeditem): self.feeds[feeditem] = True def getNotification(self, feeditem): return self.feeds[feeditem] def clear_items(self): self.items_pending = PersistentList() def setup(self, action, mode): self.config[action] = mode return True def getConfig(self, key): return self.config.get(key)
class categoricalIndex(Persistent): def __init__(self, name, low, high, legalValues): self.name = name self.data = PersistentDict() for l in legalValues: self.data[l] = PersistentSet() def __getitem__(self, keys): if isinstance(keys,slice): raise Exception('A categorical index cannot be sliced.') elif isinstance(keys,set): keys = list(keys) elif not isinstance(keys,list): keys = [keys] # start with the smallest set smallestSize=sys.maxint smallestKey=None for k in keys: if len(self.data[k]) < smallestSize: smallestSize = len(self.data[k]) smallestKey = k if smallestKey == None: return set() results = set(self.data[smallestKey]) for k in keys: if k == smallestKey: continue results.intersection_update(self.data[k]) return results def __setitem__(self, key, value): if not self.data.has_key(key): raise Exception('Unknown categorical key: %s' % key) else: self.data[key].add(value) def count(self, keys): if isinstance(keys,slice): raise Exception('A categorical index cannot be sliced.') elif isinstance(keys,set): keys = list(keys) elif not isinstance(keys,list): keys = [keys] count = 0 for k in keys: count += len(self.data[k]) return count def has_key(self, key): return self.data.has_key(key)
def setdefault(self): pd = PersistentDict() assert pd.setdefault('1', []) == [] assert pd['1'] == [] pd.setdefault('1', 1).append(1) assert pd['1'] == [1] pd.setdefault('1', []) assert pd['1'] == [1] pd.setdefault('1', 1).append(2) assert pd['1'] == [1, 2]
class Note(Persistent, MutableMapping): interface.implements(INote) def __init__(self, doc, id, props={}): self.document = doc self.id = id self._props = PersistentDict(props) self._children = PersistentList() def __setitem__(self, key, value): if value is None: del self._props[key] else: self._props[key] = value for subscriber in self.document.subscribers: if hasattr(subscriber, 'prop_change'): subscriber.prop_change(self, key, value) def __getitem__(self, key): return self._props[key] def __delitem__(self, key): raise NotImplementedError def keys(self): return self._props.keys() def children_ids(self): for child_id in self._children: yield child_id def children(self): for child_id in self._children: yield self.document.get_note(child_id)
def __init__(self): sessions = PersistentDict() SessionManager.__init__( self, session_class=PersistentSession, session_mapping=sessions, )
class PersistentOrderedDict(Persistent): ''' This class implements the same interface as the `collections.OrderedDict` class from the standard library, but uses `persistent` data types for Durus support. ''' def __init__(self, items=None): self.key_index = PersistentList() self.data = PersistentDict() if items: for k, v in items: self[k] = v def keys(self): return self.key_index[:] def __setitem__(self, k, v): if k not in self.data: self.key_index.append(k) self.data[k] = v def items(self): return [(k, v) for k, v in self.iteritems()] def iteritems(self): for k in self.key_index: yield k, self.data[k] def values(self): return [v for k, v in self.iteritems()] def get(self, key): return self.data.get(key) def __delitem__(self, key): del self.data[key] i = self.key_index.index(key) del self.key_index[i] def __getitem__(self, key): return self.data[key] def move_to_end(self, key, last=True): assert(key in self) items = [] for k, v in self.items(): if k != key: items.append((k, v)) del self[k] if last: items.append((key, self[key])) del self[key] for k, v in items: self[k] = v def __contains__(self, key): return key in self.data def __len__(self): return len(self.key_index)
def test_setdefault(self): pd = PersistentDict() assert pd.setdefault('1', []) == [] assert pd['1'] == [] pd.setdefault('1', 1).append(1) assert pd['1'] == [1] pd.setdefault('1', []) assert pd['1'] == [1] pd.setdefault('1', 1).append(2) assert pd['1'] == [1, 2]
def setdefault(self): pd = PersistentDict() assert pd.setdefault("1", []) == [] assert pd["1"] == [] pd.setdefault("1", 1).append(1) assert pd["1"] == [1] pd.setdefault("1", []) assert pd["1"] == [1] pd.setdefault("1", 1).append(2) assert pd["1"] == [1, 2]
def __init__(self): # durus file storage self.conndurus = Connection(FileStorage(CONFIG['durus_file'])) root = self.conndurus.get_root() if not root.get('users'): root['users'] = PersistentDict() # {user jid: CUser} if not root.get('feeds'): root['feeds'] = CFeeds() self.data = root['users'] self.feeds = root['feeds'] self.save()
class CFeeds(Persistent): def __init__(self): self.data = PersistentDict() # {url feed: CFeed} def __getitem__(self, key): return self.data[key] def __setitem__(self, key, item): self.data[key] = item def __delitem__(self, key): self._p_note_change() del self.data[key] def get(self, key): return self.data.get(key) def keys(self): return self.data.keys() def values(self): return self.data.values()
def makeChapterCommit(self, currentdate, book, chapterDict): dateKey = () #print 'Book name: ',book if isinstance(currentdate, tuple): dateKey = currentdate if isinstance(currentdate, datetime.date): dateKey = tuple(currentdate.strftime('%Y-%m-%d').split('-')) #print 'Datekey : ',dateKey root = self.con.get_root() if not book in root: root[book] = PersistentDict() self.con.commit() root[book][dateKey] = chapterDict self.con.commit()
def __init__(self, devname, address=None, name="", iftype=0, physaddress=None, ifindex=None): super(Interface, self).__init__() self.address = address self.devname = devname # a device name (e.g. "eth0") self.hostname = name # a "friendly" name (e.g. "Ethernet 1") or DNS name self.iftype = iftype # type of interface self.network = None # network object this interface is attached to self.owner = None # the owner (device) this interface belongs to self.physaddress = physaddress self.ifindex = ifindex self._subinterfaces = PersistentDict()
def __init__(self): self.data = PersistentDict() # {url feed: CFeed}
def add(self, name): """Add new project""" self._data[unicode(name)] = PersistentDict( autocomplete=PersistentDict()) self.sync()
def update(self): pd = PersistentDict() pd.update() raises(TypeError, pd.update, {}, {}) assert not list(pd.items()) pd.update(a=1) assert list(pd.items()) == [('a', 1)] pd = PersistentDict() pd.update(dict(b=2), a=1) assert len(list(pd.items())) == 2 assert pd['b'] == 2 assert pd['a'] == 1 pd = PersistentDict() pd.update([('b', 2)], a=1) assert len(pd.items()) == 2 assert pd['b'] == 2 assert pd['a'] == 1 pd2 = PersistentDict((x, True) for x in range(10)) pd.update(pd2) class keyed(object): data = dict(a=3) keys = data.keys __setitem__ = data.__setitem__ __getitem__ = data.__getitem__ pd.update(keyed()) assert pd['a'] == 3
def has_key(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.has_key(2) assert not pd.has_key(-1)
def get(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.get(2) == True assert pd.get(-1) == None assert pd.get(-1, 5) == 5
def __init__(self, jid): self.jid = jid self.items_pending = PersistentList() # [CItem, ...] self.config = PersistentDict() self.feeds = PersistentDict() # {CFeed: send first notification?}
class IPAssignments(OwnedPersistent): def __init__(self, name, *args): super(IPAssignments, self).__init__() self.name = name self._store = PersistentDict() for arg in args: self.add(arg) def __contains__(self, address): if isinstance(address, str): address = ipv4.IPv4(address) for ip in self._store.iterkeys(): if address == ip: return True return False def __str__(self): s = [] for address, disp in self._store.items(): s.append("%s is %s\n" % (address.cidr(), IF(disp, "used.", "free."))) s.sort() return "".join(s) def __repr__(self): return "%s(%r, ...)" % (self.__class__.__name__, self.name) def __iter__(self): return self._store.iteritems() def get(self, ip): if isinstance(ip, str): ip = ipv4.IPv4(ip) return ip, self._store.get(ip) def add(self, arg): if isinstance(arg, str): arg = ipv4.IPv4(arg) if isinstance(arg, ipv4.IPRange): for ip in arg: self._store[ip] = False elif isinstance(arg, ipv4.IPv4): for ip in arg[1:-1]: self._store[ip] = False else: raise ValueError, "must be IP address or Range." # IPv4 used as a VLSM range here def add_net(self, ipnet): if isinstance(ipnet, str): ipnet = ipv4.IPv4(ipnet) if isinstance(ipnet, ipv4.IPv4): for ip in ipnet[1:-1]: self._store[ip] = False else: raise ValueError, "must add IPv4 network" add_network = add_net def add_range(self, addr1, addr2): rng = ipv4.IPRange(addr1, addr2) for ip in rng: self._store[ip] = False def remove(self, arg): if isinstance(arg, str): arg = ipv4.IPv4(arg) if isinstance(arg, ipv4.IPRange): for ip in arg: try: del self._store[ip] except KeyError: pass elif isinstance(arg, ipv4.IPv4): for ip in arg[1:-1]: try: del self._store[ip] except KeyError: pass else: raise ValueError, "must be IP address or Range." # removes the given range of IP. Useful for making "holes" def remove_range(self, addr1, addr2): rng = ipv4.IPRange(addr1, addr2) for ip in rng: try: del self._store[ip] except KeyError: pass def remove_net(self, ipnet): if isinstance(ipnet, str): ipnet = ipv4.IPv4(ipnet) if isinstance(ipnet, ipv4.IPv4): for ip in ipnet[1:-1]: try: del self._store[ip] except KeyError: pass else: raise ValueError, "must add IPv4 network" def allocate(self, address): if isinstance(address, str): address = ipv4.IPv4(address) self._store[address] = True def deallocate(self, address): if isinstance(address, str): address = ipv4.IPv4(address) try: self._store[address] = False except KeyError: pass def reset(self): """deallocate all addressess""" for addr in self._store.iterkeys(): self._store[addr] = False def clear(self): """remove all addresses.""" self._store.clear() # find next available IP address. Raise ValueError if exhausted. # If Network is supplied, only pick an IP in that network. def get_next(self, network=None): for addr, allocated in self._store.items(): if allocated: continue if network is not None: if addr in network: self._store[addr] = True return addr else: continue else: self._store[addr] = True return addr raise ValueError, "No more addresses availiable in the assignment"
def __init__(self, items=None): self.key_index = PersistentList() self.data = PersistentDict() if items: for k, v in items: self[k] = v
def startup(self): log.info("We're running on {}".format(host_name)) log.info("Loading settings from {}".format(SETTINGS_FILE)) load_settings(settings) tzinfo = pytz.timezone(settings['tz_name']) log.info("Time zone is {}".format(tzinfo)) if not os.path.isfile(settings['user_id']): pem_cert, pem_key = generate_selfsigned_cert(host_name) with open('ca.crt', 'wb') as f: f.write(pem_cert) with open('ca.key', 'wb') as f: f.write(pem_key) else: pem_cert = open('ca.crt', 'rb').read() cert = x509.load_pem_x509_certificate(pem_cert, default_backend()) log.info("User CN={}".format( cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME)[0].value)) #@dataclass class M(Persistent, object): #created_at: datetime = None created_at = None # #class Meta(M): # pass #class Data(M): # def __init__(self, *args, **kwargs): # self.created_at = tzinfo.localize(datetime.now()) # self.modified_at = self.created_at def open_db(path_to_msf): connection = Connection(FileStorage(path_to_msf)) return connection #log.info('root: {}'.format(root.data)) db = open_db(settings['db_file']) log.info('{}'.format(db)) db_root = db.get_root() #log.info('{}'.format(len(db_root))) if len(db_root) == 0: # empty MSF #about = {} #about = dict({'created_at':tzinfo.localize(datetime.now()).isoformat()}) about = M(tzinfo.localize(datetime.now())) #about.created_at = log.info('{}'.format(about)) #about.update({'created_by_cert' : cert.public_bytes(serialization.Encoding.PEM)}) about.created_by_cert = cert.public_bytes( serialization.Encoding.PEM) #about.update({'uuid' : uuid4()}) about.uuid = uuid4() #about.update({"title" : 'About'}) about.title = 'About' #about.update({"title" : 'About'}) about.body = ''' About this mouse ''' db_root['about'] = about from durus.persistent_list import PersistentList from durus.persistent_dict import PersistentDict acl = PersistentDict() acl['default'] = None db_root['acl'] = acl db.commit() else: acl = db_root['acl'] #log.inf('{}'.format()) log.info('about: {}'.format(db_root['about'])) #start_server() log.info('Startng server . . . ') endpoint = TCP4ServerEndpoint(reactor, 5999) m_factory = MFactory() endpoint.listen(m_factory) def gotProtocol(p): """The callback to start the protocol exchange. We let connecting nodes start the hello handshake""" p.send_hello() point = TCP4ClientEndpoint(reactor, "localhost", 5999) d = connectProtocol(point, m_factory) d.addCallback(gotProtocol) # Create a main window with a name matching the app self.main_window = toga.MainWindow(title=self.name) # Create a main content box #main_box = toga.Box() # Add the content on the main window #self.main_window.content = main_box # Label to show responses. self.label = toga.Label('Ready.', style=Pack(padding_top=20)) self.workspace = toga.DetailedList(data=[{ 'icon': toga.Icon.TIBERIUS_ICON, 'title': "Misbehavin'", 'subtitle': '0' }], style=Pack(flex=1)) # Buttons btn_style = Pack(flex=1) btn_info = toga.Button('Info', on_press=self.action_info_dialog, style=btn_style) btn_question = toga.Button('Question', on_press=self.action_question_dialog, style=btn_style) btn_open = toga.Button('Open File', on_press=self.action_open_file_dialog, style=btn_style) btn_save = toga.Button('Save File', on_press=self.action_save_file_dialog, style=btn_style) btn_select = toga.Button('Select Folder', on_press=self.action_select_folder_dialog, style=btn_style) dialog_btn_box = toga.Box( children=[btn_info, btn_question, btn_open, btn_save, btn_select], style=Pack(direction=ROW)) # Dialog Buttons btn_do_stuff = toga.Button('Do stuff', on_press=self.do_stuff, style=btn_style) btn_clear = toga.Button('Clear', on_press=self.do_clear, style=btn_style) btn_box = toga.Box(children=[btn_do_stuff, btn_clear], style=Pack(direction=ROW)) # Outermost box outer_box = toga.Box( #children=[btn_box, dialog_btn_box, self.label], children=[self.workspace, self.label], style=Pack( #flex=1, direction=COLUMN #padding=10 )) # Add the content on the main window self.main_window.content = outer_box # Show the main window self.main_window.show()
def test_fromkeys(self): x = PersistentDict.fromkeys(dict(a=2), value=4) assert isinstance(x, PersistentDict) assert dict(x) == dict(a=4)
class NetworkDevice(OwnedPersistent): """NetworkDevice([name]) This object is a persistent store object that represents a networked device as a collection of interfaces. It has a name that is used for string conversion. """ # the following (class-level attributes) become the default values for # various methods. Set an instance attribute of the same name to override # these values. user = None # default user to log in as password = None # default password for default user prompt = "# " # default CLI prompt for interactive sessions accessmethod = "ssh" # default. Possible are: ssh, console, serial, telnet, snmp initialaccessmethod = "console" # how to access for initial (before accessmethod is available) access console_server = (None, None) # host and TCP port used to connect to device serial console power_controller = (None, None) # APC host and outlet number used to control power monitor_port = (None, None) # may contain tuple of (device, interface) of an etherswitch to monitor domain = None # default DNS domain of the device nameservers = [] # default DNS server list to be configured ntpserver = None # default NTP server to configure sysObjectID = None # The SNMP object identifier for a (sub)class of device. snmpRoCommunity = "public" # default RO SNMP community to use snmpRwCommunity = "private" # default RW SNMP community to use admin_interface = "eth0" # interface on administrative network. This interface is "invisible" to device methods. data_interfaces = ["eth0"] # the "business" interfaces that are in use. def __init__(self, name): super(NetworkDevice, self).__init__() self.name = self.hostname = str(name) self.INTERFACEMAP = PersistentDict() self._interfaces = PersistentDict() self.data_interfaces = PersistentList() self.admin_interface = None self.initialize() # subclass interface # a non-persistent dictionary to cache transient attributes from a device def _get_cache(self): try: return self.__dict__["_cache_"] except KeyError: import dictlib c = dictlib.AttrDict() self.__dict__["_cache_"] = c return c _cache = property(_get_cache) def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.name) def __str__(self): return self.name # don't change this or you will break a lot of things def initialize(self): pass def interface_alias(self, name, alias=None): """sets (or removes) an alias name for an interface.""" if alias is not None: self.INTERFACEMAP[str(alias)] = str(name) else: del self.INTERFACEMAP[str(name)] def set_hostname(self, name): """Sets the hostname (and alias "name" attribute).""" self.name = self.hostname = str(name) def add_interface(self, devname, address=None, mask=None, hostname=None, linktype=BROADCAST): """add_interface(devname, [address, [mask, [hostname, [linktype]]]]) Adds a new network interface to the device. Supply its interface name, and its address. """ devname = self.INTERFACEMAP.get(devname, devname) if self._interfaces.has_key(devname): return self._interfaces[devname].update(address, mask, hostname, linktype) if not address: try: address=ipv4.IPv4(self.hostname) except: address = None if not hostname: if address: try: hostname = address.hostname except: hostname = "%s_%s" % (self.hostname, devname) else: hostname = "%s_%s" % (self.hostname, devname) intf = Interface(devname, address, mask, hostname, linktype) self._interfaces[devname] = intf intf.owner = self self._p_note_change() return intf def update_interface(self, devname, address=None, mask=None, hostname=None, linktype=BROADCAST): devname = self.INTERFACEMAP.get(devname, devname) return self._interfaces[devname].update(address, mask, hostname, linktype) def get_interface(self, devname): """Return an Interface object from the index. The index value may be an integer or a name. """ devname = self.INTERFACEMAP.get(devname, devname) return self._interfaces[devname] def set_interface(self, intf): if isinstance(intf, Interface): self._interfaces[intf.device] = intf else: raise ValueError, "interfaces: value must be Interface object." def del_interface(self, devname): """Delete an interface given the name, or index as an integer.""" devname = self.INTERFACEMAP.get(devname, devname) intf = self._interfaces[devname] del self._interfaces[devname] intf.owner = None def get_interfaces(self): return self._interfaces.copy() def del_interfaces(self): self._interfaces.clear() interfaces = property(get_interfaces, None, del_interfaces, "device interfaces") # return a list of IPv4 addresses used by the data interfaces of this device. def _get_ipv4(self): rv = [] for name in self.data_interfaces: intf = self._interfaces[name] rv.append(intf.address) return rv addresses = property(_get_ipv4) def get_address(self, ifname): return self._interfaces[ifname].address def reset(self): self._interfaces.clear() self.set_hostname("") self.disown() def connect(self, ifname, network): """Connect this device to a network object (the supplied parameter).""" assert isinstance(network, Network), "network parameter must be a Network object." ifname = self.INTERFACEMAP.get(ifname, ifname) try: intf = self._interfaces[ifname] except KeyError: intf = self.add_interface(ifname) intf.connect(network) def disconnect(self, ifname): """disconnect the named interface from its network.""" ifname = self.INTERFACEMAP.get(ifname, ifname) intf = self._interfaces[ifname] intf.disconnect() def connections(self, network=None): """Return a list of interfaces connected to the given network object, or all connections if no network provided.""" rv = [] for intf in self._interfaces.values(): if network is None and intf.network is not None: rv.append(intf) elif intf.network is network: rv.append(intf) return rv
def no_arbitrary_attributes(self): pd = PersistentDict() raises(AttributeError, setattr, pd, 'bogus', 1)
def contains(self): pd = PersistentDict((x, True) for x in range(10)) assert 2 in pd assert -1 not in pd
def test_clear(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.has_key(2) pd.clear() assert not pd.has_key(2) assert list(pd.keys()) == []
def clear(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.has_key(2) pd.clear() assert not pd.has_key(2) assert list(pd.keys()) == []
def test_get(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.get(2) == True assert pd.get(-1) == None assert pd.get(-1, 5) == 5
def cmp(self): pd = PersistentDict((x, True) for x in range(10)) pd2 = PersistentDict((x, True) for x in range(10)) assert pd == pd2 assert dict(pd) == dict(pd2)
def __init__(self, name, low, high, legalValues): self.name = name self.data = PersistentDict() for l in legalValues: self.data[l] = PersistentSet()
def iter(self): pd = PersistentDict((x, True) for x in range(10)) assert list(pd.iteritems()) == list(zip(pd.iterkeys(), pd.itervalues())) assert list(pd.items()) == list(zip(pd.keys(), pd.values()))
def nonzero(self): pd = PersistentDict() assert not pd pd['1'] = 1 assert pd
def __init__(self, doc, id, props={}): self.document = doc self.id = id self._props = PersistentDict(props) self._children = PersistentList()
class Network(OwnedPersistent): _netnode_template = """| +---------------------------------------------+ |--| %-20.20s (%-20.20s) | | +---------------------------------------------+""" # don't touch this def __init__(self, subnet=None, subnetname=None): super(Network, self).__init__() self.name = None self.mask = None self._subnets = PersistentList() self.nodes = PersistentDict() # actually, Interface objects self._gatways = PersistentList() if subnet: self.add_subnet(subnet, subnetname) def __str__(self): s = ["-"*70] sbl = [] sn = [] for subnet, name in self._subnets: sbl.append("%20s" % (subnet,)) sn.append("%20s" % (name,)) s.append(" | ".join(sbl)) s.append(" | ".join(sn)) s.append("-"*70) for node in self.nodes.values(): s.append(self._netnode_template % (node.owner.name, node.owner.__class__.__name__)) return "\n".join(s) def __repr__(self): try: addr, name = self._subnets[0] return "%s(%r, %r)" % (self.__class__.__name__, addr, name) except IndexError: return "%s()" % (self.__class__.__name__) def __getitem__(self, idx): return self._subnets[idx] def __iter__(self): return iter(self._subnets) def add_interface(self, interface): self.nodes[interface.hostname] = interface interface.network = self def del_interface(self, interface): del self.nodes[interface.hostname] interface.network = None def get_interfaces(self): return self.nodes.copy() def get_node(self, hostname): intf = self.nodes[str(hostname)] return intf.owner def add_node(self, netdev): for intf in netdev.interfaces.values(): for subnet, name in self._subnets: if intf.address in subnet: self.nodes[intf.name] = intf intf.network = self return def add_subnet(self, addr, name=None): sn = ipv4.IPv4(addr) sn.host = 0 name = name or sn.cidr() if not self._subnets: # first subnet sets the name and mask self.name = name self.mask = sn.mask self._subnets.append((sn, name)) self._p_note_change() return sn def remove_subnet(self, name): for i, (sn, netname) in enumerate(self._subnets[:]): if netname == name: del self._subnets[i] def get_subnets(self): return list(self._subnets) subnets = property(get_subnets) def __contains__(self, address): if isinstance(address, str): address = ipv4.IPv4(address) for subnet, name in self._subnets: if address in subnet: return True return False
def __init__(self, name, *args): super(IPAssignments, self).__init__() self.name = name self._store = PersistentDict() for arg in args: self.add(arg)
def iter(self): pd = PersistentDict() assert list(pd) == [] pd[1] = 2 assert list(pd) == [1]
def test_pops(self): pd = PersistentDict((x, True) for x in range(10)) pd.pop(3) assert 3 not in pd assert type(pd.popitem()) is tuple
def insert_again(self): pd = PersistentDict() pd[1] = 2 pd[1] = 3 assert pd[1] == 3 assert list(pd) == [1], list(pd)
def pops(self): pd = PersistentDict((x, True) for x in range(10)) pd.pop(3) assert 3 not in pd assert type(pd.popitem()) is tuple
def test_has_key(self): pd = PersistentDict((x, True) for x in range(10)) assert pd.has_key(2) assert not pd.has_key(-1)
def fromkeys(self): x = PersistentDict.fromkeys(dict(a=2), value=4) assert isinstance(x, PersistentDict) assert dict(x) == dict(a=4)
def test_update(self): pd = PersistentDict() pd.update() raises(TypeError, pd.update, {}, {}) assert not list(pd.items()) pd.update(a=1) assert list(pd.items()) == [('a', 1)] pd = PersistentDict() pd.update(dict(b=2), a=1) assert len(list(pd.items())) == 2 assert pd['b'] == 2 assert pd['a'] == 1 pd = PersistentDict() pd.update([('b', 2)], a=1) assert len(pd.items()) == 2 assert pd['b'] == 2 assert pd['a'] == 1 pd2 = PersistentDict((x, True) for x in range(10)) pd.update(pd2) class keyed(object): data = dict(a=3) keys = data.keys __setitem__ = data.__setitem__ __getitem__ = data.__getitem__ pd.update(keyed()) assert pd['a'] == 3