Best Python code snippet using localstack_python
test_lambda_whitebox.py
Source:test_lambda_whitebox.py  
...32    THIS_FOLDER, "functions", "python3", "lambda2", "lambda2.zip"33)34class TestLambdaFallbackUrl(unittest.TestCase):35    @staticmethod36    def _run_forward_to_fallback_url(url, fallback=True, lambda_name=None, num_requests=3):37        lambda_client = aws_stack.create_external_boto_client("lambda")38        if fallback:39            config.LAMBDA_FALLBACK_URL = url40        else:41            config.LAMBDA_FORWARD_URL = url42        try:43            result = []44            for i in range(num_requests):45                lambda_name = lambda_name or "non-existing-lambda-%s" % i46                ctx = {"env": "test"}47                tmp = lambda_client.invoke(48                    FunctionName=lambda_name,49                    Payload=b'{"foo":"bar"}',50                    InvocationType="RequestResponse",51                    ClientContext=to_str(base64.b64encode(to_bytes(json.dumps(ctx)))),52                )53            result.append(tmp)54            return result55        finally:56            if fallback:57                config.LAMBDA_FALLBACK_URL = ""58            else:59                config.LAMBDA_FORWARD_URL = ""60    def test_forward_to_fallback_url_dynamodb(self):61        db_table = "lambda-records"62        ddb_client = aws_stack.create_external_boto_client("dynamodb")63        def num_items():64            return len((run_safe(ddb_client.scan, TableName=db_table) or {"Items": []})["Items"])65        items_before = num_items()66        self._run_forward_to_fallback_url("dynamodb://%s" % db_table)67        items_after = num_items()68        self.assertEqual(items_before + 3, items_after)69    def test_forward_to_fallback_url_http(self):70        class MyUpdateListener(ProxyListener):71            def forward_request(self, method, path, data, headers):72                records.append({"data": data, "headers": headers, "method": method, "path": path})73                return lambda_result74        lambda_result = {"result": "test123"}75        local_port = get_free_tcp_port()76        proxy = start_proxy(local_port, backend_url=None, update_listener=MyUpdateListener())77        local_url = "%s://localhost:%s" % (get_service_protocol(), local_port)78        # test 1: forward to LAMBDA_FALLBACK_URL79        records = []80        self._run_forward_to_fallback_url(local_url)81        items_after = len(records)82        for record in records:83            self.assertIn("non-existing-lambda", record["headers"]["lambda-function-name"])84        self.assertEqual(3, items_after)85        # create test Lambda86        lambda_name = "test-%s" % short_uid()87        testutil.create_lambda_function(88            handler_file=TEST_LAMBDA_PYTHON,89            func_name=lambda_name,90            libs=TEST_LAMBDA_LIBS,91        )92        # test 2: forward to LAMBDA_FORWARD_URL93        records = []94        inv_results = self._run_forward_to_fallback_url(95            local_url, lambda_name=lambda_name, fallback=False96        )97        items_after = len(records)98        for record in records:99            headers = record["headers"]100            self.assertIn("/lambda/", headers["Authorization"])101            self.assertEqual("POST", record["method"])102            self.assertIn("/functions/%s/invocations" % lambda_name, record["path"])103            self.assertTrue(headers.get("X-Amz-Client-Context"))104            self.assertEqual("RequestResponse", headers.get("X-Amz-Invocation-Type"))105            self.assertEqual({"foo": "bar"}, json.loads(to_str(record["data"])))106        self.assertEqual(3, items_after)107        # assert result payload matches108        response_payload = inv_results[0]["Payload"].read()...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!!
