from unittest.mock import MagicMock from unittest.mock import patch from botocore.exceptions import ClientError import pytest from ows_accounting.utils import s3 def test_extract_bucket_path(): """Test extract_bucket_path. """ bucket, path = s3.extract_bucket_path( 's3://test_bucket/test_key/test_file.zip') assert bucket == 'test_bucket' assert path == 'test_key/test_file.zip' 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('ows_accounting.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('ows_accounting.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')