Пример #1
0
    def test_put(self):
        """ Test that you can put """
        us = User(email="test@localhost", password=crypt('tset'))
        db_sess = get_session()
        db_sess.add(us)
        db_sess.commit()
        entry = Entry(userid=us.userid,
                      title="test",
                      completed=True,
                      description="test desc")
        db_sess.add(entry)
        db_sess.commit()
        response = self.session.post(self._route("/auth/login"),
                                     json={
                                         'email': us.email,
                                         'password': "******"
                                     })
        self.assertEqual(response.status_code, 200, response.text)

        new_entry = Entry(userid=us.userid,
                          title="test_updated",
                          completed=False,
                          description="test desc updated")
        response = self.session.put(self._route("/todo/entry/{}".format(
            entry.entryid)),
                                    json={
                                        'title': new_entry.title,
                                        'completed': new_entry.completed,
                                        'description': new_entry.description
                                    })
        db_sess.refresh(entry)

        self.assertEqual(response.status_code, 200, response.text)
        self.assertEqual(entry.as_dict(), response.json(), response.text)
        db_sess.close()
Пример #2
0
def put_handler(oid):
    """ Update specific todo entry for logged in user """
    try:
        body = request.json
        title = body.pop('title', None)
        completed = body.pop('completed', None)
        description = body.pop('description', None)
        if body:
            abort(400)

        user = current_user
        session = get_session()
        entry = session.query(Entry).filter(
            Entry.entryid == oid and Entry.userid == user.userid).one()

        # Can be improved
        entry.title = title if title is not None else entry.title
        entry.completed = completed if completed is not None else entry.completed
        entry.description = description if description is not None else entry.description
        session.add(entry)
        session.commit()
    except (NoResultFound, MultipleResultsFound):
        abort(404)
    response = make_response(json.dumps(entry.as_dict()), 200)
    session.close()
    return response
Пример #3
0
    def test_list(self):
        """ Test that you can list """
        us = User(email="test@localhost", password=crypt('tset'))
        db_sess = get_session()
        db_sess.add(us)
        db_sess.commit()

        e_a = Entry(userid=us.userid,
                    title="test",
                    completed=True,
                    description="test desc")
        e_b = Entry(userid=us.userid,
                    title="test2",
                    completed=False,
                    description="test2 desc")

        db_sess.add(e_a)
        db_sess.add(e_b)
        db_sess.commit()

        response = self.session.post(self._route("/auth/login"),
                                     json={
                                         'email': us.email,
                                         'password': "******"
                                     })
        self.assertEqual(response.status_code, 200, response.text)

        response = self.session.get(self._route("/todo/entry"), )
        expected = [e_a.as_dict(), e_b.as_dict()]
        db_sess.close()
        self.assertEqual(response.json(), expected, response.text)
        self.assertEqual(response.status_code, 200, response.text)
Пример #4
0
def list_handler():
    """ List todo entries of logged in user """
    session = get_session()
    user = current_user
    response = make_response(
        json.dumps([entry.as_dict() for entry in user.entries]), 200)
    session.close()
    return response
Пример #5
0
def load_user(user_email):
    session = get_session()
    user = None
    try:
        user = session.query(User).filter(User.email == user_email).one()
    except (MultipleResultsFound, NoResultFound):
        pass
    session.close()
    return user
Пример #6
0
 def setUp(self):
     self.session = requests.session()
     self.session.headers['Content-Type'] = 'application/json'
     response = self.session.post(self._route("/auth/login"),
                                  json=self.CREDENTIALS)
     self.assertEqual(response.status_code, 200, response.text)
     db_sess = get_session()
     db_sess.query(User).filter(User.email != "root@localhost").delete()
     db_sess.query(Entry).delete()
     db_sess.commit()
Пример #7
0
def delete_handler(oid):
    """ Delete specific todo entry for logged in user """
    try:
        user = current_user
        session = get_session()
        entry = session.query(Entry).filter(
            Entry.entryid == oid and Entry.userid == user.userid).delete()
    except (NoResultFound, MultipleResultsFound):
        abort(404)
    response = make_response('', 200)
    session.close()
    return response
Пример #8
0
def get_handler(oid):
    """ Get specific todo entry for logged in user """
    try:
        user = current_user
        session = get_session()
        entry = session.query(Entry).filter(
            Entry.entryid == oid and Entry.userid == user.userid).one()
    except (NoResultFound, MultipleResultsFound):
        abort(404)
    response = make_response(json.dumps(entry.as_dict()), 200)
    session.close()
    return response
Пример #9
0
 def test_post(self):
     """ Test that you can post """
     response = self.session.post(self._route("/todo/entry"),
                                  json={
                                      'title': 'test title',
                                      'completed': True,
                                      'description': 'test description'
                                  })
     self.assertEqual(response.status_code, 201, response.text)
     db_sess = get_session()
     entry = db_sess.query(Entry).filter(
         Entry.entryid == response.json()['entryid']).one()
     db_sess.close()
     self.assertEqual(response.json(), entry.as_dict(), response.text)
Пример #10
0
def post_handler():
    """ Post todo entries for logged in user """
    try:
        body = request.json
        title = body.pop('title')
        completed = body.pop('completed', None)
        description = body.pop('description')
        if body:
            abort(400)

        user = current_user
        entry = Entry(title=title,
                      completed=completed,
                      description=description,
                      userid=user.userid)
        session = get_session()
        session.add(entry)
        session.commit()
    except (KeyError):
        abort(400)
    response = make_response(json.dumps(entry.as_dict()), 201)
    session.close()
    return response
Пример #11
0
    def test_delete(self):
        """ Test that you can delete """
        us = User(email="test@localhost", password=crypt('tset'))
        db_sess = get_session()
        db_sess.add(us)
        db_sess.commit()
        entry = Entry(userid=us.userid,
                      title="test",
                      completed=True,
                      description="test desc")
        db_sess.add(entry)
        db_sess.commit()
        response = self.session.post(self._route("/auth/login"),
                                     json={
                                         'email': us.email,
                                         'password': "******"
                                     })
        self.assertEqual(response.status_code, 200, response.text)

        response = self.session.delete(
            self._route("/todo/entry/{}".format(entry.entryid)))
        self.assertEqual(response.status_code, 200, response.text)
        db_sess.close()
Пример #12
0
def login():
    body = request.json
    received_user_email = body['email']
    if not (isinstance(body['email'], str)
            and isinstance(body['password'], str)):
        abort(400)

    session = get_session()

    try:
        user = session.query(User).filter(
            User.email == str(received_user_email)).one()

        received_password = crypt(body['password'], user.password)

        if received_password == user.password:
            login_user(user)
            response = make_response(
                json.dumps({
                    'error': False,
                    'message': 'authorized'
                }), 200)
        else:
            response = make_response(
                json.dumps({
                    'error': 401,
                    'message': 'unauthorized'
                }), 401)

    except (MultipleResultsFound, NoResultFound):
        response = make_response(
            json.dumps({
                'error': 401,
                'message': 'unauthorized'
            }), 401)
    session.close()
    return response
Пример #13
0
    def verify_application_health(self, **kwargs):
        """
        Verify an application is healthy via the router.
        This is only used in conjunction with the kubernetes health check system and should
        only run after kubernetes has reported all pods as healthy
        """
        # Bail out early if the application is not routable
        release = self.release_set.filter(failed=False).latest()
        app_settings = self.appsettings_set.latest()
        if not kwargs.get('routable', False) and app_settings.routable:
            return

        app_type = kwargs.get('app_type')
        self.log(
            'Waiting for router to be ready to serve traffic to process type {}'.format(app_type),
            level=logging.DEBUG
        )

        # Get the router host and append healthcheck path
        url = 'http://{}:{}'.format(settings.ROUTER_HOST, settings.ROUTER_PORT)

        # if a httpGet probe is available then 200 is the only acceptable status code
        if 'livenessProbe' in kwargs.get('healthcheck', {}) and 'httpGet' in kwargs.get('healthcheck').get('livenessProbe'):  # noqa
            allowed = [200]
            handler = kwargs['healthcheck']['livenessProbe']['httpGet']
            url = urljoin(url, handler.get('path', '/'))
            req_timeout = handler.get('timeoutSeconds', 1)
        else:
            allowed = set(range(200, 599))
            allowed.remove(404)
            req_timeout = 3

        # Give the router max of 10 tries or max 30 seconds to become healthy
        # Uses time module to account for the timeout value of 3 seconds
        start = time.time()
        failed = False
        headers = {
            # set the Host header for the application being checked - not used for actual routing
            'Host': '{}.{}.nip.io'.format(self.id, settings.ROUTER_HOST),
        }
        for _ in range(10):
            try:
                # http://docs.python-requests.org/en/master/user/advanced/#timeouts
                response = get_session().get(url, timeout=req_timeout, headers=headers)
                failed = False
            except requests.exceptions.RequestException:
                # In case of a failure where response object is not available
                failed = True
                # We are fine with timeouts and request problems, lets keep trying
                time.sleep(1)  # just a bit of a buffer
                continue

            # 30 second timeout (timeout per request * 10)
            if (time.time() - start) > (req_timeout * 10):
                break

            # check response against the allowed pool
            if response.status_code in allowed:
                break

            # a small sleep since router usually resolve within 10 seconds
            time.sleep(1)

        # Endpoint did not report healthy in time
        if ('response' in locals() and response.status_code == 404) or failed:
            # bankers rounding
            delta = round(time.time() - start)
            self.log(
                'Router was not ready to serve traffic to process type {} in time, waited {} seconds'.format(app_type, delta),  # noqa
                level=logging.WARNING
            )
            return

        self.log(
            'Router is ready to serve traffic to process type {}'.format(app_type),
            level=logging.DEBUG
        )
Пример #14
0
    def verify_application_health(self, **kwargs):
        """
        Verify an application is healthy via the router.
        This is only used in conjunction with the kubernetes health check system and should
        only run after kubernetes has reported all pods as healthy
        """
        # Bail out early if the application is not routable
        release = self.release_set.filter(failed=False).latest()
        app_settings = self.appsettings_set.latest()
        if not kwargs.get('routable', False) and app_settings.routable:
            return

        app_type = kwargs.get('app_type')
        self.log(
            'Waiting for router to be ready to serve traffic to process type {}'.format(app_type),
            level=logging.DEBUG
        )

        # Get the router host and append healthcheck path
        url = 'http://{}:{}'.format(settings.ROUTER_HOST, settings.ROUTER_PORT)

        # if a httpGet probe is available then 200 is the only acceptable status code
        if 'livenessProbe' in kwargs.get('healthcheck', {}) and 'httpGet' in kwargs.get('healthcheck').get('livenessProbe'):  # noqa
            allowed = [200]
            handler = kwargs['healthcheck']['livenessProbe']['httpGet']
            url = urljoin(url, handler.get('path', '/'))
            req_timeout = handler.get('timeoutSeconds', 1)
        else:
            allowed = set(range(200, 599))
            allowed.remove(404)
            req_timeout = 3

        # Give the router max of 10 tries or max 30 seconds to become healthy
        # Uses time module to account for the timout value of 3 seconds
        start = time.time()
        failed = False
        headers = {
            # set the Host header for the application being checked - not used for actual routing
            'Host': '{}.{}.nip.io'.format(self.id, settings.ROUTER_HOST),
        }
        for _ in range(10):
            try:
                # http://docs.python-requests.org/en/master/user/advanced/#timeouts
                response = get_session().get(url, timeout=req_timeout, headers=headers)
                failed = False
            except requests.exceptions.RequestException:
                # In case of a failure where response object is not available
                failed = True
                # We are fine with timeouts and request problems, lets keep trying
                time.sleep(1)  # just a bit of a buffer
                continue

            # 30 second timeout (timout per request * 10)
            if (time.time() - start) > (req_timeout * 10):
                break

            # check response against the allowed pool
            if response.status_code in allowed:
                break

            # a small sleep since router usually resolve within 10 seconds
            time.sleep(1)

        # Endpoint did not report healthy in time
        if ('response' in locals() and response.status_code == 404) or failed:
            # bankers rounding
            delta = round(time.time() - start)
            self.log(
                'Router was not ready to serve traffic to process type {} in time, waited {} seconds'.format(app_type, delta),  # noqa
                level=logging.WARNING
            )
            return

        self.log(
            'Router is ready to serve traffic to process type {}'.format(app_type),
            level=logging.DEBUG
        )