示例#1
0
def test_message_persisted_in_dynamo():
    """
    When any message posted to any topic
    then the message is persisted to 'sns_log' table
    with 'interaction_id' as the hash key and 'timestamp' as the range key
    """
    interaction_id = str(uuid.uuid4())
    # replace static interaction_id
    message = {"interaction_id": interaction_id, "url": "https://github.com/foo/bar"}
    event = create_event()
    event["Records"][0]["Sns"]["Message"] = json.dumps(message)

    main.handler(event, None)
    time.sleep(1)
    response = table_sns_log.query(KeyConditionExpression=Key("interaction_id").eq(interaction_id))
    expected_items = [{
            "interaction_id": interaction_id,
            "message_timestamp": "2017-04-10T05:12:56.297Z",
            "topic_name": "build_scheduled",
            "message": {
                "interaction_id": interaction_id,
                "url": "https://github.com/foo/bar"}}]
    #sample response
    #{u'Count': 1, u'Items': [{u'timestamp': u'2017-04-10T05:12:56.297Z', u'message': {u'url': u'https://github.com/foo/bar', u'interaction_id': u'123'}, u'interaction_id': u'123'}], u'ScannedCount': 1, 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '8P0NII0TI2UR8OVDCG0UJR0RNJVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPHeaders': {'x-amzn-requestid': '8P0NII0TI2UR8OVDCG0UJR0RNJVV4KQNSO5AEMVJF66Q9ASUAAJG', 'content-length': '202', 'server': 'Server', 'connection': 'keep-alive', 'x-amz-crc32': '3831536738', 'date': 'Mon, 17 Apr 2017 02:51:30 GMT', 'content-type': 'application/x-amz-json-1.0'}}}
    actual_items = response.get("Items")

    assert actual_items == expected_items
示例#2
0
 def test_happy_case(self, FakeMastodon):
     mastodon = FakeMastodon()
     handler(None, None)
     mastodon.media_post.assert_called_once_with("images/10.jpg",
                                                 "image/jpeg")
     mastodon.status_post.assert_called_once_with(
         "BONG BONG BONG BONG BONG BONG BONG BONG BONG BONG",
         media_ids=mock.ANY)
def test_handler_success(
        sm_describe_endpoint_config_params, sm_create_endpoint_config_params,
        sm_create_endpoint_config_response, cp_expected_params,
        sm_describe_endpoint_params, sm_create_endpoint_params,
        sm_create_endpoint_response, sm_describe_endpoint_response_2, event):

    sm_client = get_client("sagemaker")
    cp_client = get_client("codepipeline")

    sm_stubber = Stubber(sm_client)
    cp_stubber = Stubber(cp_client)

    # endpoint config creation
    sm_describe_endpoint_config_response = {}

    cp_response = {}

    sm_stubber.add_client_error(
        "describe_endpoint_config",
        service_error_code="EndpointConfigExists",
        service_message="Could not find endpoint configuration",
        http_status_code=400,
        expected_params=sm_describe_endpoint_config_params,
    )
    sm_stubber.add_response(
        "create_endpoint_config",
        sm_create_endpoint_config_response,
        sm_create_endpoint_config_params,
    )

    # endpoint creation
    sm_stubber.add_client_error(
        "describe_endpoint",
        service_error_code="EndpointExists",
        service_message="Could not find endpoint",
        http_status_code=400,
        expected_params=sm_describe_endpoint_params,
    )

    sm_stubber.add_response("create_endpoint", sm_create_endpoint_response,
                            sm_create_endpoint_params)

    sm_stubber.add_response(
        "describe_endpoint",
        sm_describe_endpoint_response_2,
        sm_describe_endpoint_params,
    )

    cp_stubber.add_response("put_job_success_result", cp_response,
                            cp_expected_params)

    expected_log_message = (
        "Sent success message back to codepipeline with job_id: test_job_id")
    with sm_stubber:
        with cp_stubber:
            handler(event, {})
            cp_stubber.assert_no_pending_responses()
            reset_client()
示例#4
0
    def test_handler(self):
        self._ec2.add_response('describe_instances', self.ec2_list, {'Filters': ANY})
        self._ec2.add_response('start_instances', {}, {'InstanceIds': ['i-0ff1234']})
        self._ec2.add_response('stop_instances', {}, {'InstanceIds': ['i-0ff1236']})

        trigger = datetime.combine(date.today(), time(hour=6, tzinfo=TIMEZONE)).astimezone(tzutc())

        with freeze_time(trigger + timedelta(seconds=3)):
            handler({'time': trigger.isoformat()}, None)

        self._ec2.assert_no_pending_responses()
def test_handler_exception():
    with patch("boto3.client") as mock_client:
        event = {
            "CodePipeline.job": {"id": "test_job_id"},
        }
        failure_message = {
            "message": "Job failed. Check the logs for more info.",
            "type": "JobFailed",
        }
        handler(event, context={})
        mock_client().put_job_failure_result.assert_called()
示例#6
0
def test_handler_success(sm_expected_params, sm_response_200, event):
    sm_client = get_client("sagemaker")
    sm_stubber = Stubber(sm_client)

    # success path
    sm_stubber.add_response("create_transform_job", sm_response_200,
                            sm_expected_params)

    with sm_stubber:
        handler(event, {})
        reset_client()
示例#7
0
def test_persist_called():
    main.handler(create_event(), None)
    expected_item = {
            "interaction_id": "123",
            "message_timestamp": "2017-04-10T05:12:56.297Z",
            "topic_name": "build_scheduled",
            "message": {
                "interaction_id": "123",
                "url": "https://github.com/foo/bar"}}
    main.persist_item.assert_called_with(expected_item)
    assert main.table_sns_log.table_name == "sns_log"
示例#8
0
def test_handler_fail(sm_expected_params, sm_response_500, event):
    sm_client = get_client("sagemaker")
    sm_stubber = Stubber(sm_client)

    # fail path
    sm_stubber.add_response("create_transform_job", sm_response_500,
                            sm_expected_params)

    with pytest.raises(Exception):
        handler(event, {})

    reset_client()
def test_handler_success(
    sm_create_baseline_expected_params,
    sm_create_job_response_200,
    event,
):

    sm_client = get_client("sagemaker")
    sm_stubber = Stubber(sm_client)

    # success path
    sm_stubber.add_response("create_processing_job", sm_create_job_response_200, sm_create_baseline_expected_params)

    with sm_stubber:
        handler(event, {})
        reset_client()
示例#10
0
    def test_create_delete(self):
        # create a subscription
        request = Request('Create', self.topic_arn, sqs_arn, 'sqs',
                          test_filter)
        response = handler(request, {})
        self.assertTrue(response['Status'], 'SUCCESS')
        self.assertIn('PhysicalResourceId', response)
        physical_resource_id = response['PhysicalResourceId']
        self.assertIsInstance(physical_resource_id, str)

        # delete the subscription
        request = Request('Delete', self.topic_arn, sqs_arn, 'sqs',
                          test_filter, physical_resource_id)
        response = handler(request, {})
        assert response['Status'] == 'SUCCESS', response['Reason']
示例#11
0
def test_with_noise():
    """
    Test the handler function.
    Assert the return value is 200
    and the response contains the noise vector and the image
    """

    # generate random noise vector
    noise = np.random.normal(size=(1, 100))

    # mock the request with the noise vector
    req = Mock()
    req.get_json = lambda silent: {"noise_vector": noise.tolist()}

    # call the handler passing the request
    out = handler(req)

    # assert the response is correctly formed
    assert out[1] == 200

    # assert the latent vector is the same
    np.testing.assert_almost_equal(np.array(out[0]["noise_vector"]), noise)
    assert out[0]["base64_image"]

    # try decoding the image
    # decode image bytes
    image_bytes = base64.b64decode(out[0]["base64_image"])

    # decode bytes as rgb image
    decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)

    # assert the image has the correct shape
    assert decoded.shape == (64, 64, 3)
def test_main():
    context = unittest.mock.Mock()
    context.token = {'access_token': 'abcde'}
    event = {
        'version': 1,
        'session': {},
        'request': {
            'command': 'переведи слово katze с немецкого на английский',
            'nlu': {
                'intents': {
                    'translate_full': {
                        'slots': {
                            'phrase': {
                                'value': 'katze'
                            },
                            'from': {
                                'value': 'de'
                            },
                            'to': {
                                'value': 'en'
                            },
                        }
                    }
                }
            }
        }
    }
    with unittest.mock.patch('main.translate') as mock_translate:
        mock_translate.return_value = None, 'cat'
        resp = handler(event=event, context=context)
        mock_translate.assert_called_with(token='abcde',
                                          lang_from='de',
                                          lang_to='en',
                                          text='katze')
    assert resp['response']['text'] == 'cat'
示例#13
0
def test_main():
    """
    Test the handler function.
    Assert the return value is 200
    and the response contains the noise vector and the image
    """

    # mock the request
    req = Mock()
    req.get_json = lambda silent: {}

    # call the handler
    out = handler(req)

    # assert the response is correctly formed
    assert out[1] == 200
    assert out[0]["noise_vector"]
    assert out[0]["base64_image"]

    # try decoding the image
    # decode image bytes
    image_bytes = base64.b64decode(out[0]["base64_image"])

    # decode bytes as rgb image
    decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)

    # assert the image has the correct shape
    assert decoded.shape == (64, 64, 3)
def test_default():
    response = main.handler(new_request('NotAThingIntent'), context={})

    assert "Sorry, I didn't get that" in response['response']['outputSpeech'][
        'ssml']
    assert "Please say it again" in response['response']['reprompt'][
        'outputSpeech']['ssml']
    assert response['response']['shouldEndSession'] is False
    def test_main_handler(self):
        handler_response = main.handler(None)

        self.assertIsInstance(handler_response, bytes)
        response = json.loads(handler_response)

        self.assertIn('personaje', response)
        self.assertIn('frase', response)
示例#16
0
    def test_err(self, mock):
        '''
    Test request error handling
    '''
        mock.stats_code = 500
        mock.return_value.json.return_value = {}

        res = handler({}, self.cxt)
示例#17
0
def test_handler_success(
    sm_create_monitoring_expected_params,
    sm_create_monitoring_response_200,
    sm_describe_monitoring_schedule_response,
    cp_expected_params_success,
    sm_describe_monitoring_scheduale_params,
    event,
):

    sm_client = get_client("sagemaker")
    cp_client = get_client("codepipeline")

    sm_stubber = Stubber(sm_client)
    cp_stubber = Stubber(cp_client)

    cp_response = {}

    # job creation
    sm_stubber.add_client_error(
        "describe_monitoring_schedule",
        service_error_code="MonitorJobExists",
        service_message="Could not find requested job with name",
        http_status_code=400,
        expected_params=sm_describe_monitoring_scheduale_params,
    )

    # success path
    sm_stubber.add_response("create_monitoring_schedule",
                            sm_create_monitoring_response_200,
                            sm_create_monitoring_expected_params)

    sm_stubber.add_response(
        "describe_monitoring_schedule",
        sm_describe_monitoring_schedule_response,
        sm_describe_monitoring_scheduale_params,
    )

    cp_stubber.add_response("put_job_success_result", cp_response,
                            cp_expected_params_success)

    with sm_stubber:
        with cp_stubber:
            handler(event, {})
            cp_stubber.assert_no_pending_responses()
            reset_client()
示例#18
0
def test_handler():
    json_data = json.loads(handler(a, None))

    assert 'user_ip' in json_data
    assert type(json_data['user_ip']) is str
    assert 'user_agent' in json_data
    assert type(json_data['user_agent']) is str
    assert 'req_time' in json_data
    assert type(json_data['req_time']) is str
示例#19
0
 def test_post_with_zero_ids(self):
     event = {
       "httpMethod": "POST",
       "body": str(json.dumps({
           "ids": []
       }))
     }
     expected = response(400, 'Must provide at least one ID.')
     result = main.handler(event, 'c')
     self.assertEqual(result, expected)
示例#20
0
 def test_multi_multi(self):
     result = handler(
         {
             'resource': '/compare',
             'queryStringParameters': {
                 'text1': '瓶と雑誌',
                 'text2': 'ビンカンペットボトル'
             }
         }, {})
     self.assertEqual(result['statusCode'], 200)
def test_launch():
    response = main.handler(new_request('LaunchRequest'), context={})

    assert 'Welcome to Even Better Button Trivia.' in response['response'][
        'outputSpeech']['ssml']
    assert 'How many players' in response['response']['reprompt'][
        'outputSpeech']['ssml']
    assert response['sessionAttributes'] == {}
    assert response['response']['directives'][0][
        'type'] == 'GadgetController.SetLight'
示例#22
0
def test_handler_failure(lm_expected_params, lm_response_500,
                         cp_expected_params_failure, event):
    lm_client = get_client("lambda")
    lm_stubber = Stubber(lm_client)
    cp_client = get_client("codepipeline")
    cp_stubber = Stubber(cp_client)

    cp_response = {}

    lm_stubber.add_response("update_function_configuration", lm_response_500,
                            lm_expected_params)
    cp_stubber.add_response("put_job_failure_result", cp_response,
                            cp_expected_params_failure)

    with lm_stubber:
        with cp_stubber:
            handler(event, {})
            cp_stubber.assert_no_pending_responses()
            reset_client()
示例#23
0
 def test_post_with_invalid_ids(self):
     ids = list(map(lambda x: x[0], fixture[1:3]))
     ids.append('fake')
     event = {
         "httpMethod": "POST",
         "body": str(json.dumps({
           "ids": ids
         }))
     }
     result = main.handler(event, 'c')
     self.assertEqual(result['statusCode'], '400')
示例#24
0
    def test_handler(self, mock):
        '''
    Test the request handler
    '''
        mock.return_value.status_code = 200
        mock.return_value.json.return_value = {}

        res = handler(self.evt, self.cxt)

        self.assertEqual(res['statusCode'], 200)
        self.assertEqual(res['body'], json.dumps({}))
def test_handler_fail(sm_expected_params, sm_response_500,
                      cp_expected_params_failure, event):
    sm_client = get_client("sagemaker")
    cp_client = get_client("codepipeline")

    sm_stubber = Stubber(sm_client)
    cp_stubber = Stubber(cp_client)

    cp_response = {}
    # fail path
    sm_stubber.add_response("create_transform_job", sm_response_500,
                            sm_expected_params)
    cp_stubber.add_response("put_job_failure_result", cp_response,
                            cp_expected_params_failure)

    with sm_stubber:
        with cp_stubber:
            handler(event, {})
            cp_stubber.assert_no_pending_responses()
            reset_client()
示例#26
0
    def test_handler_returns_405_on_other_request_types(self, mock_request):
        """
        Test handler returns (data, 405) on requests where method is not POST
        """

        mock_request.get_json.return_value = self.incoming_json_data
        mock_request.get_json.silent = True
        mock_request.method = 'GET'

        self.assertEqual(
            main.handler(mock_request),
            (json.dumps({'message': 'Only POST requests permitted.'}), 405))
def test_player_count_invalid():
    request = new_request('PlayerCount', {'players': 100})
    request['session']['attributes'] = {'STATE': settings.STATES['start_game']}
    response = main.handler(request, context={})

    assert 'between 1 and 4' in response['response']['outputSpeech']['ssml']
    assert 'between 1 and 4' in response['response']['reprompt'][
        'outputSpeech']['ssml']
    assert response['sessionAttributes'] == {
        'player_count': 100,
        'STATE': settings.STATES['start_game'],
    }
示例#28
0
 def test_single_single(self):
     result = handler(
         {
             'resource': '/compare',
             'queryStringParameters': {
                 'text1': '燃えるゴミ',
                 'text2': '燃えないゴミ'
             }
         }, {})
     self.assertEqual(result['statusCode'], 200)
     self.assertEqual(json.loads(result['body']),
                      {'score': round(1 - 2 / 6, 2)})
 def test_handler_unauthorized(self):
     self.assertDictEqual(
         handler(_build_unauthorized_event(), None), {
             "status": "401",
             "statusDescription": "Unauthorized",
             "body": "Unauthorized",
             "headers": {
                 "www-authenticate": [{
                     "key": "WWW-Authenticate",
                     "value": "Basic"
                 }]
             }
         })
示例#30
0
def test_noise_error():
    # the latent space is 200 instead of 100
    noise = np.random.normal(size=(1, 200))

    # mock the request with the wrong noise vector
    req = Mock()
    req.get_json = lambda silent: {"noise_vector": noise.tolist()}

    # call the handler passing the request
    out = handler(req)

    # the response should be a user error
    assert out[1] == 400
def test_player_count():
    request = new_request('PlayerCount', {'players': 1})
    request['session']['attributes'] = {'STATE': settings.STATES['start_game']}
    response = main.handler(request, context={})

    assert 'audio src=' in response['response']['outputSpeech']['ssml']
    assert 'Fantastic! Are you ready' in response['response']['outputSpeech'][
        'ssml']
    assert 'Ready to start' in response['response']['reprompt'][
        'outputSpeech']['ssml']
    assert response['sessionAttributes'] == {
        'STATE': settings.STATES['buttonless_game'],
        'player_count': 1,
    }
示例#32
0
 def test_post_with_three_ids(self):
     event = {
       "httpMethod": "POST",
       "body": str(json.dumps({
           "ids": list(map(lambda x: x[0], fixture[:3]))
       }))
     }
     expected = response(200, json.dumps({
         'total': sum(list(map(lambda x: x[1], fixture[:3]))),
         'max': fixture[0][1],
         'min': fixture[1][1]
     }))
     result = main.handler(event, 'c')
     self.assertEqual(result, expected)
示例#33
0
def test_build_scheduled():
    main.handler(event, None)
    expected_event = {"interaction_id": "123", "url": "https://github.com/foo/bar"}
    main.publish_event.assert_called_with(expected_event)
示例#34
0
def test_build_request_published():
    response = main.handler(apigw_event, None)
    actual_interaction_id = response["headers"]["X-Shmenkins-InteractionId"]
    assert len(actual_interaction_id) == 36
    expected_message = {"interaction_id": ANY, "url": "https://github.com/rzhilkibaev/cfgen"}
    main.publish_event.assert_called_with(expected_message)