Skip to content

🎥 Make videos programmatically with React

WIP: addressing issue on session and exception

alex fernandez05bf71353a46
diff --git a/packages/lambda-python/.gitignore b/packages/lambda-python/.gitignore
index 66bd092730..868ddaa777 100644
--- a/packages/lambda-python/.gitignore
+++ b/packages/lambda-python/.gitignore
@@ -16,4 +16,5 @@ test-env/
remotion-env-lint/
.idea
-justfile
\ No newline at end of file
+justfile
+.venv
\ No newline at end of file
diff --git a/packages/lambda-python/dev-requirements.txt b/packages/lambda-python/dev-requirements.txt
index cf88bb972a..2dc707f436 100644
--- a/packages/lambda-python/dev-requirements.txt
+++ b/packages/lambda-python/dev-requirements.txt
@@ -1,4 +1,5 @@
pytest
dotenv
boto3-stubs[essential]
-mypy
\ No newline at end of file
+mypy
+boto3
\ No newline at end of file
diff --git a/packages/lambda-python/remotion_lambda/exception.py b/packages/lambda-python/remotion_lambda/exception.py
new file mode 100644
index 0000000000..19969315fd
--- /dev/null
+++ b/packages/lambda-python/remotion_lambda/exception.py
@@ -0,0 +1,12 @@
+
+class RemotionException(Exception):
+ """Base exception for Remotion client errors."""
+
+
+class RemotionInvalidArgumentException(RemotionException, ValueError):
+ """Raised when an invalid argument is provided to a Remotion client method."""
+
+
+class RemotionRenderingOutputError(RemotionException):
+ """Raised when the Remotion rendering process returns an error."""
+
\ No newline at end of file
diff --git a/packages/lambda-python/remotion_lambda/remotionclient.py b/packages/lambda-python/remotion_lambda/remotionclient.py
index 6523dd9116..6502aadc9e 100644
--- a/packages/lambda-python/remotion_lambda/remotionclient.py
+++ b/packages/lambda-python/remotion_lambda/remotionclient.py
@@ -8,7 +8,7 @@ from math import ceil
from typing import Optional, Union, List
from enum import Enum
import boto3
-from botocore.exceptions import ClientError
+from botocore.exceptions import ClientError, ParamValidationError
from botocore.config import Config
from .models import (
CostsInfo,
@@ -22,6 +22,11 @@ from .models import (
RenderType,
)
+from .exception import (
+ RemotionException,
+ RemotionInvalidArgumentException,
+ RemotionRenderingOutputError
+)
logger = logging.getLogger(__name__)
@@ -41,6 +46,8 @@ class RemotionClient:
access_key: Optional[str] = None,
secret_key: Optional[str] = None,
force_path_style=False,
+ botocore_config: Optional[Config] = None,
+ boto_session: Optional[boto3.session.Session] = None,
):
"""
Initialize the RemotionClient.
@@ -52,6 +59,8 @@ class RemotionClient:
access_key (str): AWS access key (optional).
secret_key (str): AWS secret key (optional).
force_path_style (bool): Force path-style S3 URLs (optional).
+ botocore_config (botocore.config.Config): Optional botocore Config object.
+ boto_session (boto3.session.Session): Optional boto3 Session object.
"""
self.access_key = access_key
self.secret_key = secret_key
@@ -59,6 +68,8 @@ class RemotionClient:
self.serve_url = serve_url
self.function_name = function_name
self.force_path_style = force_path_style
+ self.botocore_config = botocore_config
+ self.boto_session = boto_session
def _generate_hash(self, payload):
"""Generate a hash for the payload."""
@@ -80,12 +91,21 @@ class RemotionClient:
"""Generate S3 key for input props."""
return f"input-props/{hash_value}.json"
- def _create_s3_client(self):
- """Create S3 client with appropriate credentials."""
+ def _create_boto_client(self, service_name: str):
kwargs = {'region_name': self.region}
- if self.force_path_style:
- kwargs['config'] = Config(s3={'addressing_style': 'path'})
+ config = self.botocore_config # Start with the base config
+
+ # Apply service-specific config if needed (like s3 path style)
+ if service_name == 's3' and self.force_path_style:
+ s3_config = Config(s3={'addressing_style': 'path'})
+ if config:
+ config = config.merge(s3_config)
+ else:
+ config = s3_config
+
+ if config:
+ kwargs['config'] = config
if self.access_key and self.secret_key:
kwargs.update(
@@ -94,8 +114,12 @@ class RemotionClient:
'aws_secret_access_key': self.secret_key,
}
)
+ if self.boto_session:
+ return self.boto_session.client(service_name, **kwargs)
+ return boto3.client(service_name, **kwargs)
- return boto3.client('s3', **kwargs)
+ def _create_s3_client(self):
+ return self._create_boto_client('s3')
def _get_remotion_buckets(self) -> List[str]:
s3_client = self._create_s3_client()
@@ -103,6 +127,9 @@ class RemotionClient:
try:
response = s3_client.list_buckets()
except ClientError as e:
+ # Re-raise all ClientError exceptions
+ raise e
+ except ParamValidationError as e:
logger.warning("Could not list S3 buckets: %s", e)
return []
@@ -128,16 +155,25 @@ class RemotionClient:
return location == self.region or (
location is None and self.region == REGION_US_EAST
)
- except ClientError:
+ except ClientError as e:
# Ignore buckets we can't access (permission issues, etc.)
+ logger.debug(
+ "Could not get bucket location for %s (possibly permission issue): %s",
+ bucket_name,
+ e,
+ )
return False
+ except ParamValidationError as e:
+ raise RemotionInvalidArgumentException(
+ f"Invalid S3 client parameters for get_bucket_location: {e}"
+ ) from e
def _get_or_create_bucket(self):
"""Get existing bucket or create a new one following JS SDK logic."""
buckets = self._get_remotion_buckets()
if len(buckets) > 1:
- raise ValueError(
+ raise RemotionException( # Generic RemotionException for this specific case
f"You have multiple buckets ({', '.join(buckets)}) in your S3 region "
f"({self.region}) starting with \"remotionlambda-\". "
"Please see https://remotion.dev/docs/lambda/multiple-buckets."
@@ -161,7 +197,12 @@ class RemotionClient:
)
return bucket_name
except ClientError as e:
- raise ValueError(f"Failed to create bucket: {str(e)}") from e
+ # Re-raise all ClientError exceptions
+ raise e
+ except ParamValidationError as e:
+ raise RemotionInvalidArgumentException(
+ f"Invalid S3 client parameters for create_bucket: {e}"
+ ) from e
def _upload_to_s3(self, bucket_name, key, payload):
"""Upload payload to S3."""
@@ -174,7 +215,12 @@ class RemotionClient:
ContentType='application/json',
)
except ClientError as e:
- raise ValueError(f"Failed to upload to S3: {str(e)}") from e
+ # Re-raise all ClientError exceptions
+ raise e
+ except ParamValidationError as e:
+ raise RemotionInvalidArgumentException(
+ f"Invalid S3 client parameters for put_object: {e}"
+ ) from e
def _needs_upload(self, payload_size, render_type):
"""Determine if payload needs to be uploaded to S3."""
@@ -231,23 +277,20 @@ class RemotionClient:
'type': 'payload',
'payload': payload if payload not in ('', 'null') else json.dumps({}),
}
- except (ValueError, TypeError) as error:
- raise ValueError(
+ except (TypeError, OverflowError) as error:
+ raise RemotionInvalidArgumentException(
'Error serializing InputProps. Check for circular '
- + 'references or reduce the object size.'
+ + 'references or invalid data types in the input properties.'
) from error
+ except ClientError as e:
+ # Re-raise S3-related ClientErrors that might occur during upload
+ raise e
- def _create_lambda_client(self):
- if self.access_key and self.secret_key and self.region:
- return boto3.client(
- 'lambda',
- aws_access_key_id=self.access_key,
- aws_secret_access_key=self.secret_key,
- region_name=self.region,
- )
-
- return boto3.client('lambda', region_name=self.region)
+ def _create_lambda_client(self):
+ return self._create_boto_client('lambda')
+
+
def _find_json_objects(self, input_string):
"""Finds and returns a list of complete JSON object strings."""
objects = []
@@ -269,34 +312,58 @@ class RemotionClient:
def _parse_stream(self, stream):
"""Parses a stream of concatenated JSON objects."""
json_objects = self._find_json_objects(stream)
- parsed_objects = [json.loads(obj) for obj in json_objects]
+ parsed_objects = []
+ for obj in json_objects:
+ try:
+ parsed_objects.append(json.loads(obj))
+ except json.JSONDecodeError as e:
+ logger.error("Failed to decode JSON object from stream: %s", obj)
+ raise RemotionException(
+ f"Failed to parse Lambda response stream: {e}"
+ ) from e
return parsed_objects
def _invoke_lambda(self, function_name, payload):
-
client = self._create_lambda_client()
+ result = None # Initialize to None
try:
response = client.invoke(FunctionName=function_name, Payload=payload)
result = response['Payload'].read().decode('utf-8')
- decoded_result = self._parse_stream(result)[-1]
- except client.exceptions.ResourceNotFoundException as e:
- raise ValueError(f"The function {function_name} does not exist.") from e
- except client.exceptions.InvalidRequestContentException as e:
- raise ValueError("The request content is invalid.") from e
- except client.exceptions.RequestTooLargeException as e:
- raise ValueError("The request payload is too large.") from e
- except client.exceptions.ServiceException as e:
- raise ValueError(f"An internal service error occurred: {str(e)}") from e
- except Exception as e:
- raise ValueError(f"An unexpected error occurred: {str(e)}") from e
+ parsed_results = self._parse_stream(result)
+ decoded_result = parsed_results[-1] if parsed_results else {}
+
+ except ClientError as e:
+ # Re-raise all ClientError exceptions from botocore directly
+ raise e
+ except ParamValidationError as e:
+ # This is typically an SDK usage error
+ raise RemotionInvalidArgumentException(
+ f"Invalid Lambda invocation parameters: {e}"
+ ) from e
+ except json.JSONDecodeError as e:
+ # Catch errors if the final part of the stream is not valid JSON
+ raise RemotionException(
+ f"Failed to decode final Lambda response: {e}. Raw response: {result }"
+ ) from e
+ except UnicodeDecodeError as e:
+ raise RemotionException(
+ f"Failed to decode Lambda response payload: {e}"
+ ) from e
if 'errorMessage' in decoded_result:
- raise ValueError(decoded_result['errorMessage'])
+ raise RemotionRenderingOutputError(
+ f"Lambda function returned an error: {decoded_result['errorMessage']}"
+ )
if 'type' in decoded_result and decoded_result['type'] == 'error':
- raise ValueError(decoded_result['message'])
+ raise RemotionRenderingOutputError(
+ f"Remotion rendering error: {decoded_result['message']}"
+ )
if 'type' not in decoded_result or decoded_result['type'] != 'success':
- raise ValueError(result)
+ # This is a generic catch-all for unexpected success formats
+ raise RemotionRenderingOutputError(
+ f"Unexpected Lambda response format: {result}"
+ )
return decoded_result
@@ -309,7 +376,13 @@ class RemotionClient:
return obj.__dict__
if hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
return list(obj)
- return asdict(obj)
+ try:
+ return asdict(obj)
+ except TypeError:
+ # Fallback for objects that asdict can't handle and are not covered above
+ raise TypeError(
+ f"Object of type {obj.__class__.__name__} is not JSON serializable"
+ )
def construct_render_request(
self,
@@ -327,12 +400,22 @@ class RemotionClient:
"""
render_params.serve_url = self.serve_url
- render_params.private_serialized_input_props = self._serialize_input_props(
- input_props=render_params.input_props, render_type=render_type
- )
+ try:
+ render_params.private_serialized_input_props = self._serialize_input_props(
+ input_props=render_params.input_props, render_type=render_type
+ )
+ except (RemotionInvalidArgumentException, ClientError) as e: # Catch ClientError here too
+ raise RemotionInvalidArgumentException(
+ f"Failed to serialize input properties for rendering: {e}"
+ ) from e
payload = render_params.serialize_params()
- return json.dumps(payload, default=self._custom_serializer)
+ try:
+ return json.dumps(payload, default=self._custom_serializer)
+ except (TypeError, OverflowError) as e:
+ raise RemotionInvalidArgumentException(
+ f"Failed to serialize render parameters to JSON: {e}"
+ ) from e
def construct_render_progress_request(
self,
@@ -359,7 +442,12 @@ class RemotionClient:
log_level=log_level,
s3_output_provider=s3_output_provider,
)
- return json.dumps(progress_params.serialize_params())
+ try:
+ return json.dumps(progress_params.serialize_params())
+ except (TypeError, OverflowError) as e:
+ raise RemotionInvalidArgumentException(
+ f"Failed to serialize progress parameters to JSON: {e}"
+ ) from e
def render_media_on_lambda(
self, render_params: RenderMediaParams
@@ -452,4 +540,4 @@ class RemotionClient:
render_progress = RenderMediaProgress()
render_progress.__dict__.update(progress_response)
return render_progress
- return None
+ return None
\ No newline at end of file
diff --git a/packages/lambda-python/testclient_render_media.py b/packages/lambda-python/testclient_render_media.py
index 6eec964087..6643a8234b 100644
--- a/packages/lambda-python/testclient_render_media.py
+++ b/packages/lambda-python/testclient_render_media.py
@@ -1,5 +1,5 @@
-from remotion_lambda import RenderMediaParams, Privacy, ValidStillImageFormats, Webhook
+from remotion_lambda import RenderMediaParams, Privacy, ValidStillImageFormats
from remotion_lambda import RemotionClient
import os
from dotenv import load_dotenv
diff --git a/packages/lambda-python/testclient_render_media_session.py b/packages/lambda-python/testclient_render_media_session.py
new file mode 100644
index 0000000000..990710b27d
--- /dev/null
+++ b/packages/lambda-python/testclient_render_media_session.py
@@ -0,0 +1,90 @@
+
+from remotion_lambda import RenderMediaParams, Privacy, ValidStillImageFormats, Webhook
+from remotion_lambda import RemotionClient
+import os
+from dotenv import load_dotenv
+import boto3
+from botocore.config import Config
+
+load_dotenv()
+
+# Load env variables
+REMOTION_APP_REGION = os.getenv('REMOTION_APP_REGION')
+if not REMOTION_APP_REGION:
+ raise Exception("REMOTION_APP_REGION is not set")
+
+REMOTION_APP_FUNCTION_NAME = os.getenv('REMOTION_APP_FUNCTION_NAME')
+if not REMOTION_APP_FUNCTION_NAME:
+ raise Exception("REMOTION_APP_FUNCTION_NAME is not set")
+
+REMOTION_APP_SERVE_URL = os.getenv('REMOTION_APP_SERVE_URL')
+if not REMOTION_APP_SERVE_URL:
+ raise Exception("REMOTION_APP_SERVE_URL is not set")
+
+
+ # --- NEW: Create a custom botocore Config for timeouts ---
+# This configuration will apply to both S3 and Lambda clients created by RemotionClient
+# if passed via the botocore_config parameter.
+custom_botocore_config = Config(
+ connect_timeout=10, # Max 10 seconds to establish a connection
+ read_timeout=60, # Max 60 seconds to receive data after connection
+ retries={'max_attempts': 3, 'mode': 'adaptive'}, # Retry up to 3 times on certain errors
+ # You can add more settings here, e.g., proxies
+ # proxies={
+ # 'http': 'http://proxy.example.com:8080',
+ # 'https': 'https://proxy.example.com:8080'
+# }
+)
+print(f"Created custom botocore config: {custom_botocore_config.retries}")
+
+
+# --- NEW: Create a custom boto3 session ---
+# This session can be configured independently, for example,
+# if you need to specify a different profile or assumed role.
+# If you don't need a custom session, you can omit this and
+# RemotionClient will use boto3's default session.
+custom_boto_session = boto3.Session(
+ region_name=REMOTION_APP_REGION,
+ # profile_name='your_aws_profile', # Uncomment if you use AWS profiles
+ # If you provide aws_access_key_id, aws_secret_access_key here,
+ # it will override the ones passed to RemotionClient directly.
+ # aws_access_key_id='YOUR_ACCESS_KEY',
+ # aws_secret_access_key='YOUR_SECRET_KEY',
+)
+print(f"Created custom boto3 session with region: {custom_boto_session.region_name}")
+
+
+# Construct client
+client = RemotionClient(region=REMOTION_APP_REGION,
+ serve_url=REMOTION_APP_SERVE_URL,
+ function_name=REMOTION_APP_FUNCTION_NAME,
+ botocore_config=custom_botocore_config,
+ boto_session=custom_boto_session)
+
+# Set render request
+render_params = RenderMediaParams(
+ composition="spring-with-duration",
+ privacy=Privacy.PUBLIC,
+ image_format=ValidStillImageFormats.JPEG,
+ input_props={
+ 'hi': 'there'
+ },
+)
+
+print("Testing normal payload size...")
+render_response = client.render_media_on_lambda(render_params)
+
+if render_response:
+ print("Render ID:", render_response.render_id)
+ print("Bucket name:", render_response.bucket_name)
+
+ # Execute progress request
+ progress_response = client.get_render_progress(
+ render_id=render_response.render_id, bucket_name=render_response.bucket_name)
+
+ while progress_response and not progress_response.done:
+ print("Overall progress")
+ print(str(progress_response.overallProgress * 100) + "%")
+ progress_response = client.get_render_progress(
+ render_id=render_response.render_id, bucket_name=render_response.bucket_name)
+ print("Render done!", progress_response.outputFile)
diff --git a/packages/lambda-python/tests/conftest.py b/packages/lambda-python/tests/conftest.py
index d5cbf45452..408330f00a 100644
--- a/packages/lambda-python/tests/conftest.py
+++ b/packages/lambda-python/tests/conftest.py
@@ -31,3 +31,9 @@ def remotion_client_with_creds():
@pytest.fixture
def mock_s3_client():
return Mock()
+
+
+def mock_lambda_client():
+ """Fixture for a mocked boto3 Lambda client."""
+ return Mock()
\ No newline at end of file
diff --git a/packages/lambda-python/tests/test_large_payload_compression.py b/packages/lambda-python/tests/test_large_payload_compression.py
index 0d5cdfd30f..8707f3c384 100644
--- a/packages/lambda-python/tests/test_large_payload_compression.py
+++ b/packages/lambda-python/tests/test_large_payload_compression.py
@@ -1,7 +1,7 @@
import unittest
from unittest.mock import patch, MagicMock
from remotion_lambda.models import RenderMediaParams
-from remotion_lambda.remotionclient import RemotionClient
+from remotion_lambda.remotionclient import RemotionClient, RemotionException
class TestLargePayloadCompression(unittest.TestCase):
@@ -100,7 +100,7 @@ class TestLargePayloadCompression(unittest.TestCase):
'remotionlambda-useast1-def456',
]
- with self.assertRaises(ValueError) as context:
+ with self.assertRaises(RemotionException) as context:
self.client._get_or_create_bucket()
error_message = str(context.exception)
diff --git a/packages/lambda-python/tests/test_remotion_client.py b/packages/lambda-python/tests/test_remotion_client.py
index e8fe56ed52..914561c0bc 100644
--- a/packages/lambda-python/tests/test_remotion_client.py
+++ b/packages/lambda-python/tests/test_remotion_client.py
@@ -1,5 +1,14 @@
+import json
from tests.conftest import remotion_client, mock_s3_client, remotion_client_with_creds
from remotion_lambda.remotionclient import RemotionClient
+from remotion_lambda.models import ( RenderType )
+from remotion_lambda.exception import (
+ RemotionException,
+ RemotionInvalidArgumentException,
+ RemotionRenderingOutputError
+)
+from botocore.exceptions import ClientError, ParamValidationError
+
import pytest
from tests.constants import (
TEST_FUNCTION_NAME,
@@ -8,7 +17,7 @@ from tests.constants import (
TEST_AWS_SECRET_KEY,
TEST_AWS_ACCESS_KEY,
)
-from unittest.mock import patch, Mock
+from unittest.mock import MagicMock, patch, Mock
from botocore.config import Config
@@ -174,3 +183,190 @@ def test_get_remotion_buckets_single_match_us_east_1(
assert result == [test_bucket_name]
mock_s3_client.get_bucket_location.assert_called_once_with(Bucket=test_bucket_name)
+
+
+
[email protected](RemotionClient, '_create_s3_client')
+def test_get_or_create_bucket_client_error_on_create_bucket(
+ mock_create_client, mock_s3_client, remotion_client
+):
+ """
+ Test that ClientError from create_bucket is re-raised directly.
+ """
+ mock_s3_client.list_buckets.return_value = {'Buckets': []} # Ensure new bucket creation path
+ mock_s3_client.create_bucket.side_effect = ClientError({"Error": {"Code": "BucketAlreadyExists"}}, "CreateBucket")
+ mock_create_client.return_value = mock_s3_client
+
+ with pytest.raises(ClientError) as excinfo:
+ remotion_client._get_or_create_bucket()
+ assert excinfo.type == ClientError
+ assert "BucketAlreadyExists" in str(excinfo.value)
+ mock_s3_client.create_bucket.assert_called_once()
+
+
[email protected](RemotionClient, '_create_s3_client')
+def test_upload_to_s3_client_error_on_put_object(
+ mock_create_client, mock_s3_client, remotion_client
+):
+ """
+ Test that ClientError from put_object is re-raised directly.
+ """
+ mock_s3_client.put_object.side_effect = ClientError({"Error": {"Code": "InternalError"}}, "PutObject")
+ mock_create_client.return_value = mock_s3_client
+
+ with pytest.raises(ClientError) as excinfo:
+ remotion_client._upload_to_s3("test-bucket", "test-key", "payload")
+ assert excinfo.type == ClientError
+ assert "InternalError" in str(excinfo.value)
+ mock_s3_client.put_object.assert_called_once()
+
+
+
[email protected](RemotionClient, '_get_remotion_buckets')
+def test_get_or_create_bucket_remotion_exception_on_multiple_buckets(
+ mock_get_remotion_buckets, remotion_client
+):
+ """
+ Test that RemotionException is raised when multiple Remotion buckets are found.
+ """
+ mock_get_remotion_buckets.return_value = [
+ 'remotionlambda-us-east-1-bucket1',
+ 'remotionlambda-us-east-1-bucket2',
+ ]
+
+ with pytest.raises(RemotionException) as excinfo:
+ remotion_client._get_or_create_bucket()
+
+ assert excinfo.type == RemotionException
+ assert "You have multiple buckets" in str(excinfo.value)
+ mock_get_remotion_buckets.assert_called_once()
+
+
[email protected](RemotionClient, '_create_lambda_client')
+def test_invoke_lambda_unexpected_response_format(
+ mock_create_lambda_client, mock_lambda_client, remotion_client
+):
+ """
+ Test that _invoke_lambda raises RemotionRenderingOutputError for unexpected response types.
+ """
+ unexpected_payload = json.dumps([
+ {'type': 'log', 'level': 'info', 'message': 'Still running'},
+ {'status': 'pending', 'progress': 0.5} # Not 'success' or 'error'
+ ])
+ mock_lambda_client.invoke.return_value = {'Payload': Mock(read=lambda: unexpected_payload.encode('utf-8'))}
+ mock_create_lambda_client.return_value = mock_lambda_client
+
+ with pytest.raises(RemotionRenderingOutputError) as excinfo:
+ remotion_client._invoke_lambda("my-function", "{}")
+
+ assert excinfo.type == RemotionRenderingOutputError
+ assert "Unexpected Lambda response format" in str(excinfo.value)
+ mock_lambda_client.invoke.assert_called_once()
+
+
[email protected](RemotionClient, '_create_lambda_client')
+def test_invoke_lambda_invalid_json_decode(
+ mock_create_lambda_client, mock_lambda_client, remotion_client
+):
+ """
+ Test that _invoke_lambda raises RemotionException if the stream has invalid JSON objects.
+ (Note: This uses RemotionException, not RemotionRenderingOutputError, as it's a structural parsing error).
+ """
+ invalid_stream = b'{"type":"log"} {"malformed_json" ' # Incomplete JSON
+ mock_lambda_client.invoke.return_value = {'Payload': Mock(read=lambda: invalid_stream)}
+ mock_create_lambda_client.return_value = mock_lambda_client
+
+ with pytest.raises(RemotionRenderingOutputError) as excinfo:
+ remotion_client._invoke_lambda("my-function", "{}")
+
+ assert excinfo.type == RemotionRenderingOutputError
+ mock_lambda_client.invoke.assert_called_once()
+
+
[email protected](RemotionClient, '_serialize_input_props')
+def test_construct_render_request_client_error_from_serialize_input_props(
+ mock_serialize_input_props, remotion_client
+):
+ """
+ Test that construct_render_request raises RemotionInvalidArgumentException
+ if _serialize_input_props encounters and re-raises a ClientError.
+ """
+ # Simulate _serialize_input_props raising a ClientError (e.g., from _upload_to_s3)
+ mock_serialize_input_props.side_effect = ClientError({"Error": {"Code": "AccessDenied"}}, "PutObject")
+
+ mock_render_params = Mock()
+ mock_render_params.input_props = {"dummy": "data"}
+ mock_render_params.serialize_params.return_value = {"serialized": "params"}
+
+ with pytest.raises(RemotionInvalidArgumentException) as excinfo:
+ remotion_client.construct_render_request(mock_render_params, "still")
+
+ assert excinfo.type == RemotionInvalidArgumentException
+ assert "Failed to serialize input properties for rendering" in str(excinfo.value)
+ assert "AccessDenied" in str(excinfo.value) # Ensure the original ClientError info is present
+ mock_serialize_input_props.assert_called_once_with(
+ input_props=mock_render_params.input_props,
+ render_type="still"
+ )
+
+
+@patch('boto3.client')
+def test_create_s3_client_with_boto_session(mock_boto3_client_func):
+ """
+ Test that _create_s3_client uses the provided boto_session
+ instead of boto3.client directly.
+ """
+ # Arrange
+ mock_session = MagicMock()
+ mock_s3_client_from_session = MagicMock()
+ mock_session.client.return_value = mock_s3_client_from_session
+
+ client = RemotionClient(
+ region=TEST_REGION,
+ serve_url=TEST_SERVE_URL,
+ function_name=TEST_FUNCTION_NAME,
+ boto_session=mock_session,
+ )
+
+ # Act
+ s3_client = client._create_s3_client()
+
+ # Assert
+ assert s3_client == mock_s3_client_from_session
+ mock_session.client.assert_called_once_with('s3', region_name=TEST_REGION)
+ mock_boto3_client_func.assert_not_called() # Ensure boto3.client was not used
+
+
+@patch('boto3.client')
+def test_create_s3_client_with_custom_timeout_config(mock_boto3_client_func, mock_s3_client):
+ """
+ Test that _create_s3_client correctly applies custom timeout settings
+ provided via botocore_config.
+ """
+ # Arrange
+ custom_timeout = 10 # seconds
+ custom_config = Config(connect_timeout=custom_timeout, read_timeout=custom_timeout)
+
+ client = RemotionClient(
+ region=TEST_REGION,
+ serve_url=TEST_SERVE_URL,
+ function_name=TEST_FUNCTION_NAME,
+ botocore_config=custom_config,
+ )
+ mock_boto3_client_func.return_value = mock_s3_client
+
+ # Act
+ s3_client = client._create_s3_client()
+
+ # Assert
+ assert s3_client == mock_s3_client
+ mock_boto3_client_func.assert_called_once()
+
+ # Extract the config argument passed to boto3.client
+ call_args, call_kwargs = mock_boto3_client_func.call_args
+ passed_config = call_kwargs.get('config')
+
+ assert isinstance(passed_config, Config)
+ assert passed_config.connect_timeout == custom_timeout
+ assert passed_config.read_timeout == custom_timeout
+ assert passed_config.s3 is None # No s3 addressing_style if not forced
\ No newline at end of file