Best Python code snippet using lisa_python
h2unwrap.py
Source:h2unwrap.py
...138 self.source.write_to_source(data)139 except Exception as e:140 print "EXCEPTION reading from dest", e141 142 self.source.stop_forwarding()143 print "...ending forwarder."144 145 def write_to_dest(self, data):146 print "Sending to dest: " + str(len(data))147 hexdump.hexdump(data)148 if self.log_data:149 with open(self.id + "_out"+str(self.outiter)+".bin", "wb") as fd:150 fd.write(data)151 self.outiter = self.outiter+1152 153 if not self.connected:154 self.dest.connect((self.forward_addr, self.forward_port))155 self.connected = True156 157 self.dest.sendall(data)158 159 def stop_forwarding(self):160 print "...closing forwarding socket"161 try:162 self.dest.shutdown(SHUT_RDWR)163 except Exception:164 pass165 self.dest.close()166 self.terminate = True167 168 169 def handle(self):170 print "GOT CONNECTION."171 f = ForwardingSecureTCPServer.ConnectionForwardingHandler.Forwarder(self, self.server.forward_addr, self.server.forward_port, True, False)172 f.daemon = True173 f.start()174 175 try:176 while True:177 data = self.request.recv(4096*10)178 if len(data) == 0:179 raise Exception("endpoint closed")180 print "Received from SSL: " + str(len(data))181 f.write_to_dest(data)182 except Exception as e:183 print "Exception reading from SSL socket.", e184 185 f.stop_forwarding()186 187 print "CONNECTION FINISHED" 188 189 190 def write_to_source(self, data):191 self.request.sendall(data)192 193 def stop_forwarding(self):194 print "...closing SSL socket"195 self.request.close()196 197 198 199 def __init__(self, listen_addr, listen_port, listen_key, listen_cert, forward_addr, forward_port):200 SecureTCPServer.__init__(self, listen_addr, listen_port, listen_key, listen_cert, ForwardingSecureTCPServer.ConnectionForwardingHandler)201 self.forward_addr = forward_addr202 self.forward_port = forward_port203if __name__ == "__main__":204 print "starting"...
plc_forwarder.py
Source:plc_forwarder.py
1import sys2import socket3import logging4import argparse5import time6from serial import SerialException7from plc_connection import PlcConnection8from printrun.utils import PlcError9RASP_DEFAULT_HOSTNAME = 'localhost'10RASP_DEFAULT_PORT = 808011logger = logging.getLogger()12logger.setLevel(logging.DEBUG)13ch = logging.StreamHandler(sys.stdout)14ch.setLevel(logging.DEBUG)15formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')16ch.setFormatter(formatter)17logger.addHandler(ch)18def flushed_write(file_object):19 def wrraped(msg):20 file_object.write(msg)21 file_object.flush()22 return wrraped23class PlcForwarder(object):24 def __init__(self):25 self.serial_conn = PlcConnection()26 self.serial_conn.log, self.serial_conn.logError, self.serial_conn.logDebug = logger.log, logger.error, logger.debug27 self.sock = None28 self.tcp_conn = None29 self.hostname = RASP_DEFAULT_HOSTNAME30 self.port = RASP_DEFAULT_PORT31 self.client_addr = None32 self.stop_forwarding = False33 def open_tcp_connection(self, hostname=None, port=None):34 self.sock = socket.socket(socket.AF_INET,35 socket.SOCK_STREAM)36 self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)37 self.sock.setsockopt(38 socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)39 # self.sock.settimeout(30.0)40 if hostname is not None: self.hostname = hostname41 if port is not None: self.port = port42 try:43 self.sock.bind((self.hostname, self.port))44 self.sock.listen(1)45 logger.debug('Listening on ' + self.hostname + ':' + str(self.port) + ' ...')46 self.tcp_conn, addr = self.sock.accept()47 self.client_addr = addr[0]48 logger.debug("%s " % self.client_addr + "connected")49 self.sock = self.tcp_conn50 self.tcp_conn = self.tcp_conn.makefile(mode='r+')51 except Exception as er:52 logger.error("Couldn't open tcp connection %s:%s" % (self.hostname, self.port) +53 "\n" + "Socket error: %s" % er)54 self.exit()55 return True56 def open_serial_connection(self, port=None, baud=None):57 if self.tcp_conn is None:58 logger.error("Can't open serial with no tcp connection, exiting...")59 self.exit()60 if self.serial_conn is None:61 self.serial_conn = PlcConnection()62 if not self.serial_conn.open(port, baud):63 logger.error("Couldn't open serial connection, exiting...")64 self.exit()65 self.serial_conn.on_recv = flushed_write(self.tcp_conn)66 self.serial_conn.on_disconnect = self.exit67 return True68 def start(self):69 if self.serial_conn is None:70 logger.error("Couldn't start forwarding, no serial connection")71 self.exit()72 if self.tcp_conn is None:73 logger.error("Couldn't start forwarding, no tcp connection")74 self.exit()75 read_attempts_count = 476 while not self.stop_forwarding:77 if read_attempts_count < 1:78 logger.error("Closing connections and exiting after 4 read attempts...")79 self.exit()80 try:81 msg = self.tcp_conn.readline()82 logger.debug("Received message on tcp:" + msg)83 except socket.error as er:84 logger.error("Couldn't read from tcp" + '\n' +85 "Socket error: %s" % er)86 read_attempts_count -= 187 except Exception as er:88 logger.error("Couldn't read from tcp" + '\n' +89 "Error: %s" % er)90 read_attempts_count -= 191 else:92 read_attempts_count = 493 if msg:94 if len(msg) > 0:95 self.serial_conn.send(msg)96 else:97 logger.debug("%s " % self.client_addr + " disconnected, closing connections...")98 if self.serial_conn is not None:99 try:100 self.serial_conn.close()101 except PlcError as er:102 logger.error(er.message)103 self.exit()104 self.serial_conn = None105 if self.tcp_conn is not None:106 try:107 logger.debug("Closing connection on %s:%s..." % (self.hostname, self.port))108 self.tcp_conn.close()109 self.sock.close()110 except Exception as er:111 logger.error("Couldn't close tcp connection on %s:%s" % (self.hostname, self.port)112 + "\n" + "Error: %s" % er)113 self.exit()114 self.tcp_conn = None115 self.stop_forwarding = True116 def exit(self, status=1):117 self.stop_forwarding = True118 if self.serial_conn is not None:119 try:120 self.serial_conn.close()121 except PlcError as er:122 logger.error(er.message)123 if self.tcp_conn is not None:124 try:125 self.tcp_conn.close()126 self.sock.close()127 except Exception as er:128 logger.error("Couldn't close tcp connection on %s:%s" % (self.hostname, self.port)129 + "\n" + "Error: %s" % er)130 sys.exit(status)131if __name__ == '__main__':132 parser = argparse.ArgumentParser(description='Ethernet to serial adapter for plc')133 parser.add_argument('--tcp', dest='tcp', help="IP socket address to listen in format 'hostname:port' ")134 parser.add_argument('--serial', dest='serial', help='Plc serial port name')135 args = parser.parse_args()136 plc_forwarder = PlcForwarder()137 if args.tcp is not None:138 plc_forwarder.hostname, port = args.tcp.split(':')139 plc_forwarder.port = int(port)140 try:141 while True:142 if not plc_forwarder.open_tcp_connection():143 plc_forwarder.exit()144 if not plc_forwarder.open_serial_connection(port=args.serial):145 plc_forwarder.exit()146 plc_forwarder.start()147 plc_forwarder.stop_forwarding = False148 except KeyboardInterrupt:149 print "Closing connections and exiting..."150 plc_forwarder.exit()151 except Exception as e:152 print str(e) + "\n"...
test_forwarder.py
Source:test_forwarder.py
...27 t = threading.Thread(target=forwarder._forward_loop)28 t.start()29 time.sleep(1)30 self.assertEqual(forwarder.forward_queue.qsize(), 0, 'queue should be empty')31 forwarder.stop_forwarding()32 t.join(5)33 self.assertFalse(t.is_alive(), 'forward thread did not end')34 def test_remote_servers(self):35 client = Mock()36 digest = '975422c090e7a43ab7c9bf0065d5b661259e6d74'37 servlist = [("test1.example.com", 24441),38 ("test2.example.com", 24442)]39 forwarder = pyzor.forwarder.Forwarder(client, servlist)40 forwarder.queue_forward_request(digest)41 forwarder.queue_forward_request(digest, whitelist=True)42 forwarder.start_forwarding()43 time.sleep(2)44 forwarder.stop_forwarding()45 client.report.assert_has_calls([call(digest, servlist[0]),46 call(digest, servlist[1])])47 client.whitelist.assert_has_calls([call(digest, servlist[0]),48 call(digest, servlist[1])])49def suite():50 """Gather all the tests from this module in a test suite."""51 test_suite = unittest.TestSuite()52 test_suite.addTest(unittest.makeSuite(ForwarderTest))53 return test_suite54if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!