vxlan unit test - minor fixes
[vpp.git] / test / util.py
1 import socket
2 import sys
3 from abc import abstractmethod, ABCMeta
4 from cStringIO import StringIO
5
6
7 def ppp(headline, packet):
8     """ Return string containing the output of scapy packet.show() call. """
9     o = StringIO()
10     old_stdout = sys.stdout
11     sys.stdout = o
12     print(headline)
13     packet.show()
14     sys.stdout = old_stdout
15     return o.getvalue()
16
17
18 def ppc(headline, capture, limit=10):
19     """ Return string containing ppp() printout for a capture.
20
21     :param headline: printed as first line of output
22     :param capture: packets to print
23     :param limit: limit the print to # of packets
24     """
25     if not capture:
26         return headline
27     tail = ""
28     if limit < len(capture):
29         tail = "\nPrint limit reached, %s out of %s packets printed" % (
30             len(capture), limit)
31         limit = len(capture)
32     body = "".join([ppp("Packet #%s:" % count, p)
33                     for count, p in zip(range(0, limit), capture)])
34     return "%s\n%s%s" % (headline, body, tail)
35
36
37 def ip4_range(ip4, s, e):
38     tmp = ip4.rsplit('.', 1)[0]
39     return ("%s.%d" % (tmp, i) for i in range(s, e))
40
41
42 def ip4n_range(ip4n, s, e):
43     ip4 = socket.inet_ntop(socket.AF_INET, ip4n)
44     return (socket.inet_pton(socket.AF_INET, ip) for ip in ip4_range(ip4, s, e))
45
46
47 class NumericConstant(object):
48     __metaclass__ = ABCMeta
49
50     desc_dict = {}
51
52     @abstractmethod
53     def __init__(self, value):
54         self._value = value
55
56     def __int__(self):
57         return self._value
58
59     def __long__(self):
60         return self._value
61
62     def __str__(self):
63         if self._value in self.desc_dict:
64             return self.desc_dict[self._value]
65         return ""
66
67
68 class Host(object):
69     """ Generic test host "connected" to VPPs interface. """
70
71     @property
72     def mac(self):
73         """ MAC address """
74         return self._mac
75
76     @property
77     def ip4(self):
78         """ IPv4 address """
79         return self._ip4
80
81     @property
82     def ip4n(self):
83         """ IPv4 address """
84         return socket.inet_pton(socket.AF_INET, self._ip4)
85
86     @property
87     def ip6(self):
88         """ IPv6 address """
89         return self._ip6
90
91     def __init__(self, mac=None, ip4=None, ip6=None):
92         self._mac = mac
93         self._ip4 = ip4
94         self._ip6 = ip6