0ac23760465d8c78c6c7444dcfef37171bda3c0c
[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     result = headline + "\n"
28     count = 1
29     for p in capture:
30         result.append(ppp("Packet #%s:" % count, p))
31         count += 1
32         if count >= limit:
33             break
34     if limit < len(capture):
35         result.append(
36             "Capture contains %s packets in total, of which %s were printed" %
37             (len(capture), limit))
38
39
40 class NumericConstant(object):
41     __metaclass__ = ABCMeta
42
43     desc_dict = {}
44
45     @abstractmethod
46     def __init__(self, value):
47         self._value = value
48
49     def __int__(self):
50         return self._value
51
52     def __long__(self):
53         return self._value
54
55     def __str__(self):
56         if self._value in self.desc_dict:
57             return self.desc_dict[self._value]
58         return ""
59
60
61 class Host(object):
62     """ Generic test host "connected" to VPPs interface. """
63
64     @property
65     def mac(self):
66         """ MAC address """
67         return self._mac
68
69     @property
70     def ip4(self):
71         """ IPv4 address """
72         return self._ip4
73
74     @property
75     def ip4n(self):
76         """ IPv4 address """
77         return socket.inet_pton(socket.AF_INET, self._ip4)
78
79     @property
80     def ip6(self):
81         """ IPv6 address """
82         return self._ip6
83
84     def __init__(self, mac=None, ip4=None, ip6=None):
85         self._mac = mac
86         self._ip4 = ip4
87         self._ip6 = ip6