def test_must_set_get_debug_flag(self): ctx = Context() ctx.debug = True self.assertEquals(ctx.debug, True, "debug must be set to True") self.assertEquals(logging.getLogger().getEffectiveLevel(), logging.DEBUG)
def test_must_set_aws_region_in_boto_session(self): region = "myregion" ctx = Context() ctx.region = region self.assertEquals(ctx.region, region) self.assertEquals(region, boto3._get_default_session().region_name)
def test_must_find_context(self, click_mock): ctx = Context() result = ctx.get_current_context() self.assertEqual(click_mock.get_current_context.return_value.find_object.return_value, result) click_mock.get_current_context.return_value.find_object.assert_called_once_with(Context)
def test_must_unset_get_debug_flag(self): ctx = Context() message_record = logging.makeLogRecord({"msg": "hello world"}) timestamp_log_regex = re.compile(r"^[0-9:\- ,]+ \| .*$") sam_cli_logger = logging.getLogger(SAM_CLI_LOGGER_NAME) lambda_builders_logger = logging.getLogger(LAMBDA_BULDERS_LOGGER_NAME) SamCliLogger.configure_logger(sam_cli_logger, SAM_CLI_FORMATTER, logging.INFO) SamCliLogger.configure_logger(lambda_builders_logger, SAM_CLI_FORMATTER, logging.INFO) handlers = [ logging.getLogger(SAM_CLI_LOGGER_NAME).handlers[0], logging.getLogger(LAMBDA_BULDERS_LOGGER_NAME).handlers[0], ] # timestamp should not be output for handler in handlers: self.assertNotRegex(handler.formatter.format(message_record), timestamp_log_regex) ctx.debug = True self.assertEqual(ctx.debug, True, "debug must be set to True") # timestamp should be output for handler in handlers: self.assertRegex( handler.formatter.format(message_record), timestamp_log_regex, "debug log record should contain timestamps", ) # Flipping from True to False ctx.debug = False self.assertEqual(ctx.debug, False, "debug must be set to False")
def test_must_set_get_debug_flag(self): ctx = Context() ctx.debug = True self.assertEqual(ctx.debug, True, "debug must be set to True") self.assertEqual(logging.getLogger("samcli").getEffectiveLevel(), logging.DEBUG) self.assertEqual(logging.getLogger("aws_lambda_builders").getEffectiveLevel(), logging.DEBUG)
def test_must_set_aws_profile_in_boto_session(self, boto_mock): profile = "foo" ctx = Context() ctx.profile = profile self.assertEquals(ctx.profile, profile) boto_mock.setup_default_session.assert_called_with(region_name=None, profile_name=profile)
def test_must_set_aws_profile_in_boto_session(self, boto_mock): profile = "foo" ctx = Context() ctx.profile = profile self.assertEqual(ctx.profile, profile) boto_mock.setup_default_session.assert_called_with(region_name=None, profile_name=profile, botocore_session=ANY)
def test_must_set_all_aws_session_properties(self, boto_mock): profile = "foo" region = "myregion" ctx = Context() ctx.profile = profile ctx.region = region boto_mock.setup_default_session.assert_called_with(region_name=region, profile_name=profile)
def test_must_unset_get_debug_flag(self): ctx = Context() ctx.debug = True self.assertEquals(ctx.debug, True, "debug must be set to True") # Flipping from True to False ctx.debug = False self.assertEquals(ctx.debug, False, "debug must be set to False")
def test_create_new_context_if_not_found(self, click_mock): # Context can't be found click_mock.get_current_context.return_value.find_object.return_value = None ctx = Context() result = ctx.get_current_context() self.assertEqual(click_mock.get_current_context.return_value.ensure_object.return_value, result) click_mock.get_current_context.return_value.ensure_object.assert_called_once_with(Context)
def test_must_set_get_debug_flag(self): ctx = Context() ctx.debug = True self.assertEqual(ctx.debug, True, "debug must be set to True") self.assertEqual( logging.getLogger(SAM_CLI_LOGGER_NAME).getEffectiveLevel(), logging.DEBUG) self.assertEqual( logging.getLogger(LAMBDA_BULDERS_LOGGER_NAME).getEffectiveLevel(), logging.DEBUG)
def wrapped(*args, **kwargs): telemetry = Telemetry() template_warning_checker = TemplateWarningsChecker() ctx = Context.get_current_context() try: ctx.template_dict except AttributeError: LOG.debug( "Ignoring warning check as template is not provided in context." ) return func(*args, **kwargs) for warning_name in warning_names: warning_message = template_warning_checker.check_template_for_warning( warning_name, ctx.template_dict) if _telemetry_enabled(): telemetry.emit( "templateWarning", _build_warning_metric(ctx, warning_name, warning_message)) if warning_message: click.secho(WARNING_ANNOUNCEMENT.format(warning_message), fg="yellow") return func(*args, **kwargs)
def _default_session_id(self): """ Get the default SessionId from Click Context. """ ctx = Context.get_current_context() if ctx: return ctx.session_id
def wrapped(*args, **kwargs): telemetry = Telemetry() template_warning_checker = TemplateWarningsChecker() ctx = Context.get_current_context() try: ctx.template_dict except AttributeError: LOG.debug( "Ignoring warning check as template is not provided in context." ) return func(*args, **kwargs) for warning_name in warning_names: warning_message = template_warning_checker.check_template_for_warning( warning_name, ctx.template_dict) metric = Metric("templateWarning") metric.add_data("awsProfileProvided", bool(ctx.profile)) metric.add_data("debugFlagProvided", bool(ctx.debug)) metric.add_data("region", ctx.region or "") metric.add_data("warningName", warning_name) metric.add_data( "warningCount", 1 if warning_message else 0) # 1-True or 0-False telemetry.emit(metric) if warning_message: click.secho(WARNING_ANNOUNCEMENT.format(warning_message), fg="yellow") return func(*args, **kwargs)
def wrapped(*args, **kwargs): if not _telemetry_enabled(): # When Telemetry is disabled, call the function immediately and return. return func(*args, **kwargs) telemetry = Telemetry() exception = None return_value = None exit_reason = "success" exit_code = 0 duration_fn = _timer() try: # Execute the function and capture return value. This is returned back by the wrapper # First argument of all commands should be the Context return_value = func(*args, **kwargs) except UserException as ex: # Capture exception information and re-raise it later so we can first send metrics. exception = ex exit_code = ex.exit_code if ex.wrapped_from is None: exit_reason = type(ex).__name__ else: exit_reason = ex.wrapped_from except Exception as ex: exception = ex # Standard Unix practice to return exit code 255 on fatal/unhandled exit. exit_code = 255 exit_reason = type(ex).__name__ ctx = Context.get_current_context() telemetry.emit( "commandRun", { # Metric about command's general environment "awsProfileProvided": bool(ctx.profile), "debugFlagProvided": bool(ctx.debug), "region": ctx.region or "", "commandName": ctx.command_path, # Full command path. ex: sam local start-api # Metric about command's execution characteristics "duration": duration_fn(), "exitReason": exit_reason, "exitCode": exit_code, }, ) if exception: raise exception # pylint: disable=raising-bad-type return return_value
def _default_session_id() -> Optional[str]: """ Get the default SessionId from Click Context. Fail silently if Context does not exist. """ try: ctx = Context.get_current_context() if ctx: return ctx.session_id return None except RuntimeError: LOG.debug("Unable to find Click Context for getting session_id.") return None
def wrapped(*args, **kwargs): telemetry = Telemetry() metric = Metric("commandRun") exception = None return_value = None exit_reason = "success" exit_code = 0 duration_fn = _timer() try: # Execute the function and capture return value. This is returned back by the wrapper # First argument of all commands should be the Context return_value = func(*args, **kwargs) except UserException as ex: # Capture exception information and re-raise it later so we can first send metrics. exception = ex exit_code = ex.exit_code if ex.wrapped_from is None: exit_reason = type(ex).__name__ else: exit_reason = ex.wrapped_from except Exception as ex: exception = ex # Standard Unix practice to return exit code 255 on fatal/unhandled exit. exit_code = 255 exit_reason = type(ex).__name__ try: ctx = Context.get_current_context() metric.add_data("awsProfileProvided", bool(ctx.profile)) metric.add_data("debugFlagProvided", bool(ctx.debug)) metric.add_data("region", ctx.region or "") metric.add_data( "commandName", ctx.command_path) # Full command path. ex: sam local start-api # Metric about command's execution characteristics metric.add_data("duration", duration_fn()) metric.add_data("exitReason", exit_reason) metric.add_data("exitCode", exit_code) telemetry.emit(metric) except RuntimeError: LOG.debug("Unable to find Click Context for getting session_id.") if exception: raise exception # pylint: disable=raising-bad-type return return_value
def test_get_current_context_from_outside_of_click(self, click_mock): click_mock.get_current_context.return_value = None ctx = Context() # Context can't be found self.assertIsNone(ctx.get_current_context())
def test_must_set_session_id_to_uuid(self, uuid_mock): uuid_mock.uuid4.return_value = "abcd" ctx = Context() self.assertEquals(ctx.session_id, "abcd")
def test_must_initialize_with_defaults(self): ctx = Context() self.assertEquals(ctx.debug, False, "debug must default to False")