Beispiel #1
0
 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()))
Beispiel #2
0
 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
Beispiel #3
0
    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
Beispiel #4
0
 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()))
Beispiel #5
0
 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()))
Beispiel #6
0
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"
Beispiel #7
0
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"