def test_handler_raises_global_exception_for_bad_request_after_all_scripts_completed( _, __, mock_aiobotocore, capsys): with aioresponses() as mock_aioresponses: """ Given some news endpoints return 500 """ mock_aioresponses.get("https://www.bbc.co.uk/news", status=500), mock_aioresponses.get("https://www.wsj.com/", status=500), mock_aioresponses.get("https://www.ft.com/", status=200), mock_aioresponses.get("https://uk.finance.yahoo.com/", status=200), mock_aioresponses.get("https://www.coindesk.com/", status=200) """ And given a price endpoint returns 400 """ mock_aioresponses.get( "https://api.coingecko.com/api/v3/exchange_rates", status=400), mock_aioresponses.get("https://api.gemini.com/v1/pubticker/btcusd", status=200), mock_aioresponses.get("https://api.blockchain.info/stats", status=200) """ When the lambda handler is called then an exception is raised """ with pytest.raises(RuntimeError) as err: handler(None, None) """ And the stdout explains that both scripts failed """ captured = capsys.readouterr() assert "bitcoin_price failed" in captured.out assert "bitcoin_news failed" in captured.out """ And the stderr details both HTTP exceptions, one from each script """ assert "ClientResponseError: 400, message='Bad Request'" in captured.err assert "ClientResponseError: 500, message='Internal Server Error'" in captured.err
def test_exception(self, monkeypatch, error): def dummy(*_, **__): raise error() monkeypatch.setattr(index, 'main', dummy) with pytest.raises(error): index.handler({}, None)
def test_delete(self, _, put: MagicMock): event = make_event("Delete", True) index.handler(event, {}) put.assert_called_once_with(event["ResourceProperties"]["BucketName"], {})
def test_success(self, submit: MagicMock, *_): event = make_event("Create", True) index.handler(event, {}) submit.assert_called_once() self.assertEqual(submit.call_args_list[0][0][2], "SUCCESS")
def test_normal(self, monkeypatch): """ normal test """ monkeypatch.setattr(FetchReportService, 'fetch_report', lambda x: x) monkeypatch.setattr(PostMessageService, 'post_message', lambda *x: {}) index.handler({}, {})
def invoke_handler(requestType, resourceProps, old_resource_props=None, physical_id=None, expected_status='SUCCESS'): response_url = '<response-url>' event={ 'ResponseURL': response_url, 'StackId': '<stack-id>', 'RequestId': '<request-id>', 'LogicalResourceId': '<logical-resource-id>', 'RequestType': requestType, 'ResourceProperties': resourceProps } if old_resource_props: event['OldResourceProperties'] = old_resource_props if physical_id: event['PhysicalResourceId'] = physical_id class ContextMock: log_stream_name = 'log_stream' class ResponseMock: reason = 'OK' context = ContextMock() requests.put = MagicMock(return_value=ResponseMock()) #-------------------- # invoke the handler #-------------------- index.handler(event, context) requests.put.assert_called_once() (pos_args, kw_args) = requests.put.call_args actual_url = pos_args[0] actual_data = kw_args['data'] if actual_url != response_url: raise Exception("Invalid url used for sending CFN response. expected=%s actual=%s" % (response_url, actual_url)) resp = json.loads(actual_data) def assert_field(name, expect=None): value=resp.get(name) if not expect: if not resp.get(name): raise Exception("Missing '%s' field from response: %s" % (name, resp)) elif expect and value != expect: raise Exception("Expecting response field '%s' to be '%s' but got '%s'.\n%s" % (name, expect, value, json.dumps(resp, indent=2))) assert_field('Status', expected_status) assert_field('Reason') assert_field('PhysicalResourceId') assert_field('StackId', '<stack-id>') assert_field('RequestId', '<request-id>') assert_field('LogicalResourceId', '<logical-resource-id>') return resp
def test_normal(self, monkeypatch): """ normal test """ monkeypatch.setattr(SummaryUsersService, 'summary_report', lambda x: x) monkeypatch.setattr(SendReportService, 'send_report', lambda *x: x) index.handler({}, {})
def test_handler(self, aws_account_id): """ Test the handler operates as expected. """ test_event = MagicMock() test_context = MagicMock() aws_account_id.return_value = '1234567890' index.handler(test_event, test_context)
def test_update(self, _, put): event = make_event("Update", True) index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], event["ResourceProperties"]["NotificationConfiguration"], )
def test_create(self, _, get: MagicMock, put: MagicMock): get.return_value = {} event = make_event("Create", False) index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], event["ResourceProperties"]["NotificationConfiguration"], )
def test_handler(pkg_created_event_mock, queue_append_mock, queue_flush_mock): event = { 'Records': [{ 'body': json.dumps({'Records': records}) } for records in ((0, 1), (2, 3, 4), (5, ))] } handler(event, None) assert pkg_created_event_mock.call_args_list == [((x, ), ) for x in range(6)] assert queue_append_mock.call_args_list == [((str(x), ), ) for x in range(6)] queue_flush_mock.assert_called_once_with()
def test_failure(self, submit: MagicMock, handle_managed: MagicMock): event = make_event("Create", True) def throw(*_): raise RuntimeError("Intentional error for test") handle_managed.side_effect = throw index.handler(event, {}) submit.assert_called_once() self.assertEqual(submit.call_args_list[0][0][2], "FAILED")
def test_delete(self, _, get: MagicMock, put: MagicMock): event = make_event("Delete", False) # simulate external notifications current_notifications = make_notification_configuration() get.return_value = current_notifications index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], current_notifications, )
def test_delete(self, _, get: MagicMock, put: MagicMock): event = make_event("Delete", False) # simulate a previous create operation current_notifications = make_notification_configuration( f"{event['StackId']}-") get.return_value = current_notifications index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], make_empty_notification_configuration(), )
def test_response(self): print("testing response.") result = index.handler({'httpMethod': 'GET', 'path': '/'}, {}) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'application/json') self.assertIn('Hello World', result['body'])
def test_response(self): print("testing response.") result = index.handler(None, None) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'application/json') self.assertIn('Hello World', result['body'])
def test_handler(): event = {"headers": {}} r = index.handler(event, {}) assert r["body"] is not None rj = json.loads(r["body"]) assert rj is not None
def test_handler(self, snapshot_instances_mock, prune_snapshots_mock): """ Tests that the handler honors the value of RENTENTION_DAYS and calls the snapshot and prune functions with the expected values. """ lightsail = Mock() self.env = EnvironmentVarGuard() self.env.set('RETENTION_DAYS', '90') with patch('boto3.client', return_value=lightsail) as client_factory: with self.env: index.handler(Mock(), Mock()) client_factory.assert_called_with('lightsail') snapshot_instances_mock.assert_called_with(lightsail) prune_snapshots_mock.assert_called_with(lightsail, timedelta(days=90))
def test_valid_event_no_results_returns_next_question(mocker): get_study_guide_id_list_mock = mocker.patch( 'helper.get_study_guide_id_list') get_study_guide_id_list_mock.return_value = [ 'zc7k2nb', 'z84jtv4', 'zs8y4qt', 'zt8t3k7', 'zxr7ng8', 'z3tgw6f', 'z8fkmsg' ] get_topic_id_mock = mocker.patch('helper.get_topic_id') get_topic_id_mock.return_value = { 'zc7k2nb': 'z2s8v9q', 'z84jtv4': 'z2s8v9q', 'zs8y4qt': 'z2s8v9q', 'zt8t3k7': 'z9236yc', 'zxr7ng8': 'z9236yc', 'z3tgw6f': 'z9236yc', 'z8fkmsg': 'z9236yc' } mastery_mock = mocker.patch('algorithm.calculate_beta_distribution_mean') mastery_mock.return_value = 0.75 confidence_mock = mocker.patch('algorithm.calculate_confidence_interval') confidence_mock.return_value = 0.5 band_mock = mocker.patch('algorithm.calculate_mastery_band_and_confidence') band_mock.return_value = 3, 0.65 question_mock = mocker.patch('algorithm.choose_next_question') question_mock.return_value = NEXT_QUESTION actual_question = handler(VALID_EVENT_NO_RESULTS, CONTEXT) assert actual_question == VALID_QUESTION_RESPONSE_NO_RESULTS
def atest_response(self): print("testing response.") event = {'pathParameters': {'bucket': 'bmp2https', 'bmpid': '1'}} result = index.handler(event, None) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'image/bmp')
def test_response(self): print("testing response.") result = index.handler(None, None) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'image/bmp')
def test_full_flow(testcase: dict): lambda_event = testcase["lambda_event"] number_of_logs_expected = testcase["number_of_logs_expected"] lambda_context = SimpleNamespace(function_name="my-function-name") client_response = (200, "BODY") with patch('util.http_client.perform_http_request_for_json', return_value=client_response) as mock_http_client: with patch('boto3.client'): response = index.handler(lambda_event, lambda_context) # CHECK RESPONSE assert len(response["records"]) == len(lambda_event["records"]) for i, response_record in enumerate(response["records"]): input_record = lambda_event["records"][i] assert response_record["recordId"] == input_record["recordId"] assert response_record["data"], input_record["data"] assert response_record["result"], "Ok" # CHECK HTTP CALL assert mock_http_client.call_count == 1 request_body_bytes = mock_http_client.call_args[0][1] request_body = request_body_bytes.decode('utf-8') sent_logs = json.loads(request_body) assert len(sent_logs) == number_of_logs_expected for log in sent_logs: assert log[ "cloud.log_forwarder"] == "444652832050:us-east-1:log_forwarder"
def test(): response = index.handler({}, None) assert response == { "message": "Your function executed successfully!", "event": {} }
def test_handler_unauthorized(self): index.COGNITO.initiate_auth.side_effect = \ botocore.exceptions.ClientError( error_response={}, operation_name='InitiateAuth', ) event = {'headers': {'authorization': f'Basic {self.bad}'}} assert index.handler(event) == dict(isAuthorized=False)
def test_update_with_eventbridge(self, _, get: MagicMock, put: MagicMock): event = make_event_with_eventbridge("Update", False) # simulate external notifications current_notifications = make_notification_configuration() get.return_value = current_notifications index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], merge_notification_configurations( current_notifications, event["ResourceProperties"]["NotificationConfiguration"], ), )
def handler(event, context): envs = os.environ envs['jointfaas_env'] = 'aliyun' envs['region'] = context.region creds = context.credentials envs['accessKeyId'] = creds.accessKeyId envs['accessKeySecret'] = creds.accessKeySecret envs['securityToken'] = creds.securityToken return index.handler(json.loads(event))
def test_update_with_existing_eventbridge(self, _, get: MagicMock, put: MagicMock): event = make_event("Update", False) # simulate a previous create operation current_notifications = make_notification_configuration_with_eventbridge( f"{event['StackId']}-") get.return_value = current_notifications index.handler(event, {}) put.assert_called_once_with( event["ResourceProperties"]["BucketName"], merge_notification_configurations( make_eventbridge_configuration(), event["ResourceProperties"]["NotificationConfiguration"], ), )
def test_response(self): print("testing response.") result = index.handler( {'queryStringParameters': { 'string': 'Karsten' }}, None) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'application/json') self.assertIn(False, result['body'])
def test_response(self): print("testing response.") result = index.handler( { "Message": "this is a message from you", "body": "test" }, None) print(result) self.assertEqual(result['statusCode'], 200) self.assertEqual(result['headers']['Content-Type'], 'application/json')
def test_e6(self): event = {'queryStringParameters': {'value': '6.8k'}} response = index.handler(event=event, context=None) response = json.loads(response['body']) self.assertEqual(response['closest']['E6']['nominal'], 6800) self.assertEqual(response['closest']['E6']['colors'][0], 'blue') self.assertEqual(response['closest']['E6']['colors'][1], 'grey') self.assertEqual(response['closest']['E6']['colors'][2], 'red')