diff --git a/0-setup_web_static.sh b/0-setup_web_static.sh
index 3b2de157983..5c406021205 100755
--- a/0-setup_web_static.sh
+++ b/0-setup_web_static.sh
@@ -1,12 +1,17 @@
#!/usr/bin/env bash
-# sets up the web servers for the deployment of web_static
-
-sudo apt-get -y update
-sudo apt-get -y upgrade
+# Bash scrip to set up web servers to deploy web_static
+sudo apt-get update
sudo apt-get -y install nginx
-sudo mkdir -p /data/web_static/releases/test /data/web_static/shared
-echo "This is a test" | sudo tee /data/web_static/releases/test/index.html
+sudo mkdir -p /data/web_static/shared/
+sudo mkdir -p /data/web_static/releases/test/
+sudo echo "
+
+
+
+ Holberton School
+
+" | sudo tee /data/web_static/releases/test/index.html
sudo ln -sf /data/web_static/releases/test/ /data/web_static/current
-sudo chown -hR ubuntu:ubuntu /data/
-sudo sed -i '38i\\tlocation /hbnb_static/ {\n\t\talias /data/web_static/current/;\n\t}\n' /etc/nginx/sites-available/default
-sudo service nginx start
+sudo chown -R ubuntu:ubuntu /data
+sudo sed -i '53i \\tlocation \/hbnb_static {\n\t\t alias /data/web_static/current;\n\t}' /etc/nginx/sites-available/default
+sudo service nginx restart
diff --git a/1-pack_web_static.py b/1-pack_web_static.py
old mode 100644
new mode 100755
index f08a8aea659..89152081bcf
--- a/1-pack_web_static.py
+++ b/1-pack_web_static.py
@@ -1,22 +1,21 @@
#!/usr/bin/python3
"""
-Fabric script that generates a tgz archive from the contents of the web_static
-folder of the AirBnB Clone repo
+ Fabric script that generates tgz archive from contents of web_static
"""
-
-from datetime import datetime
from fabric.api import local
-from os.path import isdir
+from datetime import datetime
def do_pack():
- """generates a tgz archive"""
+ """
+ generates a .tgz archine from contents of web_static
+ """
+ time = datetime.utcnow().strftime('%Y%m%d%H%M%S')
+ file_name = "versions/web_static_{}.tgz".format(time)
try:
- date = datetime.now().strftime("%Y%m%d%H%M%S")
- if isdir("versions") is False:
- local("mkdir versions")
- file_name = "versions/web_static_{}.tgz".format(date)
- local("tar -cvzf {} web_static".format(file_name))
+ local("mkdir -p ./versions")
+ local("tar --create --verbose -z --file={} ./web_static"
+ .format(file_name))
return file_name
except:
return None
diff --git a/2-do_deploy_web_static.py b/2-do_deploy_web_static.py
old mode 100644
new mode 100755
index aa5ab7852c6..8abddb14eec
--- a/2-do_deploy_web_static.py
+++ b/2-do_deploy_web_static.py
@@ -1,30 +1,35 @@
#!/usr/bin/python3
"""
-Fabric script based on the file 1-pack_web_static.py that distributes an
-archive to the web servers
+ Fabric script that distributes an archive to my web servers
"""
-
-from fabric.api import put, run, env
-from os.path import exists
-env.hosts = ['142.44.167.228', '144.217.246.195']
+from fabric.api import *
+from fabric.operations import run, put, sudo
+import os
+env.hosts = ['66.70.184.249', '54.210.138.75']
def do_deploy(archive_path):
- """distributes an archive to the web servers"""
- if exists(archive_path) is False:
+ """
+ using fabric to distribute archive
+ """
+ if os.path.isfile(archive_path) is False:
return False
try:
- file_n = archive_path.split("/")[-1]
- no_ext = file_n.split(".")[0]
- path = "/data/web_static/releases/"
- put(archive_path, '/tmp/')
- run('mkdir -p {}{}/'.format(path, no_ext))
- run('tar -xzf /tmp/{} -C {}{}/'.format(file_n, path, no_ext))
- run('rm /tmp/{}'.format(file_n))
- run('mv {0}{1}/web_static/* {0}{1}/'.format(path, no_ext))
- run('rm -rf {}{}/web_static'.format(path, no_ext))
- run('rm -rf /data/web_static/current')
- run('ln -s {}{}/ /data/web_static/current'.format(path, no_ext))
+ archive = archive_path.split("/")[-1]
+ path = "/data/web_static/releases"
+ put("{}".format(archive_path), "/tmp/{}".format(archive))
+ folder = archive.split(".")
+ run("mkdir -p {}/{}/".format(path, folder[0]))
+ new_archive = '.'.join(folder)
+ run("tar -xzf /tmp/{} -C {}/{}/"
+ .format(new_archive, path, folder[0]))
+ run("rm /tmp/{}".format(archive))
+ run("mv {}/{}/web_static/* {}/{}/"
+ .format(path, folder[0], path, folder[0]))
+ run("rm -rf {}/{}/web_static".format(path, folder[0]))
+ run("rm -rf /data/web_static/current")
+ run("ln -sf {}/{} /data/web_static/current"
+ .format(path, folder[0]))
return True
except:
return False
diff --git a/3-deploy_web_static.py b/3-deploy_web_static.py
old mode 100644
new mode 100755
index f7e7e254b5e..5350712c67b
--- a/3-deploy_web_static.py
+++ b/3-deploy_web_static.py
@@ -1,52 +1,66 @@
#!/usr/bin/python3
"""
-Fabric script based on the file 2-do_deploy_web_static.py that creates and
-distributes an archive to the web servers
+ Fabric script that creates and distributes an archive
+ on my web servers, using deploy function
"""
-
-from fabric.api import env, local, put, run
+from fabric.api import *
+from fabric.operations import run, put, sudo, local
from datetime import datetime
-from os.path import exists, isdir
-env.hosts = ['142.44.167.228', '144.217.246.195']
+import os
+
+env.hosts = ['66.70.184.249', '54.210.138.75']
+created_path = None
def do_pack():
- """generates a tgz archive"""
+ """
+ generates a .tgz archine from contents of web_static
+ """
+ time = datetime.utcnow().strftime('%Y%m%d%H%M%S')
+ file_name = "versions/web_static_{}.tgz".format(time)
try:
- date = datetime.now().strftime("%Y%m%d%H%M%S")
- if isdir("versions") is False:
- local("mkdir versions")
- file_name = "versions/web_static_{}.tgz".format(date)
- local("tar -cvzf {} web_static".format(file_name))
+ local("mkdir -p ./versions")
+ local("tar --create --verbose -z --file={} ./web_static"
+ .format(file_name))
return file_name
except:
return None
def do_deploy(archive_path):
- """distributes an archive to the web servers"""
- if exists(archive_path) is False:
+ """
+ using fabric to distribute archive
+ """
+ if os.path.isfile(archive_path) is False:
return False
try:
- file_n = archive_path.split("/")[-1]
- no_ext = file_n.split(".")[0]
- path = "/data/web_static/releases/"
- put(archive_path, '/tmp/')
- run('mkdir -p {}{}/'.format(path, no_ext))
- run('tar -xzf /tmp/{} -C {}{}/'.format(file_n, path, no_ext))
- run('rm /tmp/{}'.format(file_n))
- run('mv {0}{1}/web_static/* {0}{1}/'.format(path, no_ext))
- run('rm -rf {}{}/web_static'.format(path, no_ext))
- run('rm -rf /data/web_static/current')
- run('ln -s {}{}/ /data/web_static/current'.format(path, no_ext))
+ archive = archive_path.split("/")[-1]
+ path = "/data/web_static/releases"
+ put("{}".format(archive_path), "/tmp/{}".format(archive))
+ folder = archive.split(".")
+ run("mkdir -p {}/{}/".format(path, folder[0]))
+ new_archive = '.'.join(folder)
+ run("tar -xzf /tmp/{} -C {}/{}/"
+ .format(new_archive, path, folder[0]))
+ run("rm /tmp/{}".format(archive))
+ run("mv {}/{}/web_static/* {}/{}/"
+ .format(path, folder[0], path, folder[0]))
+ run("rm -rf {}/{}/web_static".format(path, folder[0]))
+ run("rm -rf /data/web_static/current")
+ run("ln -sf {}/{} /data/web_static/current"
+ .format(path, folder[0]))
return True
except:
return False
def deploy():
- """creates and distributes an archive to the web servers"""
- archive_path = do_pack()
- if archive_path is None:
+ """
+ deploy function that creates/distributes an archive
+ """
+ global created_path
+ if created_path is None:
+ created_path = do_pack()
+ if created_path is None:
return False
- return do_deploy(archive_path)
+ return do_deploy(created_path)
diff --git a/AUTHORS b/AUTHORS
index 64b26acdc14..343fb8c0abd 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,6 +1,4 @@
# This file lists all individuals having contributed content to the repository.
-
-Jennifer Huang <133@holbertonschool.com>
-Alexa Orrico <210@holbertonschool.com>
-Joann Vuong <130@holbertonschool.com>
+Laila Mohamed
+Walid Mehelba
diff --git a/README.md b/README.md
index f1d72de6355..b5d0cd0e79b 100644
--- a/README.md
+++ b/README.md
@@ -1,162 +1 @@
-# AirBnB Clone - The Console
-The console is the first segment of the AirBnB project at Holberton School that will collectively cover fundamental concepts of higher level programming. The goal of AirBnB project is to eventually deploy our server a simple copy of the AirBnB Website(HBnB). A command interpreter is created in this segment to manage objects for the AirBnB(HBnB) website.
-
-#### Functionalities of this command interpreter:
-* Create a new object (ex: a new User or a new Place)
-* Retrieve an object from a file, a database etc...
-* Do operations on objects (count, compute stats, etc...)
-* Update attributes of an object
-* Destroy an object
-
-## Table of Content
-* [Environment](#environment)
-* [Installation](#installation)
-* [File Descriptions](#file-descriptions)
-* [Usage](#usage)
-* [Examples of use](#examples-of-use)
-* [Bugs](#bugs)
-* [Authors](#authors)
-* [License](#license)
-
-## Environment
-This project is interpreted/tested on Ubuntu 14.04 LTS using python3 (version 3.4.3)
-
-## Installation
-* Clone this repository: `git clone "https://github.com/alexaorrico/AirBnB_clone.git"`
-* Access AirBnb directory: `cd AirBnB_clone`
-* Run hbnb(interactively): `./console` and enter command
-* Run hbnb(non-interactively): `echo "" | ./console.py`
-
-## File Descriptions
-[console.py](console.py) - the console contains the entry point of the command interpreter.
-List of commands this console current supports:
-* `EOF` - exits console
-* `quit` - exits console
-* `` - overwrites default emptyline method and does nothing
-* `create` - Creates a new instance of`BaseModel`, saves it (to the JSON file) and prints the id
-* `destroy` - Deletes an instance based on the class name and id (save the change into the JSON file).
-* `show` - Prints the string representation of an instance based on the class name and id.
-* `all` - Prints all string representation of all instances based or not on the class name.
-* `update` - Updates an instance based on the class name and id by adding or updating attribute (save the change into the JSON file).
-
-#### `models/` directory contains classes used for this project:
-[base_model.py](/models/base_model.py) - The BaseModel class from which future classes will be derived
-* `def __init__(self, *args, **kwargs)` - Initialization of the base model
-* `def __str__(self)` - String representation of the BaseModel class
-* `def save(self)` - Updates the attribute `updated_at` with the current datetime
-* `def to_dict(self)` - returns a dictionary containing all keys/values of the instance
-
-Classes inherited from Base Model:
-* [amenity.py](/models/amenity.py)
-* [city.py](/models/city.py)
-* [place.py](/models/place.py)
-* [review.py](/models/review.py)
-* [state.py](/models/state.py)
-* [user.py](/models/user.py)
-
-#### `/models/engine` directory contains File Storage class that handles JASON serialization and deserialization :
-[file_storage.py](/models/engine/file_storage.py) - serializes instances to a JSON file & deserializes back to instances
-* `def all(self)` - returns the dictionary __objects
-* `def new(self, obj)` - sets in __objects the obj with key .id
-* `def save(self)` - serializes __objects to the JSON file (path: __file_path)
-* ` def reload(self)` - deserializes the JSON file to __objects
-
-#### `/tests` directory contains all unit test cases for this project:
-[/test_models/test_base_model.py](/tests/test_models/test_base_model.py) - Contains the TestBaseModel and TestBaseModelDocs classes
-TestBaseModelDocs class:
-* `def setUpClass(cls)`- Set up for the doc tests
-* `def test_pep8_conformance_base_model(self)` - Test that models/base_model.py conforms to PEP8
-* `def test_pep8_conformance_test_base_model(self)` - Test that tests/test_models/test_base_model.py conforms to PEP8
-* `def test_bm_module_docstring(self)` - Test for the base_model.py module docstring
-* `def test_bm_class_docstring(self)` - Test for the BaseModel class docstring
-* `def test_bm_func_docstrings(self)` - Test for the presence of docstrings in BaseModel methods
-
-TestBaseModel class:
-* `def test_is_base_model(self)` - Test that the instatiation of a BaseModel works
-* `def test_created_at_instantiation(self)` - Test created_at is a pub. instance attribute of type datetime
-* `def test_updated_at_instantiation(self)` - Test updated_at is a pub. instance attribute of type datetime
-* `def test_diff_datetime_objs(self)` - Test that two BaseModel instances have different datetime objects
-
-[/test_models/test_amenity.py](/tests/test_models/test_amenity.py) - Contains the TestAmenityDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_amenity(self)` - Test that models/amenity.py conforms to PEP8
-* `def test_pep8_conformance_test_amenity(self)` - Test that tests/test_models/test_amenity.py conforms to PEP8
-* `def test_amenity_module_docstring(self)` - Test for the amenity.py module docstring
-* `def test_amenity_class_docstring(self)` - Test for the Amenity class docstring
-
-[/test_models/test_city.py](/tests/test_models/test_city.py) - Contains the TestCityDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_city(self)` - Test that models/city.py conforms to PEP8
-* `def test_pep8_conformance_test_city(self)` - Test that tests/test_models/test_city.py conforms to PEP8
-* `def test_city_module_docstring(self)` - Test for the city.py module docstring
-* `def test_city_class_docstring(self)` - Test for the City class docstring
-
-[/test_models/test_file_storage.py](/tests/test_models/test_file_storage.py) - Contains the TestFileStorageDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_file_storage(self)` - Test that models/file_storage.py conforms to PEP8
-* `def test_pep8_conformance_test_file_storage(self)` - Test that tests/test_models/test_file_storage.py conforms to PEP8
-* `def test_file_storage_module_docstring(self)` - Test for the file_storage.py module docstring
-* `def test_file_storage_class_docstring(self)` - Test for the FileStorage class docstring
-
-[/test_models/test_place.py](/tests/test_models/test_place.py) - Contains the TestPlaceDoc class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_place(self)` - Test that models/place.py conforms to PEP8.
-* `def test_pep8_conformance_test_place(self)` - Test that tests/test_models/test_place.py conforms to PEP8.
-* `def test_place_module_docstring(self)` - Test for the place.py module docstring
-* `def test_place_class_docstring(self)` - Test for the Place class docstring
-
-[/test_models/test_review.py](/tests/test_models/test_review.py) - Contains the TestReviewDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_review(self)` - Test that models/review.py conforms to PEP8
-* `def test_pep8_conformance_test_review(self)` - Test that tests/test_models/test_review.py conforms to PEP8
-* `def test_review_module_docstring(self)` - Test for the review.py module docstring
-* `def test_review_class_docstring(self)` - Test for the Review class docstring
-
-[/test_models/state.py](/tests/test_models/test_state.py) - Contains the TestStateDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_state(self)` - Test that models/state.py conforms to PEP8
-* `def test_pep8_conformance_test_state(self)` - Test that tests/test_models/test_state.py conforms to PEP8
-* `def test_state_module_docstring(self)` - Test for the state.py module docstring
-* `def test_state_class_docstring(self)` - Test for the State class docstring
-
-[/test_models/user.py](/tests/test_models/test_user.py) - Contains the TestUserDocs class:
-* `def setUpClass(cls)` - Set up for the doc tests
-* `def test_pep8_conformance_user(self)` - Test that models/user.py conforms to PEP8
-* `def test_pep8_conformance_test_user(self)` - Test that tests/test_models/test_user.py conforms to PEP8
-* `def test_user_module_docstring(self)` - Test for the user.py module docstring
-* `def test_user_class_docstring(self)` - Test for the User class docstring
-
-
-## Examples of use
-```
-vagrantAirBnB_clone$./console.py
-(hbnb) help
-
-Documented commands (type help ):
-========================================
-EOF all create destroy help quit show update
-
-(hbnb) all MyModel
-** class doesn't exist **
-(hbnb) create BaseModel
-7da56403-cc45-4f1c-ad32-bfafeb2bb050
-(hbnb) all BaseModel
-[[BaseModel] (7da56403-cc45-4f1c-ad32-bfafeb2bb050) {'updated_at': datetime.datetime(2017, 9, 28, 9, 50, 46, 772167), 'id': '7da56403-cc45-4f1c-ad32-bfafeb2bb050', 'created_at': datetime.datetime(2017, 9, 28, 9, 50, 46, 772123)}]
-(hbnb) show BaseModel 7da56403-cc45-4f1c-ad32-bfafeb2bb050
-[BaseModel] (7da56403-cc45-4f1c-ad32-bfafeb2bb050) {'updated_at': datetime.datetime(2017, 9, 28, 9, 50, 46, 772167), 'id': '7da56403-cc45-4f1c-ad32-bfafeb2bb050', 'created_at': datetime.datetime(2017, 9, 28, 9, 50, 46, 772123)}
-(hbnb) destroy BaseModel 7da56403-cc45-4f1c-ad32-bfafeb2bb050
-(hbnb) show BaseModel 7da56403-cc45-4f1c-ad32-bfafeb2bb050
-** no instance found **
-(hbnb) quit
-```
-
-## Bugs
-No known bugs at this time.
-
-## Authors
-Alexa Orrico - [Github](https://github.com/alexaorrico) / [Twitter](https://twitter.com/alexa_orrico)
-Jennifer Huang - [Github](https://github.com/jhuang10123) / [Twitter](https://twitter.com/earthtojhuang)
-
-Second part of Airbnb: Joann Vuong
-## License
-Public Domain. No copy write protection.
+0x06. AirBnB clone - Web dynamic
diff --git a/__pycache__/console.cpython-312.pyc b/__pycache__/console.cpython-312.pyc
new file mode 100644
index 00000000000..31334b08ed9
Binary files /dev/null and b/__pycache__/console.cpython-312.pyc differ
diff --git a/__pycache__/console.cpython-313.pyc b/__pycache__/console.cpython-313.pyc
new file mode 100644
index 00000000000..d42fbd80611
Binary files /dev/null and b/__pycache__/console.cpython-313.pyc differ
diff --git a/__pycache__/console.cpython-38.pyc b/__pycache__/console.cpython-38.pyc
new file mode 100644
index 00000000000..ee2df66b308
Binary files /dev/null and b/__pycache__/console.cpython-38.pyc differ
diff --git a/api/v1/__init__.py b/api/v1/__init__.py
new file mode 100755
index 00000000000..e69de29bb2d
diff --git a/api/v1/__pycache__/__init__.cpython-38.pyc b/api/v1/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..bb5fd6287d1
Binary files /dev/null and b/api/v1/__pycache__/__init__.cpython-38.pyc differ
diff --git a/api/v1/__pycache__/app.cpython-38.pyc b/api/v1/__pycache__/app.cpython-38.pyc
new file mode 100644
index 00000000000..045064a7c13
Binary files /dev/null and b/api/v1/__pycache__/app.cpython-38.pyc differ
diff --git a/api/v1/app.py b/api/v1/app.py
new file mode 100755
index 00000000000..aaa27c6b333
--- /dev/null
+++ b/api/v1/app.py
@@ -0,0 +1,45 @@
+#!/usr/bin/python3
+"""
+app
+"""
+
+from flask import Flask, jsonify
+from flask_cors import CORS
+from os import getenv
+
+from api.v1.views import app_views
+from models import storage
+
+
+app = Flask(__name__)
+
+CORS(app, resources={r"/*": {"origins": "0.0.0.0"}})
+
+app.register_blueprint(app_views)
+
+
+@app.teardown_appcontext
+def teardown(exception):
+ """
+ teardown function
+ """
+ storage.close()
+
+
+@app.errorhandler(404)
+def handle_404(exception):
+ """
+ handles 404 error
+ :return: returns 404 json
+ """
+ data = {
+ "error": "Not found"
+ }
+
+ resp = jsonify(data)
+ resp.status_code = 404
+
+ return(resp)
+
+if __name__ == "__main__":
+ app.run(getenv("HBNB_API_HOST"), getenv("HBNB_API_PORT"))
diff --git a/api/v1/views/__init__.py b/api/v1/views/__init__.py
new file mode 100755
index 00000000000..12257323b92
--- /dev/null
+++ b/api/v1/views/__init__.py
@@ -0,0 +1,17 @@
+#!/usr/bin/python3
+"""
+views
+"""
+
+from flask import Blueprint
+
+app_views = Blueprint('/api/v1', __name__, url_prefix="/api/v1")
+
+from api.v1.views.index import *
+from api.v1.views.states import *
+from api.v1.views.amenities import *
+from api.v1.views.cities import *
+from api.v1.views.places import *
+from api.v1.views.places_reviews import *
+from api.v1.views.users import *
+from api.v1.views.places_amenities import *
diff --git a/api/v1/views/amenities.py b/api/v1/views/amenities.py
new file mode 100755
index 00000000000..b528fd78f2e
--- /dev/null
+++ b/api/v1/views/amenities.py
@@ -0,0 +1,99 @@
+#!/usr/bin/python3
+"""
+route for handling Amenity objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.amenity import Amenity
+
+
+@app_views.route("/amenities", methods=["GET"], strict_slashes=False)
+def amenity_get_all():
+ """
+ retrieves all Amenity objects
+ :return: json of all states
+ """
+ am_list = []
+ am_obj = storage.all("Amenity")
+ for obj in am_obj.values():
+ am_list.append(obj.to_json())
+
+ return jsonify(am_list)
+
+
+@app_views.route("/amenities", methods=["POST"], strict_slashes=False)
+def amenity_create():
+ """
+ create amenity route
+ :return: newly created amenity obj
+ """
+ am_json = request.get_json(silent=True)
+ if am_json is None:
+ abort(400, 'Not a JSON')
+ if "name" not in am_json:
+ abort(400, 'Missing name')
+
+ new_am = Amenity(**am_json)
+ new_am.save()
+ resp = jsonify(new_am.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/amenities/", methods=["GET"],
+ strict_slashes=False)
+def amenity_by_id(amenity_id):
+ """
+ gets a specific Amenity object by ID
+ :param amenity_id: amenity object id
+ :return: state obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("Amenity", str(amenity_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/amenities/", methods=["PUT"],
+ strict_slashes=False)
+def amenity_put(amenity_id):
+ """
+ updates specific Amenity object by ID
+ :param amenity_id: amenity object ID
+ :return: amenity object and 200 on success, or 400 or 404 on failure
+ """
+ am_json = request.get_json(silent=True)
+ if am_json is None:
+ abort(400, 'Not a JSON')
+ fetched_obj = storage.get("Amenity", str(amenity_id))
+ if fetched_obj is None:
+ abort(404)
+ for key, val in am_json.items():
+ if key not in ["id", "created_at", "updated_at"]:
+ setattr(fetched_obj, key, val)
+ fetched_obj.save()
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/amenities/", methods=["DELETE"],
+ strict_slashes=False)
+def amenity_delete_by_id(amenity_id):
+ """
+ deletes Amenity by id
+ :param amenity_id: Amenity object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("Amenity", str(amenity_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/api/v1/views/cities.py b/api/v1/views/cities.py
new file mode 100755
index 00000000000..d2746edc4b3
--- /dev/null
+++ b/api/v1/views/cities.py
@@ -0,0 +1,110 @@
+#!/usr/bin/python3
+"""
+route for handling State objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.city import City
+
+
+@app_views.route("/states//cities", methods=["GET"],
+ strict_slashes=False)
+def city_by_state(state_id):
+ """
+ retrieves all City objects from a specific state
+ :return: json of all cities in a state or 404 on error
+ """
+ city_list = []
+ state_obj = storage.get("State", state_id)
+
+ if state_obj is None:
+ abort(404)
+ for obj in state_obj.cities:
+ city_list.append(obj.to_json())
+
+ return jsonify(city_list)
+
+
+@app_views.route("/states//cities", methods=["POST"],
+ strict_slashes=False)
+def city_create(state_id):
+ """
+ create city route
+ param: state_id - state id
+ :return: newly created city obj
+ """
+ city_json = request.get_json(silent=True)
+ if city_json is None:
+ abort(400, 'Not a JSON')
+
+ if not storage.get("State", str(state_id)):
+ abort(404)
+
+ if "name" not in city_json:
+ abort(400, 'Missing name')
+
+ city_json["state_id"] = state_id
+
+ new_city = City(**city_json)
+ new_city.save()
+ resp = jsonify(new_city.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/cities/", methods=["GET"],
+ strict_slashes=False)
+def city_by_id(city_id):
+ """
+ gets a specific City object by ID
+ :param city_id: city object id
+ :return: city obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("City", str(city_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("cities/", methods=["PUT"], strict_slashes=False)
+def city_put(city_id):
+ """
+ updates specific City object by ID
+ :param city_id: city object ID
+ :return: city object and 200 on success, or 400 or 404 on failure
+ """
+ city_json = request.get_json(silent=True)
+ if city_json is None:
+ abort(400, 'Not a JSON')
+ fetched_obj = storage.get("City", str(city_id))
+ if fetched_obj is None:
+ abort(404)
+ for key, val in city_json.items():
+ if key not in ["id", "created_at", "updated_at", "state_id"]:
+ setattr(fetched_obj, key, val)
+ fetched_obj.save()
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/cities/", methods=["DELETE"],
+ strict_slashes=False)
+def city_delete_by_id(city_id):
+ """
+ deletes City by id
+ :param city_id: city object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("City", str(city_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/api/v1/views/index.py b/api/v1/views/index.py
new file mode 100755
index 00000000000..47895d57c67
--- /dev/null
+++ b/api/v1/views/index.py
@@ -0,0 +1,46 @@
+#!/usr/bin/python3
+"""
+index
+"""
+
+from flask import jsonify
+from api.v1.views import app_views
+
+from models import storage
+
+
+@app_views.route("/status", methods=['GET'], strict_slashes=False)
+def status():
+ """
+ status route
+ :return: response with json
+ """
+ data = {
+ "status": "OK"
+ }
+
+ resp = jsonify(data)
+ resp.status_code = 200
+
+ return resp
+
+
+@app_views.route("/stats", methods=['GET'], strict_slashes=False)
+def stats():
+ """
+ stats of all objs route
+ :return: json of all objs
+ """
+ data = {
+ "amenities": storage.count("Amenity"),
+ "cities": storage.count("City"),
+ "places": storage.count("Place"),
+ "reviews": storage.count("Review"),
+ "states": storage.count("State"),
+ "users": storage.count("User"),
+ }
+
+ resp = jsonify(data)
+ resp.status_code = 200
+
+ return resp
diff --git a/api/v1/views/places.py b/api/v1/views/places.py
new file mode 100644
index 00000000000..3ec769721a5
--- /dev/null
+++ b/api/v1/views/places.py
@@ -0,0 +1,115 @@
+#!/usr/bin/python3
+"""
+route for handling Place objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.place import Place
+
+
+@app_views.route("/cities//places", methods=["GET"],
+ strict_slashes=False)
+def places_by_city(city_id):
+ """
+ retrieves all Place objects by city
+ :return: json of all Places
+ """
+ place_list = []
+ city_obj = storage.get("City", str(city_id))
+ for obj in city_obj.places:
+ place_list.append(obj.to_json())
+
+ return jsonify(place_list)
+
+
+@app_views.route("/cities//places", methods=["POST"],
+ strict_slashes=False)
+def place_create(city_id):
+ """
+ create place route
+ :return: newly created Place obj
+ """
+ place_json = request.get_json(silent=True)
+ if place_json is None:
+ abort(400, 'Not a JSON')
+ if not storage.get("User", place_json["user_id"]):
+ abort(404)
+ if not storage.get("City", city_id):
+ abort(404)
+ if "user_id" not in place_json:
+ abort(400, 'Missing user_id')
+ if "name" not in place_json:
+ abort(400, 'Missing name')
+
+ place_json["city_id"] = city_id
+
+ new_place = Place(**place_json)
+ new_place.save()
+ resp = jsonify(new_place.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/places/", methods=["GET"],
+ strict_slashes=False)
+def place_by_id(place_id):
+ """
+ gets a specific Place object by ID
+ :param place_id: place object id
+ :return: place obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("Place", str(place_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/places/", methods=["PUT"],
+ strict_slashes=False)
+def place_put(place_id):
+ """
+ updates specific Place object by ID
+ :param place_id: Place object ID
+ :return: Place object and 200 on success, or 400 or 404 on failure
+ """
+ place_json = request.get_json(silent=True)
+
+ if place_json is None:
+ abort(400, 'Not a JSON')
+
+ fetched_obj = storage.get("Place", str(place_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ for key, val in place_json.items():
+ if key not in ["id", "created_at", "updated_at", "user_id", "city_id"]:
+ setattr(fetched_obj, key, val)
+
+ fetched_obj.save()
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/places/", methods=["DELETE"],
+ strict_slashes=False)
+def place_delete_by_id(place_id):
+ """
+ deletes Place by id
+ :param place_id: Place object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("Place", str(place_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/api/v1/views/places_amenities.py b/api/v1/views/places_amenities.py
new file mode 100755
index 00000000000..becf8b61f47
--- /dev/null
+++ b/api/v1/views/places_amenities.py
@@ -0,0 +1,105 @@
+#!/usr/bin/python3
+"""
+route for handling place and amenities linking
+"""
+from flask import jsonify, abort
+from os import getenv
+
+from api.v1.views import app_views, storage
+
+
+@app_views.route("/places//amenities",
+ methods=["GET"],
+ strict_slashes=False)
+def amenity_by_place(place_id):
+ """
+ get all amenities of a place
+ :param place_id: amenity id
+ :return: all amenities
+ """
+ fetched_obj = storage.get("Place", str(place_id))
+
+ all_amenities = []
+
+ if fetched_obj is None:
+ abort(404)
+
+ for obj in fetched_obj.amenities:
+ all_amenities.append(obj.to_json())
+
+ return jsonify(all_amenities)
+
+
+@app_views.route("/places//amenities/",
+ methods=["DELETE"],
+ strict_slashes=False)
+def unlink_amenity_from_place(place_id, amenity_id):
+ """
+ unlinks an amenity in a place
+ :param place_id: place id
+ :param amenity_id: amenity id
+ :return: empty dict or error
+ """
+ if not storage.get("Place", str(place_id)):
+ abort(404)
+ if not storage.get("Amenity", str(amenity_id)):
+ abort(404)
+
+ fetched_obj = storage.get("Place", place_id)
+ found = 0
+
+ for obj in fetched_obj.amenities:
+ if str(obj.id) == amenity_id:
+ if getenv("HBNB_TYPE_STORAGE") == "db":
+ fetched_obj.amenities.remove(obj)
+ else:
+ fetched_obj.amenity_ids.remove(obj.id)
+ fetched_obj.save()
+ found = 1
+ break
+
+ if found == 0:
+ abort(404)
+ else:
+ resp = jsonify({})
+ resp.status_code = 201
+ return resp
+
+
+@app_views.route("/places//amenities/",
+ methods=["POST"],
+ strict_slashes=False)
+def link_amenity_to_place(place_id, amenity_id):
+ """
+ links a amenity with a place
+ :param place_id: place id
+ :param amenity_id: amenity id
+ :return: return Amenity obj added or error
+ """
+
+ fetched_obj = storage.get("Place", str(place_id))
+ amenity_obj = storage.get("Amenity", str(amenity_id))
+ found_amenity = None
+
+ if not fetched_obj or not amenity_obj:
+ abort(404)
+
+ for obj in fetched_obj.amenities:
+ if str(obj.id) == amenity_id:
+ found_amenity = obj
+ break
+
+ if found_amenity is not None:
+ return jsonify(found_amenity.to_json())
+
+ if getenv("HBNB_TYPE_STORAGE") == "db":
+ fetched_obj.amenities.append(amenity_obj)
+ else:
+ fetched_obj.amenities = amenity_obj
+
+ fetched_obj.save()
+
+ resp = jsonify(amenity_obj.to_json())
+ resp.status_code = 201
+
+ return resp
diff --git a/api/v1/views/places_reviews.py b/api/v1/views/places_reviews.py
new file mode 100755
index 00000000000..41f110053be
--- /dev/null
+++ b/api/v1/views/places_reviews.py
@@ -0,0 +1,120 @@
+#!/usr/bin/python3
+"""
+route for handling Review objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.review import Review
+
+
+@app_views.route("/places//reviews", methods=["GET"],
+ strict_slashes=False)
+def reviews_by_place(place_id):
+ """
+ retrieves all Review objects by place
+ :return: json of all reviews
+ """
+ review_list = []
+ place_obj = storage.get("Place", str(place_id))
+
+ if place_obj is None:
+ abort(404)
+
+ for obj in place_obj.reviews:
+ review_list.append(obj.to_json())
+
+ return jsonify(review_list)
+
+
+@app_views.route("/places//reviews", methods=["POST"],
+ strict_slashes=False)
+def review_create(place_id):
+ """
+ create REview route
+ :return: newly created Review obj
+ """
+ review_json = request.get_json(silent=True)
+ if review_json is None:
+ abort(400, 'Not a JSON')
+ if not storage.get("Place", place_id):
+ abort(404)
+ if not storage.get("User", review_json["user_id"]):
+ abort(404)
+ if "user_id" not in review_json:
+ abort(400, 'Missing user_id')
+ if "text" not in review_json:
+ abort(400, 'Missing text')
+
+ review_json["place_id"] = place_id
+
+ new_review = Review(**review_json)
+ new_review.save()
+ resp = jsonify(new_review.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/reviews/", methods=["GET"],
+ strict_slashes=False)
+def review_by_id(review_id):
+ """
+ gets a specific Review object by ID
+ :param review_id: place object id
+ :return: review obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("Review", str(review_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/reviews/", methods=["PUT"],
+ strict_slashes=False)
+def review_put(review_id):
+ """
+ updates specific Review object by ID
+ :param review_id: Review object ID
+ :return: Review object and 200 on success, or 400 or 404 on failure
+ """
+ place_json = request.get_json(silent=True)
+
+ if place_json is None:
+ abort(400, 'Not a JSON')
+
+ fetched_obj = storage.get("Review", str(review_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ for key, val in place_json.items():
+ if key not in ["id", "created_at", "updated_at", "user_id",
+ "place_id"]:
+ setattr(fetched_obj, key, val)
+
+ fetched_obj.save()
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/reviews/", methods=["DELETE"],
+ strict_slashes=False)
+def review_delete_by_id(review_id):
+ """
+ deletes Review by id
+ :param : Review object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("Review", str(review_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/api/v1/views/states.py b/api/v1/views/states.py
new file mode 100755
index 00000000000..3a7d68b2bbd
--- /dev/null
+++ b/api/v1/views/states.py
@@ -0,0 +1,97 @@
+#!/usr/bin/python3
+"""
+route for handling State objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.state import State
+
+
+@app_views.route("/states", methods=["GET"], strict_slashes=False)
+def state_get_all():
+ """
+ retrieves all State objects
+ :return: json of all states
+ """
+ state_list = []
+ state_obj = storage.all("State")
+ for obj in state_obj.values():
+ state_list.append(obj.to_json())
+
+ return jsonify(state_list)
+
+
+@app_views.route("/states", methods=["POST"], strict_slashes=False)
+def state_create():
+ """
+ create state route
+ :return: newly created state obj
+ """
+ state_json = request.get_json(silent=True)
+ if state_json is None:
+ abort(400, 'Not a JSON')
+ if "name" not in state_json:
+ abort(400, 'Missing name')
+
+ new_state = State(**state_json)
+ new_state.save()
+ resp = jsonify(new_state.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/states/", methods=["GET"], strict_slashes=False)
+def state_by_id(state_id):
+ """
+ gets a specific State object by ID
+ :param state_id: state object id
+ :return: state obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("State", str(state_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/states/", methods=["PUT"], strict_slashes=False)
+def state_put(state_id):
+ """
+ updates specific State object by ID
+ :param state_id: state object ID
+ :return: state object and 200 on success, or 400 or 404 on failure
+ """
+ state_json = request.get_json(silent=True)
+ if state_json is None:
+ abort(400, 'Not a JSON')
+ fetched_obj = storage.get("State", str(state_id))
+ if fetched_obj is None:
+ abort(404)
+ for key, val in state_json.items():
+ if key not in ["id", "created_at", "updated_at"]:
+ setattr(fetched_obj, key, val)
+ fetched_obj.save()
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/states/", methods=["DELETE"],
+ strict_slashes=False)
+def state_delete_by_id(state_id):
+ """
+ deletes State by id
+ :param state_id: state object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("State", str(state_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/api/v1/views/users.py b/api/v1/views/users.py
new file mode 100755
index 00000000000..dcdea9975e0
--- /dev/null
+++ b/api/v1/views/users.py
@@ -0,0 +1,104 @@
+#!/usr/bin/python3
+"""
+route for handling User objects and operations
+"""
+from flask import jsonify, abort, request
+from api.v1.views import app_views, storage
+from models.user import User
+
+
+@app_views.route("/users", methods=["GET"], strict_slashes=False)
+def user_get_all():
+ """
+ retrieves all User objects
+ :return: json of all users
+ """
+ user_list = []
+ user_obj = storage.all("User")
+ for obj in user_obj.values():
+ user_list.append(obj.to_json())
+
+ return jsonify(user_list)
+
+
+@app_views.route("/users", methods=["POST"], strict_slashes=False)
+def user_create():
+ """
+ create user route
+ :return: newly created user obj
+ """
+ user_json = request.get_json(silent=True)
+ if user_json is None:
+ abort(400, 'Not a JSON')
+ if "email" not in user_json:
+ abort(400, 'Missing email')
+ if "password" not in user_json:
+ abort(400, 'Missing password')
+
+ new_user = User(**user_json)
+ new_user.save()
+ resp = jsonify(new_user.to_json())
+ resp.status_code = 201
+
+ return resp
+
+
+@app_views.route("/users/", methods=["GET"], strict_slashes=False)
+def user_by_id(user_id):
+ """
+ gets a specific User object by ID
+ :param user_id: user object id
+ :return: user obj with the specified id or error
+ """
+
+ fetched_obj = storage.get("User", str(user_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/users/", methods=["PUT"], strict_slashes=False)
+def user_put(user_id):
+ """
+ updates specific User object by ID
+ :param user_id: user object ID
+ :return: user object and 200 on success, or 400 or 404 on failure
+ """
+ user_json = request.get_json(silent=True)
+
+ if user_json is None:
+ abort(400, 'Not a JSON')
+
+ fetched_obj = storage.get("User", str(user_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ for key, val in user_json.items():
+ if key not in ["id", "created_at", "updated_at", "email"]:
+ setattr(fetched_obj, key, val)
+
+ fetched_obj.save()
+
+ return jsonify(fetched_obj.to_json())
+
+
+@app_views.route("/users/", methods=["DELETE"], strict_slashes=False)
+def user_delete_by_id(user_id):
+ """
+ deletes User by id
+ :param user_id: user object id
+ :return: empty dict with 200 or 404 if not found
+ """
+
+ fetched_obj = storage.get("User", str(user_id))
+
+ if fetched_obj is None:
+ abort(404)
+
+ storage.delete(fetched_obj)
+ storage.save()
+
+ return jsonify({})
diff --git a/console.py b/console.py
index 4798f9ac76b..701473757da 100755
--- a/console.py
+++ b/console.py
@@ -1,164 +1,365 @@
#!/usr/bin/python3
-""" console """
-
+"""
+Command interpreter for Holberton AirBnB project
+"""
+import os
import cmd
-from datetime import datetime
-import models
-from models.amenity import Amenity
-from models.base_model import BaseModel
-from models.city import City
-from models.place import Place
-from models.review import Review
-from models.state import State
-from models.user import User
-import shlex # for splitting the line along spaces except in double quotes
+from models import base_model, user, storage, CNC
-classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
- "Place": Place, "Review": Review, "State": State, "User": User}
+BaseModel = base_model.BaseModel
+User = user.User
class HBNBCommand(cmd.Cmd):
- """ HBNH console """
+ """
+ Command inerpreter class
+ """
prompt = '(hbnb) '
+ ERR = [
+ '** class name missing **',
+ '** class doesn\'t exist **',
+ '** instance id missing **',
+ '** no instance found **',
+ '** attribute name missing **',
+ '** value missing **',
+ ]
- def do_EOF(self, arg):
- """Exits console"""
- return True
+ def preloop(self):
+ """
+ handles intro to command interpreter
+ """
+ print('.----------------------------.')
+ print('| Welcome to hbnb CLI! |')
+ print('| for help, input \'help\' |')
+ print('| for quit, input \'quit\' |')
+ print('.----------------------------.')
+
+ def postloop(self):
+ """
+ handles exit to command interpreter
+ """
+ print('.----------------------------.')
+ print('| Well, that sure was fun! |')
+ print('.----------------------------.')
+
+ def default(self, line):
+ """
+ default response for unknown commands
+ """
+ pass
def emptyline(self):
- """ overwriting the emptyline method """
- return False
+ """
+ Called when an empty line is entered in response to the prompt.
+ """
+ pass
+
+ def __class_err(self, arg):
+ """
+ private: checks for missing class or unknown class
+ """
+ error = 0
+ if len(arg) == 0:
+ print(HBNBCommand.ERR[0])
+ error = 1
+ else:
+ if isinstance(arg, list):
+ arg = arg[0]
+ if arg not in CNC.keys():
+ print(HBNBCommand.ERR[1])
+ error = 1
+ return error
+
+ def __id_err(self, arg):
+ """
+ private checks for missing ID or unknown ID
+ """
+ error = 0
+ if (len(arg) < 2):
+ error += 1
+ print(HBNBCommand.ERR[2])
+ if not error:
+ file_storage_objs = storage.all()
+ for key, value in file_storage_objs.items():
+ temp_id = key.split('.')[1]
+ if temp_id == arg[1] and arg[0] in key:
+ return error
+ error += 1
+ print(HBNBCommand.ERR[3])
+ return error
+
+ def do_airbnb(self, arg):
+ """airbnb: airbnb
+ SYNOPSIS: Command changes prompt string"""
+ print(" __ ___ ")
+ print(" _ _ _ _||\ |/ \ | _ _ _|_|_ _ _ _| ")
+ print("|_||_)\)/(_|| (_|| \|\__/ || )(_)| |_| )\)/(_|| (_| ")
+ print(" | ")
+ if HBNBCommand.prompt == '(hbnb) ':
+ HBNBCommand.prompt = " /_ /_ _ /_\n/ //_// //_/ "
+ else:
+ HBNBCommand.prompt = '(hbnb) '
+ arg = arg.split()
+ error = self.__class_err(arg)
+
+ def do_quit(self, line):
+ """quit: quit
+ USAGE: Command to quit the program
+ """
+ return True
- def do_quit(self, arg):
- """Quit command to exit the program"""
+ def do_EOF(self, line):
+ """function to handle EOF"""
+ print()
return True
- def _key_value_parser(self, args):
- """creates a dictionary from a list of strings"""
- new_dict = {}
- for arg in args:
- if "=" in arg:
- kvp = arg.split('=', 1)
- key = kvp[0]
- value = kvp[1]
- if value[0] == value[-1] == '"':
- value = shlex.split(value)[0].replace('_', ' ')
- else:
- try:
- value = int(value)
- except:
- try:
- value = float(value)
- except:
- continue
- new_dict[key] = value
- return new_dict
+ def __parse_string(self, value):
+ """ parses attribute value passed as string """
+ value = value.strip('"').replace('_', ' ')
+ index = 0
+ while index < len(value):
+ index = value.find('\\', index)
+ if index == -1:
+ break
+ if value[index+1] == '"':
+ value_list = list(value)
+ del value_list[index]
+ value = ''.join(value_list)
+ index += 2
+ return value
- def do_create(self, arg):
- """Creates a new instance of a class"""
- args = arg.split()
- if len(args) == 0:
- print("** class name missing **")
- return False
- if args[0] in classes:
- new_dict = self._key_value_parser(args[1:])
- instance = classes[args[0]](**new_dict)
+ def __parse_number(self, value):
+ """ parses attribute value passed as number """
+ if value.find('.') != -1:
+ try:
+ value = float(value)
+ except:
+ pass
else:
- print("** class doesn't exist **")
- return False
- print(instance.id)
- instance.save()
+ try:
+ value = int(value)
+ except:
+ pass
+ return value
+
+ def do_create(self, arg):
+ """create: create [ARG]
+ ARG = Class Name
+ SYNOPSIS: Creates a new instance of the Class from given input ARG"""
+ arg = arg.split()
+ error = self.__class_err(arg)
+ if not error:
+ for k, v in CNC.items():
+ if k == arg[0]:
+ my_obj = v()
+ for param in arg[1:]:
+ attribute = param.split('=')
+ value = attribute[1]
+ if value[0] == '"' and value[-1] == '"':
+ value = self.__parse_string(value)
+ else:
+ value = self.__parse_number(value)
+ my_obj.bm_update(attribute[0], value)
+ my_obj.save()
+ print(my_obj.id)
def do_show(self, arg):
- """Prints an instance as a string based on the class and id"""
- args = shlex.split(arg)
- if len(args) == 0:
- print("** class name missing **")
- return False
- if args[0] in classes:
- if len(args) > 1:
- key = args[0] + "." + args[1]
- if key in models.storage.all():
- print(models.storage.all()[key])
- else:
- print("** no instance found **")
+ """show: show [ARG] [ARG1]
+ ARG = Class
+ ARG1 = ID #
+ SYNOPSIS: Prints object of given ID from given Class"""
+ arg = arg.split()
+ error = self.__class_err(arg)
+ if not error:
+ error += self.__id_err(arg)
+ if not error:
+ file_storage_objs = storage.all()
+ for k, v in file_storage_objs.items():
+ if arg[1] in k and arg[0] in k:
+ print(v)
+
+ def do_all(self, arg):
+ """all: all [ARG]
+ ARG = Class
+ SYNOPSIS: prints all objects of given class"""
+ error = 0
+ if arg:
+ arg = arg.split()
+ arg = str(arg[0])
+ error = self.__class_err(arg)
+ if not error:
+ file_storage_objs = storage.all(arg)
+ l = 0
+ if arg:
+ for v in file_storage_objs.values():
+ if isinstance(arg, str):
+ if type(v).__name__ == CNC[arg].__name__:
+ l += 1
+ else:
+ if type(v).__name__ == CNC[arg[0]].__name__:
+ l += 1
+ c = 0
+ for v in file_storage_objs.values():
+ if isinstance(arg, str):
+ if type(v).__name__ == CNC[arg].__name__:
+ c += 1
+ print(v, end=(', ' if c < l else ''))
+ else:
+ if type(v).__name__ == CNC[arg[0]].__name__:
+ c += 1
+ print(v, end=(', ' if c < l else ''))
else:
- print("** instance id missing **")
- else:
- print("** class doesn't exist **")
+ l = len(file_storage_objs)
+ c = 0
+ for v in file_storage_objs.values():
+ print(v, end=(', ' if c < l else ''))
+ print()
def do_destroy(self, arg):
- """Deletes an instance based on the class and id"""
- args = shlex.split(arg)
- if len(args) == 0:
- print("** class name missing **")
- elif args[0] in classes:
- if len(args) > 1:
- key = args[0] + "." + args[1]
- if key in models.storage.all():
- models.storage.all().pop(key)
- models.storage.save()
- else:
- print("** no instance found **")
- else:
- print("** instance id missing **")
- else:
- print("** class doesn't exist **")
+ """destroy: destroy [ARG] [ARG1]
+ ARG = Class
+ ARG1 = ID #
+ SYNOPSIS: destroys object of given ID from given Class"""
+ arg = arg.split()
+ error = self.__class_err(arg)
+ if not error:
+ error += self.__id_err(arg)
+ if not error:
+ file_storage_objs = storage.all()
+ for k in file_storage_objs.keys():
+ if arg[1] in k and arg[0] in k:
+ del file_storage_objs[k]
+ storage.save()
- def do_all(self, arg):
- """Prints string representations of instances"""
- args = shlex.split(arg)
- obj_list = []
- if len(args) == 0:
- obj_dict = models.storage.all()
- elif args[0] in classes:
- obj_dict = models.storage.all(classes[args[0]])
+ def __rreplace(self, s, l):
+ for c in l:
+ s = s.replace(c, '')
+ return s
+
+ def __check_dict(self, arg):
+ """checks if the arguments input has a dictionary"""
+ if '{' and '}' in arg:
+ l = arg.split('{')[1]
+ l = l.split(', ')
+ l = list(s.split(':') for s in l)
+ d = {}
+ for subl in l:
+ k = subl[0].strip('"\' {}')
+ v = subl[1].strip('"\' {}')
+ d[k] = v
+ return d
else:
- print("** class doesn't exist **")
- return False
- for key in obj_dict:
- obj_list.append(str(obj_dict[key]))
- print("[", end="")
- print(", ".join(obj_list), end="")
- print("]")
+ return None
+
+ def __handle_update_err(self, arg):
+ """checks for all errors in update"""
+ d = self.__check_dict(arg)
+ arg = self.__rreplace(arg, [',', '"'])
+ arg = arg.split()
+ error = self.__class_err(arg)
+ if not error:
+ error += self.__id_err(arg)
+ if not error:
+ valid_id = 0
+ file_storage_objs = storage.all()
+ for k in file_storage_objs.keys():
+ if arg[1] in k and arg[0] in k:
+ key = k
+ if len(arg) < 3:
+ print(HBNBCommand.ERR[4])
+ elif len(arg) < 4:
+ print(HBNBCommand.ERR[5])
+ else:
+ return [1, arg, d, file_storage_objs, key]
+ return [0]
def do_update(self, arg):
- """Update an instance based on the class name, id, attribute & value"""
- args = shlex.split(arg)
- integers = ["number_rooms", "number_bathrooms", "max_guest",
- "price_by_night"]
- floats = ["latitude", "longitude"]
- if len(args) == 0:
- print("** class name missing **")
- elif args[0] in classes:
- if len(args) > 1:
- k = args[0] + "." + args[1]
- if k in models.storage.all():
- if len(args) > 2:
- if len(args) > 3:
- if args[0] == "Place":
- if args[2] in integers:
- try:
- args[3] = int(args[3])
- except:
- args[3] = 0
- elif args[2] in floats:
- try:
- args[3] = float(args[3])
- except:
- args[3] = 0.0
- setattr(models.storage.all()[k], args[2], args[3])
- models.storage.all()[k].save()
- else:
- print("** value missing **")
- else:
- print("** attribute name missing **")
- else:
- print("** no instance found **")
+ """update: update [ARG] [ARG1] [ARG2] [ARG3]
+ ARG = Class
+ ARG1 = ID #
+ ARG2 = attribute name
+ ARG3 = value of new attribute
+ SYNOPSIS: updates or adds a new attribute and value of given Class"""
+ arg_inv = self.__handle_update_err(arg)
+ if arg_inv[0]:
+ arg = arg_inv[1]
+ d = arg_inv[2]
+ file_storage_objs = arg_inv[3]
+ key = arg_inv[4]
+ if not d:
+ avalue = arg[3].strip('"')
+ if avalue.isdigit():
+ avalue = int(avalue)
+ file_storage_objs[key].bm_update(arg[2], avalue)
else:
- print("** instance id missing **")
- else:
- print("** class doesn't exist **")
+ for k, v in d.items():
+ if v.isdigit():
+ v = int(v)
+ file_storage_objs[key].bm_update(k, v)
+
+ def do_BaseModel(self, arg):
+ """class method with .function() syntax
+ Usage: BaseModel.()"""
+ self.__parse_exec('BaseModel', arg)
+
+ def do_Amenity(self, arg):
+ """class method with .function() syntax
+ Usage: Amenity.()"""
+ self.__parse_exec('Amenity', arg)
+
+ def do_City(self, arg):
+ """class method with .function() syntax
+ Usage: City.()"""
+ self.__parse_exec('City', arg)
+
+ def do_Place(self, arg):
+ """class method with .function() syntax
+ Usage: Place.()"""
+ self.__parse_exec('Place', arg)
+
+ def do_Review(self, arg):
+ """class method with .function() syntax
+ Usage: Review.()"""
+ self.__parse_exec('Review', arg)
+
+ def do_State(self, arg):
+ """class method with .function() syntax
+ Usage: State.()"""
+ self.__parse_exec('State', arg)
+
+ def do_User(self, arg):
+ """class method with .function() syntax
+ Usage: User.()"""
+ self.__parse_exec('User', arg)
+
+ def __count(self, arg):
+ args = arg.split()
+ file_storage_objs = storage.all()
+ count = 0
+ for k in file_storage_objs.keys():
+ if args[0] in k:
+ count += 1
+ print(count)
+
+ def __parse_exec(self, c, arg):
+ CMD_MATCH = {
+ '.all': self.do_all,
+ '.count': self.__count,
+ '.show': self.do_show,
+ '.destroy': self.do_destroy,
+ '.update': self.do_update,
+ '.create': self.do_create,
+ }
+ if '(' and ')' in arg:
+ check = arg.split('(')
+ new_arg = "{} {}".format(c, check[1][:-1])
+ for k, v in CMD_MATCH.items():
+ if k == check[0]:
+ if ((',' or '"' in new_arg) and k != '.update'):
+ new_arg = self.__rreplace(new_arg, ['"', ','])
+ v(new_arg)
+ return
+ self.default(arg)
if __name__ == '__main__':
HBNBCommand().cmdloop()
diff --git a/dev/AirBnb_DB_diagramm.jpg b/dev/AirBnb_DB_diagramm.jpg
new file mode 100644
index 00000000000..432a8c1856d
Binary files /dev/null and b/dev/AirBnb_DB_diagramm.jpg differ
diff --git a/dev/hbnb_step5.png b/dev/hbnb_step5.png
new file mode 100644
index 00000000000..2e503bdd9da
Binary files /dev/null and b/dev/hbnb_step5.png differ
diff --git a/dev/hbtn_tests/main_30.py b/dev/hbtn_tests/main_30.py
new file mode 100644
index 00000000000..4f3c4b50a9b
--- /dev/null
+++ b/dev/hbtn_tests/main_30.py
@@ -0,0 +1,91 @@
+#!/usr/bin/python3
+import inspect
+import io
+import sys
+import cmd
+import shutil
+import console
+"""
+ Cleanup file storage
+"""
+import os
+file_path = "file.json"
+if not os.path.exists(file_path):
+ try:
+ from models.engine.file_storage import FileStorage
+ file_path = FileStorage._FileStorage__file_path
+ except:
+ pass
+if os.path.exists(file_path):
+ os.remove(file_path)
+
+
+"""
+ Backup console file
+"""
+if os.path.exists("tmp_console_main.py"):
+ shutil.copy("tmp_console_main.py", "console.py")
+shutil.copy("console.py", "tmp_console_main.py")
+
+"""
+ Updating console to remove "__main__"
+"""
+with open("tmp_console_main.py", "r") as file_i:
+ console_lines = file_i.readlines()
+ with open("console.py", "w") as file_o:
+ in_main = False
+ for line in console_lines:
+ if "__main__" in line:
+ in_main = True
+ elif in_main:
+ if "cmdloop" not in line:
+ file_o.write(line.lstrip(" "))
+ else:
+ file_o.write(line)
+
+"""
+ Create console
+"""
+console_obj = "HBNBCommand"
+for name, obj in inspect.getmembers(console):
+ if inspect.isclass(obj) and issubclass(obj, cmd.Cmd):
+ console_obj = obj
+
+my_console = console_obj(stdout=io.StringIO(), stdin=io.StringIO())
+my_console.use_rawinput = False
+
+"""
+ Exec command
+"""
+
+
+def exec_command(my_console, the_command, last_lines=1):
+ my_console.stdout = io.StringIO()
+ real_stdout = sys.stdout
+ sys.stdout = my_console.stdout
+ my_console.onecmd(the_command)
+ sys.stdout = real_stdout
+ lines = my_console.stdout.getvalue().split("\n")
+ return "\n".join(lines[(-1*(last_lines+1)):-1])
+
+"""
+ Tests
+"""
+result = exec_command(my_console, "create Place")
+if result is None or result == "":
+ print("FAIL: No ID retrieved")
+
+model_id = result
+
+result = exec_command(my_console, "show Review {}".format(model_id))
+if result is None or result == "":
+ print("FAIL: no output")
+
+search_str = "** no instance found **"
+if result != search_str:
+ print("FAIL: wrong output \"{}\" instead of \"{}\"".format(result,
+ search_str))
+
+print("OK", end="")
+
+shutil.copy("tmp_console_main.py", "console.py")
diff --git a/dev/hbtn_tests/test_base_model_dict.py b/dev/hbtn_tests/test_base_model_dict.py
new file mode 100644
index 00000000000..4232e20f68d
--- /dev/null
+++ b/dev/hbtn_tests/test_base_model_dict.py
@@ -0,0 +1,25 @@
+#!/usr/bin/python3
+from models.base_model import BaseModel
+
+my_model = BaseModel()
+my_model.name = "Holberton"
+my_model.my_number = 89
+print(my_model.id)
+print(my_model)
+print(type(my_model.created_at))
+print("--")
+my_model_json = my_model.to_json()
+print(my_model_json)
+print("JSON of my_model:")
+for key in my_model_json.keys():
+ print("\t{}: ({}) - {}".format(key, type(my_model_json[key]),
+ my_model_json[key]))
+
+print("--")
+my_new_model = BaseModel(**my_model_json)
+print(my_new_model.id)
+print(my_new_model)
+print(type(my_new_model.created_at))
+
+print("--")
+print(my_model is my_new_model)
diff --git a/dev/hbtn_tests/test_save_reload_base_model.py b/dev/hbtn_tests/test_save_reload_base_model.py
new file mode 100644
index 00000000000..82d55b55abb
--- /dev/null
+++ b/dev/hbtn_tests/test_save_reload_base_model.py
@@ -0,0 +1,17 @@
+#!/usr/bin/python3
+from models import storage
+from models.base_model import BaseModel
+
+print(BaseModel.__name__)
+all_objs = storage.all()
+print("-- Reloaded objects --")
+for obj_id in all_objs.keys():
+ obj = all_objs[obj_id]
+ print(obj)
+
+print("-- Create a new object --")
+my_model = BaseModel()
+my_model.name = "Holberton"
+my_model.my_number = 89
+my_model.save()
+print(my_model)
diff --git a/dev/hbtn_tests/test_save_reload_user.py b/dev/hbtn_tests/test_save_reload_user.py
new file mode 100644
index 00000000000..3f8bc877be0
--- /dev/null
+++ b/dev/hbtn_tests/test_save_reload_user.py
@@ -0,0 +1,22 @@
+#!/usr/bin/python3
+from models import storage
+from models.base_model import BaseModel
+from models.user import User
+
+all_objs = storage.all()
+print("-- End Reloaded objects --")
+print("printing values only of reloaded:")
+for obj_id in all_objs.keys():
+ obj = all_objs[obj_id]
+ print(obj)
+
+print("-- Begin Create a new User --")
+my_user = User()
+my_user.first_name = "Betty"
+my_user.last_name = "Holberton"
+my_user.email = "airbnb@holbertonshool.com"
+my_user.password = "root"
+my_user.save()
+an_bm = BaseModel()
+an_bm.save()
+print(my_user)
diff --git a/dev/init_test.sh b/dev/init_test.sh
new file mode 100644
index 00000000000..271cf25b5b8
--- /dev/null
+++ b/dev/init_test.sh
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+# This initializes testing suite.
+# Checks pep8 style of all python files
+# also runs all unittests
+pep8 . && python3 -m unittest discover -v ./tests/ \
+ && ./dev/w3c_validator.py \
+ $(find ./web_static -maxdepth 1 -name "*.html" -type f ! -name "4*") \
+ && ./dev/w3c_validator.py \
+ $(find ./web_static/styles -maxdepth 1 -name "*.css" -type f)
+
+# stores the return value
+ret_val=$?
+
+# clears file.json
+> ./dev/file.json
+
+# removes __pycache__ folder
+py3clean .
+
+# exits with status from tests
+exit "$ret_val"
diff --git a/dev/w3c_validator.py b/dev/w3c_validator.py
new file mode 100644
index 00000000000..ee9593fce40
--- /dev/null
+++ b/dev/w3c_validator.py
@@ -0,0 +1,123 @@
+#!/usr/bin/python3
+"""
+W3C validator for Holberton School
+
+For HTML and CSS files.
+
+Based on 2 APIs:
+
+- https://validator.w3.org/nu/
+- http://jigsaw.w3.org/css-validator/validator
+
+
+Usage:
+
+Simple file:
+
+```
+./w3c_validator.py index.html
+```
+
+Multiple files:
+
+```
+./w3c_validator.py index.html header.html styles/common.css
+```
+
+All errors are printed in `STDERR`
+
+Return:
+Exit status is the # of errors, 0 on Success
+
+References
+
+https://developer.mozilla.org/en-US/
+
+"""
+import sys
+import requests
+
+
+def __print_stdout(msg):
+ """Print message in STDOUT
+ """
+ sys.stdout.write(msg)
+
+
+def __print_stderr(msg):
+ """Print message in STDERR
+ """
+ sys.stderr.write(msg)
+
+
+def __analyse_html(file_path):
+ """Start analyse of HTML file
+ """
+ h = {'Content-Type': "text/html; charset=utf-8"}
+ d = open(file_path, "rb").read()
+ u = "https://validator.w3.org/nu/?out=json"
+ r = requests.post(u, headers=h, data=d)
+ res = []
+ messages = r.json().get('messages', [])
+ for m in messages:
+ res.append("[{}:{}] {}".format(file_path, m['lastLine'], m['message']))
+ return res
+
+
+def __analyse_css(file_path):
+ """Start analyse of CSS file
+ """
+ d = {'output': "json"}
+ f = {'file': (file_path, open(file_path, 'rb'), 'text/css')}
+ u = "http://jigsaw.w3.org/css-validator/validator"
+ r = requests.post(u, data=d, files=f)
+ res = []
+ errors = r.json().get('cssvalidation', {}).get('errors', [])
+ for e in errors:
+ res.append("[{}:{}] {}".format(file_path, e['line'], e['message']))
+ return res
+
+
+def __analyse(file_path):
+ """Start analyse of a file and print the result
+ """
+ nb_errors = 0
+ try:
+ result = None
+ if file_path.endswith('.css'):
+ result = __analyse_css(file_path)
+ else:
+ result = __analyse_html(file_path)
+
+ if len(result) > 0:
+ for msg in result:
+ __print_stderr("{}\n".format(msg))
+ nb_errors += 1
+ else:
+ __print_stdout("{}: OK\n".format(file_path))
+
+ except Exception as e:
+ __print_stderr("[{}] {}\n".format(e.__class__.__name__, e))
+ return nb_errors
+
+
+def __files_loop():
+ """Loop that analyses for each file from input arguments
+ """
+ nb_errors = 0
+ for file_path in sys.argv[1:]:
+ nb_errors += __analyse(file_path)
+
+ return nb_errors
+
+
+if __name__ == "__main__":
+ """Main
+ """
+ if len(sys.argv) < 2:
+ __print_stderr("usage: w3c_validator.py file1 file2 ...\n")
+ exit(1)
+
+ """execute tests, then exit. Exit status = # of errors (0 on success)
+ """
+ sys.exit(__files_loop())
diff --git a/file.json b/file.json
new file mode 100755
index 00000000000..6b8a64ebcf2
--- /dev/null
+++ b/file.json
@@ -0,0 +1 @@
+{"Amenity.30b85c70-749b-4e48-a376-a2aa1090089a": {"id": "30b85c70-749b-4e48-a376-a2aa1090089a", "created_at": "2025-02-15T19:30:59.646993", "updated_at": "2025-02-15T19:30:59.646993", "__class__": "Amenity"}, "BaseModel.9f1de2a6-6092-483e-b1b3-b07a12c4b774": {"id": "9f1de2a6-6092-483e-b1b3-b07a12c4b774", "created_at": "2025-02-15T19:30:59.647003", "updated_at": "2025-02-15T19:30:59.647003", "__class__": "BaseModel"}, "City.58b044cb-d933-4f88-87d1-5a287c9108d9": {"id": "58b044cb-d933-4f88-87d1-5a287c9108d9", "created_at": "2025-02-15T19:30:59.647012", "updated_at": "2025-02-15T19:30:59.647012", "__class__": "City"}, "Place.807cd2c9-5695-424a-b1f4-368564cc8598": {"id": "807cd2c9-5695-424a-b1f4-368564cc8598", "created_at": "2025-02-15T19:30:59.647020", "updated_at": "2025-02-15T19:30:59.647020", "__class__": "Place"}, "Review.17ad8563-7403-44eb-81a6-832da631db10": {"id": "17ad8563-7403-44eb-81a6-832da631db10", "created_at": "2025-02-15T19:30:59.647028", "updated_at": "2025-02-15T19:30:59.647028", "__class__": "Review"}, "State.35529960-c596-44d7-a140-0ea150ee312b": {"id": "35529960-c596-44d7-a140-0ea150ee312b", "created_at": "2025-02-15T19:30:59.647037", "updated_at": "2025-02-15T19:30:59.647037", "__class__": "State"}, "User.fb424752-8f65-4917-b24b-9730df4bd0ee": {"id": "fb424752-8f65-4917-b24b-9730df4bd0ee", "created_at": "2025-02-15T19:30:59.647045", "updated_at": "2025-02-15T19:30:59.647045", "__class__": "User"}}
\ No newline at end of file
diff --git a/models/__init__.py b/models/__init__.py
index defef6378c1..8f2b5c55889 100755
--- a/models/__init__.py
+++ b/models/__init__.py
@@ -1,17 +1,21 @@
-#!/usr/bin/python3
-"""
-initialize the models package
-"""
+import os
+from models.base_model import BaseModel
+from models.amenity import Amenity
+from models.city import City
+from models.place import Place
+from models.review import Review
+from models.state import State
+from models.user import User
-from os import getenv
+"""CNC - dictionary = { Class Name (string) : Class Type }"""
-
-storage_t = getenv("HBNB_TYPE_STORAGE")
-
-if storage_t == "db":
- from models.engine.db_storage import DBStorage
- storage = DBStorage()
+if os.environ.get('HBNB_TYPE_STORAGE') == 'db':
+ from models.engine import db_storage
+ CNC = db_storage.DBStorage.CNC
+ storage = db_storage.DBStorage()
else:
- from models.engine.file_storage import FileStorage
- storage = FileStorage()
+ from models.engine import file_storage
+ CNC = file_storage.FileStorage.CNC
+ storage = file_storage.FileStorage()
+
storage.reload()
diff --git a/models/__pycache__/__init__.cpython-312.pyc b/models/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 00000000000..a8513cadb2c
Binary files /dev/null and b/models/__pycache__/__init__.cpython-312.pyc differ
diff --git a/models/__pycache__/__init__.cpython-313.pyc b/models/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 00000000000..24c45252b46
Binary files /dev/null and b/models/__pycache__/__init__.cpython-313.pyc differ
diff --git a/models/__pycache__/__init__.cpython-38.pyc b/models/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..5bf7e6ebbff
Binary files /dev/null and b/models/__pycache__/__init__.cpython-38.pyc differ
diff --git a/models/__pycache__/amenity.cpython-312.pyc b/models/__pycache__/amenity.cpython-312.pyc
new file mode 100644
index 00000000000..54d3875eb1c
Binary files /dev/null and b/models/__pycache__/amenity.cpython-312.pyc differ
diff --git a/models/__pycache__/amenity.cpython-38.pyc b/models/__pycache__/amenity.cpython-38.pyc
new file mode 100644
index 00000000000..b81d3f06ea9
Binary files /dev/null and b/models/__pycache__/amenity.cpython-38.pyc differ
diff --git a/models/__pycache__/base_model.cpython-312.pyc b/models/__pycache__/base_model.cpython-312.pyc
new file mode 100644
index 00000000000..edfc1505257
Binary files /dev/null and b/models/__pycache__/base_model.cpython-312.pyc differ
diff --git a/models/__pycache__/base_model.cpython-313.pyc b/models/__pycache__/base_model.cpython-313.pyc
new file mode 100644
index 00000000000..60b2007964d
Binary files /dev/null and b/models/__pycache__/base_model.cpython-313.pyc differ
diff --git a/models/__pycache__/base_model.cpython-38.pyc b/models/__pycache__/base_model.cpython-38.pyc
new file mode 100644
index 00000000000..8ee4c87ac5c
Binary files /dev/null and b/models/__pycache__/base_model.cpython-38.pyc differ
diff --git a/models/__pycache__/city.cpython-38.pyc b/models/__pycache__/city.cpython-38.pyc
new file mode 100644
index 00000000000..2b0af2a071f
Binary files /dev/null and b/models/__pycache__/city.cpython-38.pyc differ
diff --git a/models/__pycache__/place.cpython-38.pyc b/models/__pycache__/place.cpython-38.pyc
new file mode 100644
index 00000000000..ada28ad46d4
Binary files /dev/null and b/models/__pycache__/place.cpython-38.pyc differ
diff --git a/models/__pycache__/review.cpython-38.pyc b/models/__pycache__/review.cpython-38.pyc
new file mode 100644
index 00000000000..e74b886328d
Binary files /dev/null and b/models/__pycache__/review.cpython-38.pyc differ
diff --git a/models/__pycache__/state.cpython-38.pyc b/models/__pycache__/state.cpython-38.pyc
new file mode 100644
index 00000000000..741f92ad9bf
Binary files /dev/null and b/models/__pycache__/state.cpython-38.pyc differ
diff --git a/models/__pycache__/user.cpython-38.pyc b/models/__pycache__/user.cpython-38.pyc
new file mode 100644
index 00000000000..567a6d1871b
Binary files /dev/null and b/models/__pycache__/user.cpython-38.pyc differ
diff --git a/models/amenity.py b/models/amenity.py
index 557728bafdc..ec4a9c43958 100755
--- a/models/amenity.py
+++ b/models/amenity.py
@@ -1,21 +1,20 @@
-#!/usr/bin/python
-""" holds class Amenity"""
-import models
+#!/usr/bin/python3
+"""
+Amenity Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
+from sqlalchemy import Column, Integer, String, Float
+from sqlalchemy.orm import backref
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class Amenity(BaseModel, Base):
- """Representation of Amenity """
- if models.storage_t == 'db':
+ """Amenity class handles all application amenities"""
+ if storage_type == "db":
__tablename__ = 'amenities'
name = Column(String(128), nullable=False)
+ place_amenities = relationship("Place", secondary="place_amenity")
else:
- name = ""
-
- def __init__(self, *args, **kwargs):
- """initializes Amenity"""
- super().__init__(*args, **kwargs)
+ name = ''
diff --git a/models/base_model.py b/models/base_model.py
old mode 100755
new mode 100644
index 9a86addb366..d1a07cafa4c
--- a/models/base_model.py
+++ b/models/base_model.py
@@ -1,75 +1,96 @@
#!/usr/bin/python3
"""
-Contains class BaseModel
+BaseModel Class of Models Module
"""
-from datetime import datetime
+import os
+import json
import models
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String, DateTime
+from uuid import uuid4, UUID
+from datetime import datetime
from sqlalchemy.ext.declarative import declarative_base
-import uuid
+from sqlalchemy import Column, Integer, String, Float, DateTime
-time = "%Y-%m-%dT%H:%M:%S.%f"
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
-if models.storage_t == "db":
+"""
+ Creates instance of Base if storage type is a database
+ If not database storage, uses class Base
+"""
+if storage_type == 'db':
Base = declarative_base()
else:
- Base = object
+ class Base:
+ pass
class BaseModel:
- """The BaseModel class from which future classes will be derived"""
- if models.storage_t == "db":
- id = Column(String(60), primary_key=True)
- created_at = Column(DateTime, default=datetime.utcnow)
- updated_at = Column(DateTime, default=datetime.utcnow)
+ """
+ attributes and functions for BaseModel class
+ """
+
+ if storage_type == 'db':
+ id = Column(String(60), nullable=False, primary_key=True)
+ created_at = Column(DateTime, nullable=False,
+ default=datetime.utcnow())
+ updated_at = Column(DateTime, nullable=False,
+ default=datetime.utcnow())
def __init__(self, *args, **kwargs):
- """Initialization of the base model"""
+ """instantiation of new BaseModel Class"""
+ self.id = str(uuid4())
+ self.created_at = datetime.now()
if kwargs:
for key, value in kwargs.items():
- if key != "__class__":
- setattr(self, key, value)
- if kwargs.get("created_at", None) and type(self.created_at) is str:
- self.created_at = datetime.strptime(kwargs["created_at"], time)
- else:
- self.created_at = datetime.utcnow()
- if kwargs.get("updated_at", None) and type(self.updated_at) is str:
- self.updated_at = datetime.strptime(kwargs["updated_at"], time)
- else:
- self.updated_at = datetime.utcnow()
- if kwargs.get("id", None) is None:
- self.id = str(uuid.uuid4())
- else:
- self.id = str(uuid.uuid4())
- self.created_at = datetime.utcnow()
- self.updated_at = self.created_at
+ setattr(self, key, value)
- def __str__(self):
- """String representation of the BaseModel class"""
- return "[{:s}] ({:s}) {}".format(self.__class__.__name__, self.id,
- self.__dict__)
+ def __is_serializable(self, obj_v):
+ """
+ private: checks if object is serializable
+ """
+ try:
+ obj_to_str = json.dumps(obj_v)
+ return obj_to_str is not None and isinstance(obj_to_str, str)
+ except:
+ return False
+
+ def bm_update(self, name, value):
+ """
+ updates the basemodel and sets the correct attributes
+ """
+ setattr(self, name, value)
+ if storage_type != 'db':
+ self.save()
def save(self):
- """updates the attribute 'updated_at' with the current datetime"""
- self.updated_at = datetime.utcnow()
+ """updates attribute updated_at to current time"""
+ if storage_type != 'db':
+ self.updated_at = datetime.now()
models.storage.new(self)
models.storage.save()
- def to_dict(self):
- """returns a dictionary containing all keys/values of the instance"""
- new_dict = self.__dict__.copy()
- if "created_at" in new_dict:
- new_dict["created_at"] = new_dict["created_at"].strftime(time)
- if "updated_at" in new_dict:
- new_dict["updated_at"] = new_dict["updated_at"].strftime(time)
- new_dict["__class__"] = self.__class__.__name__
- if "_sa_instance_state" in new_dict:
- del new_dict["_sa_instance_state"]
- return new_dict
+ def to_json(self):
+ """returns json representation of self"""
+ bm_dict = {}
+ for key, value in (self.__dict__).items():
+ if (self.__is_serializable(value)):
+ bm_dict[key] = value
+ else:
+ bm_dict[key] = str(value)
+ bm_dict['__class__'] = type(self).__name__
+ if '_sa_instance_state' in bm_dict:
+ bm_dict.pop('_sa_instance_state')
+ if storage_type == "db" and 'password' in bm_dict:
+ bm_dict.pop('password')
+ return bm_dict
+
+ def __str__(self):
+ """returns string type representation of object instance"""
+ class_name = type(self).__name__
+ return '[{}] ({}) {}'.format(class_name, self.id, self.__dict__)
def delete(self):
- """delete the current instance from the storage"""
- models.storage.delete(self)
+ """
+ deletes current instance from storage
+ """
+ self.delete()
diff --git a/models/city.py b/models/city.py
index 8c46f0d2f4c..43ced6ae91a 100755
--- a/models/city.py
+++ b/models/city.py
@@ -1,24 +1,39 @@
-#!/usr/bin/python
-""" holds class City"""
-import models
+#!/usr/bin/python3
+"""
+City Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String, ForeignKey
from sqlalchemy.orm import relationship
+from sqlalchemy import Column, Integer, String, Float, ForeignKey
+import models
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class City(BaseModel, Base):
- """Representation of city """
- if models.storage_t == "db":
+ """City class handles all application cities"""
+ if storage_type == "db":
__tablename__ = 'cities'
- state_id = Column(String(60), ForeignKey('states.id'), nullable=False)
name = Column(String(128), nullable=False)
- places = relationship("Place", backref="cities")
+ state_id = Column(String(60), ForeignKey('states.id'), nullable=False)
+ places = relationship('Place', backref='cities', cascade='delete')
else:
- state_id = ""
- name = ""
+ state_id = ''
+ name = ''
+
+ if storage_type != 'db':
+ @property
+ def places(self):
+ """
+ getter for places
+ :return: list of places in that city
+ """
+ all_places = models.storage.all("Place")
+
+ result = []
+
+ for obj in all_places.values():
+ if str(obj.city_id) == str(self.id):
+ result.append(obj)
- def __init__(self, *args, **kwargs):
- """initializes city"""
- super().__init__(*args, **kwargs)
+ return result
diff --git a/models/engine/__pycache__/__init__.cpython-312.pyc b/models/engine/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 00000000000..2fc90f95fbf
Binary files /dev/null and b/models/engine/__pycache__/__init__.cpython-312.pyc differ
diff --git a/models/engine/__pycache__/__init__.cpython-38.pyc b/models/engine/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..58d0e88a825
Binary files /dev/null and b/models/engine/__pycache__/__init__.cpython-38.pyc differ
diff --git a/models/engine/__pycache__/db_storage.cpython-38.pyc b/models/engine/__pycache__/db_storage.cpython-38.pyc
new file mode 100644
index 00000000000..6531a97b760
Binary files /dev/null and b/models/engine/__pycache__/db_storage.cpython-38.pyc differ
diff --git a/models/engine/__pycache__/file_storage.cpython-312.pyc b/models/engine/__pycache__/file_storage.cpython-312.pyc
new file mode 100644
index 00000000000..6b9e28dfe41
Binary files /dev/null and b/models/engine/__pycache__/file_storage.cpython-312.pyc differ
diff --git a/models/engine/__pycache__/file_storage.cpython-38.pyc b/models/engine/__pycache__/file_storage.cpython-38.pyc
new file mode 100644
index 00000000000..facbdc2e003
Binary files /dev/null and b/models/engine/__pycache__/file_storage.cpython-38.pyc differ
diff --git a/models/engine/db_storage.py b/models/engine/db_storage.py
index b8e7d291e6f..911286945aa 100755
--- a/models/engine/db_storage.py
+++ b/models/engine/db_storage.py
@@ -1,76 +1,105 @@
#!/usr/bin/python3
-"""
-Contains the class DBStorage
-"""
+""" Database engine """
-import models
-from models.amenity import Amenity
-from models.base_model import BaseModel, Base
-from models.city import City
-from models.place import Place
-from models.review import Review
-from models.state import State
-from models.user import User
-from os import getenv
-import sqlalchemy
-from sqlalchemy import create_engine
-from sqlalchemy.orm import scoped_session, sessionmaker
-
-classes = {"Amenity": Amenity, "City": City,
- "Place": Place, "Review": Review, "State": State, "User": User}
+import os
+from sqlalchemy import create_engine, MetaData
+from sqlalchemy.orm import sessionmaker, scoped_session
+from models.base_model import Base
+from models import base_model, amenity, city, place, review, state, user
class DBStorage:
- """interaacts with the MySQL database"""
+ """handles long term storage of all class instances"""
+ CNC = {
+ 'BaseModel': base_model.BaseModel,
+ 'Amenity': amenity.Amenity,
+ 'City': city.City,
+ 'Place': place.Place,
+ 'Review': review.Review,
+ 'State': state.State,
+ 'User': user.User
+ }
+
+ """ handles storage for database """
__engine = None
__session = None
def __init__(self):
- """Instantiate a DBStorage object"""
- HBNB_MYSQL_USER = getenv('HBNB_MYSQL_USER')
- HBNB_MYSQL_PWD = getenv('HBNB_MYSQL_PWD')
- HBNB_MYSQL_HOST = getenv('HBNB_MYSQL_HOST')
- HBNB_MYSQL_DB = getenv('HBNB_MYSQL_DB')
- HBNB_ENV = getenv('HBNB_ENV')
- self.__engine = create_engine('mysql+mysqldb://{}:{}@{}/{}'.
- format(HBNB_MYSQL_USER,
- HBNB_MYSQL_PWD,
- HBNB_MYSQL_HOST,
- HBNB_MYSQL_DB))
- if HBNB_ENV == "test":
+ """ creates the engine self.__engine """
+ self.__engine = create_engine(
+ 'mysql+mysqldb://{}:{}@{}/{}'.format(
+ os.environ.get('HBNB_MYSQL_USER'),
+ os.environ.get('HBNB_MYSQL_PWD'),
+ os.environ.get('HBNB_MYSQL_HOST'),
+ os.environ.get('HBNB_MYSQL_DB')))
+ if os.environ.get("HBNB_ENV") == 'test':
Base.metadata.drop_all(self.__engine)
def all(self, cls=None):
- """query on the current database session"""
- new_dict = {}
- for clss in classes:
- if cls is None or cls is classes[clss] or cls is clss:
- objs = self.__session.query(classes[clss]).all()
- for obj in objs:
- key = obj.__class__.__name__ + '.' + obj.id
- new_dict[key] = obj
- return (new_dict)
+ """ returns a dictionary of all objects """
+ obj_dict = {}
+ if cls:
+ obj_class = self.__session.query(self.CNC.get(cls)).all()
+ for item in obj_class:
+ key = str(item.__class__.__name__) + "." + str(item.id)
+ obj_dict[key] = item
+ return obj_dict
+ for class_name in self.CNC:
+ if class_name == 'BaseModel':
+ continue
+ obj_class = self.__session.query(
+ self.CNC.get(class_name)).all()
+ for item in obj_class:
+ key = str(item.__class__.__name__) + "." + str(item.id)
+ obj_dict[key] = item
+ return obj_dict
def new(self, obj):
- """add the object to the current database session"""
+ """ adds objects to current database session """
self.__session.add(obj)
+ def get(self, cls, id):
+ """
+ fetches specific object
+ :param cls: class of object as string
+ :param id: id of object as string
+ :return: found object or None
+ """
+ all_class = self.all(cls)
+
+ for obj in all_class.values():
+ if id == str(obj.id):
+ return obj
+
+ return None
+
+ def count(self, cls=None):
+ """
+ count of how many instances of a class
+ :param cls: class name
+ :return: count of instances of a class
+ """
+ return len(self.all(cls))
+
def save(self):
- """commit all changes of the current database session"""
+ """ commits all changes of current database session """
self.__session.commit()
def delete(self, obj=None):
- """delete from the current database session obj if not None"""
+ """ deletes obj from current database session if not None """
if obj is not None:
self.__session.delete(obj)
def reload(self):
- """reloads data from the database"""
+ """ creates all tables in database & session from engine """
Base.metadata.create_all(self.__engine)
- sess_factory = sessionmaker(bind=self.__engine, expire_on_commit=False)
- Session = scoped_session(sess_factory)
- self.__session = Session
+ self.__session = scoped_session(
+ sessionmaker(
+ bind=self.__engine,
+ expire_on_commit=False))
def close(self):
- """call remove() method on the private session attribute"""
+ """
+ calls remove() on private session attribute (self.session)
+ """
self.__session.remove()
diff --git a/models/engine/file_storage.py b/models/engine/file_storage.py
index c8cb8c1764d..12bd1883395 100755
--- a/models/engine/file_storage.py
+++ b/models/engine/file_storage.py
@@ -1,70 +1,110 @@
#!/usr/bin/python3
"""
-Contains the FileStorage class
+Handles I/O, writing and reading, of JSON for storage of all class instances
"""
-
import json
-from models.amenity import Amenity
-from models.base_model import BaseModel
-from models.city import City
-from models.place import Place
-from models.review import Review
-from models.state import State
-from models.user import User
+from models import base_model, amenity, city, place, review, state, user
+from datetime import datetime
-classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
- "Place": Place, "Review": Review, "State": State, "User": User}
+strptime = datetime.strptime
+to_json = base_model.BaseModel.to_json
class FileStorage:
- """serializes instances to a JSON file & deserializes back to instances"""
-
- # string - path to the JSON file
- __file_path = "file.json"
- # dictionary - empty but will store all objects by .id
+ """handles long term storage of all class instances"""
+ CNC = {
+ 'BaseModel': base_model.BaseModel,
+ 'Amenity': amenity.Amenity,
+ 'City': city.City,
+ 'Place': place.Place,
+ 'Review': review.Review,
+ 'State': state.State,
+ 'User': user.User
+ }
+ """CNC - this variable is a dictionary with:
+ keys: Class Names
+ values: Class type (used for instantiation)
+ """
+ __file_path = './dev/file.json'
__objects = {}
def all(self, cls=None):
- """returns the dictionary __objects"""
- if cls is not None:
- new_dict = {}
- for key, value in self.__objects.items():
- if cls == value.__class__ or cls == value.__class__.__name__:
- new_dict[key] = value
- return new_dict
- return self.__objects
+ """returns private attribute: __objects"""
+ if cls:
+ objects_dict = {}
+ for class_id, obj in FileStorage.__objects.items():
+ if type(obj).__name__ == cls:
+ objects_dict[class_id] = obj
+ return objects_dict
+ return FileStorage.__objects
def new(self, obj):
- """sets in __objects the obj with key .id"""
- if obj is not None:
- key = obj.__class__.__name__ + "." + obj.id
- self.__objects[key] = obj
+ """sets / updates in __objects the obj with key .id"""
+ bm_id = "{}.{}".format(type(obj).__name__, obj.id)
+ FileStorage.__objects[bm_id] = obj
+
+ def get(self, cls, id):
+ """
+ gets specific object
+ :param cls: class
+ :param id: id of instance
+ :return: object or None
+ """
+ all_class = self.all(cls)
+
+ for obj in all_class.values():
+ if id == str(obj.id):
+ return obj
+
+ return None
+
+ def count(self, cls=None):
+ """
+ count of instances
+ :param cls: class
+ :return: number of instances
+ """
+
+ return len(self.all(cls))
def save(self):
"""serializes __objects to the JSON file (path: __file_path)"""
- json_objects = {}
- for key in self.__objects:
- json_objects[key] = self.__objects[key].to_dict()
- with open(self.__file_path, 'w') as f:
- json.dump(json_objects, f)
+ fname = FileStorage.__file_path
+ d = {}
+ for bm_id, bm_obj in FileStorage.__objects.items():
+ d[bm_id] = bm_obj.to_json()
+ with open(fname, mode='w+', encoding='utf-8') as f_io:
+ json.dump(d, f_io)
def reload(self):
- """deserializes the JSON file to __objects"""
+ """if file exists, deserializes JSON file to __objects, else nothing"""
+ fname = FileStorage.__file_path
+ FileStorage.__objects = {}
try:
- with open(self.__file_path, 'r') as f:
- jo = json.load(f)
- for key in jo:
- self.__objects[key] = classes[jo[key]["__class__"]](**jo[key])
+ with open(fname, mode='r', encoding='utf-8') as f_io:
+ new_objs = json.load(f_io)
except:
- pass
+ return
+ for o_id, d in new_objs.items():
+ k_cls = d['__class__']
+ d.pop("__class__", None)
+ d["created_at"] = datetime.strptime(d["created_at"],
+ "%Y-%m-%d %H:%M:%S.%f")
+ d["updated_at"] = datetime.strptime(d["updated_at"],
+ "%Y-%m-%d %H:%M:%S.%f")
+ FileStorage.__objects[o_id] = FileStorage.CNC[k_cls](**d)
def delete(self, obj=None):
- """delete obj from __objects if it’s inside"""
- if obj is not None:
- key = obj.__class__.__name__ + '.' + obj.id
- if key in self.__objects:
- del self.__objects[key]
+ """deletes obj"""
+ if obj is None:
+ return
+ for k in list(FileStorage.__objects.keys()):
+ if obj.id == k.split(".")[1] and k.split(".")[0] in str(obj):
+ FileStorage.__objects.pop(k, None)
+ self.save()
def close(self):
- """call reload() method for deserializing the JSON file to objects"""
+ """
+ calls the reload() method for deserialization from JSON to objects
+ """
self.reload()
diff --git a/models/place.py b/models/place.py
index 0aed5a744e6..b17cfb9f8c2 100755
--- a/models/place.py
+++ b/models/place.py
@@ -1,27 +1,31 @@
-#!/usr/bin/python
-""" holds class Place"""
-import models
+#!/usr/bin/python3
+"""
+Place Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String, Integer, Float, ForeignKey, Table
from sqlalchemy.orm import relationship
+from sqlalchemy import Column, Integer, String, Float, ForeignKey,\
+ MetaData, Table, ForeignKey
+from sqlalchemy.orm import backref
+import models
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
+
-if models.storage_t == 'db':
+if os.getenv("HBNB_TYPE_STORAGE") == "db":
place_amenity = Table('place_amenity', Base.metadata,
- Column('place_id', String(60),
- ForeignKey('places.id', onupdate='CASCADE',
- ondelete='CASCADE'),
- primary_key=True),
- Column('amenity_id', String(60),
- ForeignKey('amenities.id', onupdate='CASCADE',
- ondelete='CASCADE'),
- primary_key=True))
+ Column('place_id',
+ String(60),
+ ForeignKey('places.id')),
+ Column('amenity_id',
+ String(60),
+ ForeignKey('amenities.id',
+ ondelete="CASCADE")))
class Place(BaseModel, Base):
- """Representation of Place """
- if models.storage_t == 'db':
+ """Place class handles all application places"""
+ if storage_type == "db":
__tablename__ = 'places'
city_id = Column(String(60), ForeignKey('cities.id'), nullable=False)
user_id = Column(String(60), ForeignKey('users.id'), nullable=False)
@@ -33,15 +37,15 @@ class Place(BaseModel, Base):
price_by_night = Column(Integer, nullable=False, default=0)
latitude = Column(Float, nullable=True)
longitude = Column(Float, nullable=True)
- reviews = relationship("Review", backref="place")
- amenities = relationship("Amenity", secondary="place_amenity",
- backref="place_amenities",
+
+ amenities = relationship('Amenity', secondary="place_amenity",
viewonly=False)
+ reviews = relationship('Review', backref='place', cascade='delete')
else:
- city_id = ""
- user_id = ""
- name = ""
- description = ""
+ city_id = ''
+ user_id = ''
+ name = ''
+ description = ''
number_rooms = 0
number_bathrooms = 0
max_guest = 0
@@ -50,29 +54,39 @@ class Place(BaseModel, Base):
longitude = 0.0
amenity_ids = []
- def __init__(self, *args, **kwargs):
- """initializes Place"""
- super().__init__(*args, **kwargs)
+ if storage_type != "db":
+ @property
+ def amenities(self):
+ """
+ ammenities getter
+ :return: list of amenitites
+ """
+ amenity_objs = []
+
+ for a_id in self.amenity_ids:
+ amenity_objs.append(models.storage.get("Amenity", str(a_id)))
+
+ return amenity_objs
+
+ @amenities.setter
+ def amenities(self, amenity):
+ """
+ ammenities setter
+ :return:
+ """
+ self.amenity_ids.append(amenity.id)
- if models.storage_t != 'db':
@property
def reviews(self):
- """getter attribute returns the list of Review instances"""
- from models.review import Review
- review_list = []
- all_reviews = models.storage.all(Review)
+ """
+ reviews getter
+ :return: list of reviews
+ """
+ all_reviews = models.storage.all("Review")
+ place_reviews = []
+
for review in all_reviews.values():
if review.place_id == self.id:
- review_list.append(review)
- return review_list
+ place_reviews.append(review)
- @property
- def amenities(self):
- """getter attribute returns the list of Amenity instances"""
- from models.amenity import Amenity
- amenity_list = []
- all_amenities = models.storage.all(Amenity)
- for amenity in all_amenities.values():
- if amenity.place_id == self.id:
- amenity_list.append(amenity)
- return amenity_list
+ return place_reviews
diff --git a/models/review.py b/models/review.py
index cd6c1d1ff98..82aad586fde 100755
--- a/models/review.py
+++ b/models/review.py
@@ -1,24 +1,21 @@
-#!/usr/bin/python
-""" holds class Review"""
-import models
+#!/usr/bin/python3
+"""
+Review Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String, ForeignKey
+from sqlalchemy import Column, Integer, String, Float, ForeignKey
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class Review(BaseModel, Base):
- """Representation of Review """
- if models.storage_t == 'db':
+ """Review class handles all application reviews"""
+ if storage_type == "db":
__tablename__ = 'reviews'
+ text = Column(String(1024), nullable=False)
place_id = Column(String(60), ForeignKey('places.id'), nullable=False)
user_id = Column(String(60), ForeignKey('users.id'), nullable=False)
- text = Column(String(1024), nullable=False)
else:
- place_id = ""
- user_id = ""
- text = ""
-
- def __init__(self, *args, **kwargs):
- """initializes Review"""
- super().__init__(*args, **kwargs)
+ place_id = ''
+ user_id = ''
+ text = ''
diff --git a/models/state.py b/models/state.py
index ca5c8961d80..9b1a2b1dc0d 100755
--- a/models/state.py
+++ b/models/state.py
@@ -1,34 +1,33 @@
#!/usr/bin/python3
-""" holds class State"""
-import models
+"""
+State Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from models.city import City
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String, ForeignKey
from sqlalchemy.orm import relationship
+from sqlalchemy import Column, Integer, String, Float
+import models
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class State(BaseModel, Base):
- """Representation of state """
- if models.storage_t == "db":
+ """State class handles all application states"""
+ if storage_type == "db":
__tablename__ = 'states'
name = Column(String(128), nullable=False)
- cities = relationship("City", backref="state")
+ cities = relationship('City', backref='state', cascade='delete')
else:
- name = ""
-
- def __init__(self, *args, **kwargs):
- """initializes state"""
- super().__init__(*args, **kwargs)
+ name = ''
- if models.storage_t != "db":
+ if storage_type != 'db':
@property
def cities(self):
- """getter for list of city instances related to the state"""
+ """
+ getter method, returns list of City objs from storage
+ linked to the current State
+ """
city_list = []
- all_cities = models.storage.all(City)
- for city in all_cities.values():
+ for city in models.storage.all("City").values():
if city.state_id == self.id:
city_list.append(city)
return city_list
diff --git a/models/user.py b/models/user.py
index 36b1b70b994..3f609f583e5 100755
--- a/models/user.py
+++ b/models/user.py
@@ -1,29 +1,51 @@
#!/usr/bin/python3
-""" holds class User"""
-import models
+"""
+User Class from Models Module
+"""
+import os
from models.base_model import BaseModel, Base
-from os import getenv
-import sqlalchemy
-from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
+from sqlalchemy import Column, Integer, String, Float
+from hashlib import md5
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class User(BaseModel, Base):
- """Representation of a user """
- if models.storage_t == 'db':
+ """User class handles all application users"""
+ if storage_type == "db":
__tablename__ = 'users'
email = Column(String(128), nullable=False)
- password = Column(String(128), nullable=False)
+ password = Column("password", String(128), nullable=False)
first_name = Column(String(128), nullable=True)
last_name = Column(String(128), nullable=True)
- places = relationship("Place", backref="user")
- reviews = relationship("Review", backref="user")
+
+ places = relationship('Place', backref='user', cascade='delete')
+ reviews = relationship('Review', backref='user', cascade='delete')
else:
- email = ""
- password = ""
- first_name = ""
- last_name = ""
+ email = ''
+ password = ''
+ first_name = ''
+ last_name = ''
def __init__(self, *args, **kwargs):
- """initializes user"""
+ """
+ initialize User Model, inherits from BaseModel
+ """
super().__init__(*args, **kwargs)
+
+ @property
+ def password(self):
+ """
+ getter for password
+ :return: password (hashed)
+ """
+ return self.__dict__.get("password")
+
+ @password.setter
+ def password(self, password):
+ """
+ Password setter, with md5 hasing
+ :param password: password
+ :return: nothing
+ """
+ self.__dict__["password"] = md5(password.encode('utf-8')).hexdigest()
diff --git a/setup_mysql_dev.sql b/setup_mysql_dev.sql
index 30fc4cd108d..3cac5735daf 100644
--- a/setup_mysql_dev.sql
+++ b/setup_mysql_dev.sql
@@ -1,7 +1,7 @@
--- prepares a MySQL server for the project
-
+-- Creates database hbnb_dev_db
CREATE DATABASE IF NOT EXISTS hbnb_dev_db;
-CREATE USER IF NOT EXISTS 'hbnb_dev'@'localhost' IDENTIFIED BY 'hbnb_dev_pwd';
-GRANT ALL PRIVILEGES ON `hbnb_dev_db`.* TO 'hbnb_dev'@'localhost';
-GRANT SELECT ON `performance_schema`.* TO 'hbnb_dev'@'localhost';
-FLUSH PRIVILEGES;
+USE hbnb_dev_db;
+CREATE USER IF NOT EXISTS 'hbnb_dev'@'localhost';
+SET PASSWORD FOR 'hbnb_dev'@'localhost' = 'hbnb_dev_pwd';
+GRANT ALL PRIVILEGES ON hbnb_dev_db.* TO 'hbnb_dev'@'localhost';
+GRANT SELECT ON performance_schema.* TO 'hbnb_dev'@'localhost';
diff --git a/setup_mysql_test.sql b/setup_mysql_test.sql
index ddb44205f78..1e09ea595d6 100644
--- a/setup_mysql_test.sql
+++ b/setup_mysql_test.sql
@@ -1,7 +1,7 @@
--- prepares a MySQL server for the project
-
+-- Creates database hbnb_test_db
CREATE DATABASE IF NOT EXISTS hbnb_test_db;
-CREATE USER IF NOT EXISTS 'hbnb_test'@'localhost' IDENTIFIED BY 'hbnb_test_pwd';
-GRANT ALL PRIVILEGES ON `hbnb_test_db`.* TO 'hbnb_test'@'localhost';
-GRANT SELECT ON `performance_schema`.* TO 'hbnb_test'@'localhost';
-FLUSH PRIVILEGES;
+USE hbnb_test_db;
+CREATE USER IF NOT EXISTS 'hbnb_test'@'localhost';
+SET PASSWORD FOR 'hbnb_test'@'localhost' = 'hbnb_test_pwd';
+GRANT ALL PRIVILEGES ON hbnb_test_db.* TO 'hbnb_test'@'localhost';
+GRANT SELECT ON performance_schema.* TO 'hbnb_test'@'localhost';
diff --git a/tests/__pycache__/__init__.cpython-38.pyc b/tests/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..97987ae84cf
Binary files /dev/null and b/tests/__pycache__/__init__.cpython-38.pyc differ
diff --git a/tests/__pycache__/test_console.cpython-312.pyc b/tests/__pycache__/test_console.cpython-312.pyc
new file mode 100644
index 00000000000..7573e3394db
Binary files /dev/null and b/tests/__pycache__/test_console.cpython-312.pyc differ
diff --git a/tests/__pycache__/test_console.cpython-313.pyc b/tests/__pycache__/test_console.cpython-313.pyc
new file mode 100644
index 00000000000..9e3432273b1
Binary files /dev/null and b/tests/__pycache__/test_console.cpython-313.pyc differ
diff --git a/tests/__pycache__/test_console.cpython-38.pyc b/tests/__pycache__/test_console.cpython-38.pyc
new file mode 100644
index 00000000000..8fac61516e3
Binary files /dev/null and b/tests/__pycache__/test_console.cpython-38.pyc differ
diff --git a/tests/test_console.py b/tests/test_console.py
index 015e5c46886..51cf653d3f9 100755
--- a/tests/test_console.py
+++ b/tests/test_console.py
@@ -1,41 +1,36 @@
#!/usr/bin/python3
"""
-Contains the class TestConsoleDocs
+Unit Test for BaseModel Class
"""
-
-import console
-import inspect
-import pep8
import unittest
+from datetime import datetime
+import console
+import json
+
HBNBCommand = console.HBNBCommand
-class TestConsoleDocs(unittest.TestCase):
- """Class for testing documentation of the console"""
- def test_pep8_conformance_console(self):
- """Test that console.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['console.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
+class TestHBNBCommandDocs(unittest.TestCase):
+ """Class for testing BaseModel docs"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('....... For the Console .......')
+ print('.................................\n\n')
- def test_pep8_conformance_test_console(self):
- """Test that tests/test_console.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_console.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nCommand interpreter for Holberton AirBnB project\n'
+ actual = console.__doc__
+ self.assertEqual(expected, actual)
- def test_console_module_docstring(self):
- """Test for the console.py module docstring"""
- self.assertIsNot(console.__doc__, None,
- "console.py needs a docstring")
- self.assertTrue(len(console.__doc__) >= 1,
- "console.py needs a docstring")
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = '\n Command inerpreter class\n '
+ actual = HBNBCommand.__doc__
+ self.assertEqual(expected, actual)
- def test_HBNBCommand_class_docstring(self):
- """Test for the HBNBCommand class docstring"""
- self.assertIsNot(HBNBCommand.__doc__, None,
- "HBNBCommand class needs a docstring")
- self.assertTrue(len(HBNBCommand.__doc__) >= 1,
- "HBNBCommand class needs a docstring")
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/__pycache__/__init__.cpython-312.pyc b/tests/test_models/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 00000000000..05ee3c18575
Binary files /dev/null and b/tests/test_models/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/__init__.cpython-313.pyc b/tests/test_models/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 00000000000..04a1f4850f9
Binary files /dev/null and b/tests/test_models/__pycache__/__init__.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/__init__.cpython-38.pyc b/tests/test_models/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..566753d3ac7
Binary files /dev/null and b/tests/test_models/__pycache__/__init__.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_amenity.cpython-312.pyc b/tests/test_models/__pycache__/test_amenity.cpython-312.pyc
new file mode 100644
index 00000000000..e6feeee2e75
Binary files /dev/null and b/tests/test_models/__pycache__/test_amenity.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_amenity.cpython-313.pyc b/tests/test_models/__pycache__/test_amenity.cpython-313.pyc
new file mode 100644
index 00000000000..e8fb095bcca
Binary files /dev/null and b/tests/test_models/__pycache__/test_amenity.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_amenity.cpython-38.pyc b/tests/test_models/__pycache__/test_amenity.cpython-38.pyc
new file mode 100644
index 00000000000..6d1ddc079c4
Binary files /dev/null and b/tests/test_models/__pycache__/test_amenity.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_base_model.cpython-312.pyc b/tests/test_models/__pycache__/test_base_model.cpython-312.pyc
new file mode 100644
index 00000000000..af32a1c0d1c
Binary files /dev/null and b/tests/test_models/__pycache__/test_base_model.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_base_model.cpython-313.pyc b/tests/test_models/__pycache__/test_base_model.cpython-313.pyc
new file mode 100644
index 00000000000..57312b72e98
Binary files /dev/null and b/tests/test_models/__pycache__/test_base_model.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_base_model.cpython-38.pyc b/tests/test_models/__pycache__/test_base_model.cpython-38.pyc
new file mode 100644
index 00000000000..c45f50ed341
Binary files /dev/null and b/tests/test_models/__pycache__/test_base_model.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_city.cpython-312.pyc b/tests/test_models/__pycache__/test_city.cpython-312.pyc
new file mode 100644
index 00000000000..bb1d319793e
Binary files /dev/null and b/tests/test_models/__pycache__/test_city.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_city.cpython-313.pyc b/tests/test_models/__pycache__/test_city.cpython-313.pyc
new file mode 100644
index 00000000000..e44ff2b606a
Binary files /dev/null and b/tests/test_models/__pycache__/test_city.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_city.cpython-38.pyc b/tests/test_models/__pycache__/test_city.cpython-38.pyc
new file mode 100644
index 00000000000..9e25947a1c6
Binary files /dev/null and b/tests/test_models/__pycache__/test_city.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_place.cpython-312.pyc b/tests/test_models/__pycache__/test_place.cpython-312.pyc
new file mode 100644
index 00000000000..0c4a48a9316
Binary files /dev/null and b/tests/test_models/__pycache__/test_place.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_place.cpython-313.pyc b/tests/test_models/__pycache__/test_place.cpython-313.pyc
new file mode 100644
index 00000000000..88b85b7a151
Binary files /dev/null and b/tests/test_models/__pycache__/test_place.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_place.cpython-38.pyc b/tests/test_models/__pycache__/test_place.cpython-38.pyc
new file mode 100644
index 00000000000..1f31f90b7ab
Binary files /dev/null and b/tests/test_models/__pycache__/test_place.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_review.cpython-312.pyc b/tests/test_models/__pycache__/test_review.cpython-312.pyc
new file mode 100644
index 00000000000..c0b71567193
Binary files /dev/null and b/tests/test_models/__pycache__/test_review.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_review.cpython-313.pyc b/tests/test_models/__pycache__/test_review.cpython-313.pyc
new file mode 100644
index 00000000000..47f38b1422b
Binary files /dev/null and b/tests/test_models/__pycache__/test_review.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_review.cpython-38.pyc b/tests/test_models/__pycache__/test_review.cpython-38.pyc
new file mode 100644
index 00000000000..f0acc5c3a47
Binary files /dev/null and b/tests/test_models/__pycache__/test_review.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_state.cpython-312.pyc b/tests/test_models/__pycache__/test_state.cpython-312.pyc
new file mode 100644
index 00000000000..3daf650d655
Binary files /dev/null and b/tests/test_models/__pycache__/test_state.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_state.cpython-313.pyc b/tests/test_models/__pycache__/test_state.cpython-313.pyc
new file mode 100644
index 00000000000..57b872788d5
Binary files /dev/null and b/tests/test_models/__pycache__/test_state.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_state.cpython-38.pyc b/tests/test_models/__pycache__/test_state.cpython-38.pyc
new file mode 100644
index 00000000000..dbab50e48c8
Binary files /dev/null and b/tests/test_models/__pycache__/test_state.cpython-38.pyc differ
diff --git a/tests/test_models/__pycache__/test_user.cpython-312.pyc b/tests/test_models/__pycache__/test_user.cpython-312.pyc
new file mode 100644
index 00000000000..9618f770d6b
Binary files /dev/null and b/tests/test_models/__pycache__/test_user.cpython-312.pyc differ
diff --git a/tests/test_models/__pycache__/test_user.cpython-313.pyc b/tests/test_models/__pycache__/test_user.cpython-313.pyc
new file mode 100644
index 00000000000..62fc45da394
Binary files /dev/null and b/tests/test_models/__pycache__/test_user.cpython-313.pyc differ
diff --git a/tests/test_models/__pycache__/test_user.cpython-38.pyc b/tests/test_models/__pycache__/test_user.cpython-38.pyc
new file mode 100644
index 00000000000..7c0bcedaed2
Binary files /dev/null and b/tests/test_models/__pycache__/test_user.cpython-38.pyc differ
diff --git a/tests/test_models/test_amenity.py b/tests/test_models/test_amenity.py
index 66b0bb69bc2..40fd456895a 100755
--- a/tests/test_models/test_amenity.py
+++ b/tests/test_models/test_amenity.py
@@ -1,106 +1,117 @@
#!/usr/bin/python3
"""
-Contains the TestAmenityDocs classes
+Unit Test for Amenity Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import amenity
-from models.base_model import BaseModel
-import pep8
-import unittest
-Amenity = amenity.Amenity
+import json
+import os
+
+Amenity = models.amenity.Amenity
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestAmenityDocs(unittest.TestCase):
- """Tests to check the documentation and style of Amenity class"""
+ """Class for testing BaseModel docs"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.amenity_f = inspect.getmembers(Amenity, inspect.isfunction)
-
- def test_pep8_conformance_amenity(self):
- """Test that models/amenity.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/amenity.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_amenity(self):
- """Test that tests/test_models/test_amenity.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_amenity.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_amenity_module_docstring(self):
- """Test for the amenity.py module docstring"""
- self.assertIsNot(amenity.__doc__, None,
- "amenity.py needs a docstring")
- self.assertTrue(len(amenity.__doc__) >= 1,
- "amenity.py needs a docstring")
-
- def test_amenity_class_docstring(self):
- """Test for the Amenity class docstring"""
- self.assertIsNot(Amenity.__doc__, None,
- "Amenity class needs a docstring")
- self.assertTrue(len(Amenity.__doc__) >= 1,
- "Amenity class needs a docstring")
-
- def test_amenity_func_docstrings(self):
- """Test for the presence of docstrings in Amenity methods"""
- for func in self.amenity_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestAmenity(unittest.TestCase):
- """Test the Amenity class"""
- def test_is_subclass(self):
- """Test that Amenity is a subclass of BaseModel"""
- amenity = Amenity()
- self.assertIsInstance(amenity, BaseModel)
- self.assertTrue(hasattr(amenity, "id"))
- self.assertTrue(hasattr(amenity, "created_at"))
- self.assertTrue(hasattr(amenity, "updated_at"))
-
- def test_name_attr(self):
- """Test that Amenity has attribute name, and it's as an empty string"""
- amenity = Amenity()
- self.assertTrue(hasattr(amenity, "name"))
- if models.storage_t == 'db':
- self.assertEqual(amenity.name, None)
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('........ Amenity Class ........')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nAmenity Class from Models Module\n'
+ actual = models.amenity.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'Amenity class handles all application amenities'
+ actual = Amenity.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestAmenityInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('......... Amenity Class .........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new amenity for testing"""
+ self.amenity = Amenity()
+
+ def test_instantiation(self):
+ """... checks if Amenity is properly instantiated"""
+ self.assertIsInstance(self.amenity, Amenity)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.amenity)
+ my_list = ['Amenity', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ my_str = str(self.amenity)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.amenity.save()
+ actual = type(self.amenity.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.amenity_json = self.amenity.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.amenity_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value Amenity"""
+ self.amenity_json = self.amenity.to_json()
+ actual = None
+ if self.amenity_json['__class__']:
+ actual = self.amenity_json['__class__']
+ expected = 'Amenity'
+ self.assertEqual(expected, actual)
+
+ def test_amenity_attribute(self):
+ """... add amenity attribute"""
+ self.amenity.name = "greatWifi"
+ if hasattr(self.amenity, 'name'):
+ actual = self.amenity.name
else:
- self.assertEqual(amenity.name, "")
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- am = Amenity()
- print(am.__dict__)
- new_d = am.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in am.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- am = Amenity()
- new_d = am.to_dict()
- self.assertEqual(new_d["__class__"], "Amenity")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], am.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], am.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- amenity = Amenity()
- string = "[Amenity] ({}) {}".format(amenity.id, amenity.__dict__)
- self.assertEqual(string, str(amenity))
+ actual = ''
+ expected = "greatWifi"
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_base_model.py b/tests/test_models/test_base_model.py
old mode 100644
new mode 100755
index 231dab48ccd..bfb975df237
--- a/tests/test_models/test_base_model.py
+++ b/tests/test_models/test_base_model.py
@@ -1,160 +1,148 @@
#!/usr/bin/python3
-"""Test BaseModel for expected behavior and documentation"""
+"""
+Unit Test for BaseModel Class
+"""
+import unittest
from datetime import datetime
-import inspect
import models
-import pep8 as pycodestyle
-import time
-import unittest
-from unittest import mock
+import json
+import os
+
BaseModel = models.base_model.BaseModel
-module_doc = models.base_model.__doc__
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestBaseModelDocs(unittest.TestCase):
- """Tests to check the documentation and style of BaseModel class"""
+ """Class for testing BaseModel docs"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('..... For BaseModel Class .....')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nBaseModel Class of Models Module\n'
+ actual = models.base_model.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_init(self):
+ """... documentation for init function"""
+ expected = 'instantiation of new BaseModel Class'
+ actual = BaseModel.__init__.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_save(self):
+ """... documentation for save function"""
+ expected = 'updates attribute updated_at to current time'
+ actual = BaseModel.save.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_to_json(self):
+ """... documentation for to_json function"""
+ expected = 'returns json representation of self'
+ actual = BaseModel.to_json.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_str(self):
+ """... documentation for to str function"""
+ expected = 'returns string type representation of object instance'
+ actual = BaseModel.__str__.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestBaseModelInstances(unittest.TestCase):
+ """testing for class instances"""
@classmethod
- def setUpClass(self):
- """Set up for docstring tests"""
- self.base_funcs = inspect.getmembers(BaseModel, inspect.isfunction)
-
- def test_pep8_conformance(self):
- """Test that models/base_model.py conforms to PEP8."""
- for path in ['models/base_model.py',
- 'tests/test_models/test_base_model.py']:
- with self.subTest(path=path):
- errors = pycodestyle.Checker(path).check_all()
- self.assertEqual(errors, 0)
-
- def test_module_docstring(self):
- """Test for the existence of module docstring"""
- self.assertIsNot(module_doc, None,
- "base_model.py needs a docstring")
- self.assertTrue(len(module_doc) > 1,
- "base_model.py needs a docstring")
-
- def test_class_docstring(self):
- """Test for the BaseModel class docstring"""
- self.assertIsNot(BaseModel.__doc__, None,
- "BaseModel class needs a docstring")
- self.assertTrue(len(BaseModel.__doc__) >= 1,
- "BaseModel class needs a docstring")
-
- def test_func_docstrings(self):
- """Test for the presence of docstrings in BaseModel methods"""
- for func in self.base_funcs:
- with self.subTest(function=func):
- self.assertIsNot(
- func[1].__doc__,
- None,
- "{:s} method needs a docstring".format(func[0])
- )
- self.assertTrue(
- len(func[1].__doc__) > 1,
- "{:s} method needs a docstring".format(func[0])
- )
-
-
-class TestBaseModel(unittest.TestCase):
- """Test the BaseModel class"""
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('..... For BaseModel Class .....')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new BaseModel instance for testing"""
+ self.model = BaseModel()
+
def test_instantiation(self):
- """Test that object is correctly created"""
- inst = BaseModel()
- self.assertIs(type(inst), BaseModel)
- inst.name = "Holberton"
- inst.number = 89
- attrs_types = {
- "id": str,
- "created_at": datetime,
- "updated_at": datetime,
- "name": str,
- "number": int
- }
- for attr, typ in attrs_types.items():
- with self.subTest(attr=attr, typ=typ):
- self.assertIn(attr, inst.__dict__)
- self.assertIs(type(inst.__dict__[attr]), typ)
- self.assertEqual(inst.name, "Holberton")
- self.assertEqual(inst.number, 89)
-
- def test_datetime_attributes(self):
- """Test that two BaseModel instances have different datetime objects
- and that upon creation have identical updated_at and created_at
- value."""
- tic = datetime.now()
- inst1 = BaseModel()
- toc = datetime.now()
- self.assertTrue(tic <= inst1.created_at <= toc)
- time.sleep(1e-4)
- tic = datetime.now()
- inst2 = BaseModel()
- toc = datetime.now()
- self.assertTrue(tic <= inst2.created_at <= toc)
- self.assertEqual(inst1.created_at, inst1.updated_at)
- self.assertEqual(inst2.created_at, inst2.updated_at)
- self.assertNotEqual(inst1.created_at, inst2.created_at)
- self.assertNotEqual(inst1.updated_at, inst2.updated_at)
-
- def test_uuid(self):
- """Test that id is a valid uuid"""
- inst1 = BaseModel()
- inst2 = BaseModel()
- for inst in [inst1, inst2]:
- uuid = inst.id
- with self.subTest(uuid=uuid):
- self.assertIs(type(uuid), str)
- self.assertRegex(uuid,
- '^[0-9a-f]{8}-[0-9a-f]{4}'
- '-[0-9a-f]{4}-[0-9a-f]{4}'
- '-[0-9a-f]{12}$')
- self.assertNotEqual(inst1.id, inst2.id)
-
- def test_to_dict(self):
- """Test conversion of object attributes to dictionary for json"""
- my_model = BaseModel()
- my_model.name = "Holberton"
- my_model.my_number = 89
- d = my_model.to_dict()
- expected_attrs = ["id",
- "created_at",
- "updated_at",
- "name",
- "my_number",
- "__class__"]
- self.assertCountEqual(d.keys(), expected_attrs)
- self.assertEqual(d['__class__'], 'BaseModel')
- self.assertEqual(d['name'], "Holberton")
- self.assertEqual(d['my_number'], 89)
-
- 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"
- bm = BaseModel()
- new_d = bm.to_dict()
- self.assertEqual(new_d["__class__"], "BaseModel")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], bm.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], bm.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- inst = BaseModel()
- string = "[BaseModel] ({}) {}".format(inst.id, inst.__dict__)
- self.assertEqual(string, str(inst))
-
- @mock.patch('models.storage')
- def test_save(self, mock_storage):
- """Test that save method updates `updated_at` and calls
- `storage.save`"""
- inst = BaseModel()
- old_created_at = inst.created_at
- old_updated_at = inst.updated_at
- inst.save()
- new_created_at = inst.created_at
- new_updated_at = inst.updated_at
- self.assertNotEqual(old_updated_at, new_updated_at)
- self.assertEqual(old_created_at, new_created_at)
- self.assertTrue(mock_storage.new.called)
- self.assertTrue(mock_storage.save.called)
+ """... checks if BaseModel is properly instantiated"""
+ self.assertIsInstance(self.model, BaseModel)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.model)
+ my_list = ['BaseModel', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.model)
+ my_list = ['BaseModel', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ my_str = str(self.model)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_save(self):
+ """... save function should add updated_at attribute"""
+ self.model.save()
+ actual = type(self.model.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ my_model_json = self.model.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(my_model_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value BaseModel"""
+ my_model_json = self.model.to_json()
+ actual = None
+ if my_model_json['__class__']:
+ actual = my_model_json['__class__']
+ expected = 'BaseModel'
+ self.assertEqual(expected, actual)
+
+ def test_name_attribute(self):
+ """... add name attribute"""
+ self.model.name = "Holberton"
+ actual = self.model.name
+ expected = "Holberton"
+ self.assertEqual(expected, actual)
+
+ def test_number_attribute(self):
+ """... add number attribute"""
+ self.model.number = 98
+ actual = self.model.number
+ self.assertTrue(98 == actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_city.py b/tests/test_models/test_city.py
index 1ed666115b6..f6babcf4fbf 100755
--- a/tests/test_models/test_city.py
+++ b/tests/test_models/test_city.py
@@ -1,114 +1,118 @@
#!/usr/bin/python3
"""
-Contains the TestCityDocs classes
+Unit Test for City Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import city
-from models.base_model import BaseModel
-import pep8
-import unittest
-City = city.City
+import json
+import os
+
+City = models.city.City
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestCityDocs(unittest.TestCase):
- """Tests to check the documentation and style of City class"""
+ """Class for testing BaseModel docs"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.city_f = inspect.getmembers(City, inspect.isfunction)
-
- def test_pep8_conformance_city(self):
- """Test that models/city.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/city.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_city(self):
- """Test that tests/test_models/test_city.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_city.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_city_module_docstring(self):
- """Test for the city.py module docstring"""
- self.assertIsNot(city.__doc__, None,
- "city.py needs a docstring")
- self.assertTrue(len(city.__doc__) >= 1,
- "city.py needs a docstring")
-
- def test_city_class_docstring(self):
- """Test for the City class docstring"""
- self.assertIsNot(City.__doc__, None,
- "City class needs a docstring")
- self.assertTrue(len(City.__doc__) >= 1,
- "City class needs a docstring")
-
- def test_city_func_docstrings(self):
- """Test for the presence of docstrings in City methods"""
- for func in self.city_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestCity(unittest.TestCase):
- """Test the City class"""
- def test_is_subclass(self):
- """Test that City is a subclass of BaseModel"""
- city = City()
- self.assertIsInstance(city, BaseModel)
- self.assertTrue(hasattr(city, "id"))
- self.assertTrue(hasattr(city, "created_at"))
- self.assertTrue(hasattr(city, "updated_at"))
-
- def test_name_attr(self):
- """Test that City has attribute name, and it's an empty string"""
- city = City()
- self.assertTrue(hasattr(city, "name"))
- if models.storage_t == 'db':
- self.assertEqual(city.name, None)
- else:
- self.assertEqual(city.name, "")
-
- def test_state_id_attr(self):
- """Test that City has attribute state_id, and it's an empty string"""
- city = City()
- self.assertTrue(hasattr(city, "state_id"))
- if models.storage_t == 'db':
- self.assertEqual(city.state_id, None)
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('........ City Class ........')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nCity Class from Models Module\n'
+ actual = models.city.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'City class handles all application cities'
+ actual = City.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestCityInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('......... City Class .........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new city for testing"""
+ self.city = City()
+
+ def test_instantiation(self):
+ """... checks if City is properly instantiated"""
+ self.assertIsInstance(self.city, City)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.city)
+ my_list = ['City', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ self.city = City()
+ my_str = str(self.city)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.city.save()
+ actual = type(self.city.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.city_json = self.city.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.city_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value City"""
+ self.city_json = self.city.to_json()
+ actual = None
+ if self.city_json['__class__']:
+ actual = self.city_json['__class__']
+ expected = 'City'
+ self.assertEqual(expected, actual)
+
+ def test_state_attribute(self):
+ """... add state attribute"""
+ self.city.state_id = 'IL'
+ if hasattr(self.city, 'state_id'):
+ actual = self.city.state_id
else:
- self.assertEqual(city.state_id, "")
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- c = City()
- new_d = c.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in c.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- c = City()
- new_d = c.to_dict()
- self.assertEqual(new_d["__class__"], "City")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], c.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], c.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- city = City()
- string = "[City] ({}) {}".format(city.id, city.__dict__)
- self.assertEqual(string, str(city))
+ actual = ''
+ expected = 'IL'
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_engine/__pycache__/__init__.cpython-312.pyc b/tests/test_models/test_engine/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 00000000000..c347d635848
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/__init__.cpython-313.pyc b/tests/test_models/test_engine/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 00000000000..ca922928ca3
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/__init__.cpython-313.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/__init__.cpython-38.pyc b/tests/test_models/test_engine/__pycache__/__init__.cpython-38.pyc
new file mode 100644
index 00000000000..bdc2fe3b98e
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/__init__.cpython-38.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-312.pyc b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-312.pyc
new file mode 100644
index 00000000000..7d5f4155f8f
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-312.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-313.pyc b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-313.pyc
new file mode 100644
index 00000000000..e6a307b85c8
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-313.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-38.pyc b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-38.pyc
new file mode 100644
index 00000000000..95e8ac4ce36
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_db_storage.cpython-38.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-312.pyc b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-312.pyc
new file mode 100644
index 00000000000..cc5bf6bb3f2
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-312.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-313.pyc b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-313.pyc
new file mode 100644
index 00000000000..7459b763339
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-313.pyc differ
diff --git a/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-38.pyc b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-38.pyc
new file mode 100644
index 00000000000..6fd9466a3f1
Binary files /dev/null and b/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-38.pyc differ
diff --git a/tests/test_models/test_engine/test_db_storage.py b/tests/test_models/test_engine/test_db_storage.py
index 766e625b5af..fd2b3be499d 100755
--- a/tests/test_models/test_engine/test_db_storage.py
+++ b/tests/test_models/test_engine/test_db_storage.py
@@ -1,88 +1,412 @@
#!/usr/bin/python3
"""
-Contains the TestDBStorageDocs and TestDBStorage classes
+Unit Test for BaseModel Class
"""
-
+import unittest
from datetime import datetime
-import inspect
-import models
-from models.engine import db_storage
-from models.amenity import Amenity
-from models.base_model import BaseModel
-from models.city import City
-from models.place import Place
-from models.review import Review
-from models.state import State
-from models.user import User
-import json
+from models import *
import os
-import pep8
-import unittest
-DBStorage = db_storage.DBStorage
-classes = {"Amenity": Amenity, "City": City, "Place": Place,
- "Review": Review, "State": State, "User": User}
+from models.base_model import Base
+from models.engine.db_storage import DBStorage
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
class TestDBStorageDocs(unittest.TestCase):
- """Tests to check the documentation and style of DBStorage class"""
+ """Class for testing BaseModel docs"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('..... For FileStorage Class .....')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = ' Database engine '
+ actual = db_storage.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'handles long term storage of all class instances'
+ actual = DBStorage.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_all(self):
+ """... documentation for all function"""
+ expected = ' returns a dictionary of all objects '
+ actual = DBStorage.all.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_new(self):
+ """... documentation for new function"""
+ expected = ' adds objects to current database session '
+ actual = DBStorage.new.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_save(self):
+ """... documentation for save function"""
+ expected = ' commits all changes of current database session '
+ actual = DBStorage.save.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_reload(self):
+ """... documentation for reload function"""
+ expected = ' creates all tables in database & session from engine '
+ actual = DBStorage.reload.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_delete(self):
+ """... documentation for delete function"""
+ expected = ' deletes obj from current database session if not None '
+ actual = DBStorage.delete.__doc__
+ self.assertEqual(expected, actual)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestStateDBInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('......... Testing DBStorage .;.......')
+ print('........ For State Class ........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new BaseModel object for testing"""
+ self.state = State()
+ self.state.name = 'California'
+ self.state.save()
+
+ def test_state_all(self):
+ """... checks if all() function returns newly created instance"""
+ all_objs = storage.all()
+ all_state_objs = storage.all('State')
+
+ exist_in_all = False
+ for k in all_objs.keys():
+ if self.state.id in k:
+ exist_in_all = True
+ exist_in_all_states = False
+ for k in all_state_objs.keys():
+ if self.state.id in k:
+ exist_in_all_states = True
+
+ self.assertTrue(exist_in_all)
+ self.assertTrue(exist_in_all_states)
+
+ def test_state_delete(self):
+ state_id = self.state.id
+ storage.delete(self.state)
+ self.state = None
+ storage.save()
+ exist_in_all = False
+ for k in storage.all().keys():
+ if state_id in k:
+ exist_in_all = True
+ self.assertFalse(exist_in_all)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestUserDBInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('...... Testing FileStorage ......')
+ print('.......... User Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.user = User()
+ self.user.email = 'test'
+ self.user.password = 'test'
+ self.user.save()
+
+ def test_user_all(self):
+ """... checks if all() function returns newly created instance"""
+ all_objs = storage.all()
+ all_user_objs = storage.all('User')
+
+ exist_in_all = False
+ for k in all_objs.keys():
+ if self.user.id in k:
+ exist_in_all = True
+ exist_in_all_users = False
+ for k in all_user_objs.keys():
+ if self.user.id in k:
+ exist_in_all_users = True
+
+ self.assertTrue(exist_in_all)
+ self.assertTrue(exist_in_all_users)
+
+ def test_user_delete(self):
+ user_id = self.user.id
+ storage.delete(self.user)
+ self.user = None
+ storage.save()
+ exist_in_all = False
+ for k in storage.all().keys():
+ if user_id in k:
+ exist_in_all = True
+ self.assertFalse(exist_in_all)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestCityDBInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('...... Testing DBStorage ......')
+ print('.......... City Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.state = State()
+ self.state.name = 'California'
+ self.state.save()
+ self.city = City()
+ self.city.name = 'Fremont'
+ self.city.state_id = self.state.id
+ self.city.save()
+
+ def test_city_all(self):
+ """... checks if all() function returns newly created instance"""
+ all_objs = storage.all()
+ all_city_objs = storage.all('City')
+
+ exist_in_all = False
+ for k in all_objs.keys():
+ if self.city.id in k:
+ exist_in_all = True
+ exist_in_all_city = False
+ for k in all_city_objs.keys():
+ if self.city.id in k:
+ exist_in_all_city = True
+
+ self.assertTrue(exist_in_all)
+ self.assertTrue(exist_in_all_city)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestCityDBInstancesUnderscore(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('...... Testing FileStorage ......')
+ print('.......... City Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.state = State()
+ self.state.name = 'California'
+ self.state.save()
+ self.city = City()
+ self.city.name = 'San_Francisco'
+ self.city.state_id = self.state.id
+ self.city.save()
+
+ def test_city_underscore_all(self):
+ """... checks if all() function returns newly created instance"""
+ all_objs = storage.all()
+ all_city_objs = storage.all('City')
+
+ exist_in_all = False
+ for k in all_objs.keys():
+ if self.city.id in k:
+ exist_in_all = True
+ exist_in_all_city = False
+ for k in all_city_objs.keys():
+ if self.city.id in k:
+ exist_in_all_city = True
+
+ self.assertTrue(exist_in_all)
+ self.assertTrue(exist_in_all_city)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestPlaceDBInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('...... Testing DBStorage ......')
+ print('.......... Place Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.user = User()
+ self.user.email = 'test'
+ self.user.password = 'test'
+ self.user.save()
+ self.state = State()
+ self.state.name = 'California'
+ self.state.save()
+ self.city = City()
+ self.city.name = 'San_Mateo'
+ self.city.state_id = self.state.id
+ self.city.save()
+ self.place = Place()
+ self.place.city_id = self.city.id
+ self.place.user_id = self.user.id
+ self.place.name = 'test_place'
+ self.place.description = 'test_description'
+ self.place.number_rooms = 2
+ self.place.number_bathrooms = 1
+ self.place.max_guest = 4
+ self.place.price_by_night = 100
+ self.place.latitude = 120.12
+ self.place.longitude = 101.4
+ self.place.save()
+
+ def test_place_all(self):
+ """... checks if all() function returns newly created instance"""
+ all_objs = storage.all()
+ all_place_objs = storage.all('Place')
+
+ exist_in_all = False
+ for k in all_objs.keys():
+ if self.place.id in k:
+ exist_in_all = True
+ exist_in_all_place = False
+ for k in all_place_objs.keys():
+ if self.place.id in k:
+ exist_in_all_place = True
+
+ self.assertTrue(exist_in_all)
+ self.assertTrue(exist_in_all_place)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestStorageGet(unittest.TestCase):
+ """
+ Testing `get()` method in DBStorage
+ """
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.dbs_f = inspect.getmembers(DBStorage, inspect.isfunction)
-
- def test_pep8_conformance_db_storage(self):
- """Test that models/engine/db_storage.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/engine/db_storage.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_db_storage(self):
- """Test tests/test_models/test_db_storage.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_engine/\
-test_db_storage.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_db_storage_module_docstring(self):
- """Test for the db_storage.py module docstring"""
- self.assertIsNot(db_storage.__doc__, None,
- "db_storage.py needs a docstring")
- self.assertTrue(len(db_storage.__doc__) >= 1,
- "db_storage.py needs a docstring")
-
- def test_db_storage_class_docstring(self):
- """Test for the DBStorage class docstring"""
- self.assertIsNot(DBStorage.__doc__, None,
- "DBStorage class needs a docstring")
- self.assertTrue(len(DBStorage.__doc__) >= 1,
- "DBStorage class needs a docstring")
-
- def test_dbs_func_docstrings(self):
- """Test for the presence of docstrings in DBStorage methods"""
- for func in self.dbs_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestFileStorage(unittest.TestCase):
- """Test the FileStorage class"""
- @unittest.skipIf(models.storage_t != 'db', "not testing db storage")
- def test_all_returns_dict(self):
- """Test that all returns a dictionaty"""
- self.assertIs(type(models.storage.all()), dict)
-
- @unittest.skipIf(models.storage_t != 'db', "not testing db storage")
- def test_all_no_class(self):
- """Test that all returns all rows when no class is passed"""
-
- @unittest.skipIf(models.storage_t != 'db', "not testing db storage")
- def test_new(self):
- """test that new adds an object to the database"""
-
- @unittest.skipIf(models.storage_t != 'db', "not testing db storage")
- def test_save(self):
- """Test that save properly saves objects to file.json"""
+ """
+ setup tests for class
+ """
+ print('\n\n.................................')
+ print('...... Testing Get() Method ......')
+ print('.......... Place Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """
+ setup method
+ """
+ self.state = State(name="Florida")
+ self.state.save()
+
+ def test_get_method_obj(self):
+ """
+ testing get() method
+ :return: True if pass, False if not pass
+ """
+ result = storage.get(cls="State", id=self.state.id)
+
+ self.assertIsInstance(result, State)
+
+ def test_get_method_return(self):
+ """
+ testing get() method for id match
+ :return: True if pass, false if not pass
+ """
+ result = storage.get(cls="State", id=str(self.state.id))
+
+ self.assertEqual(self.state.id, result.id)
+
+ def test_get_method_none(self):
+ """
+ testing get() method for None return
+ :return: True if pass, false if not pass
+ """
+ result = storage.get(cls="State", id="doesnotexist")
+
+ self.assertIsNone(result)
+
+
+@unittest.skipIf(storage_type != 'db', 'skip if environ is not db')
+class TestStorageCount(unittest.TestCase):
+ """
+ tests count() method in DBStorage
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ setup tests for class
+ """
+ print('\n\n.................................')
+ print('...... Testing Get() Method ......')
+ print('.......... Place Class ..........')
+ print('.................................\n\n')
+
+ def setup(self):
+ """
+ setup method
+ """
+ self.state1 = State(name="California")
+ self.state1.save()
+ self.state2 = State(name="Colorado")
+ self.state2.save()
+ self.state3 = State(name="Wyoming")
+ self.state3.save()
+ self.state4 = State(name="Virgina")
+ self.state4.save()
+ self.state5 = State(name="Oregon")
+ self.state5.save()
+ self.state6 = State(name="New_York")
+ self.state6.save()
+ self.state7 = State(name="Ohio")
+ self.state7.save()
+
+ def test_count_all(self):
+ """
+ testing counting all instances
+ :return: True if pass, false if not pass
+ """
+ result = storage.count()
+
+ self.assertEqual(len(storage.all()), result)
+
+ def test_count_state(self):
+ """
+ testing counting state instances
+ :return: True if pass, false if not pass
+ """
+ result = storage.count(cls="State")
+
+ self.assertEqual(len(storage.all("State")), result)
+
+ def test_count_city(self):
+ """
+ testing counting non existent
+ :return: True if pass, false if not pass
+ """
+ result = storage.count(cls="City")
+
+ self.assertEqual(int(0 if len(storage.all("City")) is None else
+ len(storage.all("City"))), result)
+
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_engine/test_file_storage.py b/tests/test_models/test_engine/test_file_storage.py
index 1474a34fec0..7470e0e2c54 100755
--- a/tests/test_models/test_engine/test_file_storage.py
+++ b/tests/test_models/test_engine/test_file_storage.py
@@ -1,115 +1,315 @@
#!/usr/bin/python3
"""
-Contains the TestFileStorageDocs classes
+Unit Test for BaseModel Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models.engine import file_storage
-from models.amenity import Amenity
-from models.base_model import BaseModel
-from models.city import City
-from models.place import Place
-from models.review import Review
-from models.state import State
-from models.user import User
+from models import engine
+from models.engine.file_storage import FileStorage
import json
import os
-import pep8
-import unittest
-FileStorage = file_storage.FileStorage
-classes = {"Amenity": Amenity, "BaseModel": BaseModel, "City": City,
- "Place": Place, "Review": Review, "State": State, "User": User}
+
+User = models.user.User
+BaseModel = models.base_model.BaseModel
+FileStorage = engine.file_storage.FileStorage
+storage = models.storage
+F = './dev/file.json'
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
+@unittest.skipIf(storage_type == 'db', 'skip if environ is db')
class TestFileStorageDocs(unittest.TestCase):
- """Tests to check the documentation and style of FileStorage class"""
+ """Class for testing BaseModel docs"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('..... For FileStorage Class .....')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = ("\nHandles I/O, writing and reading, of JSON for storage "
+ "of all class instances\n")
+ actual = models.file_storage.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'handles long term storage of all class instances'
+ actual = FileStorage.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_all(self):
+ """... documentation for all function"""
+ expected = 'returns private attribute: __objects'
+ actual = FileStorage.all.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_new(self):
+ """... documentation for new function"""
+ expected = ("sets / updates in __objects the obj with key .id")
+ actual = FileStorage.new.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_save(self):
+ """... documentation for save function"""
+ expected = 'serializes __objects to the JSON file (path: __file_path)'
+ actual = FileStorage.save.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_reload(self):
+ """... documentation for reload function"""
+ expected = ("if file exists, deserializes JSON file to __objects, "
+ "else nothing")
+ actual = FileStorage.reload.__doc__
+ self.assertEqual(expected, actual)
+
+
+@unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+class TestBmFsInstances(unittest.TestCase):
+ """testing for class instances"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.fs_f = inspect.getmembers(FileStorage, inspect.isfunction)
-
- def test_pep8_conformance_file_storage(self):
- """Test that models/engine/file_storage.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/engine/file_storage.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_file_storage(self):
- """Test tests/test_models/test_file_storage.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_engine/\
-test_file_storage.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_file_storage_module_docstring(self):
- """Test for the file_storage.py module docstring"""
- self.assertIsNot(file_storage.__doc__, None,
- "file_storage.py needs a docstring")
- self.assertTrue(len(file_storage.__doc__) >= 1,
- "file_storage.py needs a docstring")
-
- def test_file_storage_class_docstring(self):
- """Test for the FileStorage class docstring"""
- self.assertIsNot(FileStorage.__doc__, None,
- "FileStorage class needs a docstring")
- self.assertTrue(len(FileStorage.__doc__) >= 1,
- "FileStorage class needs a docstring")
-
- def test_fs_func_docstrings(self):
- """Test for the presence of docstrings in FileStorage methods"""
- for func in self.fs_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestFileStorage(unittest.TestCase):
- """Test the FileStorage class"""
- @unittest.skipIf(models.storage_t == 'db', "not testing file storage")
- def test_all_returns_dict(self):
- """Test that all returns the FileStorage.__objects attr"""
- storage = FileStorage()
- new_dict = storage.all()
- self.assertEqual(type(new_dict), dict)
- self.assertIs(new_dict, storage._FileStorage__objects)
-
- @unittest.skipIf(models.storage_t == 'db', "not testing file storage")
- def test_new(self):
- """test that new adds an object to the FileStorage.__objects attr"""
- storage = FileStorage()
- save = FileStorage._FileStorage__objects
- FileStorage._FileStorage__objects = {}
- test_dict = {}
- for key, value in classes.items():
- with self.subTest(key=key, value=value):
- instance = value()
- instance_key = instance.__class__.__name__ + "." + instance.id
- storage.new(instance)
- test_dict[instance_key] = instance
- self.assertEqual(test_dict, storage._FileStorage__objects)
- FileStorage._FileStorage__objects = save
-
- @unittest.skipIf(models.storage_t == 'db', "not testing file storage")
- def test_save(self):
- """Test that save properly saves objects to file.json"""
- storage = FileStorage()
- new_dict = {}
- for key, value in classes.items():
- instance = value()
- instance_key = instance.__class__.__name__ + "." + instance.id
- new_dict[instance_key] = instance
- save = FileStorage._FileStorage__objects
- FileStorage._FileStorage__objects = new_dict
- storage.save()
- FileStorage._FileStorage__objects = save
- for key, value in new_dict.items():
- new_dict[key] = value.to_dict()
- string = json.dumps(new_dict)
- with open("file.json", "r") as f:
- js = f.read()
- self.assertEqual(json.loads(string), json.loads(js))
+ print('\n\n.................................')
+ print('...... Testing FileStorate ......')
+ print('..... For FileStorage Class .....')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new storage object for testing"""
+ self.storage = FileStorage()
+ self.bm_obj = BaseModel()
+
+ def test_instantiation(self):
+ """... checks proper FileStorage instantiation"""
+ self.assertIsInstance(self.storage, FileStorage)
+
+ def test_storage_file_exists(self):
+ """... checks proper FileStorage instantiation"""
+ os.remove(F)
+ self.bm_obj.save()
+ self.assertTrue(os.path.isfile(F))
+
+ def test_obj_saved_to_file(self):
+ """... checks proper FileStorage instantiation"""
+ os.remove(F)
+ self.bm_obj.save()
+ bm_id = self.bm_obj.id
+ actual = 0
+ with open(F, mode='r', encoding='utf-8') as f_obj:
+ storage_dict = json.load(f_obj)
+ for k in storage_dict.keys():
+ if bm_id in k:
+ actual = 1
+ self.assertTrue(1 == actual)
+
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ my_model_json = self.bm_obj.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(my_model_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ def test_reload(self):
+ """... checks proper usage of reload function"""
+ os.remove(F)
+ self.bm_obj.save()
+ bm_id = self.bm_obj.id
+ actual = 0
+ new_storage = FileStorage()
+ new_storage.reload()
+ all_obj = new_storage.all()
+ for k in all_obj.keys():
+ if bm_id in k:
+ actual = 1
+ self.assertTrue(1 == actual)
+
+ def test_save_reload_class(self):
+ """... checks proper usage of class attribute in file storage"""
+ os.remove(F)
+ self.bm_obj.save()
+ bm_id = self.bm_obj.id
+ actual = 0
+ new_storage = FileStorage()
+ new_storage.reload()
+ all_obj = new_storage.all()
+ for k, v in all_obj.items():
+ if bm_id in k:
+ if type(v).__name__ == 'BaseModel':
+ actual = 1
+ self.assertTrue(1 == actual)
+
+
+class TestUserFsInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('...... Testing FileStorage ......')
+ print('.......... User Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.user = User()
+ self.bm_obj = BaseModel()
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_storage_file_exists(self):
+ """... checks proper FileStorage instantiation"""
+ os.remove(F)
+ self.user.save()
+ self.assertTrue(os.path.isfile(F))
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_obj_saved_to_file(self):
+ """... checks proper FileStorage instantiation"""
+ os.remove(F)
+ self.user.save()
+ u_id = self.user.id
+ actual = 0
+ with open(F, mode='r', encoding='utf-8') as f_obj:
+ storage_dict = json.load(f_obj)
+ for k in storage_dict.keys():
+ if u_id in k:
+ actual = 1
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_reload(self):
+ """... checks proper usage of reload function"""
+ os.remove(F)
+ self.bm_obj.save()
+ u_id = self.bm_obj.id
+ actual = 0
+ new_storage = FileStorage()
+ new_storage.reload()
+ all_obj = new_storage.all()
+ for k in all_obj.keys():
+ if u_id in k:
+ actual = 1
+ self.assertTrue(1 == actual)
+
+
+@unittest.skipIf(storage_type == 'db', 'skip if environ is not db')
+class TestStorageGet(unittest.TestCase):
+ """
+ Testing `get()` method in DBStorage
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ setup tests for class
+ """
+ print('\n\n.................................')
+ print('...... Testing Get() Method ......')
+ print('.......... Place Class ..........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """
+ setup method
+ """
+ self.state = models.state.State(name="Florida")
+ self.state.save()
+
+ def test_get_method_obj(self):
+ """
+ testing get() method
+ :return: True if pass, False if not pass
+ """
+
+ print(self.state.id)
+ result = storage.get(cls="State", id=self.state.id)
+
+ self.assertIsInstance(result, models.state.State)
+
+ def test_get_method_return(self):
+ """
+ testing get() method for id match
+ :return: True if pass, false if not pass
+ """
+ result = storage.get(cls="State", id=str(self.state.id))
+
+ self.assertEqual(self.state.id, result.id)
+
+ def test_get_method_none(self):
+ """
+ testing get() method for None return
+ :return: True if pass, false if not pass
+ """
+ result = storage.get(cls="State", id="doesnotexist")
+
+ self.assertIsNone(result)
+
+
+@unittest.skipIf(storage_type == 'db', 'skip if environ is not db')
+class TestStorageCount(unittest.TestCase):
+ """
+ tests count() method in DBStorage
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ setup tests for class
+ """
+ print('\n\n.................................')
+ print('...... Testing Get() Method ......')
+ print('.......... Place Class ..........')
+ print('.................................\n\n')
+
+ def setup(self):
+ """
+ setup method
+ """
+ models.state.State()
+ models.state.State()
+ models.state.State()
+ models.state.State()
+ models.state.State()
+ models.state.State()
+ models.state.State()
+
+ def test_count_all(self):
+ """
+ testing counting all instances
+ :return: True if pass, false if not pass
+ """
+ result = storage.count()
+
+ self.assertEqual(len(storage.all()), result)
+
+ def test_count_state(self):
+ """
+ testing counting state instances
+ :return: True if pass, false if not pass
+ """
+ result = storage.count(cls="State")
+
+ self.assertEqual(len(storage.all("State")), result)
+
+ def test_count_city(self):
+ """
+ testing counting non existent
+ :return: True if pass, false if not pass
+ """
+ result = storage.count(cls="City")
+
+ self.assertEqual(
+ int(0 if len(storage.all("City")) is None else
+ len(storage.all("City"))), result)
+
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_place.py b/tests/test_models/test_place.py
index 233e7742e2c..f58ba8ac96e 100755
--- a/tests/test_models/test_place.py
+++ b/tests/test_models/test_place.py
@@ -1,200 +1,117 @@
#!/usr/bin/python3
"""
-Contains the TestPlaceDocs classes
+Unit Test for Place Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import place
-from models.base_model import BaseModel
-import pep8
-import unittest
-Place = place.Place
+import json
+import os
+
+Place = models.place.Place
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestPlaceDocs(unittest.TestCase):
- """Tests to check the documentation and style of Place class"""
+ """Class for testing BaseModel docs"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.place_f = inspect.getmembers(Place, inspect.isfunction)
-
- def test_pep8_conformance_place(self):
- """Test that models/place.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/place.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_place(self):
- """Test that tests/test_models/test_place.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_place.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_place_module_docstring(self):
- """Test for the place.py module docstring"""
- self.assertIsNot(place.__doc__, None,
- "place.py needs a docstring")
- self.assertTrue(len(place.__doc__) >= 1,
- "place.py needs a docstring")
-
- def test_place_class_docstring(self):
- """Test for the Place class docstring"""
- self.assertIsNot(Place.__doc__, None,
- "Place class needs a docstring")
- self.assertTrue(len(Place.__doc__) >= 1,
- "Place class needs a docstring")
-
- def test_place_func_docstrings(self):
- """Test for the presence of docstrings in Place methods"""
- for func in self.place_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestPlace(unittest.TestCase):
- """Test the Place class"""
- def test_is_subclass(self):
- """Test that Place is a subclass of BaseModel"""
- place = Place()
- self.assertIsInstance(place, BaseModel)
- self.assertTrue(hasattr(place, "id"))
- self.assertTrue(hasattr(place, "created_at"))
- self.assertTrue(hasattr(place, "updated_at"))
-
- def test_city_id_attr(self):
- """Test Place has attr city_id, and it's an empty string"""
- place = Place()
- self.assertTrue(hasattr(place, "city_id"))
- if models.storage_t == 'db':
- self.assertEqual(place.city_id, None)
- else:
- self.assertEqual(place.city_id, "")
-
- 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"))
- if models.storage_t == 'db':
- self.assertEqual(place.user_id, None)
- else:
- self.assertEqual(place.user_id, "")
-
- def test_name_attr(self):
- """Test Place has attr name, and it's an empty string"""
- place = Place()
- self.assertTrue(hasattr(place, "name"))
- if models.storage_t == 'db':
- self.assertEqual(place.name, None)
- else:
- self.assertEqual(place.name, "")
-
- def test_description_attr(self):
- """Test Place has attr description, and it's an empty string"""
- place = Place()
- self.assertTrue(hasattr(place, "description"))
- if models.storage_t == 'db':
- self.assertEqual(place.description, None)
- else:
- self.assertEqual(place.description, "")
-
- def test_number_rooms_attr(self):
- """Test Place has attr number_rooms, and it's an int == 0"""
- place = Place()
- self.assertTrue(hasattr(place, "number_rooms"))
- if models.storage_t == 'db':
- self.assertEqual(place.number_rooms, None)
- else:
- self.assertEqual(type(place.number_rooms), int)
- self.assertEqual(place.number_rooms, 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"))
- if models.storage_t == 'db':
- self.assertEqual(place.number_bathrooms, None)
- else:
- self.assertEqual(type(place.number_bathrooms), int)
- self.assertEqual(place.number_bathrooms, 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"))
- if models.storage_t == 'db':
- self.assertEqual(place.max_guest, None)
- else:
- self.assertEqual(type(place.max_guest), int)
- self.assertEqual(place.max_guest, 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"))
- if models.storage_t == 'db':
- self.assertEqual(place.price_by_night, None)
- else:
- self.assertEqual(type(place.price_by_night), int)
- self.assertEqual(place.price_by_night, 0)
-
- def test_latitude_attr(self):
- """Test Place has attr latitude, and it's a float == 0.0"""
- place = Place()
- self.assertTrue(hasattr(place, "latitude"))
- if models.storage_t == 'db':
- self.assertEqual(place.latitude, None)
- else:
- self.assertEqual(type(place.latitude), float)
- self.assertEqual(place.latitude, 0.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"))
- if models.storage_t == 'db':
- self.assertEqual(place.longitude, None)
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('........ Place Class ........')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nPlace Class from Models Module\n'
+ actual = models.place.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'Place class handles all application places'
+ actual = Place.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestPlaceInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('......... Place Class .........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new place for testing"""
+ self.place = Place()
+
+ def test_instantiation(self):
+ """... checks if Place is properly instantiated"""
+ self.assertIsInstance(self.place, Place)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.place)
+ my_list = ['Place', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ my_str = str(self.place)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.place.save()
+ actual = type(self.place.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.place_json = self.place.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.place_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value Place"""
+ self.place_json = self.place.to_json()
+ actual = None
+ if self.place_json['__class__']:
+ actual = self.place_json['__class__']
+ expected = 'Place'
+ self.assertEqual(expected, actual)
+
+ def test_guest_attribute(self):
+ """... add guest attribute"""
+ self.place.max_guest = 3
+ if hasattr(self.place, 'max_guest'):
+ actual = self.place.max_guest
else:
- self.assertEqual(type(place.longitude), float)
- self.assertEqual(place.longitude, 0.0)
-
- @unittest.skipIf(models.storage_t == 'db', "not testing File Storage")
- 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)
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- p = Place()
- new_d = p.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in p.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- p = Place()
- new_d = p.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"], p.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], p.updated_at.strftime(t_format))
-
- 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))
+ actual = ''
+ expected = 3
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_review.py b/tests/test_models/test_review.py
index 171b725b77f..977bb5a2b26 100755
--- a/tests/test_models/test_review.py
+++ b/tests/test_models/test_review.py
@@ -1,123 +1,117 @@
#!/usr/bin/python3
"""
-Contains the TestReviewDocs classes
+Unit Test for Review Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import review
-from models.base_model import BaseModel
-import pep8
-import unittest
-Review = review.Review
+import json
+import os
+
+Review = models.review.Review
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestReviewDocs(unittest.TestCase):
- """Tests to check the documentation and style of Review class"""
+ """Class for testing BaseModel docs"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.review_f = inspect.getmembers(Review, inspect.isfunction)
-
- def test_pep8_conformance_review(self):
- """Test that models/review.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/review.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_review(self):
- """Test that tests/test_models/test_review.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_review.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_review_module_docstring(self):
- """Test for the review.py module docstring"""
- self.assertIsNot(review.__doc__, None,
- "review.py needs a docstring")
- self.assertTrue(len(review.__doc__) >= 1,
- "review.py needs a docstring")
-
- def test_review_class_docstring(self):
- """Test for the Review class docstring"""
- self.assertIsNot(Review.__doc__, None,
- "Review class needs a docstring")
- self.assertTrue(len(Review.__doc__) >= 1,
- "Review class needs a docstring")
-
- def test_review_func_docstrings(self):
- """Test for the presence of docstrings in Review methods"""
- for func in self.review_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestReview(unittest.TestCase):
- """Test the Review class"""
- def test_is_subclass(self):
- """Test if Review is a subclass of BaseModel"""
- review = Review()
- self.assertIsInstance(review, BaseModel)
- self.assertTrue(hasattr(review, "id"))
- self.assertTrue(hasattr(review, "created_at"))
- self.assertTrue(hasattr(review, "updated_at"))
-
- def test_place_id_attr(self):
- """Test Review has attr place_id, and it's an empty string"""
- review = Review()
- self.assertTrue(hasattr(review, "place_id"))
- if models.storage_t == 'db':
- self.assertEqual(review.place_id, None)
- else:
- self.assertEqual(review.place_id, "")
-
- def test_user_id_attr(self):
- """Test Review has attr user_id, and it's an empty string"""
- review = Review()
- self.assertTrue(hasattr(review, "user_id"))
- if models.storage_t == 'db':
- self.assertEqual(review.user_id, None)
- else:
- self.assertEqual(review.user_id, "")
-
- def test_text_attr(self):
- """Test Review has attr text, and it's an empty string"""
- review = Review()
- self.assertTrue(hasattr(review, "text"))
- if models.storage_t == 'db':
- self.assertEqual(review.text, None)
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('....... Review Class .......')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nReview Class from Models Module\n'
+ actual = models.review.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'Review class handles all application reviews'
+ actual = Review.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestReviewInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('........ Review Class ........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new review for testing"""
+ self.review = Review()
+
+ def test_instantiation(self):
+ """... checks if Review is properly instantiated"""
+ self.assertIsInstance(self.review, Review)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.review)
+ my_list = ['Review', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ my_str = str(self.review)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.review.save()
+ actual = type(self.review.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.review_json = self.review.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.review_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value Review"""
+ self.review_json = self.review.to_json()
+ actual = None
+ if self.review_json['__class__']:
+ actual = self.review_json['__class__']
+ expected = 'Review'
+ self.assertEqual(expected, actual)
+
+ def test_review_attribute(self):
+ """... add review attribute"""
+ self.review.text = "This place smells"
+ if hasattr(self.review, 'text'):
+ actual = self.review.text
else:
- self.assertEqual(review.text, "")
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- r = Review()
- new_d = r.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in r.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- r = Review()
- new_d = r.to_dict()
- self.assertEqual(new_d["__class__"], "Review")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], r.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], r.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- review = Review()
- string = "[Review] ({}) {}".format(review.id, review.__dict__)
- self.assertEqual(string, str(review))
+ acual = ''
+ expected = "This place smells"
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_state.py b/tests/test_models/test_state.py
index 2ac2391d0c3..d00495c0d24 100755
--- a/tests/test_models/test_state.py
+++ b/tests/test_models/test_state.py
@@ -1,105 +1,116 @@
#!/usr/bin/python3
"""
-Contains the TestStateDocs classes
+Unit Test for State Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import state
-from models.base_model import BaseModel
-import pep8
-import unittest
-State = state.State
+import json
+import os
+State = models.state.State
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestStateDocs(unittest.TestCase):
- """Tests to check the documentation and style of State class"""
+ """Class for testing State docs"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('........ State Class ........')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nState Class from Models Module\n'
+ actual = models.state.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'State class handles all application states'
+ actual = State.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestStateInstances(unittest.TestCase):
+ """testing for class instances"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.state_f = inspect.getmembers(State, inspect.isfunction)
-
- def test_pep8_conformance_state(self):
- """Test that models/state.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/state.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_state(self):
- """Test that tests/test_models/test_state.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_state.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_state_module_docstring(self):
- """Test for the state.py module docstring"""
- self.assertIsNot(state.__doc__, None,
- "state.py needs a docstring")
- self.assertTrue(len(state.__doc__) >= 1,
- "state.py needs a docstring")
-
- def test_state_class_docstring(self):
- """Test for the State class docstring"""
- self.assertIsNot(State.__doc__, None,
- "State class needs a docstring")
- self.assertTrue(len(State.__doc__) >= 1,
- "State class needs a docstring")
-
- def test_state_func_docstrings(self):
- """Test for the presence of docstrings in State methods"""
- for func in self.state_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestState(unittest.TestCase):
- """Test the State class"""
- def test_is_subclass(self):
- """Test that State is a subclass of BaseModel"""
- state = State()
- self.assertIsInstance(state, BaseModel)
- self.assertTrue(hasattr(state, "id"))
- self.assertTrue(hasattr(state, "created_at"))
- self.assertTrue(hasattr(state, "updated_at"))
-
- def test_name_attr(self):
- """Test that State has attribute name, and it's as an empty string"""
- state = State()
- self.assertTrue(hasattr(state, "name"))
- if models.storage_t == 'db':
- self.assertEqual(state.name, None)
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('......... State Class .........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new state for testing"""
+ self.state = State()
+
+ def test_instantiation(self):
+ """... checks if State is properly instantiated"""
+ self.assertIsInstance(self.state, State)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.state)
+ my_list = ['State', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ my_str = str(self.state)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.state.save()
+ actual = type(self.state.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.state_json = self.state.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.state_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value State"""
+ self.state_json = self.state.to_json()
+ actual = None
+ if self.state_json['__class__']:
+ actual = self.state_json['__class__']
+ expected = 'State'
+ self.assertEqual(expected, actual)
+
+ def test_name_attribute(self):
+ """... add name attribute"""
+ self.state.name = "betty"
+ if hasattr(self.state, 'name'):
+ actual = self.state.name
else:
- self.assertEqual(state.name, "")
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- s = State()
- new_d = s.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in s.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- s = State()
- new_d = s.to_dict()
- self.assertEqual(new_d["__class__"], "State")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], s.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], s.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- state = State()
- string = "[State] ({}) {}".format(state.id, state.__dict__)
- self.assertEqual(string, str(state))
+ acual = ''
+ expected = "betty"
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/tests/test_models/test_user.py b/tests/test_models/test_user.py
index f2ed662b971..27e6884c701 100755
--- a/tests/test_models/test_user.py
+++ b/tests/test_models/test_user.py
@@ -1,132 +1,118 @@
#!/usr/bin/python3
"""
-Contains the TestUserDocs classes
+Unit Test for User Class
"""
-
+import unittest
from datetime import datetime
-import inspect
import models
-from models import user
-from models.base_model import BaseModel
-import pep8
-import unittest
-User = user.User
+import json
+import os
+
+User = models.user.User
+BaseModel = models.base_model.BaseModel
+storage_type = os.environ.get('HBNB_TYPE_STORAGE')
class TestUserDocs(unittest.TestCase):
- """Tests to check the documentation and style of User class"""
+ """Class for testing User Class docs"""
+
@classmethod
def setUpClass(cls):
- """Set up for the doc tests"""
- cls.user_f = inspect.getmembers(User, inspect.isfunction)
-
- def test_pep8_conformance_user(self):
- """Test that models/user.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['models/user.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_pep8_conformance_test_user(self):
- """Test that tests/test_models/test_user.py conforms to PEP8."""
- pep8s = pep8.StyleGuide(quiet=True)
- result = pep8s.check_files(['tests/test_models/test_user.py'])
- self.assertEqual(result.total_errors, 0,
- "Found code style errors (and warnings).")
-
- def test_user_module_docstring(self):
- """Test for the user.py module docstring"""
- self.assertIsNot(user.__doc__, None,
- "user.py needs a docstring")
- self.assertTrue(len(user.__doc__) >= 1,
- "user.py needs a docstring")
-
- def test_user_class_docstring(self):
- """Test for the City class docstring"""
- self.assertIsNot(User.__doc__, None,
- "User class needs a docstring")
- self.assertTrue(len(User.__doc__) >= 1,
- "User class needs a docstring")
-
- def test_user_func_docstrings(self):
- """Test for the presence of docstrings in User methods"""
- for func in self.user_f:
- self.assertIsNot(func[1].__doc__, None,
- "{:s} method needs a docstring".format(func[0]))
- self.assertTrue(len(func[1].__doc__) >= 1,
- "{:s} method needs a docstring".format(func[0]))
-
-
-class TestUser(unittest.TestCase):
- """Test the User class"""
- def test_is_subclass(self):
- """Test that User is a subclass of BaseModel"""
- user = User()
- self.assertIsInstance(user, BaseModel)
- self.assertTrue(hasattr(user, "id"))
- self.assertTrue(hasattr(user, "created_at"))
- self.assertTrue(hasattr(user, "updated_at"))
-
- def test_email_attr(self):
- """Test that User has attr email, and it's an empty string"""
- user = User()
- self.assertTrue(hasattr(user, "email"))
- if models.storage_t == 'db':
- self.assertEqual(user.email, None)
- else:
- self.assertEqual(user.email, "")
-
- def test_password_attr(self):
- """Test that User has attr password, and it's an empty string"""
- user = User()
- self.assertTrue(hasattr(user, "password"))
- if models.storage_t == 'db':
- self.assertEqual(user.password, None)
- else:
- self.assertEqual(user.password, "")
-
- def test_first_name_attr(self):
- """Test that User has attr first_name, and it's an empty string"""
- user = User()
- self.assertTrue(hasattr(user, "first_name"))
- if models.storage_t == 'db':
- self.assertEqual(user.first_name, None)
- else:
- self.assertEqual(user.first_name, "")
-
- def test_last_name_attr(self):
- """Test that User has attr last_name, and it's an empty string"""
- user = User()
- self.assertTrue(hasattr(user, "last_name"))
- if models.storage_t == 'db':
- self.assertEqual(user.last_name, None)
+ print('\n\n.................................')
+ print('..... Testing Documentation .....')
+ print('........ User Class ........')
+ print('.................................\n\n')
+
+ def test_doc_file(self):
+ """... documentation for the file"""
+ expected = '\nUser Class from Models Module\n'
+ actual = models.user.__doc__
+ self.assertEqual(expected, actual)
+
+ def test_doc_class(self):
+ """... documentation for the class"""
+ expected = 'User class handles all application users'
+ actual = User.__doc__
+ self.assertEqual(expected, actual)
+
+
+class TestUserInstances(unittest.TestCase):
+ """testing for class instances"""
+
+ @classmethod
+ def setUpClass(cls):
+ print('\n\n.................................')
+ print('....... Testing Functions .......')
+ print('......... User Class .........')
+ print('.................................\n\n')
+
+ def setUp(self):
+ """initializes new user for testing"""
+ self.user = User()
+
+ def test_instantiation(self):
+ """... checks if User is properly instantiated"""
+ self.assertIsInstance(self.user, User)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_string(self):
+ """... checks if BaseModel is properly casted to string"""
+ my_str = str(self.user)
+ my_list = ['User', 'id', 'created_at']
+ actual = 0
+ for sub_str in my_list:
+ if sub_str in my_str:
+ actual += 1
+ self.assertTrue(3 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_instantiation_no_updated(self):
+ """... should not have updated attribute"""
+ self.user = User()
+ my_str = str(self.user)
+ actual = 0
+ if 'updated_at' in my_str:
+ actual += 1
+ self.assertTrue(0 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_updated_at(self):
+ """... save function should add updated_at attribute"""
+ self.user.save()
+ actual = type(self.user.updated_at)
+ expected = type(datetime.now())
+ self.assertEqual(expected, actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_to_json(self):
+ """... to_json should return serializable dict object"""
+ self.user_json = self.user.to_json()
+ actual = 1
+ try:
+ serialized = json.dumps(self.user_json)
+ except:
+ actual = 0
+ self.assertTrue(1 == actual)
+
+ @unittest.skipIf(storage_type == 'db', 'skip if environ is db')
+ def test_json_class(self):
+ """... to_json should include class key with value User"""
+ self.user_json = self.user.to_json()
+ actual = None
+ if self.user_json['__class__']:
+ actual = self.user_json['__class__']
+ expected = 'User'
+ self.assertEqual(expected, actual)
+
+ def test_email_attribute(self):
+ """... add email attribute"""
+ self.user.email = "bettyholbertn@gmail.com"
+ if hasattr(self.user, 'email'):
+ actual = self.user.email
else:
- self.assertEqual(user.last_name, "")
-
- def test_to_dict_creates_dict(self):
- """test to_dict method creates a dictionary with proper attrs"""
- u = User()
- new_d = u.to_dict()
- self.assertEqual(type(new_d), dict)
- self.assertFalse("_sa_instance_state" in new_d)
- for attr in u.__dict__:
- if attr is not "_sa_instance_state":
- 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"
- u = User()
- new_d = u.to_dict()
- self.assertEqual(new_d["__class__"], "User")
- self.assertEqual(type(new_d["created_at"]), str)
- self.assertEqual(type(new_d["updated_at"]), str)
- self.assertEqual(new_d["created_at"], u.created_at.strftime(t_format))
- self.assertEqual(new_d["updated_at"], u.updated_at.strftime(t_format))
-
- def test_str(self):
- """test that the str method has the correct output"""
- user = User()
- string = "[User] ({}) {}".format(user.id, user.__dict__)
- self.assertEqual(string, str(user))
+ actual = ''
+ expected = "bettyholbertn@gmail.com"
+ self.assertEqual(expected, actual)
+
+if __name__ == '__main__':
+ unittest.main
diff --git a/web_flask/0-hello_route.py b/web_flask/0-hello_route.py
index 194749fecd4..572bcad2975 100755
--- a/web_flask/0-hello_route.py
+++ b/web_flask/0-hello_route.py
@@ -1,16 +1,16 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
-
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/1-hbnb_route.py b/web_flask/1-hbnb_route.py
index f1829cfc6dc..be9c6c30194 100755
--- a/web_flask/1-hbnb_route.py
+++ b/web_flask/1-hbnb_route.py
@@ -1,22 +1,24 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
-
+ """
+ function to return HBNB
+ """
+ return "HBNB"
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/10-hbnb_filters.py b/web_flask/10-hbnb_filters.py
index b6d8e50f797..37db04cb31a 100755
--- a/web_flask/10-hbnb_filters.py
+++ b/web_flask/10-hbnb_filters.py
@@ -1,27 +1,30 @@
#!/usr/bin/python3
"""
-starts a Flask web application
+ Sript that starts a Flask web application
"""
-
from flask import Flask, render_template
-from models import *
from models import storage
+import os
app = Flask(__name__)
-@app.route('/hbnb_filters', strict_slashes=False)
-def filters():
- """display a HTML page like 6-index.html from static"""
- states = storage.all("State").values()
- amenities = storage.all("Amenity").values()
- return render_template('10-hbnb_filters.html', states=states,
- amenities=amenities)
+def handle_teardown(self):
+ """
+ method to handle teardown
+ """
+ storage.close()
-@app.teardown_appcontext
-def teardown_db(exception):
- """closes the storage on teardown"""
- storage.close()
+@app.route('/hbnb_filters', strict_slashes=False)
+def filters_list():
+ """
+ method to display html page 6-index.html
+ """
+ states = storage.all('State').values()
+ amenities = storage.all('Amenity').values()
+ return render_template(
+ "10-hbnb_filters.html",
+ states=states, amenities=amenities)
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/2-c_route.py b/web_flask/2-c_route.py
index bb3818a09b2..9c16d71c0b4 100755
--- a/web_flask/2-c_route.py
+++ b/web_flask/2-c_route.py
@@ -1,28 +1,32 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
+ """
+ function to return HBNB
+ """
+ return "HBNB"
@app.route('/c/', strict_slashes=False)
-def cisfun(text):
- """display “C ” followed by the value of the text variable"""
- return 'C ' + text.replace('_', ' ')
-
+def text_var(text):
+ """
+ function to display text variable passed in
+ """
+ return "C {}".format(text.replace("_", " "))
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/3-python_route.py b/web_flask/3-python_route.py
index caf0f632694..efb2f3f2251 100755
--- a/web_flask/3-python_route.py
+++ b/web_flask/3-python_route.py
@@ -1,35 +1,41 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
+ """
+ function to return HBNB
+ """
+ return "HBNB"
@app.route('/c/', strict_slashes=False)
-def cisfun(text):
- """display “C ” followed by the value of the text variable"""
- return 'C ' + text.replace('_', ' ')
+def text_var(text):
+ """
+ function to display text variable passed in
+ """
+ return "C {}".format(text.replace("_", " "))
@app.route('/python', strict_slashes=False)
@app.route('/python/', strict_slashes=False)
-def pythoniscool(text='is cool'):
- """display “Python ”, followed by the value of the text variable"""
- return 'Python ' + text.replace('_', ' ')
-
+def text_var_python(text="is cool"):
+ """
+ function to display text variable, with default "is cool"
+ """
+ return "Python {}".format(text.replace("_", " "))
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/4-number_route.py b/web_flask/4-number_route.py
index f2948b12e11..804245225fc 100755
--- a/web_flask/4-number_route.py
+++ b/web_flask/4-number_route.py
@@ -1,41 +1,48 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
+ """
+ function to return HBNB
+ """
+ return "HBNB"
@app.route('/c/', strict_slashes=False)
-def cisfun(text):
- """display “C ” followed by the value of the text variable"""
- return 'C ' + text.replace('_', ' ')
+def text_var(text):
+ """
+ function to display text variable passed in
+ """
+ return "C {}".format(text.replace("_", " "))
-@app.route('/python', strict_slashes=False)
@app.route('/python/', strict_slashes=False)
-def pythoniscool(text='is cool'):
- """display “Python ”, followed by the value of the text variable"""
- return 'Python ' + text.replace('_', ' ')
+def text_var_python(text="is cool"):
+ """
+ function to display text variable, with default "is cool"
+ """
+ return "Python {}".format(text.replace("_", " "))
@app.route('/number/', strict_slashes=False)
-def imanumber(n):
- """display “n is a number” only if n is an integer"""
- return "{:d} is a number".format(n)
-
+def var_num(n):
+ """
+ function to display a variable, but only if an int
+ """
+ return "{} is a number".format(n)
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/5-number_template.py b/web_flask/5-number_template.py
index 17841a1a3a7..ee4792f017d 100755
--- a/web_flask/5-number_template.py
+++ b/web_flask/5-number_template.py
@@ -1,47 +1,56 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
+ """
+ function to return HBNB
+ """
+ return "HBNB"
@app.route('/c/', strict_slashes=False)
-def cisfun(text):
- """display “C ” followed by the value of the text variable"""
- return 'C ' + text.replace('_', ' ')
+def text_var(text):
+ """
+ function to display text variable passed in
+ """
+ return "C {}".format(text.replace("_", " "))
-@app.route('/python', strict_slashes=False)
@app.route('/python/', strict_slashes=False)
-def pythoniscool(text='is cool'):
- """display “Python ”, followed by the value of the text variable"""
- return 'Python ' + text.replace('_', ' ')
+def text_var_python(text="is cool"):
+ """
+ function to display text variable, with default "is cool"
+ """
+ return "Python {}".format(text.replace("_", " "))
@app.route('/number/', strict_slashes=False)
-def imanumber(n):
- """display “n is a number” only if n is an integer"""
- return "{:d} is a number".format(n)
+def var_num(n):
+ """
+ function to display a variable, but only if an int
+ """
+ return "{} is a number".format(n)
@app.route('/number_template/', strict_slashes=False)
-def numbersandtemplates(n):
- """display a HTML page only if n is an integer"""
- return render_template('5-number.html', n=n)
-
+def var_num_template(n):
+ """
+ function to display number in html page
+ """
+ return render_template("5-number.html", n=n)
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/6-number_odd_or_even.py b/web_flask/6-number_odd_or_even.py
index 7875c4c7b32..77f27d02a62 100755
--- a/web_flask/6-number_odd_or_even.py
+++ b/web_flask/6-number_odd_or_even.py
@@ -1,58 +1,64 @@
#!/usr/bin/python3
"""
-starts a Flask web application
-"""
-
+ Sript that starts a Flask web application
+ """
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', strict_slashes=False)
-def index():
- """returns Hello HBNB!"""
- return 'Hello HBNB!'
+def hello_hbn():
+ """
+ function to return Hello HBNB!
+ """
+ return "Hello HBNB!"
@app.route('/hbnb', strict_slashes=False)
def hbnb():
- """returns HBNB"""
- return 'HBNB'
+ """
+ function to return HBNB
+ """
+ return "HBNB"
@app.route('/c/', strict_slashes=False)
-def cisfun(text):
- """display “C ” followed by the value of the text variable"""
- return 'C ' + text.replace('_', ' ')
+def text_var(text):
+ """
+ function to display text variable passed in
+ """
+ return "C {}".format(text.replace("_", " "))
-@app.route('/python', strict_slashes=False)
@app.route('/python/', strict_slashes=False)
-def pythoniscool(text='is cool'):
- """display “Python ”, followed by the value of the text variable"""
- return 'Python ' + text.replace('_', ' ')
+def text_var_python(text="is cool"):
+ """
+ function to display text variable, with default "is cool"
+ """
+ return "Python {}".format(text.replace("_", " "))
@app.route('/number/', strict_slashes=False)
-def imanumber(n):
- """display “n is a number” only if n is an integer"""
- return "{:d} is a number".format(n)
+def var_num(n):
+ """
+ function to display a variable, but only if an int
+ """
+ return "{} is a number".format(n)
@app.route('/number_template/', strict_slashes=False)
-def numbersandtemplates(n):
- """display a HTML page only if n is an integer"""
- return render_template('5-number.html', n=n)
+def var_num_template(n):
+ """
+ function to display number in html page
+ """
+ return render_template("5-number.html", n=n)
@app.route('/number_odd_or_even/', strict_slashes=False)
-def numbersandevenness(n):
- """display a HTML page only if n is an integer"""
- if n % 2 == 0:
- evenness = 'even'
- else:
- evenness = 'odd'
- return render_template('6-number_odd_or_even.html', n=n,
- evenness=evenness)
-
+def var_num_even_odd(n):
+ """
+ function to display even or odd number
+ """
+ return render_template("6-number_odd_or_even.html", n=n)
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/7-states_list.py b/web_flask/7-states_list.py
index fa9ae29ae54..d41a6c0b24f 100755
--- a/web_flask/7-states_list.py
+++ b/web_flask/7-states_list.py
@@ -1,25 +1,27 @@
#!/usr/bin/python3
"""
-starts a Flask web application
+ Sript that starts a Flask web application
"""
-
from flask import Flask, render_template
-from models import *
from models import storage
app = Flask(__name__)
-@app.route('/states_list', strict_slashes=False)
-def states_list():
- """display a HTML page with the states listed in alphabetical order"""
- states = sorted(list(storage.all("State").values()), key=lambda x: x.name)
- return render_template('7-states_list.html', states=states)
-
-
@app.teardown_appcontext
-def teardown_db(exception):
- """closes the storage on teardown"""
+def handle_teardown(self):
+ """
+ method to handle teardown
+ """
storage.close()
+
+@app.route('/states_list', strict_slashes=False)
+def state_list():
+ """
+ method to render states
+ """
+ states = storage.all('State').values()
+ return render_template("7-states_list.html", states=states)
+
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/8-cities_by_states.py b/web_flask/8-cities_by_states.py
old mode 100755
new mode 100644
index 3d2ae2b733a..7d24da39ebd
--- a/web_flask/8-cities_by_states.py
+++ b/web_flask/8-cities_by_states.py
@@ -1,25 +1,28 @@
#!/usr/bin/python3
"""
-starts a Flask web application
+ Sript that starts a Flask web application
"""
-
from flask import Flask, render_template
-from models import *
from models import storage
+import os
app = Flask(__name__)
-@app.route('/cities_by_states', strict_slashes=False)
-def cities_by_states():
- """display the states and cities listed in alphabetical order"""
- states = storage.all("State").values()
- return render_template('8-cities_by_states.html', states=states)
-
-
@app.teardown_appcontext
-def teardown_db(exception):
- """closes the storage on teardown"""
+def handle_teardown(self):
+ """
+ method to handle teardown
+ """
storage.close()
+
+@app.route('/cities_by_states', strict_slashes=False)
+def city_state_list():
+ """
+ method to render states from storage
+ """
+ states = storage.all('State').values()
+ return render_template("8-cities_by_states.html", states=states)
+
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/9-states.py b/web_flask/9-states.py
index cf9f5a704ce..983b2c14700 100755
--- a/web_flask/9-states.py
+++ b/web_flask/9-states.py
@@ -1,28 +1,43 @@
#!/usr/bin/python3
"""
-starts a Flask web application
+ Sript that starts a Flask web application
"""
-
from flask import Flask, render_template
-from models import *
from models import storage
+import os
app = Flask(__name__)
+@app.teardown_appcontext
+def handle_teardown(self):
+ """
+ method to handle teardown
+ """
+ storage.close()
+
+
@app.route('/states', strict_slashes=False)
-@app.route('/states/', strict_slashes=False)
-def states(state_id=None):
- """display the states and cities listed in alphabetical order"""
- states = storage.all("State")
- if state_id is not None:
- state_id = 'State.' + state_id
- return render_template('9-states.html', states=states, state_id=state_id)
+def state_list():
+ """
+ method to render states
+ """
+ states = storage.all('State').values()
+ return render_template("9-states.html", states=states,
+ condition="states_list")
-@app.teardown_appcontext
-def teardown_db(exception):
- """closes the storage on teardown"""
- storage.close()
+@app.route('/states/', strict_slashes=False)
+def states_id(id):
+ """
+ method to render state ids
+ """
+ state_all = storage.all('State')
+ try:
+ state_id = state_all[id]
+ return render_template('9-states.html', state_id=state_id,
+ condition="state_id")
+ except:
+ return render_template('9-states.html', condition="not_found")
if __name__ == '__main__':
- app.run(host='0.0.0.0', port='5000')
+ app.run(host='0.0.0.0', port=5000)
diff --git a/web_flask/__init__.py b/web_flask/__init__.py
old mode 100644
new mode 100755