def test_handler_rotates_credentials(self, post): # Initializer stubbers iam_stubber = Stubber(iam) sts_stubber = Stubber(sts) secretsmanager_stubber = Stubber(secretsmanager) stubbers = [iam_stubber, sts_stubber, secretsmanager_stubber] # IAM stubs create_request = {'UserName': '******'} create_response = { 'AccessKey': { 'UserName': '******', 'AccessKeyId': access_key_id, 'Status': 'Active', 'SecretAccessKey': secret_access_key } } delete_request = {'UserName': '******', 'AccessKeyId': access_key_id} iam_stubber.add_response('create_access_key', create_response, create_request) iam_stubber.add_response('delete_access_key', {}, delete_request) # STS stub sts_request = {'DurationSeconds': 900} sts_response = { 'Credentials': { 'AccessKeyId': access_key_id, 'SecretAccessKey': secret_access_key, 'SessionToken': session_token, 'Expiration': expiration } } sts_stubber.add_response('get_session_token', sts_response, sts_request) # SecretsManager stub request = {'SecretId': 'shhh'} response = {'SecretString': '{"circle-token":"SEKRET!"}'} secretsmanager_stubber.add_response('get_secret_value', response, request) # Requests stub post.return_value = Mock() post.return_value.status_code = 201 for stubber in stubbers: stubber.activate() app.handler({}, {}, iam=iam, secretsmanager=secretsmanager, sts=sts) for stubber in stubbers: stubber.assert_no_pending_responses() url = 'https://circleci.com/api/v2/project/jpignata/thingie/envvar' header = {'Circle-Token': 'SEKRET!'} values = { 'AWS_ACCESS_KEY_ID': access_key_id, 'AWS_SECRET_ACCESS_KEY': secret_access_key, 'AWS_SESSION_TOKEN': session_token } for i, (key, value) in enumerate(values.items()): json = {'name': key, 'value': value} expected = call(url, json=json, headers=header) self.assertEqual(post.mock_calls[i], expected)
def test_failed_log_group_creation(self): mock_context = Mock() failure_event = { "detail": { "errorCode": "AccessDenied" } } app.handler(failure_event, mock_context) mock_context.invoked_function_arn.assert_not_called()
def test_handler_no_kms_event_should_not_send_notification(self): # given os.environ[ 'ALLOWED_PRINCIPALS'] = "arn:aws:iam::123456789012:user/MyAllowedUser,arn:aws:iam::123456789012:role/MyAllowedRoleToBeAssumed" os.environ['SNS_TOPIC_ARN'] = self.topic_arn os.environ[ 'RESTRICTED_KMS_CMK_ARN'] = "arn:aws:kms:us-east-1:012345678901:key/8d3acf57-6bba-480a-9459-ed1b8e79d3d0" event = self._get_s3_event_other() # when handler(event, None)
def test_app_handler(self, mocker: MockerFixture) -> None: """ Makes sure that the app handler runs the process_event method :param mocker: :type mocker: MockerFixture """ mocker.patch.object(app, 'process_event', autospec=True) mock_event = create_sqs_event(self.event_update) app.handler(mock_event, { "function_name": "test", "aws_request_id": "test" }) app.process_event.assert_called_once_with( mock_event["Records"][0]["body"])
def test_lambda_handler(apigw_event): ret = app.handler(apigw_event, "") data = json.loads(ret["body"]) assert ret["statusCode"] == 200 assert "prediction" in ret["body"] assert data["prediction"] is not None
def test_app_import(monkeypatch): monkeypatch.setenv("DYNAMO_TABLE", "TestTable") expected_keys = ['statusCode', 'body', 'isBase64Encoded'] resp = app.handler(event=1, context="") actual_keys = list(resp.keys()) assert actual_keys == expected_keys
def test_correct_setup_for_build__build_is_triggered( self, start_build_mock, load_source_code_to_s3_mock, get_buildspec_override_mock, sleep_mock): """ Test that we trigger CodeBuild build with valid parameters """ # disable side effects sleep_mock.return_value = None get_buildspec_override_mock.side_effect = \ lambda lambda_name, file_name: file_name load_source_code_to_s3_mock.side_effect = \ lambda github_ref: github_ref start_build_mock.return_value = '' response = handler( self.generate_message_to_trigger_build(ref='refs/tags/test--1.1'), {}) self.assertEqual(response['statusCode'], HTTP_200_OK) start_build_mock.assert_called_with( projectName='test', sourceVersion='commit-hash', environmentVariablesOverride=[ { 'name': 'LAMBDA', # TODO: get lambda value on the flight 'value': 'test', }, { 'name': 'GITHUB_COMMIT', 'value': 'commit-hash' } ], buildspecOverride='buildspec-build')
def test_post_data(self, mock_pymysql): mock_cursor = mock.MagicMock() test_data = 2 mock_cursor.fetchall.return_value = test_data mock_pymysql.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor data = {'resource': '/verifyKey', 'path': '/verifyKey', 'httpMethod': 'POST', 'headers': {'Accept': '*/*', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'cxdp3vrdt6.execute-api.us-east-2.amazonaws.com', 'User-Agent': 'curl/7.54.0', 'X-Amzn-Trace-Id': 'Root=1-5bfaf522-39b47706d6ee972ededf9c40', 'x-api-key': '7NYpat2DyO6yqh6EqXSah924XRzVeBi26TEPcwfx', 'X-Forwarded-For': '69.14.78.142', 'X-Forwarded-Port': '443', 'X-Forwarded-Proto': 'https'}, 'multiValueHeaders': {'Accept': ['*/*'], 'Content-Type': ['application/x-www-form-urlencoded'], 'Host': ['cxdp3vrdt6.execute-api.us-east-2.amazonaws.com'], 'User-Agent': ['curl/7.54.0'], 'X-Amzn-Trace-Id': ['Root=1-5bfaf522-39b47706d6ee972ededf9c40'], 'x-api-key': ['7NYpat2DyO6yqh6EqXSah924XRzVeBi26TEPcwfx'], 'X-Forwarded-For': ['69.14.78.142'], 'X-Forwarded-Port': ['443'], 'X-Forwarded-Proto': ['https']}, 'queryStringParameters': None, 'multiValueQueryStringParameters': None, 'pathParameters': None, 'stageVariables': None, 'requestContext': {'resourceId': 'urwqzx', 'resourcePath': '/verifyKey', 'httpMethod': 'POST', 'extendedRequestId': 'Q7s9dHs5iYcFUDQ=', 'requestTime': '25/Nov/2018:19:16:50 +0000', 'path': '/dev/verifyKey', 'accountId': '804994069721', 'protocol': 'HTTP/1.1', 'stage': 'dev', 'domainPrefix': 'cxdp3vrdt6', 'requestTimeEpoch': 1543173410995, 'requestId': 'a9656a19-f0e6-11e8-ab2e-b75394e49a86', 'identity': {'cognitoIdentityPoolId': None, 'cognitoIdentityId': None, 'apiKey': '7NYpat2DyO6yqh6EqXSah924XRzVeBi26TEPcwfx', 'cognitoAuthenticationType': None, 'userArn': None, 'apiKeyId': 'o2axzlqtla', 'userAgent': 'curl/7.54.0', 'accountId': None, 'caller': None, 'sourceIp': '69.14.78.142', 'accessKey': None, 'cognitoAuthenticationProvider': None, 'user': None}, 'domainName': 'cxdp3vrdt6.execute-api.us-east-2.amazonaws.com', 'apiId': 'cxdp3vrdt6'}, 'body': '{"key":"gibrish12345678"}', 'isBase64Encoded': False} expected_data = {"headers":{'Content-Type':'application/json','Access-Control-Allow-Origin':'*'},"statusCode": 400,"body": json.dumps("Invalid API")} self.assertEqual(expected_data, app.handler(data, ""))
def test_handler_deletes_access_key_upon_exception(self, stub): stub.side_effect = Exception create_request = {'UserName': '******'} create_response = { 'AccessKey': { 'UserName': '******', 'AccessKeyId': access_key_id, 'Status': 'Active', 'SecretAccessKey': secret_access_key } } delete_request = {'UserName': '******', 'AccessKeyId': access_key_id} with Stubber(iam) as stubber: stubber.add_response('create_access_key', create_response, create_request) stubber.add_response('delete_access_key', {}, delete_request) with self.assertRaises(Exception): app.handler({}, {}, iam=iam) stubber.assert_no_pending_responses()
def test_correct_setup__result_is_set(self, batch_get_build_mock, set_status_to_github_mock, sleep_mock): """ Test that we use github api correctly """ # disable side effects sleep_mock.return_value = None set_status_to_github_mock.return_value = '' batch_get_build_mock.return_value = \ self.generate_batch_build_return_value() response = handler(self.generate_message_to_set_github_results(), {}) self.assertEqual(response['statusCode'], HTTP_200_OK) batch_get_build_mock.assert_called_with(ids=['1'])
def test_load_source_code_to_s3_usage(self, start_build_mock, load_source_code_to_s3_mock, get_buildspec_override_mock, sleep_mock): """ Test that we pass correct data to load_source_code_to_s3 method """ # disable side effects sleep_mock.return_value = None get_buildspec_override_mock.side_effect = \ lambda lambda_name, file_name: file_name load_source_code_to_s3_mock.side_effect = \ lambda github_ref: github_ref start_build_mock.return_value = '' response = handler( self.generate_message_to_trigger_build(ref='refs/tags/test--1.1'), {}) load_source_code_to_s3_mock.assert_called_with('commit-hash')
def test_correct_setup__build_status_is_queried_correctly( self, get_build_info, github, sleep_mock): """ Test that we request build status with correct parameters """ # disable side effects sleep_mock.return_value = None # prepare mocks get_build_info.return_value = \ self.generate_batch_build_return_value() github.Github.return_value = MagicMock() github.Github.return_value.get_repo.return_value.\ get_commit.return_value.create_status.return_value = '' response = handler(self.generate_message_to_set_github_results(), {}) self.assertEqual(response['statusCode'], HTTP_200_OK) # verify github behaviour github.Github.return_value.get_repo.return_value.\ get_commit.return_value.create_status.assert_called_with( 'pending', 'https://console.aws.amazon.com/codebuild/home?region=test-region#/builds/test-id/view/new', 'test-status') github.Github.return_value.get_repo.\ return_value.get_commit.assert_called_with('test-github-commit')
def test_handler(lambda_event): ret = app.handler(lambda_event, "") assert ret["hello"] == "world"{% endif %}
def test_handler(apigw_event): ret = app.handler(apigw_event, "") assert ret['statusCode'] == 200 assert ret['body'] == json.dumps({'hello': 'world'})
#!/usr/bin/env python3 from unittest.mock import MagicMock from app import handler if __name__ == '__main__': event = {'instance-id': 'i-033d58df5ffaf79c5', 'instance-action': 'terminate'} context = MagicMock() context.function_name = 'instance-termination' handler(event, context)