Best Python code snippet using localstack_python
test_aws_ses.py
Source:test_aws_ses.py
1import re2from base64 import b64encode3from textwrap import dedent4import botocore5import pytest6from notifications_utils.recipients import InvalidEmailError7from app import aws_ses_client8from app.clients.email.aws_ses import AwsSesClientException, punycode_encode_email9def email_b64_encoding(input):10 return f"=?utf-8?b?{b64encode(input.encode('utf-8')).decode('utf-8')}?="11@pytest.mark.parametrize(12 "reply_to_address, expected_value",13 [14 (None, []),15 ("foo@bar.com", "foo@bar.com"),16 (17 "føøøø@bååååår.com",18 email_b64_encoding(punycode_encode_email("føøøø@bååååår.com")),19 ),20 ],21 ids=["empty", "single_email", "punycode"],22)23def test_send_email_handles_reply_to_address(notify_api, mocker, reply_to_address, expected_value):24 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)25 mocker.patch.object(aws_ses_client, "statsd_client", create=True)26 with notify_api.app_context():27 aws_ses_client.send_email(28 source="from@address.com",29 to_addresses="to@address.com",30 subject="Subject",31 body="Body",32 reply_to_address=reply_to_address,33 )34 boto_mock.send_raw_email.assert_called()35 raw_message = boto_mock.send_raw_email.call_args.kwargs["RawMessage"]["Data"]36 if not expected_value:37 assert "reply-to" not in raw_message38 else:39 assert f"reply-to: {expected_value}" in raw_message40def test_send_email_txt_and_html_email(notify_api, mocker):41 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)42 mocker.patch.object(aws_ses_client, "statsd_client", create=True)43 with notify_api.app_context():44 aws_ses_client.send_email(45 "from@example.com",46 to_addresses="destination@example.com",47 subject="Subject",48 body="email body",49 html_body="<p>email body</p>",50 reply_to_address="reply@example.com",51 )52 boto_mock.send_raw_email.assert_called_once()53 raw_message = boto_mock.send_raw_email.call_args.kwargs["RawMessage"]["Data"]54 regex = dedent(55 r"""56 Content-Type: multipart\/alternative; boundary="===============(?P<boundary>.+)=="57 MIME-Version: 1\.058 Subject: Subject59 From: from@example\.com60 To: destination@example\.com61 reply-to: reply@example\.com62 --===============(?P<b1>.+)==63 Content-Type: text/plain; charset="us-ascii"64 MIME-Version: 1\.065 Content-Transfer-Encoding: 7bit66 email body67 --===============(?P<b2>.+)==68 Content-Type: text/html; charset="us-ascii"69 MIME-Version: 1\.070 Content-Transfer-Encoding: 7bit71 <p>email body</p>72 --===============(?P<b3>.+)==--73 """74 ).strip()75 assert len(set(re.findall(regex, raw_message))) == 176 assert re.match(regex, raw_message)77def test_send_email_txt_and_html_email_with_attachment(notify_api, mocker):78 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)79 mocker.patch.object(aws_ses_client, "statsd_client", create=True)80 with notify_api.app_context():81 aws_ses_client.send_email(82 "from@example.com",83 to_addresses="destination@example.com",84 subject="Subject",85 body="email body",86 html_body="<p>email body</p>",87 attachments=[{"data": "Canada", "name": "file.txt", "mime_type": "text/plain"}],88 reply_to_address="reply@example.com",89 )90 boto_mock.send_raw_email.assert_called_once()91 raw_message = boto_mock.send_raw_email.call_args.kwargs["RawMessage"]["Data"]92 regex = dedent(93 r"""94 Content-Type: multipart/mixed; boundary="===============(?P<boundary>.+)=="95 MIME-Version: 1\.096 Subject: Subject97 From: from@example\.com98 To: destination@example\.com99 reply-to: reply@example\.com100 --===============(?P<b1>.+)==101 Content-Type: multipart/alternative; boundary="===============(?P<b2>.+)=="102 MIME-Version: 1\.0103 --===============(?P<b3>.+)==104 Content-Type: text/plain; charset="us-ascii"105 MIME-Version: 1\.0106 Content-Transfer-Encoding: 7bit107 email body108 --===============(?P<b4>.+)==109 Content-Type: text/html; charset="us-ascii"110 MIME-Version: 1\.0111 Content-Transfer-Encoding: 7bit112 <p>email body</p>113 --===============(?P<b5>.+)==--114 --===============(?P<b6>.+)==115 Content-Type: application/octet-stream116 MIME-Version: 1\.0117 Content-Transfer-Encoding: base64118 Content-Type: text/plain; name="file\.txt"119 Content-Disposition: attachment; filename="file\.txt"120 Q2FuYWRh121 --===============(?P<b7>.+)==--122 """123 ).strip()124 groups = re.match(regex, raw_message).groupdict()125 assert groups["boundary"] == groups["b7"] == groups["b6"] == groups["b1"]126 assert groups["b2"] == groups["b3"] == groups["b4"] == groups["b5"]127 assert re.match(regex, raw_message)128def test_send_email_handles_punycode_to_address(notify_api, mocker):129 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)130 mocker.patch.object(aws_ses_client, "statsd_client", create=True)131 with notify_api.app_context():132 aws_ses_client.send_email(133 "from@address.com",134 to_addresses="føøøø@bååååår.com",135 subject="Subject",136 body="Body",137 )138 boto_mock.send_raw_email.assert_called()139 raw_message = boto_mock.send_raw_email.call_args.kwargs["RawMessage"]["Data"]140 expected_to = email_b64_encoding(punycode_encode_email("føøøø@bååååår.com"))141 assert f"To: {expected_to}" in raw_message142def test_send_email_raises_bad_email_as_InvalidEmailError(mocker):143 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)144 mocker.patch.object(aws_ses_client, "statsd_client", create=True)145 error_response = {146 "Error": {147 "Code": "InvalidParameterValue",148 "Message": "some error message from amazon",149 "Type": "Sender",150 }151 }152 boto_mock.send_raw_email.side_effect = botocore.exceptions.ClientError(error_response, "opname")153 mocker.patch.object(aws_ses_client, "statsd_client", create=True)154 with pytest.raises(InvalidEmailError) as excinfo:155 aws_ses_client.send_email(156 source="from@address.com",157 to_addresses="definitely@invalid_email.com",158 subject="Subject",159 body="Body",160 )161 assert "some error message from amazon" in str(excinfo.value)162 assert "definitely@invalid_email.com" in str(excinfo.value)163def test_send_email_raises_other_errs_as_AwsSesClientException(mocker):164 boto_mock = mocker.patch.object(aws_ses_client, "_client", create=True)165 mocker.patch.object(aws_ses_client, "statsd_client", create=True)166 error_response = {167 "Error": {168 "Code": "ServiceUnavailable",169 "Message": "some error message from amazon",170 "Type": "Sender",171 }172 }173 boto_mock.send_raw_email.side_effect = botocore.exceptions.ClientError(error_response, "opname")174 mocker.patch.object(aws_ses_client, "statsd_client", create=True)175 with pytest.raises(AwsSesClientException) as excinfo:176 aws_ses_client.send_email(177 source="from@address.com",178 to_addresses="foo@bar.com",179 subject="Subject",180 body="Body",181 )182 assert "some error message from amazon" in str(excinfo.value)183@pytest.mark.parametrize(184 "input, expected_output",185 [186 ("foo@domain.tld", "foo@domain.tld"),187 ("føøøø@bååååår.com", "føøøø@xn--br-yiaaaaa.com"),188 ],189)190def test_punycode_encode_email(input, expected_output):...
test_ses_boto3.py
Source:test_ses_boto3.py
...78 send_quota = conn.get_send_quota()79 sent_count = int(send_quota['SentLast24Hours'])80 sent_count.should.equal(1)81@mock_ses82def test_send_raw_email():83 conn = boto3.client('ses', region_name='us-east-1')84 message = MIMEMultipart()85 message['Subject'] = 'Test'86 message['From'] = 'test@example.com'87 message['To'] = 'to@example.com, foo@example.com'88 # Message body89 part = MIMEText('test file attached')90 message.attach(part)91 # Attachment92 part = MIMEText('contents of test file here')93 part.add_header('Content-Disposition', 'attachment; filename=test.txt')94 message.attach(part)95 kwargs = dict(96 Source=message['From'],97 RawMessage={'Data': message.as_string()},98 )99 conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)100 conn.verify_email_identity(EmailAddress="test@example.com")101 conn.send_raw_email(**kwargs)102 send_quota = conn.get_send_quota()103 sent_count = int(send_quota['SentLast24Hours'])104 sent_count.should.equal(2)105@mock_ses106def test_send_raw_email_without_source():107 conn = boto3.client('ses', region_name='us-east-1')108 message = MIMEMultipart()109 message['Subject'] = 'Test'110 message['From'] = 'test@example.com'111 message['To'] = 'to@example.com, foo@example.com'112 # Message body113 part = MIMEText('test file attached')114 message.attach(part)115 # Attachment116 part = MIMEText('contents of test file here')117 part.add_header('Content-Disposition', 'attachment; filename=test.txt')118 message.attach(part)119 kwargs = dict(120 RawMessage={'Data': message.as_string()},121 )122 conn.send_raw_email.when.called_with(**kwargs).should.throw(ClientError)123 conn.verify_email_identity(EmailAddress="test@example.com")124 conn.send_raw_email(**kwargs)125 send_quota = conn.get_send_quota()126 sent_count = int(send_quota['SentLast24Hours'])127 sent_count.should.equal(2)128@mock_ses129def test_send_raw_email_without_source_or_from():130 conn = boto3.client('ses', region_name='us-east-1')131 message = MIMEMultipart()132 message['Subject'] = 'Test'133 message['To'] = 'to@example.com, foo@example.com'134 # Message body135 part = MIMEText('test file attached')136 message.attach(part)137 # Attachment138 part = MIMEText('contents of test file here')...
test_lambda_handler.py
Source:test_lambda_handler.py
1import unittest2import logging3from StringIO import StringIO4from SimpleForwarder import *5from mock import Mock, MagicMock6from botocore.exceptions import ClientError7from test_util import *8import copy9class testSESEmail(unittest.TestCase):10 def setUp(self):11 self._ses_mock = Mock()12 self._ses_mock.send_raw_email.return_value = {13 'MessageId': 'some_message_id'14 }15 self._s3_mock = Mock()16 self._read_dict = {'Body': MagicMock(spec=file, wraps=StringIO(TEST_EMAIL_BODY))}17 self._get_mock = MagicMock()18 self._get_mock.__getitem__.side_effect = self._read_dict.__getitem__19 self._s3_mock.Object.return_value.get.return_value = self._get_mock20 21 def test_event_ok(self):22 self.assertIsNone(lambda_handler(TEST_EVENT, {},23 self._ses_mock,24 self._s3_mock,25 TEST_CONFIG))26 destinations = self._ses_mock.send_raw_email.call_args[1]['Destinations']27 original = self._ses_mock.send_raw_email.call_args[1]['Source']28 raw_message = self._ses_mock.send_raw_email.call_args[1]['RawMessage']['Data']29 self.assertTrue('user1@example.com' in destinations)30 self.assertTrue('user2@example.com' in destinations)31 self.assertTrue('user3@example.com' in destinations)32 self.assertTrue('info@example.com' in original)33 self.assertEqual(TEST_SEND_EMAIL, raw_message)34 def test_no_config(self):35 self.assertIsNone(lambda_handler(TEST_EVENT, {},36 self._ses_mock,37 self._s3_mock))38 self.assertFalse(self._ses_mock.send_raw_email.called)39if __name__ == '__main__':...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!