"""File upload logic tests.""" import io from _pytest.monkeypatch import MonkeyPatch import boto3 from moto import mock_aws import pytest from werkzeug.datastructures import FileStorage from manualadjustment import config from manualadjustment.logic import file_upload from tests.fixtures import flask_global monkeypatch = MonkeyPatch() def setup_function(function): """Set up the function. Invoked for every test function. Args: function (callable): the function that will run the test. """ flask_global.mock(monkeypatch) def teardown_function(function): """Teardown the function. Invoked everytime a test function has completed. Args: function (callable): the function that has run. """ monkeypatch.undo() @pytest.fixture def attachment_text(): """Text fixture.""" return 'i heart manual adjustments' @pytest.fixture def attachment(attachment_text): """Attachment fixture.""" return FileStorage(io.StringIO(attachment_text)) @mock_aws def test_upload_success(attachment_text, attachment): """Test a successful s3 upload.""" resource = boto3.resource('s3') resource.create_bucket(Bucket=config.bucket_name) key_path = 'over-here/some-file.csv' file_upload.upload_to_s3(attachment, key_path, False) bucket = resource.Bucket(config.bucket_name) for obj in bucket.objects.all(): body = obj.get()['Body'].read() assert attachment_text == body.decode('utf-8') @mock_aws def test_delete_success(attachment_text, attachment): """Test a successful s3 delte.""" resource = boto3.resource('s3') resource.create_bucket(Bucket=config.bucket_name) key_path = 'over-here/some-file.csv' file_upload.upload_to_s3(attachment, key_path, False) bucket = resource.Bucket(config.bucket_name) for obj in bucket.objects.all(): key = obj.key assert key == key_path key = '' file_upload.delete_from_s3(key_path) for obj in bucket.objects.all(): key = obj.key assert len(key) == 0