コード例 #1
0
    def test_must_catch_function_not_found_exception(self,
                                                     ApplicationBuilderMock,
                                                     BuildContextMock):
        ctx_mock = Mock()
        BuildContextMock.return_value.__enter__ = Mock()
        BuildContextMock.return_value.__enter__.return_value = ctx_mock
        ApplicationBuilderMock.side_effect = FunctionNotFound(
            "Function Not Found")

        with self.assertRaises(UserException) as ctx:
            do_cli(
                "function_identifier",
                "template",
                "base_dir",
                "build_dir",
                "cache_dir",
                "clean",
                "use_container",
                "cached",
                "parallel",
                "manifest_path",
                "docker_network",
                "skip_pull",
                "parameteroverrides",
                "mode",
                (""),
                "container_env_var_file",
                (),
            )

        self.assertEqual(str(ctx.exception), "Function Not Found")
コード例 #2
0
    def invoke(self, function_name, event, stdout=None, stderr=None):
        """
        Find the Lambda function with given name and invoke it. Pass the given event to the function and return
        response through the given streams.

        This function will block until either the function completes or times out.

        :param string function_name: Name of the Lambda function to invoke
        :param string event: Event data passed to the function. Must be a valid JSON String.
        :param io.BaseIO stdout: Stream to write the output of the Lambda function to.
        :param io.BaseIO stderr: Stream to write the Lambda runtime logs to.
        :raises FunctionNotfound: When we cannot find a function with the given name
        """

        # Generate the correct configuration based on given inputs
        function = self.provider.get(function_name)

        if not function:
            raise FunctionNotFound("Unable to find a Function with name '%s'",
                                   function_name)

        LOG.debug("Found one Lambda function with name '%s'", function_name)

        LOG.info("Invoking %s (%s)", function.handler, function.runtime)
        config = self._get_invoke_config(function)

        # Invoke the function
        self.local_runtime.invoke(config,
                                  event,
                                  debug_context=self.debug_context,
                                  stdout=stdout,
                                  stderr=stderr)
コード例 #3
0
 def mocked_function_provider(cls, function_name):
     if function_name == "HelloWorld":
         return cls.hello_world_function
     if function_name == "ThrowError":
         return cls.throw_error_function
     else:
         raise FunctionNotFound("Could not find Function")
コード例 #4
0
ファイル: test_cli.py プロジェクト: zsc347/aws-sam-cli
    def test_must_raise_user_exception_on_function_not_found(
            self, get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        context_mock.local_lambda_runner.invoke.side_effect = FunctionNotFound(
            "not found")

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(ctx=None,
                       function_identifier=self.function_id,
                       template=self.template,
                       event=self.eventfile,
                       env_vars=self.env_vars,
                       debug_port=self.debug_port,
                       debug_args=self.debug_args,
                       docker_volume_basedir=self.docker_volume_basedir,
                       docker_network=self.docker_network,
                       log_file=self.log_file,
                       skip_pull_image=self.skip_pull_image,
                       profile=self.profile)

        msg = str(ex_ctx.exception)
        self.assertEquals(
            msg, "Function {} not found in template".format(self.function_id))
コード例 #5
0
    def invoke(self, function_name, event, stdout=None, stderr=None):
        """
        Find the Lambda function with given name and invoke it. Pass the given event to the function and return
        response through the given streams.

        This function will block until either the function completes or times out.

        Parameters
        ----------
        function_name str
            Name of the Lambda function to invoke
        event str
            Event data passed to the function. Must be a valid JSON String.
        stdout samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the output of the Lambda function to.
        stderr samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the Lambda runtime logs to.

        Raises
        ------
        FunctionNotfound
            When we cannot find a function with the given name
        """

        # Generate the correct configuration based on given inputs
        function = self.provider.get(function_name)

        if not function:
            all_functions = [f.name for f in self.provider.get_all()]
            available_function_message = "{} not found. Possible options in your template: {}".format(
                function_name, all_functions)
            LOG.info(available_function_message)
            raise FunctionNotFound(
                "Unable to find a Function with name '{}'".format(
                    function_name))

        LOG.debug("Found one Lambda function with name '%s'", function_name)

        LOG.info("Invoking %s (%s)", function.handler, function.runtime)
        config = self._get_invoke_config(function)

        # Invoke the function
        try:
            self.local_runtime.invoke(config,
                                      event,
                                      debug_context=self.debug_context,
                                      stdout=stdout,
                                      stderr=stderr)
        except ContainerResponseException as ex:
            raise InvokeContextException(
                f"No response from invoke container for {function.name}",
                wrapped_from=ex.__class__.__name__)
        except OSError as os_error:
            # pylint: disable=no-member
            if hasattr(os_error, "winerror") and os_error.winerror == 1314:
                raise NoPrivilegeException(
                    "Administrator, Windows Developer Mode, or SeCreateSymbolicLinkPrivilege is required to create symbolic link for files: {}, {}"
                    .format(os_error.filename, os_error.filename2))

            raise
コード例 #6
0
    def test_request_handles_error_when_invoke_cant_find_function(self, service_error_responses_patch):

        not_found_response_mock = Mock()
        self.service._construct_event = Mock()
        self.service._get_current_route = Mock()
        service_error_responses_patch.lambda_not_found_response.return_value = not_found_response_mock

        self.lambda_runner.invoke.side_effect = FunctionNotFound()

        response = self.service._request_handler()

        self.assertEquals(response, not_found_response_mock)
コード例 #7
0
    def invoke(self, function_name, event, stdout=None, stderr=None):
        """
        Find the Lambda function with given name and invoke it. Pass the given event to the function and return
        response through the given streams.

        This function will block until either the function completes or times out.

        Parameters
        ----------
        function_name str
            Name of the Lambda function to invoke
        event str
            Event data passed to the function. Must be a valid JSON String.
        stdout samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the output of the Lambda function to.
        stderr samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the Lambda runtime logs to.

        Raises
        ------
        FunctionNotfound
            When we cannot find a function with the given name
        """

        # Generate the correct configuration based on given inputs
        function = self.provider.get(function_name)

        if not function:
            all_functions = [f.name for f in self.provider.get_all()]
            available_function_message = "{} not found. Possible options in your template: {}".format(
                function_name, all_functions)
            LOG.info(available_function_message)
            raise FunctionNotFound(
                "Unable to find a Function with name '{}'".format(
                    function_name))

        LOG.debug("Found one Lambda function with name '%s'", function_name)

        LOG.info("Invoking %s (%s)", function.handler, function.runtime)
        config = self._get_invoke_config(function)

        # Invoke the function
        self.local_runtime.invoke(config,
                                  event,
                                  debug_context=self.debug_context,
                                  stdout=stdout,
                                  stderr=stderr)
コード例 #8
0
    def functions_to_build(self):
        if self._function_identifier:
            function = self._function_provider.get(self._function_identifier)

            if not function:
                all_functions = [
                    f.name for f in self._function_provider.get_all()
                ]
                available_function_message = "{} not found. Possible options in your template: {}" \
                    .format(self._function_identifier, all_functions)
                LOG.info(available_function_message)
                raise FunctionNotFound(
                    "Unable to find a Function with name '%s'",
                    self._function_identifier)

            return [function]

        return self._function_provider.get_all()
コード例 #9
0
class TestCli(TestCase):
    def setUp(self):
        self.function_id = "id"
        self.template = "template"
        self.eventfile = "eventfile"
        self.env_vars = "env-vars"
        self.debug_port = 123
        self.debug_args = "args"
        self.debugger_path = "/test/path"
        self.docker_volume_basedir = "basedir"
        self.docker_network = "network"
        self.log_file = "logfile"
        self.skip_pull_image = True
        self.no_event = False
        self.parameter_overrides = {}
        self.layer_cache_basedir = "/some/layers/path"
        self.force_image_build = True
        self.region_name = "region"

    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_cli_must_setup_context_and_invoke(self, get_event_mock,
                                               InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        invoke_cli(ctx=ctx_mock,
                   function_identifier=self.function_id,
                   template=self.template,
                   event=self.eventfile,
                   no_event=self.no_event,
                   env_vars=self.env_vars,
                   debug_port=self.debug_port,
                   debug_args=self.debug_args,
                   debugger_path=self.debugger_path,
                   docker_volume_basedir=self.docker_volume_basedir,
                   docker_network=self.docker_network,
                   log_file=self.log_file,
                   skip_pull_image=self.skip_pull_image,
                   parameter_overrides=self.parameter_overrides,
                   layer_cache_basedir=self.layer_cache_basedir,
                   force_image_build=self.force_image_build)

        InvokeContextMock.assert_called_with(
            template_file=self.template,
            function_identifier=self.function_id,
            env_vars_file=self.env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            debug_port=self.debug_port,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            aws_region=self.region_name)

        context_mock.local_lambda_runner.invoke.assert_called_with(
            context_mock.function_name,
            event=event_data,
            stdout=context_mock.stdout,
            stderr=context_mock.stderr)
        get_event_mock.assert_called_with(self.eventfile)

    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_cli_must_invoke_with_no_event(self, get_event_mock,
                                           InvokeContextMock):
        self.no_event = True

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock
        invoke_cli(ctx=ctx_mock,
                   function_identifier=self.function_id,
                   template=self.template,
                   event=STDIN_FILE_NAME,
                   no_event=self.no_event,
                   env_vars=self.env_vars,
                   debug_port=self.debug_port,
                   debug_args=self.debug_args,
                   debugger_path=self.debugger_path,
                   docker_volume_basedir=self.docker_volume_basedir,
                   docker_network=self.docker_network,
                   log_file=self.log_file,
                   skip_pull_image=self.skip_pull_image,
                   parameter_overrides=self.parameter_overrides,
                   layer_cache_basedir=self.layer_cache_basedir,
                   force_image_build=self.force_image_build)

        InvokeContextMock.assert_called_with(
            template_file=self.template,
            function_identifier=self.function_id,
            env_vars_file=self.env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            debug_port=self.debug_port,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            aws_region=self.region_name)

        context_mock.local_lambda_runner.invoke.assert_called_with(
            context_mock.function_name,
            event="{}",
            stdout=context_mock.stdout,
            stderr=context_mock.stderr)
        get_event_mock.assert_not_called()

    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_no_event_and_event(
            self, get_event_mock, InvokeContextMock):
        self.no_event = True

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(ctx=ctx_mock,
                       function_identifier=self.function_id,
                       template=self.template,
                       event=self.eventfile,
                       no_event=self.no_event,
                       env_vars=self.env_vars,
                       debug_port=self.debug_port,
                       debug_args=self.debug_args,
                       debugger_path=self.debugger_path,
                       docker_volume_basedir=self.docker_volume_basedir,
                       docker_network=self.docker_network,
                       log_file=self.log_file,
                       skip_pull_image=self.skip_pull_image,
                       parameter_overrides=self.parameter_overrides,
                       layer_cache_basedir=self.layer_cache_basedir,
                       force_image_build=self.force_image_build)

        msg = str(ex_ctx.exception)
        self.assertEquals(
            msg,
            "no_event and event cannot be used together. Please provide only one."
        )

    @parameterized.expand([
        param(FunctionNotFound("not found"),
              "Function id not found in template"),
        param(DockerImagePullFailedException("Failed to pull image"),
              "Failed to pull image")
    ])
    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_function_not_found(
            self, side_effect_exception, expected_exectpion_message,
            get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        context_mock.local_lambda_runner.invoke.side_effect = side_effect_exception

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(ctx=ctx_mock,
                       function_identifier=self.function_id,
                       template=self.template,
                       event=self.eventfile,
                       no_event=self.no_event,
                       env_vars=self.env_vars,
                       debug_port=self.debug_port,
                       debug_args=self.debug_args,
                       debugger_path=self.debugger_path,
                       docker_volume_basedir=self.docker_volume_basedir,
                       docker_network=self.docker_network,
                       log_file=self.log_file,
                       skip_pull_image=self.skip_pull_image,
                       parameter_overrides=self.parameter_overrides,
                       layer_cache_basedir=self.layer_cache_basedir,
                       force_image_build=self.force_image_build)

        msg = str(ex_ctx.exception)
        self.assertEquals(msg, expected_exectpion_message)

    @parameterized.expand([
        (InvalidSamDocumentException("bad template"), "bad template"),
        (InvalidLayerReference(), "Layer References need to be of type "
         "'AWS::Serverless::LayerVersion' or 'AWS::Lambda::LayerVersion'"),
        (DebuggingNotSupported("Debugging not supported"),
         "Debugging not supported")
    ])
    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_invalid_sam_template(
            self, exeception_to_raise, execption_message, get_event_mock,
            InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        InvokeContextMock.side_effect = exeception_to_raise

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(ctx=ctx_mock,
                       function_identifier=self.function_id,
                       template=self.template,
                       event=self.eventfile,
                       no_event=self.no_event,
                       env_vars=self.env_vars,
                       debug_port=self.debug_port,
                       debug_args=self.debug_args,
                       debugger_path=self.debugger_path,
                       docker_volume_basedir=self.docker_volume_basedir,
                       docker_network=self.docker_network,
                       log_file=self.log_file,
                       skip_pull_image=self.skip_pull_image,
                       parameter_overrides=self.parameter_overrides,
                       layer_cache_basedir=self.layer_cache_basedir,
                       force_image_build=self.force_image_build)

        msg = str(ex_ctx.exception)
        self.assertEquals(msg, execption_message)

    @patch("samcli.commands.local.invoke.cli.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_invalid_env_vars(
            self, get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name

        InvokeContextMock.side_effect = OverridesNotWellDefinedError(
            "bad env vars")

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(ctx=ctx_mock,
                       function_identifier=self.function_id,
                       template=self.template,
                       event=self.eventfile,
                       no_event=self.no_event,
                       env_vars=self.env_vars,
                       debug_port=self.debug_port,
                       debug_args=self.debug_args,
                       debugger_path=self.debugger_path,
                       docker_volume_basedir=self.docker_volume_basedir,
                       docker_network=self.docker_network,
                       log_file=self.log_file,
                       skip_pull_image=self.skip_pull_image,
                       parameter_overrides=self.parameter_overrides,
                       layer_cache_basedir=self.layer_cache_basedir,
                       force_image_build=self.force_image_build)

        msg = str(ex_ctx.exception)
        self.assertEquals(msg, "bad env vars")
コード例 #10
0
ファイル: test_cli.py プロジェクト: wchengru/aws-sam-cli
class TestCli(TestCase):
    def setUp(self):
        self.function_id = "id"
        self.template = "template"
        self.eventfile = "eventfile"
        self.env_vars = "env-vars"
        self.container_env_vars = "debug-env-vars"
        self.debug_ports = [123]
        self.debug_args = "args"
        self.debugger_path = "/test/path"
        self.docker_volume_basedir = "basedir"
        self.docker_network = "network"
        self.log_file = "logfile"
        self.skip_pull_image = True
        self.no_event = True
        self.parameter_overrides = {}
        self.layer_cache_basedir = "/some/layers/path"
        self.force_image_build = True
        self.shutdown = False
        self.region_name = "region"
        self.profile = "profile"

    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_cli_must_setup_context_and_invoke(self, get_event_mock,
                                               InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        invoke_cli(
            ctx=ctx_mock,
            function_identifier=self.function_id,
            template=self.template,
            event=self.eventfile,
            no_event=self.no_event,
            env_vars=self.env_vars,
            debug_port=self.debug_ports,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            container_env_vars=self.container_env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            shutdown=self.shutdown,
        )

        InvokeContextMock.assert_called_with(
            template_file=self.template,
            function_identifier=self.function_id,
            env_vars_file=self.env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            debug_ports=self.debug_ports,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            container_env_vars_file=self.container_env_vars,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            shutdown=self.shutdown,
            aws_region=self.region_name,
            aws_profile=self.profile,
        )

        context_mock.local_lambda_runner.invoke.assert_called_with(
            context_mock.function_identifier,
            event=event_data,
            stdout=context_mock.stdout,
            stderr=context_mock.stderr)
        get_event_mock.assert_called_with(self.eventfile)

    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_cli_must_invoke_with_no_event(self, get_event_mock,
                                           InvokeContextMock):
        self.event = None

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock
        invoke_cli(
            ctx=ctx_mock,
            function_identifier=self.function_id,
            template=self.template,
            event=self.event,
            no_event=self.no_event,
            env_vars=self.env_vars,
            debug_port=self.debug_ports,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            container_env_vars=self.container_env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            shutdown=self.shutdown,
        )

        InvokeContextMock.assert_called_with(
            template_file=self.template,
            function_identifier=self.function_id,
            env_vars_file=self.env_vars,
            docker_volume_basedir=self.docker_volume_basedir,
            docker_network=self.docker_network,
            log_file=self.log_file,
            skip_pull_image=self.skip_pull_image,
            debug_ports=self.debug_ports,
            debug_args=self.debug_args,
            debugger_path=self.debugger_path,
            container_env_vars_file=self.container_env_vars,
            parameter_overrides=self.parameter_overrides,
            layer_cache_basedir=self.layer_cache_basedir,
            force_image_build=self.force_image_build,
            shutdown=self.shutdown,
            aws_region=self.region_name,
            aws_profile=self.profile,
        )

        get_event_mock.assert_not_called()
        context_mock.local_lambda_runner.invoke.assert_called_with(
            context_mock.function_identifier,
            event="{}",
            stdout=context_mock.stdout,
            stderr=context_mock.stderr)

    @parameterized.expand([
        param(FunctionNotFound("not found"),
              "Function id not found in template"),
        param(DockerImagePullFailedException("Failed to pull image"),
              "Failed to pull image"),
    ])
    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_function_not_found(
            self, side_effect_exception, expected_exectpion_message,
            get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        context_mock.local_lambda_runner.invoke.side_effect = side_effect_exception

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(
                ctx=ctx_mock,
                function_identifier=self.function_id,
                template=self.template,
                event=self.eventfile,
                no_event=self.no_event,
                env_vars=self.env_vars,
                debug_port=self.debug_ports,
                debug_args=self.debug_args,
                debugger_path=self.debugger_path,
                container_env_vars=self.container_env_vars,
                docker_volume_basedir=self.docker_volume_basedir,
                docker_network=self.docker_network,
                log_file=self.log_file,
                skip_pull_image=self.skip_pull_image,
                parameter_overrides=self.parameter_overrides,
                layer_cache_basedir=self.layer_cache_basedir,
                force_image_build=self.force_image_build,
                shutdown=self.shutdown,
            )

        msg = str(ex_ctx.exception)
        self.assertEqual(msg, expected_exectpion_message)

    @parameterized.expand([
        param(
            InvalidIntermediateImageError(
                "ImageUri not set to a reference-able image for Function: MyFunction"
            ),
            "ImageUri not set to a reference-able image for Function: MyFunction",
        ),
    ])
    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_function_local_invoke_image_not_found_for_IMAGE_packagetype(
            self, side_effect_exception, expected_exectpion_message,
            get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        context_mock.local_lambda_runner.invoke.side_effect = side_effect_exception

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(
                ctx=ctx_mock,
                function_identifier=self.function_id,
                template=self.template,
                event=self.eventfile,
                no_event=self.no_event,
                env_vars=self.env_vars,
                debug_port=self.debug_ports,
                debug_args=self.debug_args,
                debugger_path=self.debugger_path,
                container_env_vars=self.container_env_vars,
                docker_volume_basedir=self.docker_volume_basedir,
                docker_network=self.docker_network,
                log_file=self.log_file,
                skip_pull_image=self.skip_pull_image,
                parameter_overrides=self.parameter_overrides,
                layer_cache_basedir=self.layer_cache_basedir,
                force_image_build=self.force_image_build,
                shutdown=self.shutdown,
            )

        msg = str(ex_ctx.exception)
        self.assertEqual(msg, expected_exectpion_message)

    @parameterized.expand([
        (InvalidSamDocumentException("bad template"), "bad template"),
        (
            InvalidLayerReference(),
            "Layer References need to be of type "
            "'AWS::Serverless::LayerVersion' or 'AWS::Lambda::LayerVersion'",
        ),
        (DebuggingNotSupported("Debugging not supported"),
         "Debugging not supported"),
    ])
    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_invalid_sam_template(
            self, exeception_to_raise, execption_message, get_event_mock,
            InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        InvokeContextMock.side_effect = exeception_to_raise

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(
                ctx=ctx_mock,
                function_identifier=self.function_id,
                template=self.template,
                event=self.eventfile,
                no_event=self.no_event,
                env_vars=self.env_vars,
                debug_port=self.debug_ports,
                debug_args=self.debug_args,
                debugger_path=self.debugger_path,
                container_env_vars=self.container_env_vars,
                docker_volume_basedir=self.docker_volume_basedir,
                docker_network=self.docker_network,
                log_file=self.log_file,
                skip_pull_image=self.skip_pull_image,
                parameter_overrides=self.parameter_overrides,
                layer_cache_basedir=self.layer_cache_basedir,
                force_image_build=self.force_image_build,
                shutdown=self.shutdown,
            )

        msg = str(ex_ctx.exception)
        self.assertEqual(msg, execption_message)

    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_invalid_env_vars(
            self, get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        InvokeContextMock.side_effect = OverridesNotWellDefinedError(
            "bad env vars")

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(
                ctx=ctx_mock,
                function_identifier=self.function_id,
                template=self.template,
                event=self.eventfile,
                no_event=self.no_event,
                env_vars=self.env_vars,
                debug_port=self.debug_ports,
                debug_args=self.debug_args,
                debugger_path=self.debugger_path,
                container_env_vars=self.container_env_vars,
                docker_volume_basedir=self.docker_volume_basedir,
                docker_network=self.docker_network,
                log_file=self.log_file,
                skip_pull_image=self.skip_pull_image,
                parameter_overrides=self.parameter_overrides,
                layer_cache_basedir=self.layer_cache_basedir,
                force_image_build=self.force_image_build,
                shutdown=self.shutdown,
            )

        msg = str(ex_ctx.exception)
        self.assertEqual(msg, "bad env vars")

    @parameterized.expand([
        param(
            ContainerNotStartableException(
                "Container cannot be started, no free ports on host"),
            "Container cannot be started, no free ports on host",
        ),
    ])
    @patch("samcli.commands.local.cli_common.invoke_context.InvokeContext")
    @patch("samcli.commands.local.invoke.cli._get_event")
    def test_must_raise_user_exception_on_function_no_free_ports(
            self, side_effect_exception, expected_exectpion_message,
            get_event_mock, InvokeContextMock):
        event_data = "data"
        get_event_mock.return_value = event_data

        ctx_mock = Mock()
        ctx_mock.region = self.region_name
        ctx_mock.profile = self.profile

        # Mock the __enter__ method to return a object inside a context manager
        context_mock = Mock()
        InvokeContextMock.return_value.__enter__.return_value = context_mock

        context_mock.local_lambda_runner.invoke.side_effect = side_effect_exception

        with self.assertRaises(UserException) as ex_ctx:

            invoke_cli(
                ctx=ctx_mock,
                function_identifier=self.function_id,
                template=self.template,
                event=self.eventfile,
                no_event=self.no_event,
                env_vars=self.env_vars,
                debug_port=self.debug_ports,
                debug_args=self.debug_args,
                debugger_path=self.debugger_path,
                container_env_vars=self.container_env_vars,
                docker_volume_basedir=self.docker_volume_basedir,
                docker_network=self.docker_network,
                log_file=self.log_file,
                skip_pull_image=self.skip_pull_image,
                parameter_overrides=self.parameter_overrides,
                layer_cache_basedir=self.layer_cache_basedir,
                force_image_build=self.force_image_build,
                shutdown=self.shutdown,
            )

        msg = str(ex_ctx.exception)
        self.assertEqual(msg, expected_exectpion_message)
コード例 #11
0
ファイル: local_lambda.py プロジェクト: michael-k/aws-sam-cli
    def invoke(self, function_name, event, stdout=None, stderr=None):
        """
        Find the Lambda function with given name and invoke it. Pass the given event to the function and return
        response through the given streams.

        This function will block until either the function completes or times out.

        Parameters
        ----------
        function_name str
            Name of the Lambda function to invoke
        event str
            Event data passed to the function. Must be a valid JSON String.
        stdout samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the output of the Lambda function to.
        stderr samcli.lib.utils.stream_writer.StreamWriter
            Stream writer to write the Lambda runtime logs to.

        Raises
        ------
        FunctionNotfound
            When we cannot find a function with the given name
        """

        # Generate the correct configuration based on given inputs
        function = self.provider.get(function_name)

        if not function:
            all_functions = [f.name for f in self.provider.get_all()]
            available_function_message = "{} not found. Possible options in your template: {}".format(
                function_name, all_functions)
            LOG.info(available_function_message)
            raise FunctionNotFound(
                "Unable to find a Function with name '{}'".format(
                    function_name))

        LOG.debug("Found one Lambda function with name '%s'", function_name)
        if function.packagetype == ZIP:
            LOG.info("Invoking %s (%s)", function.handler, function.runtime)
        elif function.packagetype == IMAGE:
            if not function.imageuri:
                raise InvalidIntermediateImageError(
                    f"ImageUri not provided for Function: {function_name} of PackageType: {function.packagetype}"
                )
            LOG.info("Invoking Container created from %s", function.imageuri)
        config = self.get_invoke_config(function)

        # Invoke the function
        try:
            self.local_runtime.invoke(config,
                                      event,
                                      debug_context=self.debug_context,
                                      stdout=stdout,
                                      stderr=stderr)
        except ContainerResponseException:
            # NOTE(sriram-mv): This should still result in a exit code zero to avoid regressions.
            LOG.info("No response from invoke container for %s", function.name)
        except OSError as os_error:
            # pylint: disable=no-member
            if hasattr(os_error, "winerror") and os_error.winerror == 1314:
                raise NoPrivilegeException(
                    "Administrator, Windows Developer Mode, "
                    "or SeCreateSymbolicLinkPrivilege is required to create symbolic link for files: {}, {}"
                    .format(os_error.filename,
                            os_error.filename2)) from os_error

            raise