"""Lambda util test module.""" from datetime import date from io import BytesIO import os from unittest.mock import patch from botocore.exceptions import ClientError import pytest import util def test_say_hello(): """Test util.say_hello function.""" util.say_hello() assert True, 'Something terrible has happened.' def test_convert_xsl_to_csv_success(s3_bucket, s3_bucket_name): """Test convert_xsl_to_csv returns True if xls file exists.""" xls_key = 'test.xls' csv_key = 'test.csv' test_xls_file = 'tests/test_files/test.xlsx' s3_bucket.upload_file(test_xls_file, xls_key) assert util.convert_xsl_to_csv(s3_bucket_name, xls_key, csv_key) csv = BytesIO() s3_bucket.download_fileobj(csv_key, csv) assert csv.getvalue().decode() == 'foo,bar\n' def test_convert_xsl_to_csv_error(s3_bucket, s3_bucket_name): """Test convert_xsl_to_csv returns False if xls file does not exist.""" xls_key = 'test.xls' csv_key = 'test.csv' assert not util.convert_xsl_to_csv(s3_bucket_name, xls_key, csv_key) def test_download_file_file_exists(s3_bucket_magic_mock): """Test download_file returns True if file exists.""" assert util.download_file(s3_bucket_magic_mock, 'key', 'path') s3_bucket_magic_mock.download_file.assert_called_with('key', 'path') def test_download_file_file_does_not_exists(s3_bucket_magic_mock): """Test download_file returns False if file does not exist.""" error_response = {'Error': {'Code': '404'}} s3_bucket_magic_mock.download_file.side_effect = ClientError( error_response, 'HeadObject') assert not util.download_file(s3_bucket_magic_mock, 'key', 'path') def test_download_file_file_exception(s3_bucket_magic_mock): """Test download_file raise an exception in case error is not 404.""" error_response = {'Error': {'Code': '500'}} s3_bucket_magic_mock.download_file.side_effect = ClientError( error_response, 'HeadObject') with pytest.raises(ClientError): util.download_file(s3_bucket_magic_mock, 'key', 'path') def test_tmp_file_path(): """Test tmp_file_path context manager.""" with util.tmp_file_path() as tmp_path: assert os.path.exists(tmp_path) assert not os.path.exists(tmp_path) @patch('util.urllib') def test_notify_slack(urllib): """Test notify_slack function.""" url = 'slack-test-url' util.notify_slack('Hi!') urllib.request.urlopen.assert_called_with(url, b'{"text": "Hi!"}') def test_get_date_from_report_key(): """Test get_date_from_report_key function.""" xls_key = ( 'soundexchange_reports/reconfirmation/input' '/2018-01-29/O-6145-THE_ORCHARD_ENTERPRISES_INC-062017.xlsx') assert util.get_date_from_report_key(xls_key) == date(2018, 1, 29)