"""Test s3 file upload.""" from unittest.mock import patch import boto3 from botocore.exceptions import NoCredentialsError from botocore.stub import Stubber from flexmock import flexmock from moto import mock_aws import pytest from salessheets.connectors import s3 from salessheets.constants import error @mock_aws def test_connect_to_s3_success(): """Test s3 connection.""" conn = s3.connect_to_s3() stubber = Stubber(conn) with patch('recipe.get_s3', return_value=s3): yield stubber testconn = boto3.client('s3') assert isinstance(type(conn), type(testconn)) def test_connect_to_s3_failed(): """Test s3 get url of file in unavailable bucket.""" with patch('boto3.Session') as mock_client: # Mock boto3.client to return a client with no credentials mock_client.side_effect = NoCredentialsError() with pytest.raises(NoCredentialsError): conn = s3.connect_to_s3() test_bucket = 'bucket-doesnt-exist' test_file_key = 'some_file.pdf' s3.get_s3_file_url( conn, test_bucket, test_file_key) @mock_aws def test_get_file_url_in_s3_no_bucket(): """Test s3 get url of file in unavailable bucket.""" (flexmock(s3) .should_receive('capture_exception') .once()) conn = s3.connect_to_s3() test_bucket = 'bucket-doesnt-exist' test_file_key = 'some_file.pdf' result = s3.get_s3_file_url(conn, test_bucket, test_file_key) assert result.status == 404 @mock_aws def test_get_file_url_in_s3_no_file_in_bucket(): """Test s3 get url of file that doesn't exist.""" (flexmock(s3) .should_receive('capture_exception') .once()) conn = s3.connect_to_s3() test_bucket_name = 'test-bucket' conn.create_bucket(Bucket=test_bucket_name) test_file_key = 'some_file.pdf' expected_error = ( 'some_file.pdf not found in bucket test-bucket!') result = s3.get_s3_file_url(conn, test_bucket_name, test_file_key) assert result.status == 404 assert result.errors['message'] == expected_error assert result.errors['code'] == error.ERROR_CODE_NOT_FOUND @mock_aws def test_get_file_url_in_s3_success(): """Test s3 get url of valid file.""" conn = s3.connect_to_s3() test_bucket_name = 'test-bucket' conn.create_bucket(Bucket=test_bucket_name) test_file_key = 'some_file.pdf' more_binary_data = b'Here we have some more data' conn.put_object( Body=more_binary_data, Bucket=test_bucket_name, Key=test_file_key) result = s3.get_s3_file_url(conn, test_bucket_name, test_file_key) assert result.status