Example #1
0
 def test_delete(self):
     found_todo = TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6')
     self.assertEquals(found_todo.text,
                       'text of d490d766-8b60-11e7-adba-e0accb8996e6')
     found_todo.delete()
     with self.assertRaises(DoesNotExist):
         TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6')
def handle(event, context):
    try:
        table_name = os.environ[ENV_VAR_DYNAMODB_TABLE]
        region = os.environ[ENV_VAR_DYNAMODB_REGION]
    except KeyError as err:
        error_message = '{0} is missing from environment variables'.format(
            str(err))
        return HttpResponseServerError(error_code='ENV_VAR_NOT_SET',
                                       error_message=error_message).__dict__()

    TodoModel.setup_model(TodoModel, region, table_name, ENV_VAR_ENVIRONMENT
                          not in os.environ)

    try:
        todo_id = event['pathParameters']['todo_id']
    except KeyError:
        return HttpResponseBadRequest(
            error_code='URL_PARAMETER_MISSING',
            error_message='TODO id missing from url').__dict__()
    try:
        found_todo = TodoModel.get(hash_key=todo_id)
    except DoesNotExist:
        return HttpResponseNotFound(
            error_message='TODO was not found').__dict__()

    try:
        found_todo.delete()
    except DeleteError:
        return HttpResponseBadRequest(
            error_code='DELETE_FAILED',
            error_message='Unable to delete the TODO').__dict__()

    # create a response
    return HttpNoContentResponse().__dict__()
Example #3
0
def create(event, context):
    data = json.loads(event['body'])
    if 'text' not in data:
        logging.error('Validation Failed')
        return {
            'statusCode':
            422,
            'body':
            json.dumps({'error_message': 'Couldn\'t create the todo item.'})
        }

    if not data['text']:
        logging.error('Validation Failed - text was empty. %s', data)
        return {
            'statusCode':
            422,
            'body':
            json.dumps({
                'error_message':
                'Couldn\'t create the todo item. As text was empty.'
            })
        }

    a_todo = TodoModel(todo_id=str(uuid.uuid1()),
                       text=data['text'],
                       checked=False)

    # write the todo to the database
    a_todo.save()

    # create a response
    return {'statusCode': 201, 'body': json.dumps(dict(a_todo))}
Example #4
0
def handle(event, context):
    try:
        table_name = os.environ[ENV_VAR_DYNAMODB_TABLE]
        region = os.environ[ENV_VAR_DYNAMODB_REGION]
    except KeyError as err:
        error_message = '{0} is missing from environment variables'.format(
            str(err))
        return HttpResponseServerError(error_code='ENV_VAR_NOT_SET',
                                       error_message=error_message).__dict__()

    TodoModel.setup_model(TodoModel, region, table_name, ENV_VAR_ENVIRONMENT
                          not in os.environ)

    try:
        todo_id = event['pathParameters']['todo_id']
    except KeyError:
        return HttpResponseBadRequest(
            error_code='URL_PARAMETER_MISSING',
            error_message='TODO id missing from url').__dict__()
    try:
        found_todo = TodoModel.get(hash_key=todo_id)
    except DoesNotExist:
        return HttpResponseNotFound(
            error_message='TODO was not found').__dict__()

    try:
        data = json.loads(event['body'])
    except ValueError as err:
        return HttpResponseBadRequest(error_code='JSON_IRREGULAR',
                                      error_message=str(err)).__dict__()

    if 'text' not in data and 'checked' not in data:
        logging.error('Validation Failed %s', data)
        return HttpResponseBadRequest(
            error_code='VALIDATION_FAILED',
            error_message='Could not update the todo item.').__dict__()

    text_attr_changed = 'text' in data and data['text'] != found_todo.text
    if text_attr_changed:
        found_todo.text = data['text']
    checked_attr_changed = 'checked' in data and data[
        'checked'] != found_todo.checked
    if checked_attr_changed:
        found_todo.checked = data['checked']

    if text_attr_changed or checked_attr_changed:
        found_todo.save()
    else:
        logging.info('Nothing changed did not update')

    # create a response
    return HttpOkJSONResponse(body=dict(found_todo)).__dict__()
Example #5
0
    def test_create(self):
        todo_text = 'text'
        todo_id = str(uuid.uuid1())
        t1 = TodoModel(todo_id=todo_id,
                       text=todo_text,
                       created_at=datetime.now())
        t1.save()
        self.assertEquals(t1.text, todo_text)
        self.assertEquals(t1.checked, False)

        # get and check
        t2 = TodoModel.get(todo_id)
        self.assertEquals(t2.text, todo_text)
Example #6
0
    def test_update(self):
        found_todo = TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6')
        self.assertEquals(found_todo.text,
                          'text of d490d766-8b60-11e7-adba-e0accb8996e6')
        new_text = 'New text of item'
        found_todo.update({'text': {'action': 'put', 'value': new_text}})
        self.assertEquals(found_todo.text, new_text)

        # refresh and check
        found_todo.refresh()
        self.assertEquals(found_todo.text, new_text)

        # Get and check
        check_text = TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6')
        self.assertEquals(check_text.text, new_text)
Example #7
0
def update(event, context):
    # TODO: Figure out why this is behaving differently to the other endpoints
    # data = json.loads(event['body'])
    data = event['body']

    if 'text' not in data and 'checked' not in data:
        logging.error('Validation Failed %s', data)
        return {'statusCode': 422,
                'body': json.dumps({'error_message': 'Couldn\'t update the todo item.'})}

    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {'statusCode': 404,
                'body': json.dumps({'error_message': 'TODO was not found'})}

    todo_changed = False
    if 'text' in data and data['text'] != found_todo.text:
        found_todo.text = data['text']
        todo_changed = True
    if 'checked' in data and data['checked'] != found_todo.checked:
        found_todo.checked = data['checked']
        todo_changed = True

    if todo_changed:
        found_todo.save()
    else:
        logging.info('Nothing changed did not update')

    # create a response
    return {'statusCode': 200,
            'body': json.dumps(dict(found_todo))}
Example #8
0
def todo_list(event, context):
    # fetch all todos from the database
    results = TodoModel.scan()

    # create a response
    return {'statusCode': 200,
            'body': json.dumps({'items': [dict(result) for result in results]})}
def update(event, context):
    # TODO: Figure out why this is behaving differently to the other endpoints
    # data = json.loads(event['body'])
    data = event['body']

    if 'text' not in data and 'checked' not in data:
        logging.error('Validation Failed %s', data)
        return {'statusCode': 422,
                'body': json.dumps({'error_message': 'Couldn\'t update the todo item.'})}

    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {'statusCode': 404,
                'body': json.dumps({'error_message': 'TODO was not found'})}

    todo_changed = False
    if 'text' in data and data['text'] != found_todo.text:
        found_todo.text = data['text']
        todo_changed = True
    if 'completed' in data and data['completed'] != found_todo.completed:
        found_todo.completed = data['completed']
        todo_changed = True

    if todo_changed:
        found_todo.save()
    else:
        logging.info('Nothing changed did not update')

    # create a response
    return {'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Origin': todos.config.aws['allow-origin'],
            },
            'body': json.dumps(dict(found_todo))}
Example #10
0
 def test_delete(self):
     found_todos = TodoModel.scan()
     todos = [result for result in found_todos]
     self.assertEquals(len(todos), 1)
     self.assertEquals(todos[0].text,
                       'text of d490d766-8b60-11e7-adba-e0accb8996e6')
     self.assertEquals(todos[0].todo_id,
                       'd490d766-8b60-11e7-adba-e0accb8996e6')
Example #11
0
    def test_setup_model(self):
        mock_model = MagicMock()
        mock_model.Meta.host = 'http://localhost:8000'
        table = 'table'
        region = 'region'
        TodoModel.setup_model(mock_model, region, table, False)
        self.assertEquals(mock_model.Meta.table_name, table)
        self.assertEquals(mock_model.Meta.region, region)
        self.assertEquals(mock_model.Meta.host, 'http://localhost:8000')

        table = 'table1'
        region = 'region1'
        TodoModel.setup_model(mock_model, region, table, True)
        self.assertEquals(mock_model.Meta.table_name, table)
        self.assertEquals(mock_model.Meta.region, region)
        self.assertEquals(mock_model.Meta.host,
                          'https://dynamodb.{0}.amazonaws.com'.format(region))
Example #12
0
def todo_list(event, context):
    # fetch all todos from the database
    results = TodoModel.scan()

    # create a response
    return {
        'statusCode': 200,
        'body': json.dumps({'items': [dict(result) for result in results]})
    }
Example #13
0
def create(event, context):
    data = json.loads(event['body'])
    if 'text' not in data:
        logging.error('Validation Failed')
        return {
            'statusCode':
            422,
            'headers': {
                'Access-Control-Allow-Origin': "*",
            },
            'body':
            json.dumps({'error_message': 'Couldn\'t create the todo item.'})
        }

    if not data['text']:
        logging.error('Validation Failed - text was empty. %s', data)
        return {
            'statusCode':
            422,
            'headers': {
                'Access-Control-Allow-Origin': "*",
            },
            'body':
            json.dumps({
                'error_message':
                'Couldn\'t create the todo item. As text was empty.'
            })
        }

    a_todo = TodoModel(todo_id=str(uuid.uuid1()),
                       text=data['text'],
                       completed=False)

    # write the todo to the database
    a_todo.save()

    # create a response
    return {
        'statusCode': 201,
        'headers': {
            'Access-Control-Allow-Origin': todos.config.aws['allow-origin'],
        },
        'body': json.dumps(dict(a_todo))
    }
def handle(event, context):
    try:
        table_name = os.environ[ENV_VAR_DYNAMODB_TABLE]
        region = os.environ[ENV_VAR_DYNAMODB_REGION]
    except KeyError as err:
        error_message = '{0} is missing from environment variables'.format(
            str(err))
        return HttpResponseServerError(error_code='ENV_VAR_NOT_SET',
                                       error_message=error_message).__dict__()

    TodoModel.setup_model(TodoModel, region, table_name, ENV_VAR_ENVIRONMENT
                          not in os.environ)

    # fetch all todos from the database
    results = TodoModel.scan()

    # create a response
    items = {'items': [dict(result) for result in results]}
    return HttpOkJSONResponse(body=items).__dict__()
Example #15
0
def get(event, context):
    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {'statusCode': 404,
                'body': json.dumps({'error_message': 'TODO was not found'})}

    # create a response
    return {'statusCode': 200,
            'body': json.dumps(dict(found_todo))}
Example #16
0
 def setUp(self, load_dbs=None):
     TodoModel.setup_model(TodoModel, 'region', 'todo' + str(uuid.uuid1()),
                           'ENVIRONMENT' not in os.environ)
     if not TodoModel.exists():
         TodoModel.create_table(wait=True)
     if load_dbs:
         for db_file in load_dbs:
             TodoModel.load(db_file)
     super().setUp()
Example #17
0
def todo_list(event, context):
    # fetch all todos from the database
    results = TodoModel.scan()

    # create a response
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': todos.config.aws['allow-origin'],
        },
        'body': json.dumps({'items': [dict(result) for result in results]})
    }
Example #18
0
def create(event, context):
    data = json.loads(event['body'])
    if 'text' not in data:
        logging.error('Validation Failed')
        return {'statusCode': 422,
                'body': json.dumps({'error_message': 'Couldn\'t create the todo item.'})}

    if not data['text']:
        logging.error('Validation Failed - text was empty. %s', data)
        return {'statusCode': 422,
                'body': json.dumps({'error_message': 'Couldn\'t create the todo item. As text was empty.'})}

    a_todo = TodoModel(todo_id=str(uuid.uuid1()),
                       text=data['text'],
                       checked=False)

    # write the todo to the database
    a_todo.save()

    # create a response
    return {'statusCode': 201,
            'body': json.dumps(dict(a_todo))}
Example #19
0
def delete(event, context):
    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {'statusCode': 404,
                'body': json.dumps({'error_message': 'TODO was not found'})}
    try:
        found_todo.delete()
    except DeleteError:
        return {'statusCode': 400,
                'body': json.dumps({'error_message': 'Unable to delete the TODO'})}

    # create a response
    return {'statusCode': 204}
Example #20
0
def get(event, context):
    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {
            'statusCode': 404,
            'body': json.dumps({'error_message': 'TODO was not found'})
        }

    # create a response
    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Origin': todos.config.aws['allow-origin'],
        },
        'body': json.dumps(dict(found_todo))
    }
Example #21
0
def delete(event, context):
    try:
        found_todo = TodoModel.get(hash_key=event['path']['todo_id'])
    except DoesNotExist:
        return {
            'statusCode': 404,
            'body': json.dumps({'error_message': 'TODO was not found'})
        }
    try:
        found_todo.delete()
    except DeleteError:
        return {
            'statusCode': 400,
            'body': json.dumps({'error_message': 'Unable to delete the TODO'})
        }

    # create a response
    return {'statusCode': 204}
Example #22
0
 def test_create(self):
     todo_text = 'text'
     todo_id = str(uuid.uuid1())
     t1 = TodoModel(todo_id=todo_id,
                    text=todo_text,
                    created_at=datetime.now())
     t1.save()
     self.assertEquals(t1.text, todo_text)
     self.assertEquals(t1.checked, False)
     t2 = TodoModel.get(hash_key=todo_id)
     self.assertEquals(t2.text, todo_text)
     r = [result for result in TodoModel.scan()]
     self.assertEquals(len(r), 1)
     self.assertEquals(r[0].text, todo_text)
     self.assertEquals(r[0].todo_id, todo_id)
     t2.delete()
Example #23
0
def handle(event, context):
    try:
        table_name = os.environ[ENV_VAR_DYNAMODB_TABLE]
        region = os.environ[ENV_VAR_DYNAMODB_REGION]
    except KeyError as err:
        error_message = '{0} is missing from environment variables'.format(
            str(err))
        return HttpResponseServerError(error_code='ENV_VAR_NOT_SET',
                                       error_message=error_message).__dict__()

    TodoModel.setup_model(TodoModel, region, table_name, ENV_VAR_ENVIRONMENT
                          not in os.environ)

    try:
        data = json.loads(event['body'])
    except ValueError as err:
        return HttpResponseBadRequest(error_code='JSON_IRREGULAR',
                                      error_message=str(err)).__dict__()

    if 'text' not in data:
        logging.error('Validation Failed')
        return HttpResponseBadRequest(
            error_code='BODY_PROPERTY_MISSING',
            error_message='Could not create the todo item.').__dict__()

    if not data['text']:
        logging.error('Validation Failed - text was empty. %s', data)
        return HttpResponseBadRequest(
            error_code='VALIDATION_FAILED',
            error_message='Could not create the todo item. As text was empty.'
        ).__dict__()

    a_todo = TodoModel(todo_id=str(uuid.uuid1()),
                       text=data['text'],
                       checked=False,
                       created_at=datetime.now())

    # write the todo to the database
    a_todo.save()

    # create a response
    return HttpCreatedJSONResponse(body=dict(a_todo)).__dict__()
Example #24
0
 def test_save(self, _):
     t_model = TodoModel()
     t_model.save()
     self.assertEquals(t_model.updated_at,
                       datetime.datetime(2012, 1, 14, 12, 0, 1))
Example #25
0
 def test_get_failed(self):
     with self.assertRaises(DoesNotExist):
         TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6a')
Example #26
0
 def test_get(self):
     found_todo = TodoModel.get('d490d766-8b60-11e7-adba-e0accb8996e6')
     self.assertEquals(found_todo.text,
                       'text of d490d766-8b60-11e7-adba-e0accb8996e6')
Example #27
0
 def tearDown(self):
     if TodoModel.exists():
         TodoModel.delete_table()
     super().tearDown()