Beispiel #1
0
def drop_ponos_collections():
    """
    Drops all Ponos DB collections.
    """

    ponos_db = PonosDB()
    ponos_db.drop_collection(ponos_db.shift)
Beispiel #2
0
def mock_shift_data(self=None):
    """
    Saves mock MongoEngine Shifts to Mongo.

    Key Word Argument:
        self (TestCase): sets instance attribute of all shifts to TestCase instance if being called within unit test
        setUp method.

    Return:
        (datetime, datetime)
    """

    # Initialize helper APIs.
    ponos_db = PonosDB()
    fake = Faker()

    # Assign shifts to TestCase instance attribute for reference in unit tests.
    if self:
        self.shifts = []

    for _ in repeat(None, 10):

        # Initialize MongoEngine TimeSlots.
        time_slots = [ponos_db.init_time_slot(fake.word(), *random_time_slots()) for _ in repeat(None, random.randint(1, 10))]
        labels = [fake.word() for _ in repeat(None, random.randint(1, 10))]

        # Initialize and save MongoEngine Shift to database.
        shift = ponos_db.create_shift(fake.address(), fake.city(), fake.state(), fake.zipcode(), fake.country(),
                                      time_slots, description=fake.text(), labels=labels)

        # Assign shifts to TestCase instance attribute for reference in unit tests.
        if self:
            self.shifts.append(shift)
Beispiel #3
0
 def setUp(self):
     self.ponos_db = PonosDB()
     self.ponos_q = PonosQueue()
     self.ponos_serializer = ShiftSchema
     self.headers = {
         'Content-Type': 'application/vnd.api+json',
         'Accept': 'application/vnd.api+json',
         'Authorization': current_app.config['API_TOKEN']
     }
     mock_shift_data(self)
Beispiel #4
0
class PonosDBMiddlewareTests(TestCase):
    def create_app(self):
        app = create_app(config='test')
        return app

    def setUp(self):
        self.ponos_db = PonosDB()

    def tearDown(self):
        drop_ponos_collections()

    def test_init_time_slot(self):
        mock_shift_data(self)
        time_slot_start, time_slot_end = random_time_slots()
        time_slot = self.ponos_db.init_time_slot('First', time_slot_start,
                                                 time_slot_end)
        self.assertIsInstance(time_slot, self.ponos_db.time_slots)

    def test_shift_crud(self):
        #Create
        time_slots = [
            self.ponos_db.init_time_slot('first', *random_time_slots())
            for _ in repeat(None, 3)
        ]
        shift = self.ponos_db.create_shift(
            '1033 W. Loyola',
            'Chicago',
            'IL',
            '60626',
            'USA',
            time_slots,
            description='Test shift description')
        self.assertIsInstance(shift, self.ponos_db.shift)

        q_shift = self.ponos_db.get_first(self.ponos_db.shift,
                                          shift_id=shift.shift_id)
        self.assertEquals(shift, q_shift)

        # Read
        q_shift = self.ponos_db.get_shift(shift_id=shift.shift_id)
        self.assertEquals(shift, q_shift)

        # Update
        self.ponos_db.update_shift(q_shift, address='888 Elm Street')
        self.assertEquals(q_shift.address, '888 Elm Street')

        # Delete
        q_shift_id = q_shift.shift_id
        self.ponos_db.delete_shift(shift)
        self.assertEquals(self.ponos_db.get_shift(shift_id=q_shift_id), None)
Beispiel #5
0
class PonosShiftEndpointTests(TestCase):
    def create_app(self):
        app = create_app(config='test')
        return app

    def setUp(self):
        self.ponos_db = PonosDB()
        self.ponos_q = PonosQueue()
        self.ponos_serializer = ShiftSchema
        self.headers = {
            'Content-Type': 'application/vnd.api+json',
            'Accept': 'application/vnd.api+json',
            'Authorization': current_app.config['API_TOKEN']
        }
        mock_shift_data(self)

    def tearDown(self):
        drop_ponos_collections()

    def _test_get_id_shift(self):
        shift_id = self.shifts[0].shift_id
        resp = self.client.get(url_for('ponos', shift_id=shift_id),
                               headers=self.headers)
        self.assert200(resp)

        test_shift = self.ponos_db.get_first(self.ponos_db.shift,
                                             shift_id=shift_id)
        self.assertEqual(resp.data,
                         self.ponos_serializer().dumps(test_shift).data)

    def _test_get_all_shift(self):
        resp = self.client.get(url_for('ponos'), headers=self.headers)
        self.assert200(resp)

        test_shifts = self.ponos_db.get_all(self.ponos_db.shift)
        self.assertEqual(
            resp.data,
            self.ponos_serializer(many=True).dumps(test_shifts).data)

    def test_post_shift(self):
        resp = self.client.post(url_for('ponos'),
                                data=json.dumps(payload_1),
                                headers=self.headers)
        self.assert200(resp)
Beispiel #6
0
    def execute(self, app_config):
        app = create_app(app_config)

        with app.app_context():
            try:
                ponos_db = PonosDB()
                ponos_q = PonosQueue()
                while True:
                    self.work_jobs(ponos_db, ponos_q, app.logger)
                    time.sleep(1)
            except Exception as e:
                app.logger.error('PonosWorker - {}'.format(e.message))
Beispiel #7
0
 def __init__(self):
     self.ponos_db = PonosDB()
     self.ponos_q = PonosQueue()
     self.ponos_serializer = ShiftSchema
     self.request_parser = reqparse.RequestParser()
     super(ShiftEndpoints, self).__init__()
Beispiel #8
0
class ShiftEndpoints(Resource):
    method_decorators = [authenticate_token]

    def __init__(self):
        self.ponos_db = PonosDB()
        self.ponos_q = PonosQueue()
        self.ponos_serializer = ShiftSchema
        self.request_parser = reqparse.RequestParser()
        super(ShiftEndpoints, self).__init__()

    def __repr__(self):
        return '<{0}> Flask-Restful Resource'.format(self.__class__.__name__)

    @flask_cache.memoize(timeout=50)
    def get(self, shift_id=None):
        """
        Handles HTTP GET requests to /ponos/shift - /ponos/shift/<string:shift_id>
        """

        # Requsting single resource
        if shift_id:

            # Query Mongo database for Shift
            shift = self.ponos_db.get_shift(shift_id=shift_id)

            if shift:
                # Query returned shift. Serialize resource into JSON API specification format.
                resp_json = self.ponos_serializer().dumps(shift).data

                return json_api_resp(resp_json)
            else:
                # Resource not found.
                return json_api_not_found_resp()
        else:
            # Requesting all resources
            # TODO - allowing access to all resources without pageingation can cause a bottleneck.

            # Query Mongo database for all Shifts
            shifts = self.ponos_db.get_all_shifts()

            if shifts:

                # Query returned shifts. Serialize resource into JSON API specification format.
                resp_json = self.ponos_serializer(many=True).dumps(shifts).data

                return json_api_resp(resp_json)
            else:

                # Resources not found.
                return json_api_not_found_resp()

    def post(self, **kwargs):
        """
        Handles HTTP POST requests to /ponos/shift
        """

        try:
            # Parse request
            req_args = parse_json_api_data(self.ponos_serializer())
        except TypeError:
            # Invalid Content-Type header.
            abort(415)
        except (ValueError, ValidationError):
            # Payload invalid JSON or payload failed validation against Shift marshmallow_jsonapi.flask.Schema
            abort(422)

        # Add create shift job to queue
        self.ponos_q.add_create_shift_job(req_args)

        return json_api_success()
Beispiel #9
0
 def setUp(self):
     self.ponos_db = PonosDB()