Best Python code snippet using tempest_python
serve.py
Source:serve.py  
...42class FluttererHandler(BaseHTTPRequestHandler):43    def __init__(self, *args, **kwargs):44        self._http_error = None45        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)46    def _log_request_start(self):47        # Print the first half of the log message, so students can see what the48        # request was if they print some debugging messages49        print_gray(f"{self.command} {self.path}")50    def log_request(self, code=None, size=None):51        # Print the second half of the log message (response info)52        msg = f"  -> {code} {self.responses[code][0]}"53        if self._http_error:54            msg += f": {self._http_error.message}"55            self._http_error = None56        (print_green if code == 200 else print_red)(msg)57    def _service_request(self, routes, extra_params=None):58        try:59            route_match = find_route(self.path, routes)60            if not route_match:61                raise HTTPError(404, "Matching route not found")62            handler, args = route_match63            if extra_params:64                args.update(extra_params)65            output = handler(**args)66            self._send_reponse(handler, output)67        except HTTPError as e:68            self._handle_http_error(e)69        except Exception:70            self._handle_internal_server_error()71            raise72    def _send_reponse(self, handler_function, output):73        # These are the acceptable output types:74        #75        # * string (gets returned as plain text)76        # * list or dict (gets serialized to JSON)77        # * Response (gets written out with appropriate content type)78        # * HTTPError (gets thrown as an exception, which is subsequently79        #   caught and written as an error with appropriate status code)80        #81        # Anything else indicates the student is probably not doing what they82        # meant to do, so we throw an exception.83        if isinstance(output, str):84            output = Response(output, content_type="text/plain")85        elif isinstance(output, list) or isinstance(output, dict):86            output = Response(json.dumps(output, indent=4),87                              content_type="application/json")88        elif isinstance(output, Response):89            # nothing to do here90            pass91        elif isinstance(output, HTTPError):92            raise output93        else:94            raise TypeError(f"Function {handler_function.__name__!r} returned unacceptable "95                    f"output: {output!r}\n"96                    "Your function should return one of these:\n"97                    " * A string (to be sent to the client as plain text)\n"98                    " * A list or dictionary (to be sent to the client as JSON)\n"99                    " * A Response object (if you are trying to send a specific content-type)\n"100                    " * An HTTPError (if you want to report an error to the client)")101        self.send_response(200)102        self.send_header("Content-Type", output.get_content_type())103        self.end_headers()104        self.wfile.write(output.get_body_bytes())105    def _handle_internal_server_error(self):106        self.send_response(500)107        self.send_header("Content-Type", "text/plain")108        self.end_headers()109        self.wfile.write(bytes(f"Unexpected server error (see terminal for details)",110                                "utf-8"))111    def _handle_http_error(self, e):112        self._http_error = e113        self.send_response(e.status)114        self.send_header("Content-Type", "text/plain")115        self.end_headers()116        self.wfile.write(bytes(f"Error: {e.message}", "utf-8"))117    def do_GET(self):118        self._log_request_start()119        self._service_request(api.GET_ROUTES)120    # Handles POST requests121    def do_POST(self):122        self._log_request_start()123        ctype = self.headers["Content-Type"]124        # refuse to receive non-json content125        if ctype != "application/json":126            self._handle_http_error(HTTPError(400,127                    "Error in serve.py: Expected the client to specify a content "128                    f"type of 'application/json', but got {ctype!r} instead."))129            return130        # read the message and convert it into a python dictionary131        length = int(self.headers["Content-Length"])132        try:133            info = json.loads(self.rfile.read(length))134        except json.JSONDecodeError:135            self._handle_http_error(HTTPError(400,136                    "Error in serve.py: The request body received from the client "...versions_client.py
Source:versions_client.py  
...24        # Note: we do a raw_request here because we want to use25        # an unversioned URL, not "v2/$project_id/".26        # Since raw_request doesn't log anything, we do that too.27        start = time.time()28        self._log_request_start('GET', version_url)29        response, body = self.raw_request(version_url, 'GET')30        self._error_checker(response, body)31        end = time.time()32        self._log_request('GET', version_url, response,33                          secs=(end - start), resp_body=body)34        self.response_checker('GET', response, body)35        self.expected_success(200, response.status)36        body = json.loads(body)...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!!
