Best Python code snippet using localstack_python
lambda_executors.py
Source:lambda_executors.py  
...1027                    sys.path.insert(0, "")1028                if environment:1029                    os.environ.update(environment)1030                # set default env variables required for most Lambda handlers1031                self.set_default_env_variables()1032                # run the actual handler function1033                result = lambda_function_callable(inv_context.event, context)1034            except Exception as e:1035                result = str(e)1036                sys.stderr.write("%s %s" % (e, traceback.format_exc()))1037                raise1038            finally:1039                queue.put(result)1040        process = Process(target=do_execute)1041        start_time = now(millis=True)1042        error = None1043        with CaptureOutput() as c:1044            try:1045                process.run()1046            except Exception as e:1047                error = e1048        result = queue.get()1049        end_time = now(millis=True)1050        # Make sure to keep the log line below, to ensure the log stream gets created1051        request_id = long_uid()1052        log_output = 'START %s: Lambda %s started via "local" executor ...' % (1053            request_id,1054            lambda_function.arn(),1055        )1056        # TODO: Interweaving stdout/stderr currently not supported1057        for stream in (c.stdout(), c.stderr()):1058            if stream:1059                log_output += ("\n" if log_output else "") + stream1060        if isinstance(result, InvocationResult) and result.log_output:1061            log_output += "\n" + result.log_output1062        log_output += "\nEND RequestId: %s" % request_id1063        log_output += "\nREPORT RequestId: %s Duration: %s ms" % (1064            request_id,1065            int((end_time - start_time) * 1000),1066        )1067        # store logs to CloudWatch1068        store_lambda_logs(lambda_function, log_output)1069        result = result.result if isinstance(result, InvocationResult) else result1070        if error:1071            LOG.info(1072                'Error executing Lambda "%s": %s %s',1073                lambda_function.arn(),1074                error,1075                "".join(traceback.format_tb(error.__traceback__)),1076            )1077            raise InvocationException(result, log_output)1078        # construct final invocation result1079        invocation_result = InvocationResult(result, log_output=log_output)1080        # run plugins post-processing logic1081        invocation_result = self.process_result_via_plugins(inv_context, invocation_result)1082        return invocation_result1083    def provide_file_to_lambda(self, local_file: str, inv_context: InvocationContext) -> str:1084        # This is a no-op for local executors - simply return the given local file path1085        return local_file1086    def execute_java_lambda(1087        self, event, context, main_file, lambda_function: LambdaFunction = None1088    ) -> InvocationResult:1089        lambda_function.envvars = lambda_function.envvars or {}1090        java_opts = config.LAMBDA_JAVA_OPTS or ""1091        handler = lambda_function.handler1092        lambda_function.envvars[LAMBDA_HANDLER_ENV_VAR_NAME] = handler1093        event_file = EVENT_FILE_PATTERN.replace("*", short_uid())1094        save_file(event_file, json.dumps(json_safe(event)))1095        TMP_FILES.append(event_file)1096        classpath = "%s:%s:%s" % (1097            main_file,1098            Util.get_java_classpath(main_file),1099            LAMBDA_EXECUTOR_JAR,1100        )1101        cmd = "java %s -cp %s %s %s" % (1102            java_opts,1103            classpath,1104            LAMBDA_EXECUTOR_CLASS,1105            event_file,1106        )1107        # apply plugin patches1108        inv_context = InvocationContext(1109            lambda_function, event, environment=lambda_function.envvars, lambda_command=cmd1110        )1111        result = self.apply_plugin_patches(inv_context)1112        if isinstance(result, InvocationResult):1113            return result1114        cmd = inv_context.lambda_command1115        LOG.info(cmd)1116        # execute Lambda and get invocation result1117        invocation_result = self._execute_in_custom_runtime(cmd, lambda_function=lambda_function)1118        return invocation_result1119    def execute_javascript_lambda(1120        self, event, context, main_file, lambda_function: LambdaFunction = None1121    ):1122        handler = lambda_function.handler1123        function = handler.split(".")[-1]1124        event_json_string = "%s" % (json.dumps(json_safe(event)) if event else "{}")1125        context_json_string = "%s" % (json.dumps(context.__dict__) if context else "{}")1126        cmd = [1127            "node",1128            "-e",1129            'require("%s").%s(%s,%s).then(r => process.stdout.write(JSON.stringify(r)))'1130            % (1131                main_file,1132                function,1133                event_json_string,1134                context_json_string,1135            ),1136        ]1137        LOG.info(cmd)1138        result = self._execute_in_custom_runtime(cmd, lambda_function=lambda_function)1139        return result1140    @staticmethod1141    def set_default_env_variables():1142        # set default env variables required for most Lambda handlers1143        default_env_vars = {"AWS_DEFAULT_REGION": aws_stack.get_region()}1144        env_vars_before = {var: os.environ.get(var) for var in default_env_vars}1145        os.environ.update({k: v for k, v in default_env_vars.items() if not env_vars_before.get(k)})1146        return env_vars_before1147    @staticmethod1148    def reset_default_env_variables(env_vars_before):1149        for env_name, env_value in env_vars_before.items():1150            env_value_before = env_vars_before.get(env_name)1151            os.environ[env_name] = env_value_before or ""1152            if env_value_before is None:1153                os.environ.pop(env_name, None)1154    def execute_go_lambda(self, event, context, main_file, lambda_function: LambdaFunction = None):1155        if lambda_function:1156            lambda_function.envvars["AWS_LAMBDA_FUNCTION_HANDLER"] = main_file1157            lambda_function.envvars["AWS_LAMBDA_EVENT_BODY"] = json.dumps(json_safe(event))1158        else:1159            LOG.warning("Unable to get function details for local execution of Golang Lambda")1160        cmd = GO_LAMBDA_RUNTIME1161        LOG.info(cmd)1162        result = self._execute_in_custom_runtime(cmd, lambda_function=lambda_function)...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!!
