Skip to content

Commit

Permalink
Merge branch 'main' of github.com:brianbryank/AirBnB-clone
Browse files Browse the repository at this point in the history
Update repository
  • Loading branch information
mwongess committed Jan 30, 2022
2 parents 5ca710b + 01b55d7 commit dbcada7
Show file tree
Hide file tree
Showing 18 changed files with 523 additions and 43 deletions.
12 changes: 10 additions & 2 deletions models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
#!/usr/bin/python3
"""__init__ magic method for models directory"""
"""
__init__ modules
"""
from models.engine.file_storage import FileStorage

from .base_model import BaseModel
from .user import User
from .review import Review
from .city import City
from .amenity import Amenity
from .place import Place
from .state import State

storage = FileStorage()
storage.reload()
8 changes: 8 additions & 0 deletions models/amenity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/python
""" class Amenity"""
from models.base_model import BaseModel


class Amenity(BaseModel):
"""Representation of Amenity"""
name = ""
81 changes: 43 additions & 38 deletions models/base_model.py
Original file line number Diff line number Diff line change
@@ -1,51 +1,56 @@
#!/usr/bin/python3
"""Defines the BaseModel class."""
import models
from uuid import uuid4
"""
a base class for other classes to use from it
"""
from datetime import datetime
from uuid import uuid4
import models


class BaseModel:
"""Represents the BaseModel of the HBnB project."""
"""
Base Class of AirBnb Console
"""

def __init__(self, *args, **kwargs):
"""Initialize a new BaseModel.
Args:
*args (any): Unused.
**kwargs (dict): Key/value pairs of attributes.
"""
tform = "%Y-%m-%dT%H:%M:%S.%f"
self.id = str(uuid4())
self.created_at = datetime.today()
self.updated_at = datetime.today()
if len(kwargs) != 0:
for k, v in kwargs.items():
if k == "created_at" or k == "updated_at":
self.__dict__[k] = datetime.strptime(v, tform)
else:
self.__dict__[k] = v
else:
"""
Init of Object
"""
if len(kwargs) == 0:
self.id = str(uuid4())
self.created_at = datetime.now()
self.updated_at = self.created_at
models.storage.new(self)
models.storage.save()
else:
kwargs["created_at"] = datetime.strptime(kwargs["created_at"],
"%Y-%m-%dT%H:%M:%S.%f")
kwargs["updated_at"] = datetime.strptime(kwargs["updated_at"],
"%Y-%m-%dT%H:%M:%S.%f")
for key, val in kwargs.items():
if "__class__" not in key:
setattr(self, key, val)

def __str__(self):
"""
print the instance
"""
return "[{:s}] ({:s}) {}".format(self.__class__.__name__, self.id,
self.__dict__)

def save(self):
"""Update updated_at with the current datetime."""
self.updated_at = datetime.today()
"""
updates the public instance attribute
"""
self.updated_at = datetime.now()
models.storage.save()

def to_dict(self):
"""Return the dictionary of the BaseModel instance.
Includes the key/value pair __class__ representing
the class name of the object.
"""
rdict = self.__dict__.copy()
rdict["created_at"] = self.created_at.isoformat()
rdict["updated_at"] = self.updated_at.isoformat()
rdict["__class__"] = self.__class__.__name__
return rdict

def __str__(self):
"""Return the print/str representation of the BaseModel instance."""
clname = self.__class__.__name__
return "[{}] ({}) {}".format(clname, self.id, self.__dict__)
"""
returns a dictionary containing all keys/values
"""
temp = dict(self.__dict__)
temp['__class__'] = self.__class__.__name__
temp['updated_at'] = self.updated_at.strftime("%Y-%m-%dT%H:%M:%S.%f")
temp['created_at'] = self.created_at.strftime("%Y-%m-%dT%H:%M:%S.%f")
return temp
11 changes: 11 additions & 0 deletions models/city.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/python3
"""
class City that inherits from BaseModel
"""
from models.base_model import BaseModel


class City(BaseModel):
""" defining City class """
name = ""
state_id = ""
Empty file added models/engine/__init__.py
Empty file.
48 changes: 48 additions & 0 deletions models/engine/file_storage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/python3
"""
FileStorage that serializes and deserializes instances to a JSON file
"""
import json
import os.path
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.place import Place
from models.review import Review
from models.state import State
from models.amenity import Amenity


class FileStorage:
""" String representing a simple data structure in JSON format.
ex: '{ "12": { "numbers": [1, 2, 3], "name": "John" } }'
"""
__file_path = "file.json"
__objects = {}

def all(self):
""" returns the dictionary __objects """
return self.__objects

def new(self, obj):
"""
sets in __objects the obj with key <obj class name>.id
"""
dict_key = obj.__class__.__name__ + '.' + obj.id
self.__objects.update({dict_key: obj})

def save(self):
""" serializes __objects to the JSON file """
dict = {}
for key in self.__objects:
dict[key] = self.__objects[key].to_dict()
with open(self.__file_path, "w") as f:
json.dump(dict, f)

def reload(self):
""" deserializes the JSON file to __objects """
if os.path.isfile(self.__file_path):
with open(self.__file_path, "r") as f:
json_obj = json.load(f)
for key, val in json_obj.items():
self.__objects[key] = eval(val["__class__"])(**val)
22 changes: 22 additions & 0 deletions models/place.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/python3
"""
Place modules
"""
from models.base_model import BaseModel


class Place(BaseModel):
"""
Place Class inherit from base
"""
city_id = ""
user_id = ""
name = ""
description = ""
number_rooms = 0
number_bathrooms = 0
max_guest = 0
price_by_night = 0
latitude = 0.0
longitude = 0.0
amenity_ids = []
12 changes: 12 additions & 0 deletions models/review.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/python3
"""
class Review that inherits from BaseModel
"""
from models.base_model import BaseModel


class Review(BaseModel):
""" defining User class """
place_id = ""
user_id = ""
text = ""
10 changes: 10 additions & 0 deletions models/state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/python3
"""
class State that inherits from BaseModel
"""
from models.base_model import BaseModel


class State(BaseModel):
""" defining State class """
name = ""
13 changes: 13 additions & 0 deletions models/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/usr/bin/python3
"""
class User that inherits from BaseModel
"""
from models.base_model import BaseModel


class User(BaseModel):
""" defining User class """
email = ""
password = ""
first_name = ""
last_name = ""
46 changes: 46 additions & 0 deletions tests/test_models/test_amenity.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,49 @@
#!/usr/bin/python3
<<<<<<< HEAD
"""Amenity"""
import unittest
from models.base_model import BaseModel
from models.city import City
from models.place import Place
from models.amenity import Amenity
from models.state import State
from models.review import Review


class Testamenity(unittest.TestCase):
"""unit test"""
def test_class(self):
amen = Amenity()
self.assertEqual(amen.__class__.__name__, "Amenity")

def test_base(self):
amen = Amenity()
self.assertTrue(issubclass(amen.__class__, BaseModel))

def test_amenity(self):
"""Test attributes of Class Amenity"""
amenity = Amenity()
self.Assert true(hasattr(amenity, "name"))
self.assertEqual(amenity.name, "")

def test_dict_value(self):
"""
test dict values
"""
time_format = "%Y-%m-%dT%H:%M:%S.%f"
inst = Amenity()
dict_con = inst.to_dict()
self.assertEqual(dict_con["__class__"], "Amenity")
self.assertEqual(type(dict_con["created_at"]), str)
self.assertEqual(type(dict_con["updated_at"]), str)
self.assertEqual(
dict_con["created_at"],
inst.created_at.strftime(time_format)
)
self.assertEqual(
dict_con["updated_at"],
inst.updated_at.strftime(time_format))
=======
"""Test suite for Amenity class of the models.amenity module"""
import unittest

Expand All @@ -21,3 +66,4 @@ def test_attr_is_a_class_attr(self):
def test_class_attr(self):
self.assertIs(type(self.amenity.name), str)
self.assertFalse(bool(getattr(self.amenity, "name")))
>>>>>>> ab680e0da1b3fa8090fb95252d6db9d0c0e4ae7f
Loading

0 comments on commit dbcada7

Please sign in to comment.