def test_booking_end_date_before_start_date(self): with self.app.app_context(): schema = BookingSchema(exclude=['id']) booking = DummyBooking.person1_car1_available booking.start_time = datetime.now() + timedelta(days=100) booking.end_time = datetime.now() booking_jsonstr = json.dumps(schema.dump(booking)) with self.assertRaises(ValidationError) as cm: schema.loads(booking_jsonstr) self.assertEqual(['end_time can not be before start_time'], cm.exception.messages['_schema'])
def booking(id: int): """ Get, put, delete booking Args: id (int): booking id Returns: 403 if booking not found, 200 Ok """ booking = Booking.query.get(id) if booking is None: return abort(403, description='Booking not found') if request.method == 'DELETE': Booking.query.filter_by(id=id).delete() handle_db_operation(db.session.commit) return jsonify('Booking deleted'), 200 elif request.method == 'PUT': schema = BookingSchema() try: new_booking = schema.loads(request.get_json()) except ValidationError as ve: return abort(403, description=ve.messages) booking.person_id = new_booking.person_id booking.car_id = new_booking.car_id booking.start_time = new_booking.start_time booking.end_time = new_booking.end_time booking.status = new_booking.status handle_db_operation(db.session.commit) return jsonify('Booking updated successfully'), 200 else: schema = BookingSchema() return jsonify(schema.dumps(booking)), 200
def add_booking_admin(): """ Add a new booking Returns: Json string of booking, or error """ schema = BookingSchema(exclude=['id']) try: booking = schema.loads(request.get_json()) except ValidationError as ve: return abort(400, description=ve.messages) # wow generic message # check that references to data in db is valid person = Person.query.filter_by(id=booking.person_id).first() car = Car.query.filter_by(id=booking.car_id).first() if None in [person, car]: return abort(403, description='Booking references invalid person/car id(s)') # Check that no booking with car is currently active if Booking.is_car_busy(booking.start_time, booking.end_time, booking.car_id): return abort(403, description=f'A booking with car id {booking.car_id}' f' is already mad in that time period') db.session.add(booking) handle_db_operation(db.session.commit) return schema.jsonify(booking), 201
def test_schema_load_data_from_json(self): with self.app.app_context(): person_schema = PersonSchema() person = person_schema.loads(DummyPerson.creat_random_json(id=None)) self.assertEqual(type(person), Person) booking_schema = BookingSchema() # deserialize to json string booking_json = booking_schema.dumps(DummyBooking.person1_car1_available) # serialize from json string booking = booking_schema.loads(DummyBooking.b1_json) self.assertEqual(type(booking), Booking)