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