Advertisement
Guest User

marshmallow_test.py

a guest
May 16th, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. # Requires Marshmallow version 3 in order to raise exceptions from
  2. # loading
  3. # pip install marshmallow --pre
  4. from marshmallow import fields, Schema, post_load, validates, ValidationError
  5.  
  6.  
  7. class Location():
  8.     def __init__(self, latitude: float, longitude: float) -> None:
  9.         self.latitude = latitude
  10.         self.longitude = longitude
  11.  
  12.  
  13. class ParkingLot():
  14.     def __init__(self, capacity: int, name: str, price: float, location: Location) -> None:
  15.         self.capacity = capacity
  16.         self.name = name
  17.         self.price = price
  18.         self.location = location
  19.         self.id = None
  20.  
  21.  
  22. class LocationSchema(Schema):
  23.     latitude = fields.Float(required=True)
  24.     longitude = fields.Float(required=True)
  25.  
  26.  
  27. class ParkingLotSchema(Schema):
  28.     capacity = fields.Int(required=True)
  29.     name = fields.Str(required=True)
  30.     price = fields.Float()
  31.     location = fields.Nested(LocationSchema, required=True)
  32.  
  33.     @validates('price')
  34.     def validate_price(self, price: float):
  35.         if price < 0:
  36.             raise ValidationError("Price must be non-negative")
  37.  
  38.     @validates('capacity')
  39.     def validate_capacity(self, capacity: int):
  40.         if capacity < 1:
  41.             raise ValidationError("Capacity must be positive")
  42.  
  43.     @post_load
  44.     def build_parking_lot(self, data: dict) -> ParkingLot:
  45.         return ParkingLot(**data)
  46.  
  47.  
  48. if __name__ == '__main__':
  49.     schema = ParkingLotSchema()
  50.     correct_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
  51.                     'name': 'my_parking_lot', 'capacity': 500, 'price': 1.5}
  52.     invalid_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
  53.                     'name': 'my_parking_lot', 'capacity': -999, 'price': 1.5}
  54.     missing_data = {'location': {'latitude': 1.0, 'longitude': 2.0},
  55.                     'name': 'my_parking_lot', 'price': 1.5}
  56.     missing_loc_data = {'location': {'longitude': 2.0},
  57.                         'name': 'my_parking_lot', 'capacity': 500, 'price': 1.5}
  58.  
  59.     for data in (correct_data, invalid_data, missing_data, missing_loc_data):
  60.         try:
  61.             pl = schema.load(data)
  62.             print(pl)
  63.         except ValidationError as err:
  64.             print(err)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement