"""Tests for S3 utilities.""" from unittest.mock import MagicMock, patch from botocore.exceptions import ClientError import pytest from collaborator.utils import s3 @pytest.mark.parametrize( "s3_path,expected_bucket,expected_path", [ ( "https://bucket-name.s3.amazonaws.com/path/to/file.txt", "bucket-name", "path/to/file.txt", ), ("s3://bucket-name/path/to/file.txt", "bucket-name", "path/to/file.txt"), ], ) def test_extract_bucket_path_success(s3_path, expected_bucket, expected_path): """Test extract_bucket_path.""" bucket, path = s3.extract_bucket_path(s3_path) assert bucket == expected_bucket assert path == expected_path def test_extract_bucket_path_bad_s3_link(): """Test extract_bucket_path.""" with pytest.raises(Exception) as err: s3.extract_bucket_path("huh!?") assert str(err.value) == ("The S3 url 'huh!?' is not valid.") @patch("collaborator.utils.s3.boto3") def test_get_presigned_url(mock_boto3): """Test get_presigned_url.""" mock_s3_obj = MagicMock() mock_s3_obj.generate_presigned_url.return_value = "test_url" mock_boto3.client.return_value = mock_s3_obj s3.get_presigned_url("test_bucket", "test_key", 888) mock_s3_obj.generate_presigned_url.assert_any_call( ClientMethod="get_object", Params={"Bucket": "test_bucket", "Key": "test_key"}, ExpiresIn=888, ) @patch("collaborator.utils.s3.boto3") def test_object_exists(mock_boto3): """Test object_exists.""" mock_client = MagicMock() mock_boto3.client.return_value = mock_client mock_client.head_object.return_value = {"Contents": ["test"]} assert s3.object_exists("test_bucket", "test_key") mock_client.head_object.side_effect = ClientError( {"Error": {"Code": "404", "Message": "NotFound"}}, "ListBuckets" ) assert not s3.object_exists("test_bucket", "test_key") @patch("collaborator.utils.s3.boto3") def test_delete_object(mock_boto3): """Test delete_object.""" mock_client = MagicMock() mock_boto3.client.return_value = mock_client mock_delete_object = MagicMock() mock_client.delete_object = mock_delete_object s3.delete_object("my-bucket", "some/key.wav") mock_delete_object.assert_called_with(Bucket="my-bucket", Key="some/key.wav")