Example #1
0
  def get(self):
    place_name = self.request.get("p", None)
    callback = self.request.get("callback", None)

    if not place_name:
      raise InvalidPlace(" ")
    elif place_name == "favicon.ico":
      """ This happens so often, it's annoying. """
      self.response.set_status(204)
    else:
      place_name = urllib2.unquote(place_name)
      p = memcache.get(self.PLACE_KEY % place_name)
      if not p:
        p = Place(place_name)
        memcache.set(self.PLACE_KEY % place_name, p) # cache indefinitely

      alerts = memcache.get(self.ALERT_KEY % place_name)
      if not alerts:
        alerts = Alert.alerts_for(p)
        try:
          memcache.set(self.ALERT_KEY % place_name, alerts, time=10) # cache a SHORT time
        except:
          logging.error('Error setting memcache.')
          logging.error(''.join(traceback.format_exception(*sys.exc_info())))

      p.alerts = alerts
      javascript = json.dumps(p, sort_keys=True, indent=2, cls=PlaceEncoder)

      self.response.headers['Content-Type'] = 'text/javascript'
      self.response.out.write("%s(%s)" % (callback, javascript) if callback else javascript)
Example #2
0
 def test_delete_place_wrong(self):
     """the id does not match a place"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.delete('{}/places/{}/'.format(self.path, "noID"),
                          follow_redirects=True)
     self.assertEqual(rv.status_code, 404)
     storage.delete(place)
Example #3
0
 def test_getplaces_bad_city(self):
     """test listing all places with a bad city id"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id}
     place = Place(**place_args)
     place.save()
     rv = self.app.get('{}/cities/{}/places'.format(self.path, "noID"),
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 404)
     storage.delete(place)
Example #4
0
 def test_update_city_bad_id(self):
     """test update with no matching id"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.put('{}/places/{}/'.format(self.path, "noID"),
                       content_type="application/json",
                       data=json.dumps({"name": "Z"}),
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 404)
     storage.delete(place)
Example #5
0
 def test_update_place_bad_json(self):
     """test update with ill formed json"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.put('{}/places/{}/'.format(self.path, place.id),
                       content_type="application/json",
                       data={"id": "Z"},
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 400)
     self.assertEqual(rv.get_data(), b"Not a JSON")
     storage.delete(place)
Example #6
0
 def test_delete_place(self):
     """test delete a place"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.delete('{}/places/{}/'.format(self.path,
                                                 place_args["id"]),
                          follow_redirects=True)
     self.assertEqual(rv.status_code, 200)
     self.assertEqual(rv.headers.get("Content-Type"), "application/json")
     json_format = getJson(rv)
     self.assertEqual(json_format, {})
     self.assertIsNone(storage.get("Place", place_args["id"]))
Example #7
0
 def test_view_one_place(self):
     """test retrieving one place"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.get('{}/places/{}'.format(self.path, place_args["id"]),
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 200)
     self.assertEqual(rv.headers.get("Content-Type"), "application/json")
     json_format = getJson(rv)
     self.assertEqual(json_format.get("name"), place_args["name"])
     self.assertEqual(json_format.get("id"), place_args["id"])
     self.assertEqual(json_format.get("user_id"), place_args["user_id"])
     storage.delete(place)
Example #8
0
 def test_getplaces(self):
     """test listing all places in a city"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id}
     place = Place(**place_args)
     place.save()
     rv = self.app.get('{}/cities/{}/places'.format(
         self.path, self.city.id),
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 200)
     self.assertEqual(rv.headers.get("Content-Type"), "application/json")
     json_format = getJson(rv)
     self.assertTrue(type(json_format), list)
     self.assertIn(place_args["name"], [e.get("name") for e in json_format])
     self.assertIn(place_args["user_id"],
                   [e.get("user_id") for e in json_format])
     storage.delete(place)
Example #9
0
 def test_update_place_user_id(self):
     """test cannot update place user_id"""
     place_args = {"name": "cage", "city_id": self.city.id,
                   "user_id": self.user.id, "id": "CA"}
     place = Place(**place_args)
     place.save()
     rv = self.app.put('{}/places/{}/'.format(self.path, place.id),
                       content_type="application/json",
                       data=json.dumps({"user_id": "Z"}),
                       follow_redirects=True)
     self.assertEqual(rv.status_code, 200)
     self.assertEqual(rv.headers.get("Content-Type"), "application/json")
     json_format = getJson(rv)
     self.assertEqual(json_format.get("name"), place_args["name"])
     self.assertEqual(json_format.get("id"), place_args["id"])
     self.assertEqual(json_format.get("city_id"), place_args["city_id"])
     self.assertEqual(json_format.get("user_id"), place_args["user_id"])
     storage.delete(place)
Example #10
0
 def test_str(self):
     """test that the str method has the correct output"""
     place = Place()
     string = "[Place] ({}) {}".format(place.id, place.__dict__)
     self.assertEqual(string, str(place))
Example #11
0
 def test_latitude_attr(self):
     """Test Place has attr longitude"""
     place = Place()
     self.assertTrue(hasattr(place, "longitude"))
     self.assertEqual(place.longitude, 0.0)
Example #12
0
 def test_father(self):
     """Test the class - BaseModel """
     place1 = Place()
     self.assertTrue(issubclass(place1.__class__, BaseModel))
Example #13
0
def get_products_from_place(id_place):
    places = Place.objects(id=id_place)
    return Product.objects(place__in=places)
Example #14
0
 def test_number_rooms_attr(self):
     """Test Place has attr number_rooms"""
     place = Place()
     self.assertTrue(hasattr(place, "number_rooms"))
     self.assertEqual(place.number_rooms, 0)
Example #15
0
 def setUp(self):
     '''
         Creates an instance for place.
     '''
     self.new_place = Place()
Example #16
0
 def test_number_bathrooms_attr(self):
     """Test Place has attr number_bathrooms, and it's an int == 0"""
     place = Place()
     self.assertTrue(hasattr(place, "number_bathrooms"))
     self.assertEqual(type(place.number_bathrooms), int)
     self.assertEqual(place.number_bathrooms, 0)
Example #17
0
 def test_max_guest_attr(self):
     """Test Place has attr max_guest, and it's an int == 0"""
     place = Place()
     self.assertTrue(hasattr(place, "max_guest"))
     self.assertEqual(type(place.max_guest), int)
     self.assertEqual(place.max_guest, 0)
Example #18
0
 def test_8_instantiation(self):
     """Tests instantiation of Place class"""
     b = Place()
     self.assertEqual(str(type(b)), "<class 'models.place.Place'>")
     self.assertIsInstance(b, Place)
     self.assertTrue(issubclass(type(b), BaseModel))
Example #19
0
 def test_user_id_attr(self):
     """Test Place has attr user_id, and it's an empty string"""
     place = Place()
     self.assertTrue(hasattr(place, "user_id"))
     self.assertEqual(place.user_id, "")
Example #20
0
from models.amenity import Amenity
from models.review import Review
# creation of a State
state = State(name="California")
state.save()

# creation of a City
city = City(state_id=state.id, name="San Francisco")
city.save()

# creation of a User
user = User(email="*****@*****.**", password="******")
user.save()

# creation of 2 Places
place_1 = Place(user_id=user.id, city_id=city.id, name="House 1")
place_1.save()
place_2 = Place(user_id=user.id, city_id=city.id, name="House 2")
place_2.save()

# creation of 3 various Amenity
amenity_1 = Amenity(name="Wifi")
amenity_1.save()
amenity_2 = Amenity(name="Cable")
amenity_2.save()
amenity_3 = Amenity(name="Oven")
amenity_3.save()

# link place_1 with 2 amenities
place_1.amenities.append(amenity_1)
place_1.amenities.append(amenity_2)
Example #21
0
 def test_Place(self):
     """Test attributes of the class."""
     my_Place = Place()
     my_Place.name = "LA"
     self.assertEqual(my_Place.name, 'LA')
Example #22
0
 def test_father_kwargs(self):
     """Test the class - BaseModel passing kwargs """
     dictonary = {'id': '662a23b3-abc7-4f43-81dc-64c000000c00'}
     place1 = Place(**dictonary)
     self.assertTrue(issubclass(place1.__class__, BaseModel))
Example #23
0
 def test_last_name_attr(self):
     """Test that Place has attr name, and it's an empty string"""
     place = Place()
     self.assertTrue(hasattr(place, "name"))
     self.assertEqual(place.name, "")
Example #24
0
 def test_father(self):
     """ checks if subclass"""
     place1 = Place()
     self.assertTrue(issubclass(place1.__class__, BaseModel))
Example #25
0
 def test_description_attr(self):
     """Test Place has attr description, and it's an empty string"""
     place = Place()
     self.assertTrue(hasattr(place, "description"))
     self.assertEqual(place.description, "")
    def test_inheritance(self):
        """Tests if Class inherits from BaseModel"""

        place_example = Place()
        self.assertTrue(issubclass(place_example.__class__, BaseModel))
Example #27
0
 def test_class(self):
     """ creates a place instance"""
     place1 = Place()
     self.assertEqual(place1.__class__.__name__, "Place")
Example #28
0
 def test_amenity_ids_attr(self):
     """Test Place has attr amenity_ids, and it's an empty list"""
     place = Place()
     self.assertTrue(hasattr(place, "amenity_ids"))
     self.assertEqual(type(place.amenity_ids), list)
     self.assertEqual(len(place.amenity_ids), 0)
Example #29
0
 def setUp(self):
     ''' appropriately set the environment for testing '''
     utility.env_switcher('file')
     self.new_place = Place()
Example #30
0
class TestPlace(unittest.TestCase):
    def setUp(self):
        if (os.getenv('HBNB_TYPE_STORAGE') == 'db'):
            self.session = db_storage.DBStorage()
            self.session.reload()

        self.state = State(name="A State")
        self.city = City(name="A City", state_id=self.state.id)
        self.user = User(email="*****@*****.**", password="******")
        self.place = Place(city_id=self.city.id,
                           user_id=self.user.id,
                           name="",
                           description="")
        if (os.getenv('HBNB_TYPE_STORAGE') == 'db'):
            self.session.new(self.state)
            self.session.new(self.city)
            self.session.new(self.user)
            self.session.new(self.place)
            self.session.save()

    """Test the Place class"""

    def test_is_subclass(self):
        """Test that Place is a subclass of BaseModel"""
        self.assertIsInstance(self.place, BaseModel)
        self.assertTrue(hasattr(self.place, "id"))
        self.assertTrue(hasattr(self.place, "created_at"))
        self.assertTrue(hasattr(self.place, "updated_at"))

    def test_city_id_attr(self):
        """Test Place has attr city_id, and it's an empty string"""
        self.assertTrue(hasattr(self.place, "city_id"))
        self.assertEqual(self.place.city_id, self.city.id)

    def test_user_id_attr(self):
        """Test Place has attr user_id, and it's an empty string"""
        self.assertTrue(hasattr(self.place, "user_id"))
        self.assertEqual(self.place.user_id, self.user.id)

    def test_name_attr(self):
        """Test Place has attr name, and it's an empty string"""
        self.assertTrue(hasattr(self.place, "name"))
        self.assertEqual(self.place.name, "")

    def test_description_attr(self):
        """Test Place has attr description, and it's an empty string"""
        self.assertTrue(hasattr(self.place, "description"))
        self.assertEqual(self.place.description, "")

    def test_number_rooms_attr(self):
        """Test Place has attr number_rooms, and it's an int == 0"""
        self.assertTrue(hasattr(self.place, "number_rooms"))
        self.assertEqual(type(self.place.number_rooms), int)
        self.assertEqual(self.place.number_rooms, 0)

    def test_number_bathrooms_attr(self):
        """Test Place has attr number_bathrooms, and it's an int == 0"""
        self.assertTrue(hasattr(self.place, "number_bathrooms"))
        self.assertEqual(type(self.place.number_bathrooms), int)
        self.assertEqual(self.place.number_bathrooms, 0)

    def test_max_guest_attr(self):
        """Test Place has attr max_guest, and it's an int == 0"""
        self.assertTrue(hasattr(self.place, "max_guest"))
        self.assertEqual(type(self.place.max_guest), int)
        self.assertEqual(self.place.max_guest, 0)

    def test_price_by_night_attr(self):
        """Test Place has attr price_by_night, and it's an int == 0"""
        self.assertTrue(hasattr(self.place, "price_by_night"))
        self.assertEqual(type(self.place.price_by_night), int)
        self.assertEqual(self.place.price_by_night, 0)

    def test_latitude_attr(self):
        """Test Place has attr latitude, and it's a float == 0.0"""
        self.assertTrue(hasattr(self.place, "latitude"))
        self.assertEqual(type(self.place.latitude), float)
        self.assertEqual(self.place.latitude, 0.0)

    def test_latitude_attr(self):
        """Test Place has attr longitude, and it's a float == 0.0"""
        self.assertTrue(hasattr(self.place, "longitude"))
        self.assertEqual(type(self.place.longitude), float)
        self.assertEqual(self.place.longitude, 0.0)

    @unittest.skipIf(
        os.getenv('HBNB_TYPE_STORAGE') == 'db', "Testing DBStorage")
    def test_amenity_ids_attr(self):
        """Test Place has attr amenity_ids, and it's an empty list"""
        self.assertTrue(hasattr(self.place, "amenity_ids"))
        self.assertEqual(type(self.place.amenity_ids), list)
        self.assertEqual(len(self.place.amenity_ids), 0)

    def test_to_dict_creates_dict(self):
        """test to_dict method creates a dictionary with proper attrs"""
        new_d = self.place.to_dict()
        self.assertEqual(type(new_d), dict)
        for attr in self.place.__dict__:
            if not attr.startswith('_sa_'):
                self.assertTrue(attr in new_d)
        self.assertTrue("__class__" in new_d)

    def test_to_dict_values(self):
        """test that values in dict returned from to_dict are correct"""
        t_format = "%Y-%m-%dT%H:%M:%S.%f"
        new_d = self.place.to_dict()
        self.assertEqual(new_d["__class__"], "Place")
        self.assertEqual(type(new_d["created_at"]), str)
        self.assertEqual(type(new_d["updated_at"]), str)
        self.assertEqual(new_d["created_at"],
                         self.place.created_at.strftime(t_format))
        self.assertEqual(new_d["updated_at"],
                         self.place.updated_at.strftime(t_format))

    def test_str(self):
        """test that the str method has the correct output"""
        string = "[Place] ({}) {}".format(self.place.id, self.place.__dict__)
        self.assertEqual(string, str(self.place))
Example #31
0
class TestUser(unittest.TestCase):
    '''
        Testing Place class
    '''

    def setUp(self):
        ''' appropriately set the environment for testing '''
        utility.env_switcher('file')
        self.new_place = Place()

    def setUp(self):
        '''
            Creates an instance for place.
        '''
        self.new_place = Place()

    def TearDown(self):
        pass

    def test_Place_inheritance(self):
        '''
            tests that the City class Inherits from BaseModel
        '''

        self.assertIsInstance(self.new_place, BaseModel)

    def test_Place_attributes(self):
        '''
            Checks that the attribute exist.
        '''
        self.assertTrue("city_id" in self.new_place.__dir__())
        self.assertTrue("user_id" in self.new_place.__dir__())
        self.assertTrue("description" in self.new_place.__dir__())
        self.assertTrue("name" in self.new_place.__dir__())
        self.assertTrue("number_rooms" in self.new_place.__dir__())
        self.assertTrue("max_guest" in self.new_place.__dir__())
        self.assertTrue("price_by_night" in self.new_place.__dir__())
        self.assertTrue("latitude" in self.new_place.__dir__())
        self.assertTrue("longitude" in self.new_place.__dir__())
        self.assertTrue("amenity_ids" in self.new_place.__dir__())

    def test_type_longitude(self):
        '''
            Test the type of longitude.
        '''
        longitude = getattr(self.new_place, "longitude")
        self.assertIsInstance(longitude, float)

    def test_type_latitude(self):
        '''
            Test the type of latitude
        '''
        latitude = getattr(self.new_place, "latitude")
        self.assertIsInstance(latitude, float)

    def test_type_amenity(self):
        '''
            Test the type of latitude
        '''
        amenity = getattr(self.new_place, "amenity_ids")
        self.assertIsInstance(amenity, list)

    def test_type_price_by_night(self):
        '''
            Test the type of price_by_night
        '''
        price_by_night = getattr(self.new_place, "price_by_night")
        self.assertIsInstance(price_by_night, int)

    def test_type_max_guest(self):
        '''
            Test the type of max_guest
        '''
        max_guest = getattr(self.new_place, "max_guest")
        self.assertIsInstance(max_guest, int)

    def test_type_number_bathrooms(self):
        '''
            Test the type of number_bathrooms
        '''
        number_bathrooms = getattr(self.new_place, "number_bathrooms")
        self.assertIsInstance(number_bathrooms, int)

    def test_type_number_rooms(self):
        '''
            Test the type of number_bathrooms
        '''
        number_rooms = getattr(self.new_place, "number_rooms")
        self.assertIsInstance(number_rooms, int)

    def test_type_description(self):
        '''
            Test the type of description
        '''
        description = getattr(self.new_place, "description")
        self.assertIsInstance(description, str)

    def test_type_name(self):
        '''
            Test the type of name
        '''
        name = getattr(self.new_place, "name")
        self.assertIsInstance(name, str)

    def test_type_user_id(self):
        '''
            Test the type of user_id
        '''
        user_id = getattr(self.new_place, "user_id")
        self.assertIsInstance(user_id, str)

    def test_type_city_id(self):
        '''
            Test the type of city_id
        '''
        city_id = getattr(self.new_place, "city_id")
        self.assertIsInstance(city_id, str)
Example #32
0
 def test_price_by_night_attr(self):
     """Test Place has attr price"""
     place = Place()
     self.assertTrue(hasattr(place, "price_by_night"))
     self.assertEqual(place.price_by_night, 0)
Example #33
0
 def test_price_by_night_attr(self):
     """Test Place has attr price_by_night, and it's an int == 0"""
     place = Place()
     self.assertTrue(hasattr(place, "price_by_night"))
     self.assertEqual(type(place.price_by_night), int)
     self.assertEqual(place.price_by_night, 0)
Example #34
0
class HBNBCommand(cmd.Cmd):
    """console to data engine of HBNB."""

    prompt = '(hbnb) '

    classes = {
        "BaseModel": BaseModel(),
        "User": User(),
        "State": State(),
        "City": City(),
        "Amenity": Amenity(),
        "Place": Place(),
        "Review": Review()
    }

    def do_EOF(self, line):
        """ implement exit command whit EOF"""
        print()
        return True

    def do_quit(self, line):
        """ Quit command to exit the program """
        return True

    def do_create(self, arg):
        """Creates a new instance of BaseModel, saves it (
            to the JSON file) and prints the id. Ex: $ create BaseModel
        """
        if arg == '':
            print('** class name missing **')
        elif arg in self.classes.keys():
            new_class = 'new_' + arg
            new_class = self.classes[arg]
            new_class.save()
            print('{}'.format(new_class.id))
            # new_BaseModel = BaseModel()
            # new_BaseModel.save()
            # print('{}'.format(new_BaseModel.id))
        else:
            print('** class doesn\'t exist **')

    def do_show(self, line):
        """
            Prints the string representation of an instance based on the class
            name and id. Ex: $ show BaseModel 1234-1234-1234.
        """
        arg = line.split()
        if len(arg) == 0:
            print('** class name missing **')
        elif arg[0] != 'BaseModel':
            print('** class doesn\'t exist **')
        elif len(arg) == 1 and arg[0] == 'BaseModel':
            print('** instance id missing **')
        elif len(arg) == 2 and arg[0] == 'BaseModel':
            key = arg[0] + '.' + arg[1]
            list_obj = storage.all()
            id_counter = 0
            for obj in list_obj.keys():
                if obj == key:
                    my_new_model = BaseModel(**list_obj[obj])
                    print(my_new_model)
                    id_counter += 1
            if id_counter == 0:
                print('** no instance found **')

    def do_destroy(self, line):
        """Deletes an instance based on the class name and id (
            save the change into the JSON file). Ex: $ destroy 
            BaseModel 1234-1234-1234.
        """
        arg = line.split()
        if len(arg) == 0:
            print('** class name missing **')
        elif arg[0] != 'BaseModel':
            print('** class doesn\'t exist **')
        elif len(arg) == 1 and arg[0] == 'BaseModel':
            print('** instance id missing **')
        elif len(arg) == 2 and arg[0] == 'BaseModel':
            key = arg[0] + '.' + arg[1]
            list_obj = storage.all()
            id_counter = 0
            for obj in list_obj.keys():
                if obj == key:
                    id_counter += 1
            if id_counter > 0:
                del list_obj[key]
                with open('/home/vagrant/arbn_prev/file.json', 'w') as file:
                    json.dump(list_obj, file)
            if id_counter == 0:
                print('** no instance found **')

    def do_all(self, line):
        """Prints all string representation of all instances
            based or not on the class name. Ex: $ all BaseModel or $ all
        """
        arg = line.split()
        list_instances = []
        if len(arg) == 0 or (len(arg) > 0 and arg[0] == 'BaseModel'):

            list_obj = storage.all()
            for obj in list_obj.keys():
                my_new_model = BaseModel(**list_obj[obj])

                list_instances.append(str(my_new_model))
            print(list_instances)

        if len(arg) > 0 and arg[0] != 'BaseModel':
            print('** class doesn\'t exist **')

    def do_update(self, line):
        """
        Updates an instance based on the class name and id by adding or updating
        attribute (save the change into the JSON file). Ex: $ update BaseModel
        1234-1234-1234 email "*****@*****.**".
        Usage: update <class name> <id> <attribute name> "<attribute value>"
        A string argument with a space must be between double quote
        """
        if not line:
            print("** class name missing **")
            return
        args = line.split(" ")
        objects = storage.all()
        if args[0] in self.classes:
            if len(args) < 2:
                print("** instance id missing **")
                return
            key = args[0] + "." + args[1]
            if key not in objects:
                print("** no instance found **")
            else:
                obj = objects[key]
                base = ["id", "created_at", "updated_at"]
                if obj:
                    arg = line.split(" ")
                    if len(arg) < 3:
                        print("** attribute name mising **")
                    elif len(arg) < 4:
                        print("** value missing **")
                    elif arg[2] not in base:
                        obj[arg[2]] = arg[3]
                        # obj["updated_at"] = datetime.now()
                        storage.save()
        else:
            print("** class doesn't exist **")
Example #35
0
 def test_longitude_attr(self):
     """Test Place has attr longitude, and it's a float == 0.0"""
     place = Place()
     self.assertTrue(hasattr(place, "longitude"))
     self.assertEqual(type(place.longitude), float)
     self.assertEqual(place.longitude, 0.0)
    def test_class_name(self):
        """Tests if class is named correctly"""

        place_example = Place()
        self.assertEqual(place_example.__class__.__name__, "Place")