Best Python code snippet using autotest_python
rss_client.py
Source:rss_client.py  
...141        self._send(struct.pack("=I", len(str)))142        self._send(str, timeout)143        self.transferred += len(str) + 4144        self._report_stats("Sent")145    def _receive_packet(self, timeout=60):146        size = struct.unpack("=I", self._receive(4))[0]147        str = self._receive(size, timeout)148        self.transferred += len(str) + 4149        self._report_stats("Received")150        return str151    def _send_file_chunks(self, filename, timeout=60):152        if self._log_func:153            self._log_func("Sending file %s" % filename)154        f = open(filename, "rb")155        try:156            try:157                end_time = time.time() + timeout158                while True:159                    data = f.read(CHUNKSIZE)160                    self._send_packet(data, end_time - time.time())161                    if len(data) < CHUNKSIZE:162                        break163            except FileTransferError, e:164                e.filename = filename165                raise166        finally:167            f.close()168    def _receive_file_chunks(self, filename, timeout=60):169        if self._log_func:170            self._log_func("Receiving file %s" % filename)171        f = open(filename, "wb")172        try:173            try:174                end_time = time.time() + timeout175                while True:176                    data = self._receive_packet(end_time - time.time())177                    f.write(data)178                    if len(data) < CHUNKSIZE:179                        break180            except FileTransferError, e:181                e.filename = filename182                raise183        finally:184            f.close()185    def _send_msg(self, msg, timeout=60):186        self._send(struct.pack("=I", msg))187    def _receive_msg(self, timeout=60):188        s = self._receive(4, timeout)189        return struct.unpack("=I", s)[0]190    def _handle_transfer_error(self):191        # Save original exception192        e = sys.exc_info()193        try:194            # See if we can get an error message195            msg = self._receive_msg()196        except FileTransferError:197            # No error message -- re-raise original exception198            raise e[0], e[1], e[2]199        if msg == RSS_ERROR:200            errmsg = self._receive_packet()201            raise FileTransferServerError(errmsg)202        raise e[0], e[1], e[2]203class FileUploadClient(FileTransferClient):204    """205    Connect to a RSS (remote shell server) and upload files or directory trees.206    """207    def __init__(self, address, port, log_func=None, timeout=20):208        """209        Connect to a server.210        @param address: The server's address211        @param port: The server's port212        @param log_func: If provided, transfer stats will be passed to this213                function during the transfer214        @param timeout: Time duration to wait for connection to succeed215        @raise FileTransferConnectError: Raised if the connection fails216        @raise FileTransferProtocolError: Raised if an incorrect magic number217                is received218        @raise FileTransferSocketError: Raised if the RSS_UPLOAD message cannot219                be sent to the server220        """221        super(FileUploadClient, self).__init__(address, port, log_func, timeout)222        self._send_msg(RSS_UPLOAD)223    def _upload_file(self, path, end_time):224        if os.path.isfile(path):225            self._send_msg(RSS_CREATE_FILE)226            self._send_packet(os.path.basename(path))227            self._send_file_chunks(path, end_time - time.time())228        elif os.path.isdir(path):229            self._send_msg(RSS_CREATE_DIR)230            self._send_packet(os.path.basename(path))231            for filename in os.listdir(path):232                self._upload_file(os.path.join(path, filename), end_time)233            self._send_msg(RSS_LEAVE_DIR)234    def upload(self, src_pattern, dst_path, timeout=600):235        """236        Send files or directory trees to the server.237        The semantics of src_pattern and dst_path are similar to those of scp.238        For example, the following are OK:239            src_pattern='/tmp/foo.txt', dst_path='C:\\'240                (uploads a single file)241            src_pattern='/usr/', dst_path='C:\\Windows\\'242                (uploads a directory tree recursively)243            src_pattern='/usr/*', dst_path='C:\\Windows\\'244                (uploads all files and directory trees under /usr/)245        The following is not OK:246            src_pattern='/tmp/foo.txt', dst_path='C:\\Windows\\*'247                (wildcards are only allowed in src_pattern)248        @param src_pattern: A path or wildcard pattern specifying the files or249                directories to send to the server250        @param dst_path: A path in the server's filesystem where the files will251                be saved252        @param timeout: Time duration in seconds to wait for the transfer to253                complete254        @raise FileTransferTimeoutError: Raised if timeout expires255        @raise FileTransferServerError: Raised if something goes wrong and the256                server sends an informative error message to the client257        @note: Other exceptions can be raised.258        """259        end_time = time.time() + timeout260        try:261            try:262                self._send_msg(RSS_SET_PATH)263                self._send_packet(dst_path)264                matches = glob.glob(src_pattern)265                for filename in matches:266                    self._upload_file(os.path.abspath(filename), end_time)267                self._send_msg(RSS_DONE)268            except FileTransferTimeoutError:269                raise270            except FileTransferError:271                self._handle_transfer_error()272            else:273                # If nothing was transferred, raise an exception274                if not matches:275                    raise FileTransferNotFoundError("Pattern %s does not "276                                                    "match any files or "277                                                    "directories" %278                                                    src_pattern)279                # Look for RSS_OK or RSS_ERROR280                msg = self._receive_msg(end_time - time.time())281                if msg == RSS_OK:282                    return283                elif msg == RSS_ERROR:284                    errmsg = self._receive_packet()285                    raise FileTransferServerError(errmsg)286                else:287                    # Neither RSS_OK nor RSS_ERROR found288                    raise FileTransferProtocolError("Received unexpected msg")289        except:290            # In any case, if the transfer failed, close the connection291            self.close()292            raise293class FileDownloadClient(FileTransferClient):294    """295    Connect to a RSS (remote shell server) and download files or directory trees.296    """297    def __init__(self, address, port, log_func=None, timeout=20):298        """299        Connect to a server.300        @param address: The server's address301        @param port: The server's port302        @param log_func: If provided, transfer stats will be passed to this303                function during the transfer304        @param timeout: Time duration to wait for connection to succeed305        @raise FileTransferConnectError: Raised if the connection fails306        @raise FileTransferProtocolError: Raised if an incorrect magic number307                is received308        @raise FileTransferSendError: Raised if the RSS_UPLOAD message cannot309                be sent to the server310        """311        super(FileDownloadClient, self).__init__(address, port, log_func, timeout)312        self._send_msg(RSS_DOWNLOAD)313    def download(self, src_pattern, dst_path, timeout=600):314        """315        Receive files or directory trees from the server.316        The semantics of src_pattern and dst_path are similar to those of scp.317        For example, the following are OK:318            src_pattern='C:\\foo.txt', dst_path='/tmp'319                (downloads a single file)320            src_pattern='C:\\Windows', dst_path='/tmp'321                (downloads a directory tree recursively)322            src_pattern='C:\\Windows\\*', dst_path='/tmp'323                (downloads all files and directory trees under C:\\Windows)324        The following is not OK:325            src_pattern='C:\\Windows', dst_path='/tmp/*'326                (wildcards are only allowed in src_pattern)327        @param src_pattern: A path or wildcard pattern specifying the files or328                directories, in the server's filesystem, that will be sent to329                the client330        @param dst_path: A path in the local filesystem where the files will331                be saved332        @param timeout: Time duration in seconds to wait for the transfer to333                complete334        @raise FileTransferTimeoutError: Raised if timeout expires335        @raise FileTransferServerError: Raised if something goes wrong and the336                server sends an informative error message to the client337        @note: Other exceptions can be raised.338        """339        dst_path = os.path.abspath(dst_path)340        end_time = time.time() + timeout341        file_count = 0342        dir_count = 0343        try:344            try:345                self._send_msg(RSS_SET_PATH)346                self._send_packet(src_pattern)347            except FileTransferError:348                self._handle_transfer_error()349            while True:350                msg = self._receive_msg()351                if msg == RSS_CREATE_FILE:352                    # Receive filename and file contents353                    filename = self._receive_packet()354                    if os.path.isdir(dst_path):355                        dst_path = os.path.join(dst_path, filename)356                    self._receive_file_chunks(dst_path, end_time - time.time())357                    dst_path = os.path.dirname(dst_path)358                    file_count += 1359                elif msg == RSS_CREATE_DIR:360                    # Receive dirname and create the directory361                    dirname = self._receive_packet()362                    if os.path.isdir(dst_path):363                        dst_path = os.path.join(dst_path, dirname)364                    if not os.path.isdir(dst_path):365                        os.mkdir(dst_path)366                    dir_count += 1367                elif msg == RSS_LEAVE_DIR:368                    # Return to parent dir369                    dst_path = os.path.dirname(dst_path)370                elif msg == RSS_DONE:371                    # Transfer complete372                    if not file_count and not dir_count:373                        raise FileTransferNotFoundError("Pattern %s does not "374                                                        "match any files or "375                                                        "directories that "376                                                        "could be downloaded" %377                                                        src_pattern)378                    break379                elif msg == RSS_ERROR:380                    # Receive error message and abort381                    errmsg = self._receive_packet()382                    raise FileTransferServerError(errmsg)383                else:384                    # Unexpected msg385                    raise FileTransferProtocolError("Received unexpected msg")386        except:387            # In any case, if the transfer failed, close the connection388            self.close()389            raise390def upload(address, port, src_pattern, dst_path, log_func=None, timeout=60,391           connect_timeout=20):392    """393    Connect to server and upload files.394    @see: FileUploadClient395    """...rnis_connector.py
Source:rnis_connector.py  
...38        logging.info("Received egts packet: %s", response)39        if not self._check_response(response):40            return False41        if self.did == 0xFFffFFff:42            auth_params = self._receive_packet(conn)43            logging.info("Received egts packet: %s", auth_params)44            self._send_replay(conn, auth_params)45            if not self._check_auth_params(auth_params):46                return False47            subrec = EgtsSrAuthInfo(EGTS_SR_AUTH_INFO, unm=self.login, upsw=self.password)48            response = self._send_auth_packet(conn, subrec)49            logging.info("Received egts packet: %s", response)50            if not self._check_response(response):51                return False52        result_code = self._receive_packet(conn)53        logging.info("Received egts packet: %s", result_code)54        self._send_replay(conn, result_code)55        if not self._check_result_code(result_code):56            return False57        return True58    def _loop(self, conn):59        while self.num < self.max:60            egts = self._receive_packet(conn)61            self._send_replay(conn, egts)62            self.num += 163            logging.info("Received egts packet: %s", egts)64    def _receive_packet(self, conn):65        while len(self.buffer) <= EGTS_MAX_PACKET_LENGTH:66            if self.buffer == b'':67                data = conn.recv(1024)68                if not data:69                    return None70                else:71                    self.buffer += data72            try:73                egts = Egts(self.buffer)74                self.buffer = egts.rest_buff75                return egts76            except EgtsPcInvdatalen as err:77                data = conn.recv(1024)78                if not data:79                    return None80                else:81                    self.buffer += data82    def _send_replay(self, conn, egts):83        reply = egts.reply(self.pid, self.rid)84        self._pid_increment()85        self._rid_increment()86    def _send_auth_packet(self, conn, subrec):87        egts_record = EgtsRecord(rid=self.rid, sst=EGTS_AUTH_SERVICE, subrecords=[subrec])88        packet = Egts.form_bin(self.pid, [egts_record])89        conn.send(packet)90        self._pid_increment()91        self._rid_increment()92        response = self._receive_packet(conn)93        return response94    def _pid_increment(self):95        self.pid += 196        if self.pid > 0xFFff:97            self.pid = 098    def _rid_increment(self):99        self.rid += 1100        if self.rid > 0xFFff:101            self.rid = 0102    @staticmethod103    def _check_response(packet):104        for record in packet.records:105            for subrec in record.subrecords:106                if subrec.rst != 0:...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!!
