def setUp(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown, mock_interfaces): # Setup the mock mock_interfaces.return_value = ["eth0", "eth1"] mock_ifaddresses.side_effect = mock_ip_ifaddresses self.name = "ethernet" self.bundle = Ethernet(connection=Mockup())
def __init__(self, host_and_port, adapter, log, device_id): self.log = log self.headers = {'Accept-Encoding': None} self.device_id = device_id """self.adapter_agent = adapter.adapter_agent self.adapter_name = adapter.name """ self.host_and_port = host_and_port.split( ':')[0] + Defaults.redfish_port requests.packages.urllib3.disable_warnings(InsecureRequestWarning) self.chassis_obj = Chassis(self) self.systems_obj = Systems(self) self.ethernet_obj = Ethernet(self) self.sys_info = {}
def send_frame(self, frame_type, dst_mac, data): if frame_type in [Ethernet.PROTO_ARP, Ethernet.PROTO_IPv4]: eth_frame = Ethernet( src_mac = binascii.unhexlify(self.mac.replace(':', '')), dst_mac = dst_mac, eth_type = frame_type, payload = data, payload_size = len(data)) self.tap.write(eth_frame.pack()) else: print("stack::send_frame() : [ERROR] unknown frame type : %d" % (frame_type))
def __init__(self, parent=None): super(MainWindows, self).__init__(parent) self.ui = Ui_MainUI() self.ethnet = Ethernet() self.timer = QtCore.QTimer() # Init ui self.ui.setupUi(self) self.ui.netSelCombo.addItems(self.ethnet.devices()) # Init auto-send timer self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.on_sendBtn_clicked) frameitems = [ 'IGMP Report', 'IGMP Leave', 'IGMP General Query', 'IGMP Specific Query' ] self.ui.frameCombo.addItems(frameitems)
def unpack(self, buf): from ethernet import Ethernet, ETH_TYPE_IP, ETH_TYPE_IPX dpkt.Packet.unpack(self, buf) if self.is_snap: self.oui, self.type = struct.unpack('>IH', '\x00' + self.data[:5]) self.data = self.data[5:] try: self.data = Ethernet.get_type(self.type)(self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except (KeyError, dpkt.UnpackError): pass else: # non-SNAP if self.dsap == 0x06: # SAP_IP self.data = self.ip = Ethernet.get_type(ETH_TYPE_IP)(self.data) elif self.dsap == 0x10 or self.dsap == 0xe0: # SAP_NETWARE{1,2} self.data = self.ipx = Ethernet.get_type(ETH_TYPE_IPX)(self.data) elif self.dsap == 0x42: # SAP_STP self.data = self.stp = stp.STP(self.data)
def handle_frame(self, raw_frame): # fill Ethernet object from the wire using unpack_hdr(). this will # only fill the header eth_frame = Ethernet() eth_frame.unpack_hdr(raw_frame) # process Ethernet payload according to eth_type frame_type = eth_frame.get_attr('header', 'eth_type') # ARP frame if frame_type == Ethernet.PROTO_ARP: eth_frame.unpack_data(raw_frame) self.arp_mod.process_dgram(eth_frame.get_attr('data', 'payload')) # IPv4 datagram elif frame_type == Ethernet.PROTO_IPv4: eth_frame.unpack_data(raw_frame) self.ipv4_mod.process_dgram(eth_frame.get_attr('data', 'payload'))
def unpack(self, buf): from ethernet import Ethernet, ETH_TYPE_IP, ETH_TYPE_IPX dpkt.Packet.unpack(self, buf) if self.is_snap: self.oui, self.type = struct.unpack('>IH', '\x00' + self.data[:5]) self.data = self.data[5:] try: self.data = Ethernet.get_type(self.type)(self.data) setattr(self, self.data.__class__.__name__.lower(), self.data) except (KeyError, dpkt.UnpackError): pass else: # non-SNAP if self.dsap == 0x06: # SAP_IP self.data = self.ip = Ethernet.get_type(ETH_TYPE_IP)(self.data) elif self.dsap == 0x10 or self.dsap == 0xe0: # SAP_NETWARE{1,2} self.data = self.ipx = Ethernet.get_type(ETH_TYPE_IPX)( self.data) elif self.dsap == 0x42: # SAP_STP self.data = self.stp = stp.STP(self.data)
def pack_hdr(self): buf = dpkt.Packet.pack_hdr(self) if self.is_snap: # add SNAP sublayer oui = getattr(self, 'oui', 0) _type = getattr(self, 'type', 0) if not _type and isinstance(self.data, dpkt.Packet): from ethernet import Ethernet try: _type = Ethernet.get_type_rev(self.data.__class__) except KeyError: pass buf += struct.pack('>IH', oui, _type)[1:] return buf
class TestEthernetClass(unittest.TestCase): @patch("ethernet.ip.interfaces") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def setUp(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown, mock_interfaces): # Setup the mock mock_interfaces.return_value = ["eth0", "eth1"] mock_ifaddresses.side_effect = mock_ip_ifaddresses self.name = "ethernet" self.bundle = Ethernet(connection=Mockup()) def tearDown(self): self.bundle.stop() self.bundle = None try: os.remove("%s/data/%s.json" % (dirpath, self.name)) except OSError: pass try: os.remove("%s/data/%s.json.backup" % (dirpath, self.name)) except OSError: pass @patch("ethernet.ip.interfaces") def test__init__no_iface(self, mock_interfaces): """ init: no interface """ mock_interfaces.return_value = [] with self.assertRaises(ValueError): self.bundle.init() @patch("ethernet.ip.interfaces") def test__init__no_conf(self, mock_interfaces): """ init: no configuration file """ mock_interfaces.return_value = ["eth0"] with self.assertRaises(IOError): with patch("ethernet.ModelInitiator") as mock_modelinit: mock_modelinit.side_effect = IOError self.bundle.init() @patch("ethernet.ip.ifaddresses") def test__load__current_conf(self, mock_ifaddresses): """ load: current configuration file """ mock_ifaddresses.side_effect = mock_ip_ifaddresses ifaces = ["eth0", "eth1"] self.bundle.load(dirpath, ifaces) self.assertEqual(2, len(self.bundle.model.db)) for iface in self.bundle.model.db: ifname = "eth%d" % (iface["id"] - 1) self.assertTrue(ifname in ifaces) @patch("ethernet.ip.ifaddresses") def test__load__backup_conf(self, mock_ifaddresses): """ load: backup configuration file """ mock_ifaddresses.side_effect = mock_ip_ifaddresses os.remove("%s/data/%s.json" % (dirpath, self.name)) ifaces = ["eth0", "eth1"] self.bundle.load(dirpath, ifaces) self.assertEqual(2, len(self.bundle.model.db)) def test__load__no_conf(self): """ load: no configuration file """ # case: cannot load any configuration with self.assertRaises(Exception): self.bundle.load("%s/mock" % dirpath, []) def test__save(self): """ save: tested in init() """ # Already tested in init() pass @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_down(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "down" """ # TODO: how to determine if setting success data = {"id": 1, "enable": False} self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_up_static(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "up" with static IP """ # TODO: how to determine if setting success data = { "id": 1, "enable": True, "enableDhcp": False, "ip": "192.168.31.39", "netmask": "255.255.255.0", "gateway": "192.168.31.254" } self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_up_dhcp(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "up" with dhcp enabled """ # TODO: how to determine if setting success data = {"id": 1, "enable": True, "enableDhcp": True} self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_unknown(self, mock_ifconfig, mock_ifupdown): """ apply: set an unknown interface """ data = {"id": 0, "enable": True} with self.assertRaises(ValueError): mock_ifupdown.side_effect = ValueError mock_ifconfig.side_effect = ValueError self.bundle.apply(data) @patch("ethernet.ip.ifaddresses") def test__read(self, mock_ifaddresses): """ read: read current status and mac """ mock_ifaddresses.side_effect = mock_ip_ifaddresses data = self.bundle.read(1) self.assertEqual(True, data["status"]) self.assertEqual("78:ac:c0:c1:a8:fe", data["mac"]) @patch("ethernet.ip.ifaddresses") def test__read__unknown_iface(self, mock_ifaddresses): """ read: no such interface """ mock_ifaddresses.side_effect = mock_ip_ifaddresses data = self.bundle.read(3) self.assertEqual(None, data) data = self.bundle.read(0) self.assertEqual(None, data) @patch("ethernet.ip.ifaddresses") def test__get__collection(self, mock_ifaddresses): """ get (/network/ethernets): collection """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: collection def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, len(data)) self.bundle.get(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get__by_id(self, mock_ifaddresses): """ get (/network/ethernets?id=2) """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: by id def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, data[0]["id"]) self.assertEqual(False, data[0]["status"]) self.assertEqual("78:ac:c0:c1:a8:ff", data[0]["mac"]) message.query["id"] = "2" self.bundle.get(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get_by_id(self, mock_ifaddresses): """ get_by_id (/network/ethernets/1) """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: get an interface successfully def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(1, data["id"]) self.assertEqual(True, data["status"]) self.assertEqual("78:ac:c0:c1:a8:fe", data["mac"]) message.param["id"] = 1 self.bundle.get_by_id(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get_by_id__unknown_iface(self, mock_ifaddresses): """ get_by_id (/network/ethernets/3): unknown interface """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: get an interface successfully def resp(code=200, data=None): self.assertEqual(404, code) self.assertEqual(data, {"message": "No such device."}) message.param["id"] = 3 self.bundle.get_by_id(message=message, response=resp, test=True) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__no_data(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): no data attribute "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"query": {}, "param": {}}) # case: no data attribute def resp(code=200, data=None): self.assertEqual(400, code) self.bundle.put(message, response=resp, test=True) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__invalid_json(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): invalid json schema "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ # case: invalid json schema def resp(code=200, data=None): self.assertEqual(400, code) message = Message({"data": {}, "query": {}, "param": {}}) self.bundle.put(message, response=resp, test=True) message = Message({"data": [], "query": {}, "param": {}}) self.bundle.put(message, response=resp, test=True) message.data.append({"id": 0, "enable": True}) self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__partial_success(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): one interface is not exist "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ def mock_put(resource, data): pass self.bundle.publish.put = mock_put self.bundle.publish.event.put = mock_put # case: one interface is not exist (bulk); exist one will be updated message = Message({"data": [], "query": {}, "param": {}}) # always true for response reply before apply the settings def resp(code=200, data=None): self.assertEqual(200, code) message.data.append({ "id": 1, "enable": True, "enableDhcp": False, "ip": u"192.168.31.36" }) message.data.append({"id": 3, "enable": True, "enableDhcp": False}) self.bundle.put(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.36", data["ip"]) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__unknown_ifaces(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): all interfaces are not exist "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def resp(code=200, data=None): self.assertEqual(400, code) message.data.append({"id": 0, "enable": True}) message.data.append({"id": 3, "enable": True}) self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets) "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, len(data)) message.data.append({ "id": 1, "enable": True, "enableDhcp": False, "ip": u"192.168.31.37" }) message.data.append({ "id": 2, "enable": True, "enableDhcp": False, "ip": u"192.168.41.37" }) def mock_event_put(resource, data): pass self.bundle.publish.event.put = mock_event_put self.bundle.put(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.37", data["ip"]) data = self.bundle.read(2, config=True) self.assertEqual("192.168.41.37", data["ip"]) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__by_id(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): by id "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(True, data["enable"]) self.assertEqual("192.168.31.39", data["ip"]) message = Message({"data": {}, "query": {}, "param": {}}) message.param["id"] = 1 message.data["id"] = 1 message.data["enable"] = True message.data["enableDhcp"] = False message.data["ip"] = u"192.168.31.39" def mock_event_put(resource, data): pass self.bundle.publish.event.put = mock_event_put self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id__invalid_json(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/1): invalid json schema "data": { "id": 1, ... } """ message = Message({"query": {}, "param": {"id": 1}}) # no data attribute, other case already tested in "test_put()" def resp(code=200, data=None): self.assertEqual(400, code) self.bundle.put_by_id(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id__unknown_iface(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/3): unknown interface "data": { "id": 1, ... } """ message = Message({"data": {}, "query": {}, "param": {"id": 3}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(404, code) message.data["id"] = 3 message.data["enable"] = False message.data["enableDhcp"] = False message.data["ip"] = u"192.168.31.37" self.bundle.put_by_id(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/1) "data": { "id": 1, ... } """ message = Message({"data": {}, "query": {}, "param": {"id": 1}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(404, code) message.data["id"] = 1 message.data["enable"] = False message.data["enableDhcp"] = False message.data["ip"] = u"192.168.31.40" self.bundle.put_by_id(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.40", data["ip"]) def test__event_dhcp_info__invalid_json(self): """ event_dhcp_info (/network/interfaces/:iface): invalid json schema "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({"query": {}, "param": {"iface": "eth1"}}) with self.assertRaises(ValueError): self.bundle.event_dhcp_info(message, test=True) def test__event_dhcp_info__unknown_iface(self): """ event_dhcp_info (/network/interfaces/:iface): unknown interface "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({ "data": {}, "query": {}, "param": { "iface": "eth2" } }) message.data["name"] = "eth2" message.data["type"] = "eth" message.data["ip"] = "192.168.41.3" message.data["netmask"] = "255.255.255.0" message.data["gateway"] = "192.168.41.254" message.data["dns"] = ["8.8.8.8"] with self.assertRaises(ValueError): self.bundle.event_dhcp_info(message, test=True) @patch("ethernet.ip.ifaddresses") def test__event_dhcp_info(self, mock_ifaddresses): """ event_dhcp_info (/network/interfaces/:iface) "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({ "data": {}, "query": {}, "param": { "iface": "eth1" } }) message.data["name"] = "eth1" message.data["type"] = "eth" message.data["ip"] = "192.168.41.3" message.data["netmask"] = "255.255.255.0" message.data["gateway"] = "192.168.41.254" message.data["dns"] = ["8.8.8.8"] self.bundle.event_dhcp_info(message, test=True) data = self.bundle.read(2, config=True) self.assertEqual("192.168.41.3", data["ip"]) self.assertEqual("255.255.255.0", data["netmask"]) self.assertEqual("192.168.41.254", data["gateway"]) self.assertEqual(["8.8.8.8"], data["dns"])
class TestEthernetClass(unittest.TestCase): @patch("ethernet.ip.interfaces") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def setUp(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown, mock_interfaces): # Setup the mock mock_interfaces.return_value = ["eth0", "eth1"] mock_ifaddresses.side_effect = mock_ip_ifaddresses self.name = "ethernet" self.bundle = Ethernet(connection=Mockup()) def tearDown(self): self.bundle.stop() self.bundle = None try: os.remove("%s/data/%s.json" % (dirpath, self.name)) except OSError: pass try: os.remove("%s/data/%s.json.backup" % (dirpath, self.name)) except OSError: pass @patch("ethernet.ip.interfaces") def test__init__no_iface(self, mock_interfaces): """ init: no interface """ mock_interfaces.return_value = [] with self.assertRaises(ValueError): self.bundle.init() @patch("ethernet.ip.interfaces") def test__init__no_conf(self, mock_interfaces): """ init: no configuration file """ mock_interfaces.return_value = ["eth0"] with self.assertRaises(IOError): with patch("ethernet.ModelInitiator") as mock_modelinit: mock_modelinit.side_effect = IOError self.bundle.init() @patch("ethernet.ip.ifaddresses") def test__load__current_conf(self, mock_ifaddresses): """ load: current configuration file """ mock_ifaddresses.side_effect = mock_ip_ifaddresses ifaces = ["eth0", "eth1"] self.bundle.load(dirpath, ifaces) self.assertEqual(2, len(self.bundle.model.db)) for iface in self.bundle.model.db: ifname = "eth%d" % (iface["id"]-1) self.assertTrue(ifname in ifaces) @patch("ethernet.ip.ifaddresses") def test__load__backup_conf(self, mock_ifaddresses): """ load: backup configuration file """ mock_ifaddresses.side_effect = mock_ip_ifaddresses os.remove("%s/data/%s.json" % (dirpath, self.name)) ifaces = ["eth0", "eth1"] self.bundle.load(dirpath, ifaces) self.assertEqual(2, len(self.bundle.model.db)) def test__load__no_conf(self): """ load: no configuration file """ # case: cannot load any configuration with self.assertRaises(Exception): self.bundle.load("%s/mock" % dirpath, []) def test__save(self): """ save: tested in init() """ # Already tested in init() pass @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_down(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "down" """ # TODO: how to determine if setting success data = { "id": 1, "enable": 0 } self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_up_static(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "up" with static IP """ # TODO: how to determine if setting success data = { "id": 1, "enable": 1, "enableDhcp": 0, "ip": "192.168.31.39", "netmask": "255.255.255.0", "gateway": "192.168.31.254" } self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_up_dhcp(self, mock_ifconfig, mock_ifupdown): """ apply: set the interface to "up" with dhcp enabled """ # TODO: how to determine if setting success data = { "id": 1, "enable": 1, "enableDhcp": 1 } self.bundle.apply(data) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") def test__apply__iface_unknown(self, mock_ifconfig, mock_ifupdown): """ apply: set an unknown interface """ data = { "id": 0, "enable": 1 } with self.assertRaises(ValueError): mock_ifupdown.side_effect = ValueError mock_ifconfig.side_effect = ValueError self.bundle.apply(data) @patch("ethernet.ip.ifaddresses") def test__read(self, mock_ifaddresses): """ read: read current status and mac """ mock_ifaddresses.side_effect = mock_ip_ifaddresses data = self.bundle.read(1) self.assertEqual(1, data["currentStatus"]) self.assertEqual("78:ac:c0:c1:a8:fe", data["mac"]) @patch("ethernet.ip.ifaddresses") def test__read__unknown_iface(self, mock_ifaddresses): """ read: no such interface """ mock_ifaddresses.side_effect = mock_ip_ifaddresses data = self.bundle.read(3) self.assertEqual(None, data) data = self.bundle.read(0) self.assertEqual(None, data) @patch("ethernet.ip.ifaddresses") def test__get__collection(self, mock_ifaddresses): """ get (/network/ethernets): collection """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: collection def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, len(data)) self.bundle.get(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get__by_id(self, mock_ifaddresses): """ get (/network/ethernets?id=2) """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: by id def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, data["id"]) self.assertEqual(0, data["currentStatus"]) self.assertEqual("78:ac:c0:c1:a8:ff", data["mac"]) message.query["id"] = 2 self.bundle.get(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get_by_id(self, mock_ifaddresses): """ get_by_id (/network/ethernets/1) """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: get an interface successfully def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(1, data["id"]) self.assertEqual(1, data["currentStatus"]) self.assertEqual("78:ac:c0:c1:a8:fe", data["mac"]) message.param["id"] = 1 self.bundle.get_by_id(message=message, response=resp, test=True) @patch("ethernet.ip.ifaddresses") def test__get_by_id__unknown_iface(self, mock_ifaddresses): """ get_by_id (/network/ethernets/3): unknown interface """ mock_ifaddresses.side_effect = mock_ip_ifaddresses message = Message({"data": {}, "query": {}, "param": {}}) # case: get an interface successfully def resp(code=200, data=None): self.assertEqual(404, code) self.assertEqual(data, {"message": "No such device."}) message.param["id"] = 3 self.bundle.get_by_id(message=message, response=resp, test=True) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__no_data(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): no data attribute "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"query": {}, "param": {}}) # case: no data attribute def resp(code=200, data=None): self.assertEqual(400, code) self.bundle.put(message, response=resp, test=True) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__invalid_json(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): invalid json schema "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ # case: invalid json schema def resp(code=200, data=None): self.assertEqual(400, code) message = Message({"data": {}, "query": {}, "param": {}}) self.bundle.put(message, response=resp, test=True) message = Message({"data": [], "query": {}, "param": {}}) self.bundle.put(message, response=resp, test=True) message.data.append({"id": 0, "enable": 1}) self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__partial_success(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): one interface is not exist "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ def mock_put(resource, data): pass self.bundle.publish.put = mock_put self.bundle.publish.event.put = mock_put # case: one interface is not exist (bulk); exist one will be updated message = Message({"data": [], "query": {}, "param": {}}) # always true for response reply before apply the settings def resp(code=200, data=None): self.assertEqual(200, code) message.data.append({"id": 1, "enable": 1, "ip": u"192.168.31.36"}) message.data.append({"id": 3, "enable": 1}) self.bundle.put(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.36", data["ip"]) @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__unknown_ifaces(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): all interfaces are not exist "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def resp(code=200, data=None): self.assertEqual(400, code) message.data.append({"id": 0, "enable": 1}) message.data.append({"id": 3, "enable": 1}) self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets) "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(2, len(data)) message.data.append({"id": 1, "enable": 1, "ip": u"192.168.31.37"}) message.data.append({"id": 2, "enable": 1, "ip": u"192.168.41.37"}) def mock_event_put(resource, data): pass self.bundle.publish.event.put = mock_event_put self.bundle.put(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.37", data["ip"]) data = self.bundle.read(2, config=True) self.assertEqual("192.168.41.37", data["ip"]) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put__by_id(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put (/network/ethernets): by id "data": [ { "id": 1, ... }, { "id": 2, ... } ] """ message = Message({"data": [], "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(200, code) self.assertEqual(1, data["enable"]) self.assertEqual("192.168.31.39", data["ip"]) message = Message({"data": {}, "query": {}, "param": {}}) message.param["id"] = 1 message.data["id"] = 1 message.data["enable"] = 1 message.data["ip"] = u"192.168.31.39" def mock_event_put(resource, data): pass self.bundle.publish.event.put = mock_event_put self.bundle.put(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id__invalid_json(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/1): invalid json schema "data": { "id": 1, ... } """ message = Message({"query": {}, "param": {}}) # no data attribute, other case already tested in "test_put()" def resp(code=200, data=None): self.assertEqual(400, code) self.bundle.put_by_id(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id__unknown_iface(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/3): unknown interface "data": { "id": 1, ... } """ message = Message({"data": {}, "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(404, code) message.data["id"] = 3 message.data["enable"] = 0 message.data["ip"] = u"192.168.31.37" self.bundle.put_by_id(message, response=resp, test=True) # @patch("ethernet.time.sleep") @patch("ethernet.ip.ifupdown") @patch("ethernet.ip.ifconfig") @patch("ethernet.ip.ifaddresses") def test__put_by_id(self, mock_ifaddresses, mock_ifconfig, mock_ifupdown): """ put_by_id (/network/ethernets/1) "data": { "id": 1, ... } """ message = Message({"data": {}, "query": {}, "param": {}}) def mock_put(resource, data): pass self.bundle.publish.put = mock_put def resp(code=200, data=None): self.assertEqual(404, code) message.data["id"] = 1 message.data["enable"] = 0 message.data["ip"] = u"192.168.31.40" self.bundle.put_by_id(message, response=resp, test=True) data = self.bundle.read(1, config=True) self.assertEqual("192.168.31.40", data["ip"]) def test__put_dhcp_info__invalid_json(self): """ put_dhcp_info (/network/interface/dhcp): invalid json schema "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({"query": {}, "param": {}}) with self.assertRaises(ValueError): self.bundle.put_dhcp_info(message, test=True) def test__put_dhcp_info__unknown_iface(self): """ put_dhcp_info (/network/interface/dhcp): unknown interface "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({"data": {}, "query": {}, "param": {}}) message.data["name"] = "eth2" message.data["ip"] = "192.168.41.3" message.data["netmask"] = "255.255.255.0" message.data["gateway"] = "192.168.41.254" message.data["dns"] = ["8.8.8.8"] with self.assertRaises(ValueError): self.bundle.put_dhcp_info(message, test=True) @patch("ethernet.ip.ifaddresses") def test__put_dhcp_info(self, mock_ifaddresses): """ put_dhcp_info (/network/interface/dhcp) "data": { "name": "", "ip": "", "netmask": "", "subnet": "", "dns": [], "gateway": "" } """ message = Message({"data": {}, "query": {}, "param": {}}) message.data["name"] = "eth1" message.data["ip"] = "192.168.41.3" message.data["netmask"] = "255.255.255.0" message.data["gateway"] = "192.168.41.254" message.data["dns"] = ["8.8.8.8"] self.bundle.put_dhcp_info(message, test=True) data = self.bundle.read(2, config=True) self.assertEqual("192.168.41.3", data["ip"]) self.assertEqual("255.255.255.0", data["netmask"]) self.assertEqual("192.168.41.254", data["gateway"]) self.assertEqual(["8.8.8.8"], data["dns"])
pcap = Pcap('capture.pcap') # Maximum packet read number. count_pkt = 0 if len(sys.argv) == 1: sys.exit("Have to pass full packet number.") else: max_pkt = int(sys.argv[1]) while True: pkt, addr = s.recvfrom(65565) pcap.write(pkt) eth = Ethernet(pkt) t = time.localtime() print("%d's Packet." % count_pkt) print('Time: {}.{}.{}, {}.{}.{}'.format(t.tm_mon, t.tm_mday, t.tm_year, t.tm_hour, t.tm_min, t.tm_sec)) print('Ethernet Frame:') print(TAB_1 + 'Destination: {}, Source: {}, Protocol: {}'.format( eth.dest_mac, eth.src_mac, eth.proto)) # IPv4 if eth.proto == 8: ipv4 = IPv4(eth.data) print(TAB_1 + 'IPv4 Packet:') print(TAB_2 + 'Version: {}, Header Length: {}, TTL: {},'.format( ipv4.version, ipv4.header_length, ipv4.ttl))
class RestClient(object): def __init__(self, host_and_port, adapter, log, device_id): self.log = log self.headers = {'Accept-Encoding': None} self.device_id = device_id """self.adapter_agent = adapter.adapter_agent self.adapter_name = adapter.name """ self.host_and_port = host_and_port.split( ':')[0] + Defaults.redfish_port requests.packages.urllib3.disable_warnings(InsecureRequestWarning) self.chassis_obj = Chassis(self) self.systems_obj = Systems(self) self.ethernet_obj = Ethernet(self) self.sys_info = {} def get_system_details(self): """ Method to fetch OLT info. This method is supposed to get invoked from NBI API get_device_details. Currently the get_device_details() is in NotImplemented stated """ self.systems_obj.system_get(self.sys_info) return self.sys_info def start_health_monitoring(self): """ Method to fetch health status of asfvolt16 olt hardware modules """ self.chassis_obj.get_chassis_health() self.ethernet_obj.get_ethernet_health() def stop_health_monitoring(self): """ Method to stop health monitoring of asfvolt16 olt modules are not controlled by bal """ self.chassis_obj.stop_chassis_monitoring() self.ethernet_obj.stop_ether_monitoring() def reboot_device(self): """ Reboot asfvolt16 olt through Redfish service """ self.systems_obj.reboot_olt() """def generate_alarm(self, status, alarm, alarm_severity): Method to create and submit alarms. if(alarm_severity == "Warning"): al_severity = AlarmEventSeverity.WARNING elif (alarm_severity == "Critical"): al_severity = AlarmEventSeverity.CRITICAL try: ts = arrow.utcnow().timestamp alarm_event = self.adapter_agent.create_alarm( id='voltha.{}.{}.olt'.format(self.adapter_name, self.device_id), resource_id='olt', type=AlarmEventType.EQUIPMENT, severity=al_severity, category=AlarmEventCategory.OLT, state=AlarmEventState.RAISED if status else AlarmEventState.CLEARED, description='OLT Alarm - Health Monitoring asfvolt16 olt - {}' .format('Raised' if status else 'Cleared'), context=alarm, raised_ts=ts) self.adapter_agent.submit_alarm(self.device_id, alarm_event) except Exception as e: self.log.exception('failed-to-submit-alarm', e=e) """ def http_get(self, uri=UriConst.base_uri): """ Method to send http GET request. """ url = UriConst.HTTPS + self.host_and_port + uri #print ("http_get url[%s]"%url) try: ret = requests.request(RestConst.GET, url=url, headers=self.headers, auth=None, verify=False) return ret except requests.exceptions.ConnectTimeout: print("Connection-timed-out.") except Exception as e: print("Exception1-occurred-:", str(e)) def http_put(self, uri=UriConst.base_uri, data=None): """ Method to send http PUT request. """ url = UriConst.HTTPS + self.host_and_port + uri try: ret = requests.request(RestConst.PUT, url=url, headers=self.headers, auth=None, verify=False, data=data) return ret except requests.exceptions.ConnectTimeout: print("Connection-timed-out.") except Exception as e: print("Exception1-occurred-:", str(e)) def http_post(self, uri=UriConst.base_uri, data=None): """ Method to send http POST request. """ url = UriConst.HTTPS + self.host_and_port + uri try: ret = requests.request(RestConst.POST, url=url, headers=self.headers, auth=None, verify=False, data=data) return ret except requests.exceptions.ConnectTimeout: print("Connection-timed-out.") except Exception as e: print("Exception1-occurred-:", str(e)) def http_patch(self, uri=UriConst.base_uri, data=None): """ Method to send http Patch request. """ url = UriConst.HTTPS + self.host_and_port + uri try: ret = requests.request(RestConst.PATCH, url=url, headers=self.headers, auth=None, verify=False, data=data) return ret except requests.exceptions.ConnectTimeout: print("Connection-timed-out.") except Exception as e: print("Exception1-occurred-:", str(e))
class MainWindows(QMainWindow): def __init__(self, parent=None): super(MainWindows, self).__init__(parent) self.ui = Ui_MainUI() self.ethnet = Ethernet() self.timer = QtCore.QTimer() # Init ui self.ui.setupUi(self) self.ui.netSelCombo.addItems(self.ethnet.devices()) # Init auto-send timer self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.on_sendBtn_clicked) frameitems = [ 'IGMP Report', 'IGMP Leave', 'IGMP General Query', 'IGMP Specific Query' ] self.ui.frameCombo.addItems(frameitems) @QtCore.pyqtSlot() def on_sendBtn_clicked(self): # Get all data sendData = str(self.ui.daEdit.text()) sendData += str(self.ui.saEdit.text()) sendData += str(self.ui.typeEdit.text()) sendData += str(self.ui.payloadEdit.toPlainText()) # Send packet self.ethnet.sendHex(sendData) # Packet count ++ self.ui.statusbar.showMessage("Send Times: " + str(self.ethnet.sendtimes())) @QtCore.pyqtSlot() def on_autoSendBtn_clicked(self): btnText = self.ui.autoSendBtn.text() if btnText == u"自动发送": self.ui.autoSendBtn.setText(u"停止发送") self.ui.autoTimeEdit.setEnabled(False) # Start auto send time self.timer.start(int(self.ui.autoTimeEdit.text())) else: self.ui.autoSendBtn.setText(u"自动发送") self.ui.autoTimeEdit.setEnabled(True) # Stop auto send time self.timer.stop() @QtCore.pyqtSlot() def on_netSelBtn_clicked(self): btnText = self.ui.netSelBtn.text() if btnText == u"确认选择": self.ui.netSelBtn.setText(u"取消选择") self.ui.sendBtn.setEnabled(True) self.ui.frameCombo.setEnabled(True) self.ui.autoSendBtn.setEnabled(True) self.ui.autoTimeEdit.setEnabled(True) self.ui.netSelCombo.setEnabled(False) # Open the current select device devName = self.ui.netSelCombo.currentText() self.ethnet.open(devName) self.ui.statusbar.showMessage("Open: " + devName + ":" + self.ethnet.address()) else: self.ui.netSelBtn.setText(u"确认选择") self.ui.sendBtn.setEnabled(False) self.ui.frameCombo.setEnabled(False) self.ui.autoSendBtn.setEnabled(False) self.ui.autoTimeEdit.setEnabled(False) self.ui.netSelCombo.setEnabled(True) @QtCore.pyqtSlot('const QString&') def on_netSelCombo_currentIndexChanged(self, item): self.ui.statusbar.showMessage("Select Net: " + item) @QtCore.pyqtSlot('const QString&') def on_frameCombo_currentIndexChanged(self, item): if item == 'IGMP Report': da = '01 00 5E 01 01 01' sa = '01 00 5E 01 01 01' payload = '45 05 00 32 00 00 00 00 01 02 D8 19 C0 A8 40 01 E0 01 01 01 16 03 08 FA E0 01 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00' elif item == "IGMP Leave": da = '01 00 5E 01 01 01' sa = '01 00 5E 01 01 01' payload = '45 05 00 32 00 00 00 00 01 02 D8 19 C0 A8 40 01 E0 01 01 01 17 00 07 FD E0 01 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00' elif item == "IGMP General Query": da = '01 00 5E 01 01 01' sa = '01 00 5E 01 01 01' payload = '45 05 00 32 00 00 00 00 01 02 D9 1B C0 A8 40 01 E0 00 00 00 11 03 F9 0D E0 01 01 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00' elif item == "IGMP Specific Query": da = '01 00 5E 01 01 01' sa = '01 00 5E 01 01 01' payload = '45 05 00 32 00 00 00 00 01 02 D8 19 C0 A8 40 01 E0 01 01 01 11 03 F9 0D E0 01 01 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00' self.ui.daEdit.setText(da) self.ui.saEdit.setText(sa) self.ui.payloadEdit.setPlainText(payload)