├── tests ├── __init__.py ├── test_models │ ├── __init__.py │ ├── test_engine │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ └── test_file_storage.cpython-38.pyc │ │ └── test_file_storage.py │ ├── .#test_review.py │ ├── test_state.py │ ├── test_user.py │ ├── test_amenity.py │ ├── test_city.py │ ├── test_base_model.py │ ├── test_review.py │ └── test_place.py └── test_console.py ├── models ├── engine │ ├── __init__.py │ └── file_storage.py ├── __init__.py ├── state.py ├── amenity.py ├── city.py ├── review.py ├── user.py ├── place.py └── base_model.py ├── AUTHORS ├── web_static ├── styles │ ├── 2-common.css │ ├── 2-header.css │ ├── 3-common.css │ ├── 2-footer.css │ ├── 3-footer.css │ ├── 3-header.css │ ├── 4-common.css │ ├── 7-places.css │ ├── 4-filters.css │ ├── 5-filters.css │ ├── 8-places.css │ └── 6-filters.css ├── images │ ├── icon.png │ ├── logo.png │ ├── icon_bed.png │ ├── icon_bath.png │ └── icon_group.png ├── 0-index.html ├── 2-index.html ├── 1-index.html ├── 3-index.html ├── README.md ├── 4-index.html ├── W3C-Validator │ ├── README.md │ └── w3c_validator.py ├── 5-index.html ├── 6-index.html ├── 7-index.html └── 8-index.html ├── __pycache__ └── console.cpython-310.pyc ├── one ├── AUTHORS ├── models │ ├── __init__.py │ ├── state.py │ ├── amenity.py │ ├── city.py │ ├── review.py │ ├── user.py │ ├── place.py │ ├── base_model.py │ └── engine │ │ └── file_storage.py ├── tests │ └── test_console.py ├── README.md └── console.py ├── README.md └── console.py /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /models/engine/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_models/test_engine/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/test_models/.#test_review.py: -------------------------------------------------------------------------------- 1 | root@dd09d64a3073.28907 -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # I do this project alone. 2 | 3 | Yonas Leykun 4 | -------------------------------------------------------------------------------- /web_static/styles/2-common.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | -------------------------------------------------------------------------------- /web_static/images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/web_static/images/icon.png -------------------------------------------------------------------------------- /web_static/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/web_static/images/logo.png -------------------------------------------------------------------------------- /web_static/images/icon_bed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/web_static/images/icon_bed.png -------------------------------------------------------------------------------- /web_static/styles/2-header.css: -------------------------------------------------------------------------------- 1 | header { 2 | background-color: #FF0000; 3 | height: 70px; 4 | width: 100%; 5 | } -------------------------------------------------------------------------------- /web_static/images/icon_bath.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/web_static/images/icon_bath.png -------------------------------------------------------------------------------- /web_static/images/icon_group.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/web_static/images/icon_group.png -------------------------------------------------------------------------------- /__pycache__/console.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/__pycache__/console.cpython-310.pyc -------------------------------------------------------------------------------- /models/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Initializes the package""" 3 | from models.engine.file_storage import FileStorage 4 | storage = FileStorage() 5 | storage.reload() 6 | -------------------------------------------------------------------------------- /one/AUTHORS: -------------------------------------------------------------------------------- 1 | # This file lists all individuals having contributed content to the repository. 2 | 3 | Ehoneah Obed 4 | Anthony Ekim 5 | -------------------------------------------------------------------------------- /tests/test_models/test_engine/__pycache__/__init__.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/tests/test_models/test_engine/__pycache__/__init__.cpython-38.pyc -------------------------------------------------------------------------------- /web_static/styles/3-common.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | color: #484848; 5 | font-size: 14px; 6 | font-family: Circular, "Helvetica Neue", Arial, sans-serif; 7 | } -------------------------------------------------------------------------------- /tests/test_models/test_engine/__pycache__/test_file_storage.cpython-38.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yonasleykun27/AirBnB_clone/HEAD/tests/test_models/test_engine/__pycache__/test_file_storage.cpython-38.pyc -------------------------------------------------------------------------------- /web_static/styles/2-footer.css: -------------------------------------------------------------------------------- 1 | footer { 2 | background-color: #00FF00; 3 | height: 60px; 4 | width: 100%; 5 | position: fixed; 6 | bottom: 0; 7 | text-align: center; 8 | line-height: 60px; 9 | } 10 | -------------------------------------------------------------------------------- /one/models/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''Initializes the package''' 3 | # from models.base_model import BaseModel 4 | from models.engine import file_storage 5 | 6 | 7 | storage = file_storage.FileStorage() 8 | storage.reload() 9 | -------------------------------------------------------------------------------- /models/state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a User class""" 3 | 4 | from models.base_model import BaseModel 5 | 6 | 7 | class State(BaseModel): 8 | """Class for managing state objects""" 9 | 10 | name = "" 11 | -------------------------------------------------------------------------------- /models/amenity.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a Amenity class""" 3 | 4 | from models.base_model import BaseModel 5 | 6 | 7 | class Amenity(BaseModel): 8 | """Class for managing amenity objects""" 9 | 10 | name = "" 11 | -------------------------------------------------------------------------------- /models/city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a User class""" 3 | 4 | from models.base_model import BaseModel 5 | 6 | 7 | class City(BaseModel): 8 | """Class for managing city objects""" 9 | 10 | state_id = "" 11 | name = "" 12 | -------------------------------------------------------------------------------- /web_static/styles/3-footer.css: -------------------------------------------------------------------------------- 1 | footer { 2 | background-color: white; 3 | height: 60px; 4 | width: 100%; 5 | border-top: 1px solid #CCCCCC; 6 | position: fixed; 7 | bottom: 0; 8 | text-align: center; 9 | line-height: 60px; 10 | } 11 | -------------------------------------------------------------------------------- /web_static/styles/3-header.css: -------------------------------------------------------------------------------- 1 | header { 2 | background-color: white; 3 | height: 70px; 4 | width: 100%; 5 | border-bottom: 1px solid #CCCCCC; 6 | background-image: url(../images/logo.png); 7 | background-repeat: no-repeat; 8 | background-position: 20px 50%; 9 | } -------------------------------------------------------------------------------- /models/review.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a Review class""" 3 | 4 | from models.base_model import BaseModel 5 | 6 | 7 | class Review(BaseModel): 8 | """Class for managing review objects""" 9 | 10 | place_id = "" 11 | user_id = "" 12 | text = "" 13 | -------------------------------------------------------------------------------- /models/user.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a User class""" 3 | from models.base_model import BaseModel 4 | 5 | 6 | class User(BaseModel): 7 | """Class for managing user objects""" 8 | 9 | email = "" 10 | password = "" 11 | first_name = "" 12 | last_name = "" 13 | -------------------------------------------------------------------------------- /web_static/styles/4-common.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | color: #484848; 5 | font-size: 14px; 6 | font-family: Circular, "Helvetica Neue", Arial, sans-serif; 7 | } 8 | div.container { 9 | max-width: 1000px; 10 | margin: 30px auto; 11 | /* text-align: center; */ 12 | } -------------------------------------------------------------------------------- /one/models/state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a User class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class State(BaseModel): 7 | '''Class for managing state objects''' 8 | name = "" 9 | 10 | def __init__(self, *args, **kwargs): 11 | '''Initializes attributes for the State class''' 12 | super().__init__(*args, **kwargs) 13 | -------------------------------------------------------------------------------- /web_static/styles/7-places.css: -------------------------------------------------------------------------------- 1 | .places { 2 | text-align: center; 3 | } 4 | .places h1 { 5 | font-size: 30px; 6 | text-align: left; 7 | } 8 | article { 9 | width: 390px; 10 | border: 1px solid #FF5A5F; 11 | border-radius: 4px; 12 | padding: 20px; 13 | margin: 20px; 14 | display: inline-block; 15 | } 16 | article h2 { 17 | font-size: 30px; 18 | text-align: center; 19 | } 20 | -------------------------------------------------------------------------------- /one/models/amenity.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a Amenity class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class Amenity(BaseModel): 7 | '''Class for managing amenity objects''' 8 | name = "" 9 | 10 | def __init__(self, *args, **kwargs): 11 | '''Initializes attributes for the Amenity class''' 12 | super().__init__(*args, **kwargs) 13 | -------------------------------------------------------------------------------- /one/models/city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a User class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class City(BaseModel): 7 | '''Class for managing city objects''' 8 | state_id = "" 9 | name = "" 10 | 11 | def __init__(self, *args, **kwargs): 12 | '''Initializes attributes for the city class''' 13 | super().__init__(*args, **kwargs) 14 | -------------------------------------------------------------------------------- /one/models/review.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a Review class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class Review(BaseModel): 7 | '''Class for managing review objects''' 8 | place_id = "" 9 | user_id = "" 10 | text = "" 11 | 12 | def __init__(self, *args, **kwargs): 13 | '''Initializes attributes for the review class''' 14 | super().__init__(*args, **kwargs) 15 | -------------------------------------------------------------------------------- /one/models/user.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a User class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class User(BaseModel): 7 | '''Class for managing user objects''' 8 | email = "" 9 | password = "" 10 | first_name = "" 11 | last_name = "" 12 | 13 | def __init__(self, *args, **kwargs): 14 | '''Initializes attributes for the User class''' 15 | super().__init__(*args, **kwargs) 16 | -------------------------------------------------------------------------------- /models/place.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module creates a Place class""" 3 | 4 | from models.base_model import BaseModel 5 | 6 | 7 | class Place(BaseModel): 8 | """Class for managing place objects""" 9 | 10 | city_id = "" 11 | user_id = "" 12 | name = "" 13 | description = "" 14 | number_rooms = 0 15 | number_bathrooms = 0 16 | max_guest = 0 17 | price_by_night = 0 18 | latitude = 0.0 19 | longitude = 0.0 20 | amenity_ids = [] 21 | -------------------------------------------------------------------------------- /web_static/0-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Airbnb 6 | 7 | 8 |
9 |
10 | Holberton School 11 |
12 | 13 | 14 | -------------------------------------------------------------------------------- /web_static/2-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Airbnb 9 | 10 | 11 |
12 |
13 |
14 | Holberton School 15 |
16 | 17 | 18 | -------------------------------------------------------------------------------- /web_static/1-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Airbnb 6 | 11 | 12 | 13 |
14 |
15 |
16 | Holberton School 17 |
18 | 19 | 20 | -------------------------------------------------------------------------------- /web_static/3-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Airbnb 10 | 11 | 12 |
13 |
14 |
15 | Holberton School 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /web_static/styles/4-filters.css: -------------------------------------------------------------------------------- 1 | div.container { 2 | max-width: 1000px; 3 | margin: 30px auto; 4 | text-align: center; 5 | } 6 | section.filters { 7 | background-color: white; 8 | height: 70px; 9 | width: 100%; 10 | border: 1px solid #DDDDDD; 11 | border-radius: 4px; 12 | } 13 | section.filters button { 14 | background-color: #FF5A5F; 15 | height: 48px; 16 | width: 20%; 17 | border: 0; 18 | border-radius: 4px; 19 | font-size: 18px; 20 | color: #FFFFFF; 21 | float: right; 22 | margin: 11px 30px; 23 | } 24 | section.filters button:hover { 25 | opacity: .9; 26 | } 27 | -------------------------------------------------------------------------------- /one/models/place.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''This module creates a Place class''' 3 | from models.base_model import BaseModel 4 | 5 | 6 | class Place(BaseModel): 7 | '''Class for managing place objects''' 8 | city_id = "" 9 | user_id = "" 10 | name = "" 11 | description = "" 12 | number_rooms = 0 13 | number_bathrooms = 0 14 | max_guest = 0 15 | price_by_night = 0 16 | latitude = 0.0 17 | longitude = 0.0 18 | amenity_ids = [] 19 | 20 | def __init__(self, *args, **kwargs): 21 | '''Initializes attributes for the place class''' 22 | super().__init__(*args, **kwargs) 23 | -------------------------------------------------------------------------------- /web_static/README.md: -------------------------------------------------------------------------------- 1 | ### Airbnb Clone 2 | 3 | #### Description 4 | > This is one phase of the Airbnb Clone: the HTML and CSS part. The Images 5 | > folder holds icons for the site (e.g. logo, bathroom icons, bedroom icons, 6 | > guest icons). The Styles folder holds CSS styling files. The largest numbered 7 | > style file of each category (e.g. common, footer, header, places) is most 8 | > relevant to the finished product. The highlest numbered index.html file is 9 | > likewise the most relevant to the finished product. 10 | 11 | ![M](https://i.imgur.com/ujItUkN.png) 12 | 13 | ### Environment 14 | * Languages: HTML, CSS 15 | * OS: Ubuntu 14.04 LTS 16 | * Style guidelines: ```./wc3validator.py [filename]``` 17 | * Preview: paste index.html link and run on: http://htmlpreview.github.io/? 18 | -------------------------------------------------------------------------------- /web_static/4-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Airbnb 11 | 12 | 13 |
14 |
15 |
16 |
17 | 18 |
19 |
20 |
21 | Holberton School 22 |
23 | 24 | 25 | -------------------------------------------------------------------------------- /web_static/W3C-Validator/README.md: -------------------------------------------------------------------------------- 1 | # W3C validator for Holberton School 2 | 3 | For HTML and CSS files. 4 | 5 | Based on 2 APIs: 6 | 7 | - https://validator.w3.org/nu/ 8 | - http://jigsaw.w3.org/css-validator/validator 9 | 10 | ## Installation 11 | 1. Clone this repo 12 | ```sh 13 | git clone https://github.com/holbertonschool/W3C-Validator.git 14 | ``` 15 | 16 | 2. Run shell script (see example in [usage](#usage) section below) 17 | 18 | ## Usage: 19 | 20 | Simple file: 21 | 22 | ```sh 23 | ./w3c_validator.py index.html 24 | ``` 25 | 26 | Multiple files: 27 | 28 | ```sh 29 | ./w3c_validator.py index.html header.html styles/common.css 30 | ``` 31 | 32 | All errors are printed in `STDERR`; Exit status = # of errors (0 on success) 33 | 34 | 35 | ## References 36 | 37 | https://developer.mozilla.org/en-US/ 38 | -------------------------------------------------------------------------------- /web_static/5-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Airbnb 11 | 12 | 13 |
14 |
15 |
16 |
17 |
18 |

States

19 |

California, Arizona...

20 |
21 |
22 |

Amenities

23 |

Internet, Kitchen...

24 |
25 | 26 |
27 |
28 |
29 | Holberton School 30 |
31 | 32 | 33 | -------------------------------------------------------------------------------- /web_static/styles/5-filters.css: -------------------------------------------------------------------------------- 1 | /* search bar */ 2 | div.container { 3 | max-width: 1000px; 4 | margin: 30px auto; 5 | text-align: center; 6 | } 7 | section.filters { 8 | background-color: white; 9 | height: 70px; 10 | width: 100%; 11 | border: 1px solid #DDDDDD; 12 | border-radius: 4px; 13 | } 14 | section.filters button { 15 | background-color: #FF5A5F; 16 | height: 48px; 17 | width: 20%; 18 | border: 0; 19 | border-radius: 4px; 20 | font-size: 18px; 21 | color: #FFFFFF; 22 | float: right; 23 | margin: 11px 30px; 24 | } 25 | section.filters button:hover { 26 | opacity: .9; 27 | } 28 | /* location and amenities part of search bar */ 29 | .locations, 30 | .amenities { 31 | height: 100%; 32 | width: 25%; 33 | float: left; 34 | } 35 | .locations { 36 | border-right: 1px solid #DDDDDD; 37 | } 38 | .locations h3, 39 | .amenities h3 { 40 | font-weight: 600; 41 | font-size: 16px; 42 | margin-top: 20px; 43 | margin-bottom: 0px; 44 | text-align: left; 45 | margin-left: 30px; 46 | } 47 | .locations h4, 48 | .amenities h4 { 49 | font-weight: 400; 50 | font-size: 14px; 51 | margin-top: 0px; 52 | margin-bottom: 0px; 53 | text-align: left; 54 | margin-left: 30px; 55 | } 56 | -------------------------------------------------------------------------------- /web_static/styles/8-places.css: -------------------------------------------------------------------------------- 1 | /* boxed list structure of places */ 2 | .places { 3 | text-align: center; 4 | } 5 | .places h1 { 6 | font-size: 30px; 7 | text-align: left; 8 | } 9 | article { 10 | width: 390px; 11 | border: 1px solid #FF5A5F; 12 | border-radius: 4px; 13 | padding: 20px; 14 | margin: 20px; 15 | display: inline-block; 16 | min-height: 250px; 17 | vertical-align: top; 18 | } 19 | article h2 { 20 | font-size: 30px; 21 | margin-top: 5px; 22 | } 23 | /* structure within boxed lists of places */ 24 | div.price_by_night { 25 | color: #FF5A5F; 26 | border: 4px solid #FF5A5F; 27 | border-radius: 100%; 28 | min-width: 60px; 29 | height: 60px; 30 | line-height: 60px; 31 | font-size: 30px; 32 | position: relative; 33 | float: right; 34 | top: -80px; 35 | } 36 | div.information { 37 | height: 80px; 38 | border-top: 1px solid #DDDDDD; 39 | border-bottom: 1px solid #DDDDDD; 40 | } 41 | div.max_guest, 42 | div.number_rooms, 43 | div.number_bathrooms { 44 | line-height: 140px; 45 | width: 100px; 46 | height: 100%; 47 | display: inline-block; 48 | background-position: 50% 5px; 49 | background-repeat: no-repeat; 50 | } 51 | .max_guest { 52 | background-image: url("../images/icon_group.png"); 53 | } 54 | .number_rooms { 55 | background-image: url("../images/icon_bed.png"); 56 | } 57 | .number_bathrooms { 58 | background-image: url("../images/icon_bath.png"); 59 | } 60 | div.user, 61 | div.description { 62 | text-align: left; 63 | margin-bottom: 10px; 64 | margin-top: 10px; 65 | } 66 | -------------------------------------------------------------------------------- /web_static/6-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | Airbnb 11 | 12 | 13 |
14 |
15 |
16 |
17 |
18 |

States

19 |

California, Arizona...

20 |
    21 |
  • Arizona:

    22 |
      23 |
    • Page
    • 24 |
    • Page2
    • 25 |
    26 |
  • 27 |
  • California:

    28 |
      29 |
    • San Francisco
    • 30 |
    • Los Altos
    • 31 |
    32 |
33 |
34 |
35 |

Amenities

36 |

Internet, Kitchen...

37 |
    38 |
  • Internet
  • 39 |
  • TV
  • 40 |
  • Kitchen
  • 41 |
  • Iron
  • 42 |
43 |
44 | 45 |
46 |
47 |
48 | Holberton School 49 |
50 | 51 | 52 | -------------------------------------------------------------------------------- /web_static/styles/6-filters.css: -------------------------------------------------------------------------------- 1 | /* search bar */ 2 | div.container { 3 | max-width: 1000px; 4 | margin: 30px auto; 5 | /* text-align: center; */ 6 | } 7 | section.filters { 8 | background-color: white; 9 | height: 70px; 10 | width: 100%; 11 | border: 1px solid #DDDDDD; 12 | border-radius: 4px; 13 | } 14 | section.filters button { 15 | background-color: #FF5A5F; 16 | height: 48px; 17 | width: 20%; 18 | border: 0; 19 | border-radius: 4px; 20 | font-size: 18px; 21 | color: #FFFFFF; 22 | float: right; 23 | margin: 11px 30px; 24 | } 25 | section.filters button:hover { 26 | opacity: .9; 27 | } 28 | /* location and amenities part of search bar */ 29 | .locations, 30 | .amenities { 31 | height: 100%; 32 | width: 25%; 33 | float: left; 34 | } 35 | .locations { 36 | border-right: 1px solid #DDDDDD; 37 | } 38 | .locations h3, 39 | .amenities h3 { 40 | font-weight: 600; 41 | font-size: 16px; 42 | margin-top: 20px; 43 | margin-bottom: 0px; 44 | text-align: left; 45 | margin-left: 30px; 46 | } 47 | .locations h4, 48 | .amenities h4 { 49 | font-weight: 400; 50 | font-size: 14px; 51 | margin-top: 0px; 52 | margin-bottom: 0px; 53 | text-align: left; 54 | margin-left: 30px; 55 | } 56 | /* display location and amenities options upon hover */ 57 | .popover { 58 | display: none; 59 | background-color: #FAFAFA; 60 | border: 1px solid #DDDDDD; 61 | border-radius: 4px; 62 | position: relative; 63 | z-index: 1; 64 | } 65 | .popover h2 { 66 | font-size: 16px; 67 | } 68 | li { 69 | list-style-type: none; 70 | margin-top:10px; 71 | margin-bottom: 10px; 72 | } 73 | .locations:hover .popover, 74 | .amenities:hover .popover { 75 | display: block; 76 | } 77 | -------------------------------------------------------------------------------- /web_static/7-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Airbnb 12 | 13 | 14 |
15 |
16 |
17 |
18 |
19 |

States

20 |

California, Arizona...

21 |
    22 |
  • Arizona:

    23 |
      24 |
    • Page
    • 25 |
    • Page2
    • 26 |
    27 |
  • 28 |
  • California:

    29 |
      30 |
    • San Francisco
    • 31 |
    • Los Altos
    • 32 |
    33 |
34 |
35 |
36 |

Amenities

37 |

Internet, Kitchen...

38 |
    39 |
  • Internet
  • 40 |
  • TV
  • 41 |
  • Kitchen
  • 42 |
  • Iron
  • 43 |
44 |
45 | 46 |
47 |
48 |

Places

49 |

My home

50 |

Tiny house

51 |

A suite

52 |
53 |
54 |
55 | Holberton School 56 |
57 | 58 | 59 | -------------------------------------------------------------------------------- /models/base_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This script is the base model""" 3 | 4 | import uuid 5 | from datetime import datetime 6 | from models import storage 7 | 8 | 9 | class BaseModel: 10 | 11 | """Class from which all other classes will inherit""" 12 | 13 | def __init__(self, *args, **kwargs): 14 | """Initializes instance attributes 15 | 16 | Args: 17 | - *args: list of arguments 18 | - **kwargs: dict of key-values arguments 19 | """ 20 | 21 | if kwargs is not None and kwargs != {}: 22 | for key in kwargs: 23 | if key == "created_at": 24 | self.__dict__["created_at"] = datetime.strptime( 25 | kwargs["created_at"], "%Y-%m-%dT%H:%M:%S.%f") 26 | elif key == "updated_at": 27 | self.__dict__["updated_at"] = datetime.strptime( 28 | kwargs["updated_at"], "%Y-%m-%dT%H:%M:%S.%f") 29 | else: 30 | self.__dict__[key] = kwargs[key] 31 | else: 32 | self.id = str(uuid.uuid4()) 33 | self.created_at = datetime.now() 34 | self.updated_at = datetime.now() 35 | storage.new(self) 36 | 37 | def __str__(self): 38 | """Returns official string representation""" 39 | 40 | return "[{}] ({}) {}".\ 41 | format(type(self).__name__, self.id, self.__dict__) 42 | 43 | def save(self): 44 | """updates the public instance attribute updated_at""" 45 | 46 | self.updated_at = datetime.now() 47 | storage.save() 48 | 49 | def to_dict(self): 50 | """returns a dictionary containing all keys/values of __dict__""" 51 | 52 | my_dict = self.__dict__.copy() 53 | my_dict["__class__"] = type(self).__name__ 54 | my_dict["created_at"] = my_dict["created_at"].isoformat() 55 | my_dict["updated_at"] = my_dict["updated_at"].isoformat() 56 | return my_dict 57 | -------------------------------------------------------------------------------- /one/models/base_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This script is the base model""" 3 | import uuid 4 | import datetime 5 | from models import storage 6 | 7 | 8 | class BaseModel(): 9 | ''''Class from which all other classes will inherit''' 10 | 11 | def __init__(self, *args, **kwargs): 12 | '''Initializes instance attributes''' 13 | 14 | if len(kwargs) == 0: 15 | self.id = str(uuid.uuid4()) 16 | self.created_at = datetime.datetime.now() 17 | self.updated_at = datetime.datetime.now() 18 | storage.new(self) 19 | else: 20 | for key in kwargs.keys(): 21 | # check and escape the __class__ key 22 | if key == "__class__": 23 | continue 24 | else: 25 | # check and change the format for updated_at & created_at 26 | if key == "updated_at" or key == "created_at": 27 | kwargs[key] = datetime.datetime.strptime( 28 | kwargs[key], "%Y-%m-%dT%H:%M:%S.%f") 29 | # set the attributes of the instance 30 | setattr(self, key, kwargs[key]) 31 | # self.key = kwargs[key] 32 | # print(f"{key}: {kwargs[key]}") 33 | 34 | def __str__(self): 35 | '''Returns official string representation''' 36 | return (f"[{self.__class__.__name__}] ({self.id}) \ 37 | {str(self.__dict__)}") 38 | 39 | def save(self): 40 | '''updates the public instance attribute updated_at''' 41 | storage.save() 42 | self.updated_at = datetime.datetime.now() 43 | 44 | def to_dict(self): 45 | '''returns a dictionary containing all keys/values of __dict__''' 46 | object_dict = {} 47 | for key in self.__dict__.keys(): 48 | if key not in ('created_at', 'updated_at'): 49 | object_dict[key] = self.__dict__[key] 50 | else: 51 | object_dict[key] = datetime.datetime.isoformat( 52 | self.__dict__[key]) 53 | object_dict['__class__'] = self.__class__.__name__ 54 | return (object_dict) 55 | -------------------------------------------------------------------------------- /web_static/W3C-Validator/w3c_validator.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """ 3 | W3C validator for Holberton School 4 | 5 | For HTML and CSS files. 6 | 7 | Based on 2 APIs: 8 | 9 | - https://validator.w3.org/nu/ 10 | - http://jigsaw.w3.org/css-validator/validator 11 | 12 | 13 | Usage: 14 | 15 | Simple file: 16 | 17 | ``` 18 | ./w3c_validator.py index.html 19 | ``` 20 | 21 | Multiple files: 22 | 23 | ``` 24 | ./w3c_validator.py index.html header.html styles/common.css 25 | ``` 26 | 27 | All errors are printed in `STDERR` 28 | 29 | Return: 30 | Exit status is the # of errors, 0 on Success 31 | 32 | References 33 | 34 | https://developer.mozilla.org/en-US/ 35 | 36 | """ 37 | import sys 38 | import requests 39 | 40 | 41 | def __print_stdout(msg): 42 | """Print message in STDOUT 43 | """ 44 | sys.stdout.write(msg) 45 | 46 | 47 | def __print_stderr(msg): 48 | """Print message in STDERR 49 | """ 50 | sys.stderr.write(msg) 51 | 52 | 53 | def __analyse_html(file_path): 54 | """Start analyse of HTML file 55 | """ 56 | h = {'Content-Type': "text/html; charset=utf-8"} 57 | d = open(file_path, "rb").read() 58 | u = "https://validator.w3.org/nu/?out=json" 59 | r = requests.post(u, headers=h, data=d) 60 | res = [] 61 | messages = r.json().get('messages', []) 62 | for m in messages: 63 | res.append("[{}:{}] {}".format(file_path, m['lastLine'], m['message'])) 64 | return res 65 | 66 | 67 | def __analyse_css(file_path): 68 | """Start analyse of CSS file 69 | """ 70 | d = {'output': "json"} 71 | f = {'file': (file_path, open(file_path, 'rb'), 'text/css')} 72 | u = "http://jigsaw.w3.org/css-validator/validator" 73 | r = requests.post(u, data=d, files=f) 74 | res = [] 75 | errors = r.json().get('cssvalidation', {}).get('errors', []) 76 | for e in errors: 77 | res.append("[{}:{}] {}".format(file_path, e['line'], e['message'])) 78 | return res 79 | 80 | 81 | def __analyse(file_path): 82 | """Start analyse of a file and print the result 83 | """ 84 | nb_errors = 0 85 | try: 86 | result = None 87 | if file_path.endswith('.css'): 88 | result = __analyse_css(file_path) 89 | else: 90 | result = __analyse_html(file_path) 91 | 92 | if len(result) > 0: 93 | for msg in result: 94 | __print_stderr("{}\n".format(msg)) 95 | nb_errors += 1 96 | else: 97 | __print_stdout("{}: OK\n".format(file_path)) 98 | 99 | except Exception as e: 100 | __print_stderr("[{}] {}\n".format(e.__class__.__name__, e)) 101 | return nb_errors 102 | 103 | 104 | def __files_loop(): 105 | """Loop that analyses for each file from input arguments 106 | """ 107 | nb_errors = 0 108 | for file_path in sys.argv[1:]: 109 | nb_errors += __analyse(file_path) 110 | 111 | return nb_errors 112 | 113 | 114 | if __name__ == "__main__": 115 | """Main 116 | """ 117 | if len(sys.argv) < 2: 118 | __print_stderr("usage: w3c_validator.py file1 file2 ...\n") 119 | exit(1) 120 | 121 | """execute tests, then exit. Exit status = # of errors (0 on success) 122 | """ 123 | sys.exit(__files_loop()) 124 | -------------------------------------------------------------------------------- /models/engine/file_storage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module for FileStorage class.""" 3 | import datetime 4 | import json 5 | import os 6 | 7 | 8 | class FileStorage: 9 | 10 | """Class for storing and retrieving data""" 11 | __file_path = "file.json" 12 | __objects = {} 13 | 14 | def all(self): 15 | """returns the dictionary __objects""" 16 | return FileStorage.__objects 17 | 18 | def new(self, obj): 19 | """sets in __objects the obj with key .id""" 20 | key = "{}.{}".format(type(obj).__name__, obj.id) 21 | FileStorage.__objects[key] = obj 22 | 23 | def save(self): 24 | """ serializes __objects to the JSON file (path: __file_path)""" 25 | with open(FileStorage.__file_path, "w", encoding="utf-8") as f: 26 | d = {k: v.to_dict() for k, v in FileStorage.__objects.items()} 27 | json.dump(d, f) 28 | 29 | def classes(self): 30 | """Returns a dictionary of valid classes and their references""" 31 | from models.base_model import BaseModel 32 | from models.user import User 33 | from models.state import State 34 | from models.city import City 35 | from models.amenity import Amenity 36 | from models.place import Place 37 | from models.review import Review 38 | 39 | classes = {"BaseModel": BaseModel, 40 | "User": User, 41 | "State": State, 42 | "City": City, 43 | "Amenity": Amenity, 44 | "Place": Place, 45 | "Review": Review} 46 | return classes 47 | 48 | def reload(self): 49 | """Reloads the stored objects""" 50 | if not os.path.isfile(FileStorage.__file_path): 51 | return 52 | with open(FileStorage.__file_path, "r", encoding="utf-8") as f: 53 | obj_dict = json.load(f) 54 | obj_dict = {k: self.classes()[v["__class__"]](**v) 55 | for k, v in obj_dict.items()} 56 | # TODO: should this overwrite or insert? 57 | FileStorage.__objects = obj_dict 58 | 59 | def attributes(self): 60 | """Returns the valid attributes and their types for classname""" 61 | attributes = { 62 | "BaseModel": 63 | {"id": str, 64 | "created_at": datetime.datetime, 65 | "updated_at": datetime.datetime}, 66 | "User": 67 | {"email": str, 68 | "password": str, 69 | "first_name": str, 70 | "last_name": str}, 71 | "State": 72 | {"name": str}, 73 | "City": 74 | {"state_id": str, 75 | "name": str}, 76 | "Amenity": 77 | {"name": str}, 78 | "Place": 79 | {"city_id": str, 80 | "user_id": str, 81 | "name": str, 82 | "description": str, 83 | "number_rooms": int, 84 | "number_bathrooms": int, 85 | "max_guest": int, 86 | "price_by_night": int, 87 | "latitude": float, 88 | "longitude": float, 89 | "amenity_ids": list}, 90 | "Review": 91 | {"place_id": str, 92 | "user_id": str, 93 | "text": str} 94 | } 95 | return attributes 96 | -------------------------------------------------------------------------------- /web_static/8-index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | Airbnb 15 | 16 | 17 |
18 |
19 |
20 |
21 |
22 |

States

23 |

California, Arizona...

24 |
    25 |
  • Arizona:

    26 |
      27 |
    • Page
    • 28 |
    • Page2
    • 29 |
    30 |
  • 31 |
  • California:

    32 |
      33 |
    • San Francisco
    • 34 |
    • Los Altos
    • 35 |
    36 |
37 |
38 |
39 |

Amenities

40 |

Internet, Kitchen...

41 |
    42 |
  • Internet
  • 43 |
  • TV
  • 44 |
  • Kitchen
  • 45 |
  • Iron
  • 46 |
47 |
48 | 49 |
50 |
51 |

Places

52 |
53 |

My home

54 |
$80
55 |
56 |
2 guests
57 |
1 bedroom
58 |
1 bathroom
59 |
60 |
Owner: Longye Chen
61 |
This is a lovely 1 bedroom and 1 bathroom apartment that can accomodate 2 people. It is located at the center of Shanghai and next to subway line 1, 1 stop to People Square, 2 stops to Bund, and 3 stops to Jingan Temple.
62 |
63 |

Tiny house

64 |
$50
65 |
66 |
1 guest
67 |
1 bedroom
68 |
1 bathroom
69 |
70 |
Owner: Mel X
71 |
This is a tiny, tight, and cozy getaway. Affordable and not too shabby. Perfect for those on a budget.
72 |
73 |

A suite

74 |
$160
75 |
76 |
2 guests
77 |
1 bedroom
78 |
2 bathrooms
79 |
80 |
Owner: Christina Chiu
81 |
Beautiful suite with balcony worthy of Romeo and Juliet's love story.
82 |
83 |
84 |
85 |
86 | Holberton School 87 |
88 | 89 | 90 | -------------------------------------------------------------------------------- /one/tests/test_console.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module for testing the HBNBCommand Class""" 3 | import unittest 4 | from console import HBNBCommand 5 | from unittest.mock import patch 6 | from io import StringIO 7 | 8 | 9 | class Test_Console(unittest.TestCase): 10 | """Test the HBNBCommand Console""" 11 | 12 | # def test_help(self): 13 | # """Tests the help commmand""" 14 | # with patch('sys.stdout', new=StringIO()) as f: 15 | # HBNBCommand().onecmd("help") 16 | # string = """ 17 | # Documented commands (type help ): 18 | # ======================================== 19 | # EOF all count create destroy help quit show update 20 | # """ 21 | # msg = f.getvalue() 22 | # self.assertEqual(string, msg) 23 | 24 | def test_help(self): 25 | """Tests the help command.""" 26 | with patch('sys.stdout', new=StringIO()) as f: 27 | HBNBCommand().onecmd("help") 28 | s = """ 29 | Documented commands (type help ): 30 | ======================================== 31 | EOF all count create destroy help quit show update\n 32 | """ 33 | self.assertEqual(s, f.getvalue()) 34 | 35 | # Test cases for quit 36 | 37 | def test_do_quit(self): 38 | """Tests the quit commmand""" 39 | with patch('sys.stdout', new=StringIO()) as f: 40 | HBNBCommand().onecmd("quit") 41 | # modelling what happens when someone types `quit` 42 | msg = f.getvalue() 43 | self.assertTrue(len(msg) == 0) 44 | self.assertEqual("", msg) 45 | 46 | with patch('sys.stdout', new=StringIO()) as f: 47 | HBNBCommand().onecmd("quit garbage") 48 | # modelling when user types `quit anything` 49 | msg = f.getvalue() 50 | self.assertTrue(len(msg) == 0) 51 | self.assertEqual("", msg) 52 | 53 | # Test cases for EOF 54 | def test_do_EOF(self): 55 | """Tests the EOF commmand""" 56 | with patch('sys.stdout', new=StringIO()) as f: 57 | HBNBCommand().onecmd("EOF") 58 | # modelling what happens when user types `quit` 59 | msg = f.getvalue() 60 | self.assertTrue(len(msg) == 1) 61 | self.assertEqual("\n", msg) 62 | 63 | with patch('sys.stdout', new=StringIO()) as f: 64 | HBNBCommand().onecmd("EOF garbage") 65 | # modelling when user types `EOF anything` 66 | msg = f.getvalue() 67 | self.assertTrue(len(msg) == 1) 68 | self.assertEqual("\n", msg) 69 | 70 | # Test cases for emptyline 71 | def test_do_emptyline(self): 72 | """Tests the emptyline command""" 73 | with patch('sys.stdout', new=StringIO()) as f: 74 | HBNBCommand().onecmd("\n") 75 | # modelling what happens when user doesn't type anything 76 | msg = f.getvalue() 77 | self.assertTrue(len(msg) == 0) 78 | self.assertEqual("", msg) 79 | 80 | with patch('sys.stdout', new=StringIO()) as f: 81 | HBNBCommand().onecmd(" \n") 82 | # modelling when user types lots of whitespaces & enter 83 | msg = f.getvalue() 84 | self.assertTrue(len(msg) == 0) 85 | self.assertEqual("", msg) 86 | 87 | # Test cases for do_all 88 | def test_do_all(self): 89 | """Tests the do_all command""" 90 | with patch('sys.stdout', new=StringIO()) as f: 91 | HBNBCommand().onecmd("all") 92 | 93 | # Test cases for do_count 94 | # Test cases for do_show 95 | # Test cases for do_create 96 | # Test cases for do_update 97 | # Test cases for do_destroy 98 | 99 | 100 | if __name__ == "__main__": 101 | unittest.main() 102 | -------------------------------------------------------------------------------- /one/models/engine/file_storage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """This module is the file storage class""" 3 | import json 4 | import os 5 | import datetime 6 | 7 | 8 | class FileStorage(): 9 | """Class for storing and retrieving data""" 10 | __file_path = "file.json" 11 | __objects = {} 12 | 13 | # def __init__(self): 14 | # pass 15 | 16 | def all(self): 17 | '''returns the dictionary __objects''' 18 | return self.__objects 19 | 20 | def new(self, obj): 21 | '''sets in __objects the obj with key .id''' 22 | objname = obj.__class__.__name__ 23 | objID = obj.id 24 | key = f"{objname}.{objID}" # .id = obj 25 | self.__objects[key] = obj 26 | 27 | def save(self): 28 | ''' serializes __objects to the JSON file (path: __file_path)''' 29 | # serialize the object by first converting it to a dictionary 30 | object_dict = {} 31 | 32 | for key in self.__objects.keys(): 33 | if type(self.__objects[key]) != dict: 34 | object_dict[key] = self.__objects[key].to_dict() 35 | # convert the dictionary object to json and write to the file 36 | file_name = self.__file_path 37 | with open(file_name, "w", encoding="utf-8") as jsonfile: 38 | # json.dump(object_dict, jsonfile) 39 | jsonfile.write(json.dumps(object_dict)) 40 | 41 | def classes(self): 42 | """Returns a dictionary of valid classes and their references.""" 43 | from models.base_model import BaseModel 44 | from models.user import User 45 | from models.state import State 46 | from models.city import City 47 | from models.amenity import Amenity 48 | from models.place import Place 49 | from models.review import Review 50 | 51 | classes = {"BaseModel": BaseModel, 52 | "User": User, 53 | "State": State, 54 | "City": City, 55 | "Amenity": Amenity, 56 | "Place": Place, 57 | "Review": Review 58 | } 59 | return classes 60 | 61 | def reload(self): 62 | """Reloads the stored objects""" 63 | if os.path.exists(FileStorage.__file_path): 64 | # load the file and dump content as dictionary 65 | with open(FileStorage.__file_path, "r", encoding="utf-8") \ 66 | as my_file: 67 | object_dict = json.loads(my_file.read()) 68 | final_dict = {} 69 | 70 | for id, dictionary in object_dict.items(): 71 | class_name = dictionary['__class__'] 72 | final_dict[id] = self.classes()[class_name](**dictionary) 73 | FileStorage.__objects = final_dict 74 | 75 | def attributes(self): 76 | """Returns the valid attributes and their types for classname.""" 77 | attributes = { 78 | "BaseModel": 79 | {"id": str, 80 | "created_at": datetime.datetime, 81 | "updated_at": datetime.datetime}, 82 | "User": 83 | {"email": str, 84 | "password": str, 85 | "first_name": str, 86 | "last_name": str}, 87 | "State": 88 | {"name": str}, 89 | "City": 90 | {"state_id": str, 91 | "name": str}, 92 | "Amenity": 93 | {"name": str}, 94 | "Place": 95 | {"city_id": str, 96 | "user_id": str, 97 | "name": str, 98 | "description": str, 99 | "number_rooms": int, 100 | "number_bathrooms": int, 101 | "max_guest": int, 102 | "price_by_night": int, 103 | "latitude": float, 104 | "longitude": float, 105 | "amenity_ids": list}, 106 | "Review": 107 | {"place_id": str, 108 | "user_id": str, 109 | "text": str} 110 | } 111 | return attributes 112 | -------------------------------------------------------------------------------- /tests/test_models/test_engine/test_file_storage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/engine/file_storage.py. 3 | 4 | Unittest classes: 5 | TestFileStorage_instantiation 6 | TestFileStorage_methods 7 | """ 8 | import os 9 | import json 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from models.base_model import BaseModel 14 | from models.engine.file_storage import FileStorage 15 | from models.user import User 16 | from models.state import State 17 | from models.place import Place 18 | from models.city import City 19 | from models.amenity import Amenity 20 | from models.review import Review 21 | 22 | 23 | class TestFileStorage_instantiation(unittest.TestCase): 24 | """Unittests for testing instantiation of the FileStorage class.""" 25 | 26 | def test_FileStorage_instantiation_no_args(self): 27 | self.assertEqual(type(FileStorage()), FileStorage) 28 | 29 | def test_FileStorage_instantiation_with_arg(self): 30 | with self.assertRaises(TypeError): 31 | FileStorage(None) 32 | 33 | def test_FileStorage_file_path_is_private_str(self): 34 | self.assertEqual(str, type(FileStorage._FileStorage__file_path)) 35 | 36 | def testFileStorage_objects_is_private_dict(self): 37 | self.assertEqual(dict, type(FileStorage._FileStorage__objects)) 38 | 39 | def test_storage_initializes(self): 40 | self.assertEqual(type(models.storage), FileStorage) 41 | 42 | 43 | class TestFileStorage_methods(unittest.TestCase): 44 | """Unittests for testing methods of the FileStorage class.""" 45 | 46 | @classmethod 47 | def setUp(self): 48 | try: 49 | os.rename("file.json", "tmp") 50 | except IOError: 51 | pass 52 | 53 | @classmethod 54 | def tearDown(self): 55 | try: 56 | os.remove("file.json") 57 | except IOError: 58 | pass 59 | try: 60 | os.rename("tmp", "file.json") 61 | except IOError: 62 | pass 63 | FileStorage._FileStorage__objects = {} 64 | 65 | def test_all(self): 66 | self.assertEqual(dict, type(models.storage.all())) 67 | 68 | def test_all_with_arg(self): 69 | with self.assertRaises(TypeError): 70 | models.storage.all(None) 71 | 72 | def test_new(self): 73 | bm = BaseModel() 74 | us = User() 75 | st = State() 76 | pl = Place() 77 | cy = City() 78 | am = Amenity() 79 | rv = Review() 80 | models.storage.new(bm) 81 | models.storage.new(us) 82 | models.storage.new(st) 83 | models.storage.new(pl) 84 | models.storage.new(cy) 85 | models.storage.new(am) 86 | models.storage.new(rv) 87 | self.assertIn("BaseModel." + bm.id, models.storage.all().keys()) 88 | self.assertIn(bm, models.storage.all().values()) 89 | self.assertIn("User." + us.id, models.storage.all().keys()) 90 | self.assertIn(us, models.storage.all().values()) 91 | self.assertIn("State." + st.id, models.storage.all().keys()) 92 | self.assertIn(st, models.storage.all().values()) 93 | self.assertIn("Place." + pl.id, models.storage.all().keys()) 94 | self.assertIn(pl, models.storage.all().values()) 95 | self.assertIn("City." + cy.id, models.storage.all().keys()) 96 | self.assertIn(cy, models.storage.all().values()) 97 | self.assertIn("Amenity." + am.id, models.storage.all().keys()) 98 | self.assertIn(am, models.storage.all().values()) 99 | self.assertIn("Review." + rv.id, models.storage.all().keys()) 100 | self.assertIn(rv, models.storage.all().values()) 101 | 102 | def test_new_with_args(self): 103 | with self.assertRaises(TypeError): 104 | models.storage.new(BaseModel(), 1) 105 | 106 | def test_new_with_None(self): 107 | with self.assertRaises(AttributeError): 108 | models.storage.new(None) 109 | 110 | def test_save(self): 111 | bm = BaseModel() 112 | us = User() 113 | st = State() 114 | pl = Place() 115 | cy = City() 116 | am = Amenity() 117 | rv = Review() 118 | models.storage.new(bm) 119 | models.storage.new(us) 120 | models.storage.new(st) 121 | models.storage.new(pl) 122 | models.storage.new(cy) 123 | models.storage.new(am) 124 | models.storage.new(rv) 125 | models.storage.save() 126 | save_text = "" 127 | with open("file.json", "r") as f: 128 | save_text = f.read() 129 | self.assertIn("BaseModel." + bm.id, save_text) 130 | self.assertIn("User." + us.id, save_text) 131 | self.assertIn("State." + st.id, save_text) 132 | self.assertIn("Place." + pl.id, save_text) 133 | self.assertIn("City." + cy.id, save_text) 134 | self.assertIn("Amenity." + am.id, save_text) 135 | self.assertIn("Review." + rv.id, save_text) 136 | 137 | def test_save_with_arg(self): 138 | with self.assertRaises(TypeError): 139 | models.storage.save(None) 140 | 141 | def test_reload(self): 142 | bm = BaseModel() 143 | us = User() 144 | st = State() 145 | pl = Place() 146 | cy = City() 147 | am = Amenity() 148 | rv = Review() 149 | models.storage.new(bm) 150 | models.storage.new(us) 151 | models.storage.new(st) 152 | models.storage.new(pl) 153 | models.storage.new(cy) 154 | models.storage.new(am) 155 | models.storage.new(rv) 156 | models.storage.save() 157 | models.storage.reload() 158 | objs = FileStorage._FileStorage__objects 159 | self.assertIn("BaseModel." + bm.id, objs) 160 | self.assertIn("User." + us.id, objs) 161 | self.assertIn("State." + st.id, objs) 162 | self.assertIn("Place." + pl.id, objs) 163 | self.assertIn("City." + cy.id, objs) 164 | self.assertIn("Amenity." + am.id, objs) 165 | self.assertIn("Review." + rv.id, objs) 166 | 167 | def test_reload_with_arg(self): 168 | with self.assertRaises(TypeError): 169 | models.storage.reload(None) 170 | 171 | 172 | if __name__ == "__main__": 173 | unittest.main() 174 | -------------------------------------------------------------------------------- /tests/test_models/test_state.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/state.py. 3 | 4 | Unittest classes: 5 | TestState_instantiation 6 | TestState_save 7 | TestState_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.state import State 15 | 16 | 17 | class TestState_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the State class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(State, type(State())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(State(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(State().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(State().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(State().updated_at)) 34 | 35 | def test_name_is_public_class_attribute(self): 36 | st = State() 37 | self.assertEqual(str, type(State.name)) 38 | self.assertIn("name", dir(st)) 39 | self.assertNotIn("name", st.__dict__) 40 | 41 | def test_two_states_unique_ids(self): 42 | st1 = State() 43 | st2 = State() 44 | self.assertNotEqual(st1.id, st2.id) 45 | 46 | def test_two_states_different_created_at(self): 47 | st1 = State() 48 | sleep(0.05) 49 | st2 = State() 50 | self.assertLess(st1.created_at, st2.created_at) 51 | 52 | def test_two_states_different_updated_at(self): 53 | st1 = State() 54 | sleep(0.05) 55 | st2 = State() 56 | self.assertLess(st1.updated_at, st2.updated_at) 57 | 58 | def test_str_representation(self): 59 | dt = datetime.today() 60 | dt_repr = repr(dt) 61 | st = State() 62 | st.id = "123456" 63 | st.created_at = st.updated_at = dt 64 | ststr = st.__str__() 65 | self.assertIn("[State] (123456)", ststr) 66 | self.assertIn("'id': '123456'", ststr) 67 | self.assertIn("'created_at': " + dt_repr, ststr) 68 | self.assertIn("'updated_at': " + dt_repr, ststr) 69 | 70 | def test_args_unused(self): 71 | st = State(None) 72 | self.assertNotIn(None, st.__dict__.values()) 73 | 74 | def test_instantiation_with_kwargs(self): 75 | dt = datetime.today() 76 | dt_iso = dt.isoformat() 77 | st = State(id="345", created_at=dt_iso, updated_at=dt_iso) 78 | self.assertEqual(st.id, "345") 79 | self.assertEqual(st.created_at, dt) 80 | self.assertEqual(st.updated_at, dt) 81 | 82 | def test_instantiation_with_None_kwargs(self): 83 | with self.assertRaises(TypeError): 84 | State(id=None, created_at=None, updated_at=None) 85 | 86 | 87 | class TestState_save(unittest.TestCase): 88 | """Unittests for testing save method of the State class.""" 89 | 90 | @classmethod 91 | def setUp(self): 92 | try: 93 | os.rename("file.json", "tmp") 94 | except IOError: 95 | pass 96 | 97 | def tearDown(self): 98 | try: 99 | os.remove("file.json") 100 | except IOError: 101 | pass 102 | try: 103 | os.rename("tmp", "file.json") 104 | except IOError: 105 | pass 106 | 107 | def test_one_save(self): 108 | st = State() 109 | sleep(0.05) 110 | first_updated_at = st.updated_at 111 | st.save() 112 | self.assertLess(first_updated_at, st.updated_at) 113 | 114 | def test_two_saves(self): 115 | st = State() 116 | sleep(0.05) 117 | first_updated_at = st.updated_at 118 | st.save() 119 | second_updated_at = st.updated_at 120 | self.assertLess(first_updated_at, second_updated_at) 121 | sleep(0.05) 122 | st.save() 123 | self.assertLess(second_updated_at, st.updated_at) 124 | 125 | def test_save_with_arg(self): 126 | st = State() 127 | with self.assertRaises(TypeError): 128 | st.save(None) 129 | 130 | def test_save_updates_file(self): 131 | st = State() 132 | st.save() 133 | stid = "State." + st.id 134 | with open("file.json", "r") as f: 135 | self.assertIn(stid, f.read()) 136 | 137 | 138 | class TestState_to_dict(unittest.TestCase): 139 | """Unittests for testing to_dict method of the State class.""" 140 | 141 | def test_to_dict_type(self): 142 | self.assertTrue(dict, type(State().to_dict())) 143 | 144 | def test_to_dict_contains_correct_keys(self): 145 | st = State() 146 | self.assertIn("id", st.to_dict()) 147 | self.assertIn("created_at", st.to_dict()) 148 | self.assertIn("updated_at", st.to_dict()) 149 | self.assertIn("__class__", st.to_dict()) 150 | 151 | def test_to_dict_contains_added_attributes(self): 152 | st = State() 153 | st.middle_name = "Holberton" 154 | st.my_number = 98 155 | self.assertEqual("Holberton", st.middle_name) 156 | self.assertIn("my_number", st.to_dict()) 157 | 158 | def test_to_dict_datetime_attributes_are_strs(self): 159 | st = State() 160 | st_dict = st.to_dict() 161 | self.assertEqual(str, type(st_dict["id"])) 162 | self.assertEqual(str, type(st_dict["created_at"])) 163 | self.assertEqual(str, type(st_dict["updated_at"])) 164 | 165 | def test_to_dict_output(self): 166 | dt = datetime.today() 167 | st = State() 168 | st.id = "123456" 169 | st.created_at = st.updated_at = dt 170 | tdict = { 171 | 'id': '123456', 172 | '__class__': 'State', 173 | 'created_at': dt.isoformat(), 174 | 'updated_at': dt.isoformat(), 175 | } 176 | self.assertDictEqual(st.to_dict(), tdict) 177 | 178 | def test_contrast_to_dict_dunder_dict(self): 179 | st = State() 180 | self.assertNotEqual(st.to_dict(), st.__dict__) 181 | 182 | def test_to_dict_with_arg(self): 183 | st = State() 184 | with self.assertRaises(TypeError): 185 | st.to_dict(None) 186 | 187 | 188 | if __name__ == "__main__": 189 | unittest.main() 190 | -------------------------------------------------------------------------------- /tests/test_models/test_user.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/user.py. 3 | 4 | Unittest classes: 5 | TestUser_instantiation 6 | TestUser_save 7 | TestUser_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.user import User 15 | 16 | 17 | class TestUser_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the User class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(User, type(User())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(User(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(User().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(User().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(User().updated_at)) 34 | 35 | def test_email_is_public_str(self): 36 | self.assertEqual(str, type(User.email)) 37 | 38 | def test_password_is_public_str(self): 39 | self.assertEqual(str, type(User.password)) 40 | 41 | def test_first_name_is_public_str(self): 42 | self.assertEqual(str, type(User.first_name)) 43 | 44 | def test_last_name_is_public_str(self): 45 | self.assertEqual(str, type(User.last_name)) 46 | 47 | def test_two_users_unique_ids(self): 48 | us1 = User() 49 | us2 = User() 50 | self.assertNotEqual(us1.id, us2.id) 51 | 52 | def test_two_users_different_created_at(self): 53 | us1 = User() 54 | sleep(0.05) 55 | us2 = User() 56 | self.assertLess(us1.created_at, us2.created_at) 57 | 58 | def test_two_users_different_updated_at(self): 59 | us1 = User() 60 | sleep(0.05) 61 | us2 = User() 62 | self.assertLess(us1.updated_at, us2.updated_at) 63 | 64 | def test_str_representation(self): 65 | dt = datetime.today() 66 | dt_repr = repr(dt) 67 | us = User() 68 | us.id = "123456" 69 | us.created_at = us.updated_at = dt 70 | usstr = us.__str__() 71 | self.assertIn("[User] (123456)", usstr) 72 | self.assertIn("'id': '123456'", usstr) 73 | self.assertIn("'created_at': " + dt_repr, usstr) 74 | self.assertIn("'updated_at': " + dt_repr, usstr) 75 | 76 | def test_args_unused(self): 77 | us = User(None) 78 | self.assertNotIn(None, us.__dict__.values()) 79 | 80 | def test_instantiation_with_kwargs(self): 81 | dt = datetime.today() 82 | dt_iso = dt.isoformat() 83 | us = User(id="345", created_at=dt_iso, updated_at=dt_iso) 84 | self.assertEqual(us.id, "345") 85 | self.assertEqual(us.created_at, dt) 86 | self.assertEqual(us.updated_at, dt) 87 | 88 | def test_instantiation_with_None_kwargs(self): 89 | with self.assertRaises(TypeError): 90 | User(id=None, created_at=None, updated_at=None) 91 | 92 | 93 | class TestUser_save(unittest.TestCase): 94 | """Unittests for testing save method of the class.""" 95 | 96 | @classmethod 97 | def setUp(self): 98 | try: 99 | os.rename("file.json", "tmp") 100 | except IOError: 101 | pass 102 | 103 | def tearDown(self): 104 | try: 105 | os.remove("file.json") 106 | except IOError: 107 | pass 108 | try: 109 | os.rename("tmp", "file.json") 110 | except IOError: 111 | pass 112 | 113 | def test_one_save(self): 114 | us = User() 115 | sleep(0.05) 116 | first_updated_at = us.updated_at 117 | us.save() 118 | self.assertLess(first_updated_at, us.updated_at) 119 | 120 | def test_two_saves(self): 121 | us = User() 122 | sleep(0.05) 123 | first_updated_at = us.updated_at 124 | us.save() 125 | second_updated_at = us.updated_at 126 | self.assertLess(first_updated_at, second_updated_at) 127 | sleep(0.05) 128 | us.save() 129 | self.assertLess(second_updated_at, us.updated_at) 130 | 131 | def test_save_with_arg(self): 132 | us = User() 133 | with self.assertRaises(TypeError): 134 | us.save(None) 135 | 136 | def test_save_updates_file(self): 137 | us = User() 138 | us.save() 139 | usid = "User." + us.id 140 | with open("file.json", "r") as f: 141 | self.assertIn(usid, f.read()) 142 | 143 | 144 | class TestUser_to_dict(unittest.TestCase): 145 | """Unittests for testing to_dict method of the User class.""" 146 | 147 | def test_to_dict_type(self): 148 | self.assertTrue(dict, type(User().to_dict())) 149 | 150 | def test_to_dict_contains_correct_keys(self): 151 | us = User() 152 | self.assertIn("id", us.to_dict()) 153 | self.assertIn("created_at", us.to_dict()) 154 | self.assertIn("updated_at", us.to_dict()) 155 | self.assertIn("__class__", us.to_dict()) 156 | 157 | def test_to_dict_contains_added_attributes(self): 158 | us = User() 159 | us.middle_name = "Holberton" 160 | us.my_number = 98 161 | self.assertEqual("Holberton", us.middle_name) 162 | self.assertIn("my_number", us.to_dict()) 163 | 164 | def test_to_dict_datetime_attributes_are_strs(self): 165 | us = User() 166 | us_dict = us.to_dict() 167 | self.assertEqual(str, type(us_dict["id"])) 168 | self.assertEqual(str, type(us_dict["created_at"])) 169 | self.assertEqual(str, type(us_dict["updated_at"])) 170 | 171 | def test_to_dict_output(self): 172 | dt = datetime.today() 173 | us = User() 174 | us.id = "123456" 175 | us.created_at = us.updated_at = dt 176 | tdict = { 177 | 'id': '123456', 178 | '__class__': 'User', 179 | 'created_at': dt.isoformat(), 180 | 'updated_at': dt.isoformat(), 181 | } 182 | self.assertDictEqual(us.to_dict(), tdict) 183 | 184 | def test_contrast_to_dict_dunder_dict(self): 185 | us = User() 186 | self.assertNotEqual(us.to_dict(), us.__dict__) 187 | 188 | def test_to_dict_with_arg(self): 189 | us = User() 190 | with self.assertRaises(TypeError): 191 | us.to_dict(None) 192 | 193 | 194 | if __name__ == "__main__": 195 | unittest.main() 196 | -------------------------------------------------------------------------------- /tests/test_models/test_amenity.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/amenity.py. 3 | 4 | Unittest classes: 5 | TestAmenity_instantiation 6 | TestAmenity_save 7 | TestAmenity_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.amenity import Amenity 15 | 16 | 17 | class TestAmenity_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the Amenity class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(Amenity, type(Amenity())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(Amenity(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(Amenity().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(Amenity().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(Amenity().updated_at)) 34 | 35 | def test_name_is_public_class_attribute(self): 36 | am = Amenity() 37 | self.assertEqual(str, type(Amenity.name)) 38 | self.assertIn("name", dir(Amenity())) 39 | self.assertNotIn("name", am.__dict__) 40 | 41 | def test_two_amenities_unique_ids(self): 42 | am1 = Amenity() 43 | am2 = Amenity() 44 | self.assertNotEqual(am1.id, am2.id) 45 | 46 | def test_two_amenities_different_created_at(self): 47 | am1 = Amenity() 48 | sleep(0.05) 49 | am2 = Amenity() 50 | self.assertLess(am1.created_at, am2.created_at) 51 | 52 | def test_two_amenities_different_updated_at(self): 53 | am1 = Amenity() 54 | sleep(0.05) 55 | am2 = Amenity() 56 | self.assertLess(am1.updated_at, am2.updated_at) 57 | 58 | def test_str_representation(self): 59 | dt = datetime.today() 60 | dt_repr = repr(dt) 61 | am = Amenity() 62 | am.id = "123456" 63 | am.created_at = am.updated_at = dt 64 | amstr = am.__str__() 65 | self.assertIn("[Amenity] (123456)", amstr) 66 | self.assertIn("'id': '123456'", amstr) 67 | self.assertIn("'created_at': " + dt_repr, amstr) 68 | self.assertIn("'updated_at': " + dt_repr, amstr) 69 | 70 | def test_args_unused(self): 71 | am = Amenity(None) 72 | self.assertNotIn(None, am.__dict__.values()) 73 | 74 | def test_instantiation_with_kwargs(self): 75 | """instantiation with kwargs test method""" 76 | dt = datetime.today() 77 | dt_iso = dt.isoformat() 78 | am = Amenity(id="345", created_at=dt_iso, updated_at=dt_iso) 79 | self.assertEqual(am.id, "345") 80 | self.assertEqual(am.created_at, dt) 81 | self.assertEqual(am.updated_at, dt) 82 | 83 | def test_instantiation_with_None_kwargs(self): 84 | with self.assertRaises(TypeError): 85 | Amenity(id=None, created_at=None, updated_at=None) 86 | 87 | 88 | class TestAmenity_save(unittest.TestCase): 89 | """Unittests for testing save method of the Amenity class.""" 90 | 91 | @classmethod 92 | def setUp(self): 93 | try: 94 | os.rename("file.json", "tmp") 95 | except IOError: 96 | pass 97 | 98 | def tearDown(self): 99 | try: 100 | os.remove("file.json") 101 | except IOError: 102 | pass 103 | try: 104 | os.rename("tmp", "file.json") 105 | except IOError: 106 | pass 107 | 108 | def test_one_save(self): 109 | am = Amenity() 110 | sleep(0.05) 111 | first_updated_at = am.updated_at 112 | am.save() 113 | self.assertLess(first_updated_at, am.updated_at) 114 | 115 | def test_two_saves(self): 116 | am = Amenity() 117 | sleep(0.05) 118 | first_updated_at = am.updated_at 119 | am.save() 120 | second_updated_at = am.updated_at 121 | self.assertLess(first_updated_at, second_updated_at) 122 | sleep(0.05) 123 | am.save() 124 | self.assertLess(second_updated_at, am.updated_at) 125 | 126 | def test_save_with_arg(self): 127 | am = Amenity() 128 | with self.assertRaises(TypeError): 129 | am.save(None) 130 | 131 | def test_save_updates_file(self): 132 | am = Amenity() 133 | am.save() 134 | amid = "Amenity." + am.id 135 | with open("file.json", "r") as f: 136 | self.assertIn(amid, f.read()) 137 | 138 | 139 | class TestAmenity_to_dict(unittest.TestCase): 140 | """Unittests for testing to_dict method of the Amenity class.""" 141 | 142 | def test_to_dict_type(self): 143 | self.assertTrue(dict, type(Amenity().to_dict())) 144 | 145 | def test_to_dict_contains_correct_keys(self): 146 | am = Amenity() 147 | self.assertIn("id", am.to_dict()) 148 | self.assertIn("created_at", am.to_dict()) 149 | self.assertIn("updated_at", am.to_dict()) 150 | self.assertIn("__class__", am.to_dict()) 151 | 152 | def test_to_dict_contains_added_attributes(self): 153 | am = Amenity() 154 | am.middle_name = "Holberton" 155 | am.my_number = 98 156 | self.assertEqual("Holberton", am.middle_name) 157 | self.assertIn("my_number", am.to_dict()) 158 | 159 | def test_to_dict_datetime_attributes_are_strs(self): 160 | am = Amenity() 161 | am_dict = am.to_dict() 162 | self.assertEqual(str, type(am_dict["id"])) 163 | self.assertEqual(str, type(am_dict["created_at"])) 164 | self.assertEqual(str, type(am_dict["updated_at"])) 165 | 166 | def test_to_dict_output(self): 167 | dt = datetime.today() 168 | am = Amenity() 169 | am.id = "123456" 170 | am.created_at = am.updated_at = dt 171 | tdict = { 172 | 'id': '123456', 173 | '__class__': 'Amenity', 174 | 'created_at': dt.isoformat(), 175 | 'updated_at': dt.isoformat(), 176 | } 177 | self.assertDictEqual(am.to_dict(), tdict) 178 | 179 | def test_contrast_to_dict_dunder_dict(self): 180 | am = Amenity() 181 | self.assertNotEqual(am.to_dict(), am.__dict__) 182 | 183 | def test_to_dict_with_arg(self): 184 | am = Amenity() 185 | with self.assertRaises(TypeError): 186 | am.to_dict(None) 187 | 188 | 189 | if __name__ == "__main__": 190 | unittest.main() 191 | -------------------------------------------------------------------------------- /tests/test_models/test_city.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/city.py. 3 | 4 | Unittest classes: 5 | TestCity_instantiation 6 | TestCity_save 7 | TestCity_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.city import City 15 | 16 | 17 | class TestCity_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the City class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(City, type(City())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(City(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(City().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(City().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(City().updated_at)) 34 | 35 | def test_state_id_is_public_class_attribute(self): 36 | cy = City() 37 | self.assertEqual(str, type(City.state_id)) 38 | self.assertIn("state_id", dir(cy)) 39 | self.assertNotIn("state_id", cy.__dict__) 40 | 41 | def test_name_is_public_class_attribute(self): 42 | cy = City() 43 | self.assertEqual(str, type(City.name)) 44 | self.assertIn("name", dir(cy)) 45 | self.assertNotIn("name", cy.__dict__) 46 | 47 | def test_two_cities_unique_ids(self): 48 | cy1 = City() 49 | cy2 = City() 50 | self.assertNotEqual(cy1.id, cy2.id) 51 | 52 | def test_two_cities_different_created_at(self): 53 | cy1 = City() 54 | sleep(0.05) 55 | cy2 = City() 56 | self.assertLess(cy1.created_at, cy2.created_at) 57 | 58 | def test_two_cities_different_updated_at(self): 59 | cy1 = City() 60 | sleep(0.05) 61 | cy2 = City() 62 | self.assertLess(cy1.updated_at, cy2.updated_at) 63 | 64 | def test_str_representation(self): 65 | dt = datetime.today() 66 | dt_repr = repr(dt) 67 | cy = City() 68 | cy.id = "123456" 69 | cy.created_at = cy.updated_at = dt 70 | cystr = cy.__str__() 71 | self.assertIn("[City] (123456)", cystr) 72 | self.assertIn("'id': '123456'", cystr) 73 | self.assertIn("'created_at': " + dt_repr, cystr) 74 | self.assertIn("'updated_at': " + dt_repr, cystr) 75 | 76 | def test_args_unused(self): 77 | cy = City(None) 78 | self.assertNotIn(None, cy.__dict__.values()) 79 | 80 | def test_instantiation_with_kwargs(self): 81 | dt = datetime.today() 82 | dt_iso = dt.isoformat() 83 | cy = City(id="345", created_at=dt_iso, updated_at=dt_iso) 84 | self.assertEqual(cy.id, "345") 85 | self.assertEqual(cy.created_at, dt) 86 | self.assertEqual(cy.updated_at, dt) 87 | 88 | def test_instantiation_with_None_kwargs(self): 89 | with self.assertRaises(TypeError): 90 | City(id=None, created_at=None, updated_at=None) 91 | 92 | 93 | class TestCity_save(unittest.TestCase): 94 | """Unittests for testing save method of the City class.""" 95 | 96 | @classmethod 97 | def setUp(self): 98 | try: 99 | os.rename("file.json", "tmp") 100 | except IOError: 101 | pass 102 | 103 | def tearDown(self): 104 | try: 105 | os.remove("file.json") 106 | except IOError: 107 | pass 108 | try: 109 | os.rename("tmp", "file.json") 110 | except IOError: 111 | pass 112 | 113 | def test_one_save(self): 114 | cy = City() 115 | sleep(0.05) 116 | first_updated_at = cy.updated_at 117 | cy.save() 118 | self.assertLess(first_updated_at, cy.updated_at) 119 | 120 | def test_two_saves(self): 121 | cy = City() 122 | sleep(0.05) 123 | first_updated_at = cy.updated_at 124 | cy.save() 125 | second_updated_at = cy.updated_at 126 | self.assertLess(first_updated_at, second_updated_at) 127 | sleep(0.05) 128 | cy.save() 129 | self.assertLess(second_updated_at, cy.updated_at) 130 | 131 | def test_save_with_arg(self): 132 | cy = City() 133 | with self.assertRaises(TypeError): 134 | cy.save(None) 135 | 136 | def test_save_updates_file(self): 137 | cy = City() 138 | cy.save() 139 | cyid = "City." + cy.id 140 | with open("file.json", "r") as f: 141 | self.assertIn(cyid, f.read()) 142 | 143 | 144 | class TestCity_to_dict(unittest.TestCase): 145 | """Unittests for testing to_dict method of the City class.""" 146 | 147 | def test_to_dict_type(self): 148 | self.assertTrue(dict, type(City().to_dict())) 149 | 150 | def test_to_dict_contains_correct_keys(self): 151 | cy = City() 152 | self.assertIn("id", cy.to_dict()) 153 | self.assertIn("created_at", cy.to_dict()) 154 | self.assertIn("updated_at", cy.to_dict()) 155 | self.assertIn("__class__", cy.to_dict()) 156 | 157 | def test_to_dict_contains_added_attributes(self): 158 | cy = City() 159 | cy.middle_name = "Holberton" 160 | cy.my_number = 98 161 | self.assertEqual("Holberton", cy.middle_name) 162 | self.assertIn("my_number", cy.to_dict()) 163 | 164 | def test_to_dict_datetime_attributes_are_strs(self): 165 | cy = City() 166 | cy_dict = cy.to_dict() 167 | self.assertEqual(str, type(cy_dict["id"])) 168 | self.assertEqual(str, type(cy_dict["created_at"])) 169 | self.assertEqual(str, type(cy_dict["updated_at"])) 170 | 171 | def test_to_dict_output(self): 172 | dt = datetime.today() 173 | cy = City() 174 | cy.id = "123456" 175 | cy.created_at = cy.updated_at = dt 176 | tdict = { 177 | 'id': '123456', 178 | '__class__': 'City', 179 | 'created_at': dt.isoformat(), 180 | 'updated_at': dt.isoformat(), 181 | } 182 | self.assertDictEqual(cy.to_dict(), tdict) 183 | 184 | def test_contrast_to_dict_dunder_dict(self): 185 | cy = City() 186 | self.assertNotEqual(cy.to_dict(), cy.__dict__) 187 | 188 | def test_to_dict_with_arg(self): 189 | cy = City() 190 | with self.assertRaises(TypeError): 191 | cy.to_dict(None) 192 | 193 | 194 | if __name__ == "__main__": 195 | unittest.main() 196 | -------------------------------------------------------------------------------- /tests/test_models/test_base_model.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/base_model.py. 3 | 4 | Unittest classes: 5 | TestBaseModel_instantiation 6 | TestBaseModel_save 7 | TestBaseModel_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.base_model import BaseModel 15 | 16 | 17 | class TestBaseModel_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the BaseModel class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(BaseModel, type(BaseModel())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(BaseModel(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(BaseModel().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(BaseModel().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(BaseModel().updated_at)) 34 | 35 | def test_two_models_unique_ids(self): 36 | bm1 = BaseModel() 37 | bm2 = BaseModel() 38 | self.assertNotEqual(bm1.id, bm2.id) 39 | 40 | def test_two_models_different_created_at(self): 41 | bm1 = BaseModel() 42 | sleep(0.05) 43 | bm2 = BaseModel() 44 | self.assertLess(bm1.created_at, bm2.created_at) 45 | 46 | def test_two_models_different_updated_at(self): 47 | bm1 = BaseModel() 48 | sleep(0.05) 49 | bm2 = BaseModel() 50 | self.assertLess(bm1.updated_at, bm2.updated_at) 51 | 52 | def test_str_representation(self): 53 | dt = datetime.today() 54 | dt_repr = repr(dt) 55 | bm = BaseModel() 56 | bm.id = "123456" 57 | bm.created_at = bm.updated_at = dt 58 | bmstr = bm.__str__() 59 | self.assertIn("[BaseModel] (123456)", bmstr) 60 | self.assertIn("'id': '123456'", bmstr) 61 | self.assertIn("'created_at': " + dt_repr, bmstr) 62 | self.assertIn("'updated_at': " + dt_repr, bmstr) 63 | 64 | def test_args_unused(self): 65 | bm = BaseModel(None) 66 | self.assertNotIn(None, bm.__dict__.values()) 67 | 68 | def test_instantiation_with_kwargs(self): 69 | dt = datetime.today() 70 | dt_iso = dt.isoformat() 71 | bm = BaseModel(id="345", created_at=dt_iso, updated_at=dt_iso) 72 | self.assertEqual(bm.id, "345") 73 | self.assertEqual(bm.created_at, dt) 74 | self.assertEqual(bm.updated_at, dt) 75 | 76 | def test_instantiation_with_None_kwargs(self): 77 | with self.assertRaises(TypeError): 78 | BaseModel(id=None, created_at=None, updated_at=None) 79 | 80 | def test_instantiation_with_args_and_kwargs(self): 81 | dt = datetime.today() 82 | dt_iso = dt.isoformat() 83 | bm = BaseModel("12", id="345", created_at=dt_iso, updated_at=dt_iso) 84 | self.assertEqual(bm.id, "345") 85 | self.assertEqual(bm.created_at, dt) 86 | self.assertEqual(bm.updated_at, dt) 87 | 88 | 89 | class TestBaseModel_save(unittest.TestCase): 90 | """Unittests for testing save method of the BaseModel class.""" 91 | 92 | @classmethod 93 | def setUp(self): 94 | try: 95 | os.rename("file.json", "tmp") 96 | except IOError: 97 | pass 98 | 99 | @classmethod 100 | def tearDown(self): 101 | try: 102 | os.remove("file.json") 103 | except IOError: 104 | pass 105 | try: 106 | os.rename("tmp", "file.json") 107 | except IOError: 108 | pass 109 | 110 | def test_one_save(self): 111 | bm = BaseModel() 112 | sleep(0.05) 113 | first_updated_at = bm.updated_at 114 | bm.save() 115 | self.assertLess(first_updated_at, bm.updated_at) 116 | 117 | def test_two_saves(self): 118 | bm = BaseModel() 119 | sleep(0.05) 120 | first_updated_at = bm.updated_at 121 | bm.save() 122 | second_updated_at = bm.updated_at 123 | self.assertLess(first_updated_at, second_updated_at) 124 | sleep(0.05) 125 | bm.save() 126 | self.assertLess(second_updated_at, bm.updated_at) 127 | 128 | def test_save_with_arg(self): 129 | bm = BaseModel() 130 | with self.assertRaises(TypeError): 131 | bm.save(None) 132 | 133 | def test_save_updates_file(self): 134 | bm = BaseModel() 135 | bm.save() 136 | bmid = "BaseModel." + bm.id 137 | with open("file.json", "r") as f: 138 | self.assertIn(bmid, f.read()) 139 | 140 | 141 | class TestBaseModel_to_dict(unittest.TestCase): 142 | """Unittests for testing to_dict method of the BaseModel class.""" 143 | 144 | def test_to_dict_type(self): 145 | bm = BaseModel() 146 | self.assertTrue(dict, type(bm.to_dict())) 147 | 148 | def test_to_dict_contains_correct_keys(self): 149 | bm = BaseModel() 150 | self.assertIn("id", bm.to_dict()) 151 | self.assertIn("created_at", bm.to_dict()) 152 | self.assertIn("updated_at", bm.to_dict()) 153 | self.assertIn("__class__", bm.to_dict()) 154 | 155 | def test_to_dict_contains_added_attributes(self): 156 | bm = BaseModel() 157 | bm.name = "Holberton" 158 | bm.my_number = 98 159 | self.assertIn("name", bm.to_dict()) 160 | self.assertIn("my_number", bm.to_dict()) 161 | 162 | def test_to_dict_datetime_attributes_are_strs(self): 163 | bm = BaseModel() 164 | bm_dict = bm.to_dict() 165 | self.assertEqual(str, type(bm_dict["created_at"])) 166 | self.assertEqual(str, type(bm_dict["updated_at"])) 167 | 168 | def test_to_dict_output(self): 169 | dt = datetime.today() 170 | bm = BaseModel() 171 | bm.id = "123456" 172 | bm.created_at = bm.updated_at = dt 173 | tdict = { 174 | 'id': '123456', 175 | '__class__': 'BaseModel', 176 | 'created_at': dt.isoformat(), 177 | 'updated_at': dt.isoformat() 178 | } 179 | self.assertDictEqual(bm.to_dict(), tdict) 180 | 181 | def test_contrast_to_dict_dunder_dict(self): 182 | bm = BaseModel() 183 | self.assertNotEqual(bm.to_dict(), bm.__dict__) 184 | 185 | def test_to_dict_with_arg(self): 186 | bm = BaseModel() 187 | with self.assertRaises(TypeError): 188 | bm.to_dict(None) 189 | 190 | 191 | if __name__ == "__main__": 192 | unittest.main() 193 | -------------------------------------------------------------------------------- /tests/test_models/test_review.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/review.py. 3 | 4 | Unittest classes: 5 | TestReview_instantiation 6 | TestReview_save 7 | TestReview_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.review import Review 15 | 16 | 17 | class TestReview_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the Review class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(Review, type(Review())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(Review(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(Review().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(Review().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(Review().updated_at)) 34 | 35 | def test_place_id_is_public_class_attribute(self): 36 | rv = Review() 37 | self.assertEqual(str, type(Review.place_id)) 38 | self.assertIn("place_id", dir(rv)) 39 | self.assertNotIn("place_id", rv.__dict__) 40 | 41 | def test_user_id_is_public_class_attribute(self): 42 | rv = Review() 43 | self.assertEqual(str, type(Review.user_id)) 44 | self.assertIn("user_id", dir(rv)) 45 | self.assertNotIn("user_id", rv.__dict__) 46 | 47 | def test_text_is_public_class_attribute(self): 48 | rv = Review() 49 | self.assertEqual(str, type(Review.text)) 50 | self.assertIn("text", dir(rv)) 51 | self.assertNotIn("text", rv.__dict__) 52 | 53 | def test_two_reviews_unique_ids(self): 54 | rv1 = Review() 55 | rv2 = Review() 56 | self.assertNotEqual(rv1.id, rv2.id) 57 | 58 | def test_two_reviews_different_created_at(self): 59 | rv1 = Review() 60 | sleep(0.05) 61 | rv2 = Review() 62 | self.assertLess(rv1.created_at, rv2.created_at) 63 | 64 | def test_two_reviews_different_updated_at(self): 65 | rv1 = Review() 66 | sleep(0.05) 67 | rv2 = Review() 68 | self.assertLess(rv1.updated_at, rv2.updated_at) 69 | 70 | def test_str_representation(self): 71 | dt = datetime.today() 72 | dt_repr = repr(dt) 73 | rv = Review() 74 | rv.id = "123456" 75 | rv.created_at = rv.updated_at = dt 76 | rvstr = rv.__str__() 77 | self.assertIn("[Review] (123456)", rvstr) 78 | self.assertIn("'id': '123456'", rvstr) 79 | self.assertIn("'created_at': " + dt_repr, rvstr) 80 | self.assertIn("'updated_at': " + dt_repr, rvstr) 81 | 82 | def test_args_unused(self): 83 | rv = Review(None) 84 | self.assertNotIn(None, rv.__dict__.values()) 85 | 86 | def test_instantiation_with_kwargs(self): 87 | dt = datetime.today() 88 | dt_iso = dt.isoformat() 89 | rv = Review(id="345", created_at=dt_iso, updated_at=dt_iso) 90 | self.assertEqual(rv.id, "345") 91 | self.assertEqual(rv.created_at, dt) 92 | self.assertEqual(rv.updated_at, dt) 93 | 94 | def test_instantiation_with_None_kwargs(self): 95 | with self.assertRaises(TypeError): 96 | Review(id=None, created_at=None, updated_at=None) 97 | 98 | 99 | class TestReview_save(unittest.TestCase): 100 | """Unittests for testing save method of the Review class.""" 101 | 102 | @classmethod 103 | def setUp(self): 104 | try: 105 | os.rename("file.json", "tmp") 106 | except IOError: 107 | pass 108 | 109 | def tearDown(self): 110 | try: 111 | os.remove("file.json") 112 | except IOError: 113 | pass 114 | try: 115 | os.rename("tmp", "file.json") 116 | except IOError: 117 | pass 118 | 119 | def test_one_save(self): 120 | rv = Review() 121 | sleep(0.05) 122 | first_updated_at = rv.updated_at 123 | rv.save() 124 | self.assertLess(first_updated_at, rv.updated_at) 125 | 126 | def test_two_saves(self): 127 | rv = Review() 128 | sleep(0.05) 129 | first_updated_at = rv.updated_at 130 | rv.save() 131 | second_updated_at = rv.updated_at 132 | self.assertLess(first_updated_at, second_updated_at) 133 | sleep(0.05) 134 | rv.save() 135 | self.assertLess(second_updated_at, rv.updated_at) 136 | 137 | def test_save_with_arg(self): 138 | rv = Review() 139 | with self.assertRaises(TypeError): 140 | rv.save(None) 141 | 142 | def test_save_updates_file(self): 143 | rv = Review() 144 | rv.save() 145 | rvid = "Review." + rv.id 146 | with open("file.json", "r") as f: 147 | self.assertIn(rvid, f.read()) 148 | 149 | 150 | class TestReview_to_dict(unittest.TestCase): 151 | """Unittests for testing to_dict method of the Review class.""" 152 | 153 | def test_to_dict_type(self): 154 | self.assertTrue(dict, type(Review().to_dict())) 155 | 156 | def test_to_dict_contains_correct_keys(self): 157 | rv = Review() 158 | self.assertIn("id", rv.to_dict()) 159 | self.assertIn("created_at", rv.to_dict()) 160 | self.assertIn("updated_at", rv.to_dict()) 161 | self.assertIn("__class__", rv.to_dict()) 162 | 163 | def test_to_dict_contains_added_attributes(self): 164 | rv = Review() 165 | rv.middle_name = "Holberton" 166 | rv.my_number = 98 167 | self.assertEqual("Holberton", rv.middle_name) 168 | self.assertIn("my_number", rv.to_dict()) 169 | 170 | def test_to_dict_datetime_attributes_are_strs(self): 171 | rv = Review() 172 | rv_dict = rv.to_dict() 173 | self.assertEqual(str, type(rv_dict["id"])) 174 | self.assertEqual(str, type(rv_dict["created_at"])) 175 | self.assertEqual(str, type(rv_dict["updated_at"])) 176 | 177 | def test_to_dict_output(self): 178 | dt = datetime.today() 179 | rv = Review() 180 | rv.id = "123456" 181 | rv.created_at = rv.updated_at = dt 182 | tdict = { 183 | 'id': '123456', 184 | '__class__': 'Review', 185 | 'created_at': dt.isoformat(), 186 | 'updated_at': dt.isoformat(), 187 | } 188 | self.assertDictEqual(rv.to_dict(), tdict) 189 | 190 | def test_contrast_to_dict_dunder_dict(self): 191 | rv = Review() 192 | self.assertNotEqual(rv.to_dict(), rv.__dict__) 193 | 194 | def test_to_dict_with_arg(self): 195 | rv = Review() 196 | with self.assertRaises(TypeError): 197 | rv.to_dict(None) 198 | 199 | 200 | if __name__ == "__main__": 201 | unittest.main() 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The AirBnB Clone Project 2 | ![AirBnB Logo](https://www.pngitem.com/pimgs/m/132-1322125_transparent-background-airbnb-logo-hd-png-download.png) 3 | 4 | ## Project Description 5 | This is the first part of the AirBnB clone project where we worked on the backend of the project whiles interfacing it with a console application with the help of the cmd module in python. 6 | 7 | Data (python objects) generated are stored in a json file and can be accessed with the help of the json module in python 8 | 9 | ## Description of the command interpreter: 10 | The interface of the application is just like the Bash shell except that this has a limited number of accepted commands that were solely defined for the purposes of the usage of the AirBnB website. 11 | 12 | This command line interpreter serves as the frontend of the web app where users can interact with the backend which was developed with python OOP programming. 13 | 14 | Some of the commands available are: 15 | - show 16 | - create 17 | - update 18 | - destroy 19 | - count 20 | 21 | And as part of the implementation of the command line interpreter coupled with the backend and file storage system, the folowing actions can be performed: 22 | - Creating new objects (ex: a new User or a new Place) 23 | - Retrieving an object from a file, a database etc… 24 | - Doing operations on objects (count, compute stats, etc…) 25 | - Updating attributes of an object 26 | - Destroying an object 27 | 28 | ## How to start it 29 | These instructions will get you a copy of the project up and running on your local machine (Linux distro) for development and testing purposes. 30 | 31 | ## Installing 32 | 33 | You will need to clone the repository of the project from Github. This will contain the simple shell program and all of its dependencies. 34 | 35 | ``` 36 | git clone https://github.com/jzamora5/AirBnB_clone.git 37 | ``` 38 | After cloning the repository you will have a folder called AirBnB_clone. In here there will be several files that allow the program to work. 39 | 40 | > /console.py : The main executable of the project, the command interpreter. 41 | > 42 | > models/engine/file_storage.py: Class that serializes instances to a JSON file and deserializes JSON file to instances 43 | > 44 | > models/__ init __.py: A unique `FileStorage` instance for the application 45 | > 46 | > models/base_model.py: Class that defines all common attributes/methods for other classes. 47 | > 48 | > models/user.py: User class that inherits from BaseModel 49 | > 50 | >models/state.py: State class that inherits from BaseModel 51 | > 52 | >models/city.py: City class that inherits from BaseModel 53 | > 54 | >models/amenity.py: Amenity class that inherits from BaseModel 55 | > 56 | >models/place.py: Place class that inherits from BaseModel 57 | > 58 | >models/review.py: Review class that inherits from BaseModel 59 | 60 | 61 | 62 | ## How to use it 63 | It can work in two different modes: 64 | 65 | 66 | **Interactive** and **Non-interactive**. 67 | 68 | In **Interactive mode**, the console will display a prompt (hbnb) indicating that the user can write and execute a command. After the command is run, the prompt will appear again a wait for a new command. This can go indefinitely as long as the user does not exit the program. 69 | 70 | ``` 71 | $ ./console.py 72 | (hbnb) help 73 | 74 | Documented commands (type help ): 75 | ======================================== 76 | EOF help quit 77 | 78 | (hbnb) 79 | (hbnb) 80 | (hbnb) quit 81 | $ 82 | ``` 83 | 84 | In **Non-interactive mode**, the shell will need to be run with a command input piped into its execution so that the command is run as soon as the Shell starts. In this mode no prompt will appear, and no further input will be expected from the user. 85 | 86 | 87 | ``` 88 | $ echo "help" | ./console.py 89 | (hbnb) 90 | 91 | Documented commands (type help ): 92 | ======================================== 93 | EOF help quit 94 | (hbnb) 95 | $ 96 | $ cat test_help 97 | help 98 | $ 99 | $ cat test_help | ./console.py 100 | (hbnb) 101 | 102 | Documented commands (type help ): 103 | ======================================== 104 | EOF help quit 105 | (hbnb) 106 | $ 107 | ``` 108 | 109 | ## Format of Command Input 110 | 111 | In order to give commands to the console, these will need to be piped through an echo in case of **Non-interactive mode**. 112 | 113 | In **Interactive Mode** the commands will need to be written with a keyboard when the prompt appears and will be recognized when an enter key is pressed (new line). As soon as this happens, the console will attempt to execute the command through several means or will show an error message if the command didn't run successfully. In this mode, the console can be exited using the **CTRL + D** combination, **CTRL + C**, or the command **quit** or **EOF**. 114 | 115 | ## Arguments 116 | 117 | Most commands have several options or arguments that can be used when executing the program. In order for the Shell to recognize those parameters, the user must separate everything with spaces. 118 | 119 | Example: 120 | 121 | ``` 122 | 123 | user@ubuntu:~/AirBnB$ ./console.py 124 | (hbnb) create BaseModel 125 | 49faff9a-6318-451f-87b6-910505c55907 126 | user@ubuntu:~/AirBnB$ ./console.py 127 | 128 | ``` 129 | 130 | or 131 | 132 | ``` 133 | user@ubuntu:~/AirBnB$ ./console.py $ echo "create BaseModel" | ./console.py 134 | (hbnb) 135 | e37ebcd3-f8e1-4c1f-8095-7a019070b1fa 136 | (hbnb) 137 | user@ubuntu:~/AirBnB$ ./console.py 138 | ``` 139 | 140 | ## Available commands and what they do 141 | 142 | The recognizable commands by the interpreter are the following: 143 | 144 | |Command| Description | 145 | |--|--| 146 | | **quit or EOF** | Exits the program | 147 | | **Usage** | By itself | 148 | | **-----** | **-----** | 149 | | **help** | Provides a text describing how to use a command. | 150 | | **Usage** | By itself --or-- **help ** | 151 | | **-----** | **-----** | 152 | | **create** | Creates a new instance of a valid `Class`, saves it (to the JSON file) and prints the `id`. Valid classes are: BaseModel, User, State, City, Amenity, Place, Review. | 153 | | **Usage** | **create **| 154 | | **-----** | **-----** | 155 | | **show** | Prints the string representation of an instance based on the class name and `id` | 156 | | **Usage** | **show ** --or-- **.show()**| 157 | | **-----** | **-----** | 158 | | **destroy** | Deletes an instance based on the class name and `id` (saves the change into a JSON file). | 159 | | **Usage** | **destroy ** --or-- **.destroy()** | 160 | | **-----** | **-----** | 161 | | **all** | Prints all string representation of all instances based or not on the class name. | 162 | | **Usage** | By itself or **all ** --or-- **.all()** | 163 | | **-----** | **-----** | 164 | | **update** | Updates an instance based on the class name and `id` by adding or updating attribute (saves the changes into a JSON file). | 165 | | **Usage** | **update ""** ---or--- **.update(, , )** --or-- **.update(, )**| 166 | | **-----** | **-----** | 167 | | **count** | Retrieve the number of instances of a class. | 168 | | **Usage** | **.count()** | 169 | 170 | ## Author 171 | 172 | Yonas Leykun 173 | -------------------------------------------------------------------------------- /one/README.md: -------------------------------------------------------------------------------- 1 | # The AirBnB Clone Project 2 | ![AirBnB Logo](https://www.pngitem.com/pimgs/m/132-1322125_transparent-background-airbnb-logo-hd-png-download.png) 3 | 4 | ## Project Description 5 | This is the first part of the AirBnB clone project where we worked on the backend of the project whiles interfacing it with a console application with the help of the cmd module in python. 6 | 7 | Data (python objects) generated are stored in a json file and can be accessed with the help of the json module in python 8 | 9 | ## Description of the command interpreter: 10 | The interface of the application is just like the Bash shell except that this has a limited number of accepted commands that were solely defined for the purposes of the usage of the AirBnB website. 11 | 12 | This command line interpreter serves as the frontend of the web app where users can interact with the backend which was developed with python OOP programming. 13 | 14 | Some of the commands available are: 15 | - show 16 | - create 17 | - update 18 | - destroy 19 | - count 20 | 21 | And as part of the implementation of the command line interpreter coupled with the backend and file storage system, the folowing actions can be performed: 22 | - Creating new objects (ex: a new User or a new Place) 23 | - Retrieving an object from a file, a database etc… 24 | - Doing operations on objects (count, compute stats, etc…) 25 | - Updating attributes of an object 26 | - Destroying an object 27 | 28 | ## How to start it 29 | These instructions will get you a copy of the project up and running on your local machine (Linux distro) for development and testing purposes. 30 | 31 | ## Installing 32 | 33 | You will need to clone the repository of the project from Github. This will contain the simple shell program and all of its dependencies. 34 | 35 | ``` 36 | git clone https://github.com/jzamora5/AirBnB_clone.git 37 | ``` 38 | After cloning the repository you will have a folder called AirBnB_clone. In here there will be several files that allow the program to work. 39 | 40 | > /console.py : The main executable of the project, the command interpreter. 41 | > 42 | > models/engine/file_storage.py: Class that serializes instances to a JSON file and deserializes JSON file to instances 43 | > 44 | > models/__ init __.py: A unique `FileStorage` instance for the application 45 | > 46 | > models/base_model.py: Class that defines all common attributes/methods for other classes. 47 | > 48 | > models/user.py: User class that inherits from BaseModel 49 | > 50 | >models/state.py: State class that inherits from BaseModel 51 | > 52 | >models/city.py: City class that inherits from BaseModel 53 | > 54 | >models/amenity.py: Amenity class that inherits from BaseModel 55 | > 56 | >models/place.py: Place class that inherits from BaseModel 57 | > 58 | >models/review.py: Review class that inherits from BaseModel 59 | 60 | 61 | 62 | ## How to use it 63 | It can work in two different modes: 64 | 65 | 66 | **Interactive** and **Non-interactive**. 67 | 68 | In **Interactive mode**, the console will display a prompt (hbnb) indicating that the user can write and execute a command. After the command is run, the prompt will appear again a wait for a new command. This can go indefinitely as long as the user does not exit the program. 69 | 70 | ``` 71 | $ ./console.py 72 | (hbnb) help 73 | 74 | Documented commands (type help ): 75 | ======================================== 76 | EOF help quit 77 | 78 | (hbnb) 79 | (hbnb) 80 | (hbnb) quit 81 | $ 82 | ``` 83 | 84 | In **Non-interactive mode**, the shell will need to be run with a command input piped into its execution so that the command is run as soon as the Shell starts. In this mode no prompt will appear, and no further input will be expected from the user. 85 | 86 | 87 | ``` 88 | $ echo "help" | ./console.py 89 | (hbnb) 90 | 91 | Documented commands (type help ): 92 | ======================================== 93 | EOF help quit 94 | (hbnb) 95 | $ 96 | $ cat test_help 97 | help 98 | $ 99 | $ cat test_help | ./console.py 100 | (hbnb) 101 | 102 | Documented commands (type help ): 103 | ======================================== 104 | EOF help quit 105 | (hbnb) 106 | $ 107 | ``` 108 | 109 | ## Format of Command Input 110 | 111 | In order to give commands to the console, these will need to be piped through an echo in case of **Non-interactive mode**. 112 | 113 | In **Interactive Mode** the commands will need to be written with a keyboard when the prompt appears and will be recognized when an enter key is pressed (new line). As soon as this happens, the console will attempt to execute the command through several means or will show an error message if the command didn't run successfully. In this mode, the console can be exited using the **CTRL + D** combination, **CTRL + C**, or the command **quit** or **EOF**. 114 | 115 | ## Arguments 116 | 117 | Most commands have several options or arguments that can be used when executing the program. In order for the Shell to recognize those parameters, the user must separate everything with spaces. 118 | 119 | Example: 120 | 121 | ``` 122 | 123 | user@ubuntu:~/AirBnB$ ./console.py 124 | (hbnb) create BaseModel 125 | 49faff9a-6318-451f-87b6-910505c55907 126 | user@ubuntu:~/AirBnB$ ./console.py 127 | 128 | ``` 129 | 130 | or 131 | 132 | ``` 133 | user@ubuntu:~/AirBnB$ ./console.py $ echo "create BaseModel" | ./console.py 134 | (hbnb) 135 | e37ebcd3-f8e1-4c1f-8095-7a019070b1fa 136 | (hbnb) 137 | user@ubuntu:~/AirBnB$ ./console.py 138 | ``` 139 | 140 | ## Available commands and what they do 141 | 142 | The recognizable commands by the interpreter are the following: 143 | 144 | |Command| Description | 145 | |--|--| 146 | | **quit or EOF** | Exits the program | 147 | | **Usage** | By itself | 148 | | **-----** | **-----** | 149 | | **help** | Provides a text describing how to use a command. | 150 | | **Usage** | By itself --or-- **help ** | 151 | | **-----** | **-----** | 152 | | **create** | Creates a new instance of a valid `Class`, saves it (to the JSON file) and prints the `id`. Valid classes are: BaseModel, User, State, City, Amenity, Place, Review. | 153 | | **Usage** | **create **| 154 | | **-----** | **-----** | 155 | | **show** | Prints the string representation of an instance based on the class name and `id` | 156 | | **Usage** | **show ** --or-- **.show()**| 157 | | **-----** | **-----** | 158 | | **destroy** | Deletes an instance based on the class name and `id` (saves the change into a JSON file). | 159 | | **Usage** | **destroy ** --or-- **.destroy()** | 160 | | **-----** | **-----** | 161 | | **all** | Prints all string representation of all instances based or not on the class name. | 162 | | **Usage** | By itself or **all ** --or-- **.all()** | 163 | | **-----** | **-----** | 164 | | **update** | Updates an instance based on the class name and `id` by adding or updating attribute (saves the changes into a JSON file). | 165 | | **Usage** | **update ""** ---or--- **.update(, , )** --or-- **.update(, )**| 166 | | **-----** | **-----** | 167 | | **count** | Retrieve the number of instances of a class. | 168 | | **Usage** | **.count()** | 169 | 170 | ## Authors 171 | 172 | Ehoneah Obed | Email: [ehoneahobed](mailto:ehoneahobed@hotmail.com) 173 | 174 | Anthony Etim | Github: [otoobongekim](mailto:otoobongekim@gmail.com) -------------------------------------------------------------------------------- /console.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Module for the entry point of the command interpreter.""" 3 | 4 | import cmd 5 | from models.base_model import BaseModel 6 | from models import storage 7 | import re 8 | import json 9 | 10 | 11 | class HBNBCommand(cmd.Cmd): 12 | 13 | """Class for the command interpreter.""" 14 | 15 | prompt = "(hbnb) " 16 | 17 | def default(self, line): 18 | """Catch commands if nothing else matches then.""" 19 | # print("DEF:::", line) 20 | self._precmd(line) 21 | 22 | def _precmd(self, line): 23 | """Intercepts commands to test for class.syntax()""" 24 | # print("PRECMD:::", line) 25 | match = re.search(r"^(\w*)\.(\w+)(?:\(([^)]*)\))$", line) 26 | if not match: 27 | return line 28 | classname = match.group(1) 29 | method = match.group(2) 30 | args = match.group(3) 31 | match_uid_and_args = re.search('^"([^"]*)"(?:, (.*))?$', args) 32 | if match_uid_and_args: 33 | uid = match_uid_and_args.group(1) 34 | attr_or_dict = match_uid_and_args.group(2) 35 | else: 36 | uid = args 37 | attr_or_dict = False 38 | 39 | attr_and_value = "" 40 | if method == "update" and attr_or_dict: 41 | match_dict = re.search('^({.*})$', attr_or_dict) 42 | if match_dict: 43 | self.update_dict(classname, uid, match_dict.group(1)) 44 | return "" 45 | match_attr_and_value = re.search( 46 | '^(?:"([^"]*)")?(?:, (.*))?$', attr_or_dict) 47 | if match_attr_and_value: 48 | attr_and_value = (match_attr_and_value.group( 49 | 1) or "") + " " + (match_attr_and_value.group(2) or "") 50 | command = method + " " + classname + " " + uid + " " + attr_and_value 51 | self.onecmd(command) 52 | return command 53 | 54 | def update_dict(self, classname, uid, s_dict): 55 | """Helper method for update() with a dictionary.""" 56 | s = s_dict.replace("'", '"') 57 | d = json.loads(s) 58 | if not classname: 59 | print("** class name missing **") 60 | elif classname not in storage.classes(): 61 | print("** class doesn't exist **") 62 | elif uid is None: 63 | print("** instance id missing **") 64 | else: 65 | key = "{}.{}".format(classname, uid) 66 | if key not in storage.all(): 67 | print("** no instance found **") 68 | else: 69 | attributes = storage.attributes()[classname] 70 | for attribute, value in d.items(): 71 | if attribute in attributes: 72 | value = attributes[attribute](value) 73 | setattr(storage.all()[key], attribute, value) 74 | storage.all()[key].save() 75 | 76 | def do_EOF(self, line): 77 | """Handles End Of File character. 78 | """ 79 | print() 80 | return True 81 | 82 | def do_quit(self, line): 83 | """Exits the program. 84 | """ 85 | return True 86 | 87 | def emptyline(self): 88 | """Doesn't do anything on ENTER. 89 | """ 90 | pass 91 | 92 | def do_create(self, line): 93 | """Creates an instance. 94 | """ 95 | if line == "" or line is None: 96 | print("** class name missing **") 97 | elif line not in storage.classes(): 98 | print("** class doesn't exist **") 99 | else: 100 | b = storage.classes()[line]() 101 | b.save() 102 | print(b.id) 103 | 104 | def do_show(self, line): 105 | """Prints the string representation of an instance. 106 | """ 107 | if line == "" or line is None: 108 | print("** class name missing **") 109 | else: 110 | words = line.split(' ') 111 | if words[0] not in storage.classes(): 112 | print("** class doesn't exist **") 113 | elif len(words) < 2: 114 | print("** instance id missing **") 115 | else: 116 | key = "{}.{}".format(words[0], words[1]) 117 | if key not in storage.all(): 118 | print("** no instance found **") 119 | else: 120 | print(storage.all()[key]) 121 | 122 | def do_destroy(self, line): 123 | """Deletes an instance based on the class name and id. 124 | """ 125 | if line == "" or line is None: 126 | print("** class name missing **") 127 | else: 128 | words = line.split(' ') 129 | if words[0] not in storage.classes(): 130 | print("** class doesn't exist **") 131 | elif len(words) < 2: 132 | print("** instance id missing **") 133 | else: 134 | key = "{}.{}".format(words[0], words[1]) 135 | if key not in storage.all(): 136 | print("** no instance found **") 137 | else: 138 | del storage.all()[key] 139 | storage.save() 140 | 141 | def do_all(self, line): 142 | """Prints all string representation of all instances. 143 | """ 144 | if line != "": 145 | words = line.split(' ') 146 | if words[0] not in storage.classes(): 147 | print("** class doesn't exist **") 148 | else: 149 | nl = [str(obj) for key, obj in storage.all().items() 150 | if type(obj).__name__ == words[0]] 151 | print(nl) 152 | else: 153 | new_list = [str(obj) for key, obj in storage.all().items()] 154 | print(new_list) 155 | 156 | def do_count(self, line): 157 | """Counts the instances of a class. 158 | """ 159 | words = line.split(' ') 160 | if not words[0]: 161 | print("** class name missing **") 162 | elif words[0] not in storage.classes(): 163 | print("** class doesn't exist **") 164 | else: 165 | matches = [ 166 | k for k in storage.all() if k.startswith( 167 | words[0] + '.')] 168 | print(len(matches)) 169 | 170 | def do_update(self, line): 171 | """Updates an instance by adding or updating attribute. 172 | """ 173 | if line == "" or line is None: 174 | print("** class name missing **") 175 | return 176 | 177 | rex = r'^(\S+)(?:\s(\S+)(?:\s(\S+)(?:\s((?:"[^"]*")|(?:(\S)+)))?)?)?' 178 | match = re.search(rex, line) 179 | classname = match.group(1) 180 | uid = match.group(2) 181 | attribute = match.group(3) 182 | value = match.group(4) 183 | if not match: 184 | print("** class name missing **") 185 | elif classname not in storage.classes(): 186 | print("** class doesn't exist **") 187 | elif uid is None: 188 | print("** instance id missing **") 189 | else: 190 | key = "{}.{}".format(classname, uid) 191 | if key not in storage.all(): 192 | print("** no instance found **") 193 | elif not attribute: 194 | print("** attribute name missing **") 195 | elif not value: 196 | print("** value missing **") 197 | else: 198 | cast = None 199 | if not re.search('^".*"$', value): 200 | if '.' in value: 201 | cast = float 202 | else: 203 | cast = int 204 | else: 205 | value = value.replace('"', '') 206 | attributes = storage.attributes()[classname] 207 | if attribute in attributes: 208 | value = attributes[attribute](value) 209 | elif cast: 210 | try: 211 | value = cast(value) 212 | except ValueError: 213 | pass # fine, stay a string then 214 | setattr(storage.all()[key], attribute, value) 215 | storage.all()[key].save() 216 | 217 | 218 | if __name__ == '__main__': 219 | HBNBCommand().cmdloop() 220 | -------------------------------------------------------------------------------- /tests/test_models/test_place.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for models/place.py. 3 | 4 | Unittest classes: 5 | TestPlace_instantiation 6 | TestPlace_save 7 | TestPlace_to_dict 8 | """ 9 | import os 10 | import models 11 | import unittest 12 | from datetime import datetime 13 | from time import sleep 14 | from models.place import Place 15 | 16 | 17 | class TestPlace_instantiation(unittest.TestCase): 18 | """Unittests for testing instantiation of the Place class.""" 19 | 20 | def test_no_args_instantiates(self): 21 | self.assertEqual(Place, type(Place())) 22 | 23 | def test_new_instance_stored_in_objects(self): 24 | self.assertIn(Place(), models.storage.all().values()) 25 | 26 | def test_id_is_public_str(self): 27 | self.assertEqual(str, type(Place().id)) 28 | 29 | def test_created_at_is_public_datetime(self): 30 | self.assertEqual(datetime, type(Place().created_at)) 31 | 32 | def test_updated_at_is_public_datetime(self): 33 | self.assertEqual(datetime, type(Place().updated_at)) 34 | 35 | def test_city_id_is_public_class_attribute(self): 36 | pl = Place() 37 | self.assertEqual(str, type(Place.city_id)) 38 | self.assertIn("city_id", dir(pl)) 39 | self.assertNotIn("city_id", pl.__dict__) 40 | 41 | def test_user_id_is_public_class_attribute(self): 42 | pl = Place() 43 | self.assertEqual(str, type(Place.user_id)) 44 | self.assertIn("user_id", dir(pl)) 45 | self.assertNotIn("user_id", pl.__dict__) 46 | 47 | def test_name_is_public_class_attribute(self): 48 | pl = Place() 49 | self.assertEqual(str, type(Place.name)) 50 | self.assertIn("name", dir(pl)) 51 | self.assertNotIn("name", pl.__dict__) 52 | 53 | def test_description_is_public_class_attribute(self): 54 | pl = Place() 55 | self.assertEqual(str, type(Place.description)) 56 | self.assertIn("description", dir(pl)) 57 | self.assertNotIn("desctiption", pl.__dict__) 58 | 59 | def test_number_rooms_is_public_class_attribute(self): 60 | pl = Place() 61 | self.assertEqual(int, type(Place.number_rooms)) 62 | self.assertIn("number_rooms", dir(pl)) 63 | self.assertNotIn("number_rooms", pl.__dict__) 64 | 65 | def test_number_bathrooms_is_public_class_attribute(self): 66 | pl = Place() 67 | self.assertEqual(int, type(Place.number_bathrooms)) 68 | self.assertIn("number_bathrooms", dir(pl)) 69 | self.assertNotIn("number_bathrooms", pl.__dict__) 70 | 71 | def test_max_guest_is_public_class_attribute(self): 72 | pl = Place() 73 | self.assertEqual(int, type(Place.max_guest)) 74 | self.assertIn("max_guest", dir(pl)) 75 | self.assertNotIn("max_guest", pl.__dict__) 76 | 77 | def test_price_by_night_is_public_class_attribute(self): 78 | pl = Place() 79 | self.assertEqual(int, type(Place.price_by_night)) 80 | self.assertIn("price_by_night", dir(pl)) 81 | self.assertNotIn("price_by_night", pl.__dict__) 82 | 83 | def test_latitude_is_public_class_attribute(self): 84 | pl = Place() 85 | self.assertEqual(float, type(Place.latitude)) 86 | self.assertIn("latitude", dir(pl)) 87 | self.assertNotIn("latitude", pl.__dict__) 88 | 89 | def test_longitude_is_public_class_attribute(self): 90 | pl = Place() 91 | self.assertEqual(float, type(Place.longitude)) 92 | self.assertIn("longitude", dir(pl)) 93 | self.assertNotIn("longitude", pl.__dict__) 94 | 95 | def test_amenity_ids_is_public_class_attribute(self): 96 | pl = Place() 97 | self.assertEqual(list, type(Place.amenity_ids)) 98 | self.assertIn("amenity_ids", dir(pl)) 99 | self.assertNotIn("amenity_ids", pl.__dict__) 100 | 101 | def test_two_places_unique_ids(self): 102 | pl1 = Place() 103 | pl2 = Place() 104 | self.assertNotEqual(pl1.id, pl2.id) 105 | 106 | def test_two_places_different_created_at(self): 107 | pl1 = Place() 108 | sleep(0.05) 109 | pl2 = Place() 110 | self.assertLess(pl1.created_at, pl2.created_at) 111 | 112 | def test_two_places_different_updated_at(self): 113 | pl1 = Place() 114 | sleep(0.05) 115 | pl2 = Place() 116 | self.assertLess(pl1.updated_at, pl2.updated_at) 117 | 118 | def test_str_representation(self): 119 | dt = datetime.today() 120 | dt_repr = repr(dt) 121 | pl = Place() 122 | pl.id = "123456" 123 | pl.created_at = pl.updated_at = dt 124 | plstr = pl.__str__() 125 | self.assertIn("[Place] (123456)", plstr) 126 | self.assertIn("'id': '123456'", plstr) 127 | self.assertIn("'created_at': " + dt_repr, plstr) 128 | self.assertIn("'updated_at': " + dt_repr, plstr) 129 | 130 | def test_args_unused(self): 131 | pl = Place(None) 132 | self.assertNotIn(None, pl.__dict__.values()) 133 | 134 | def test_instantiation_with_kwargs(self): 135 | dt = datetime.today() 136 | dt_iso = dt.isoformat() 137 | pl = Place(id="345", created_at=dt_iso, updated_at=dt_iso) 138 | self.assertEqual(pl.id, "345") 139 | self.assertEqual(pl.created_at, dt) 140 | self.assertEqual(pl.updated_at, dt) 141 | 142 | def test_instantiation_with_None_kwargs(self): 143 | with self.assertRaises(TypeError): 144 | Place(id=None, created_at=None, updated_at=None) 145 | 146 | 147 | class TestPlace_save(unittest.TestCase): 148 | """Unittests for testing save method of the Place class.""" 149 | 150 | @classmethod 151 | def setUp(self): 152 | try: 153 | os.rename("file.json", "tmp") 154 | except IOError: 155 | pass 156 | 157 | def tearDown(self): 158 | try: 159 | os.remove("file.json") 160 | except IOError: 161 | pass 162 | try: 163 | os.rename("tmp", "file.json") 164 | except IOError: 165 | pass 166 | 167 | def test_one_save(self): 168 | pl = Place() 169 | sleep(0.05) 170 | first_updated_at = pl.updated_at 171 | pl.save() 172 | self.assertLess(first_updated_at, pl.updated_at) 173 | 174 | def test_two_saves(self): 175 | pl = Place() 176 | sleep(0.05) 177 | first_updated_at = pl.updated_at 178 | pl.save() 179 | second_updated_at = pl.updated_at 180 | self.assertLess(first_updated_at, second_updated_at) 181 | sleep(0.05) 182 | pl.save() 183 | self.assertLess(second_updated_at, pl.updated_at) 184 | 185 | def test_save_with_arg(self): 186 | pl = Place() 187 | with self.assertRaises(TypeError): 188 | pl.save(None) 189 | 190 | def test_save_updates_file(self): 191 | pl = Place() 192 | pl.save() 193 | plid = "Place." + pl.id 194 | with open("file.json", "r") as f: 195 | self.assertIn(plid, f.read()) 196 | 197 | 198 | class TestPlace_to_dict(unittest.TestCase): 199 | """Unittests for testing to_dict method of the Place class.""" 200 | 201 | def test_to_dict_type(self): 202 | self.assertTrue(dict, type(Place().to_dict())) 203 | 204 | def test_to_dict_contains_correct_keys(self): 205 | pl = Place() 206 | self.assertIn("id", pl.to_dict()) 207 | self.assertIn("created_at", pl.to_dict()) 208 | self.assertIn("updated_at", pl.to_dict()) 209 | self.assertIn("__class__", pl.to_dict()) 210 | 211 | def test_to_dict_contains_added_attributes(self): 212 | pl = Place() 213 | pl.middle_name = "Holberton" 214 | pl.my_number = 98 215 | self.assertEqual("Holberton", pl.middle_name) 216 | self.assertIn("my_number", pl.to_dict()) 217 | 218 | def test_to_dict_datetime_attributes_are_strs(self): 219 | pl = Place() 220 | pl_dict = pl.to_dict() 221 | self.assertEqual(str, type(pl_dict["id"])) 222 | self.assertEqual(str, type(pl_dict["created_at"])) 223 | self.assertEqual(str, type(pl_dict["updated_at"])) 224 | 225 | def test_to_dict_output(self): 226 | dt = datetime.today() 227 | pl = Place() 228 | pl.id = "123456" 229 | pl.created_at = pl.updated_at = dt 230 | tdict = { 231 | 'id': '123456', 232 | '__class__': 'Place', 233 | 'created_at': dt.isoformat(), 234 | 'updated_at': dt.isoformat(), 235 | } 236 | self.assertDictEqual(pl.to_dict(), tdict) 237 | 238 | def test_contrast_to_dict_dunder_dict(self): 239 | pl = Place() 240 | self.assertNotEqual(pl.to_dict(), pl.__dict__) 241 | 242 | def test_to_dict_with_arg(self): 243 | pl = Place() 244 | with self.assertRaises(TypeError): 245 | pl.to_dict(None) 246 | 247 | 248 | if __name__ == "__main__": 249 | unittest.main() 250 | -------------------------------------------------------------------------------- /one/console.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | '''Command Line Interpreter''' 3 | import cmd 4 | import json 5 | import re 6 | import sys 7 | 8 | from models import * 9 | from models import storage 10 | 11 | 12 | class HBNBCommand(cmd.Cmd): 13 | prompt = "(hbnb)" 14 | 15 | def do_EOF(self, *args): 16 | '''Usage: EOF 17 | Function: Exits the program 18 | ''' 19 | print() 20 | return True 21 | 22 | def do_quit(self, *args): 23 | '''Usage: quit 24 | Function: Exits the program 25 | ''' 26 | # quit() 27 | return True 28 | 29 | def do_create(self, line): 30 | '''Usage: 1. create | 2. .create() 31 | Function: Creates an instance of the class 32 | ''' 33 | if line != "" or line is not None: 34 | if line not in storage.classes(): 35 | print("** class doesn't exist **") 36 | else: 37 | # create an instance of the given class 38 | obj_intance = storage.classes()[line]() 39 | obj_intance.save() 40 | print(obj_intance.id) 41 | else: 42 | print("** class name missing **") 43 | 44 | def do_show(self, line): 45 | '''Usage: 1. show | 2. .show() 46 | Function: Shows the instance details of the class 47 | ''' 48 | # check if class name and instance id was provided 49 | if line == "" or line is None: 50 | print("** class name missing **") 51 | 52 | else: 53 | # get all the arguments passed via the command line 54 | class_info = line.split(" ") 55 | if len(class_info) < 2: 56 | print("** instance id missing **") 57 | else: 58 | class_name = class_info[0] 59 | instance_id = class_info[1] 60 | # check if class name exists 61 | if class_name in storage.classes(): 62 | # check if instance_id exists 63 | key = f"{class_name}.{instance_id}" 64 | if key not in storage.all(): 65 | print("** no instance found **") 66 | else: 67 | instance_dict = storage.all()[key] 68 | print(instance_dict) 69 | 70 | else: 71 | print("** class doesn't exist **") 72 | 73 | def do_destroy(self, line): 74 | '''Usage: 1. destroy | 2. .delete() 75 | Function: Deletes the instance of the class 76 | ''' 77 | # check if class name and instance id was provided 78 | if line == "" or line is None: 79 | print("** class name missing **") 80 | 81 | else: 82 | # get all the arguments passed via the command line 83 | class_info = line.split(" ") 84 | if len(class_info) < 2: 85 | print("** instance id missing **") 86 | else: 87 | class_name = class_info[0] 88 | instance_id = class_info[1] 89 | # check if class name exists 90 | if class_name in storage.classes(): 91 | # check if instance_id exists 92 | key = f"{class_name}.{instance_id}" 93 | if key not in storage.all(): 94 | print("** no instance found **") 95 | else: 96 | # delete this instance and save to json 97 | del storage.all()[key] 98 | storage.save() 99 | return 100 | 101 | else: 102 | print("** class doesn't exist **") 103 | 104 | def do_all(self, line): 105 | '''Usage: 1. all | 2. all | 3. .all() 106 | Function: Prints the string representation of all instances 107 | ''' 108 | instance_obj = storage.all() 109 | instance_list = [] 110 | 111 | if line == "" or line is None: 112 | for key, value in storage.all().items(): 113 | instance_list.append(str(value)) 114 | print(instance_list) 115 | 116 | else: 117 | if line not in storage.classes(): 118 | print("** class doesn't exist **") 119 | return 120 | else: 121 | for key, value in storage.all().items(): 122 | class_name, instance_id = key.split(".") 123 | if line == class_name: 124 | instance_list.append(str(value)) 125 | print(instance_list) 126 | 127 | def do_update(self, line): 128 | '''Usage: 1. update | \ 129 | 2. .update( ) \ 130 | 3. update \ 131 | 4. .update( ) \ 132 | Function: Updates the instance of the class 133 | ''' 134 | checks = re.search(r"^(\w+)\s([\S]+?)\s({.+?})$", line) 135 | if checks: 136 | # it is a dictionary 137 | class_name = checks.group(1) 138 | instance_id = checks.group(2) 139 | update_dict = checks.group(3) 140 | 141 | if class_name is None: 142 | print("** class name missing **") 143 | elif instance_id is None: 144 | print("** instance id missing **") 145 | elif update_dict is None: 146 | print("** attribute name missing **") 147 | else: 148 | if class_name not in storage.classes(): 149 | print("** class doesn't exist **") 150 | else: 151 | key = f"{class_name}.{instance_id}" 152 | if key not in storage.all(): 153 | print("** no instance found **") 154 | else: 155 | instance_dict = storage.all()[key] 156 | update_dict = json.loads(update_dict) 157 | 158 | attributes = storage.attributes()[class_name] 159 | # print(attributes) 160 | for key, value in update_dict.items(): 161 | if key in attributes: 162 | # print(key) 163 | value = attributes[key](value) 164 | # print(attributes[key]) 165 | setattr(instance_dict, key, value) 166 | storage.save() 167 | 168 | else: 169 | # it isn't a dictionary 170 | checks = re.search( 171 | r"^(\w+)\s([\S]+?)\s\"(.+?)\"\,\s\"(.+?)\"", line) 172 | class_name = checks.group(1) 173 | instance_id = checks.group(2) 174 | attribute = checks.group(3) 175 | value = checks.group(4) 176 | 177 | if class_name is None: 178 | print("** class name missing **") 179 | elif instance_id is None: 180 | print("** instance id missing **") 181 | elif attribute is None: 182 | print("** attribute name missing **") 183 | elif value is None: 184 | print("** value missing **") 185 | else: 186 | # check if class exists 187 | if class_name not in storage.classes(): 188 | print("** class doesn't exist **") 189 | else: 190 | key = f"{class_name}.{instance_id}" 191 | if key not in storage.all(): 192 | print("** no instance found **") 193 | else: 194 | instance_dict = storage.all()[key] 195 | # print(instance_dict) 196 | attributes_dict = storage.attributes()[class_name] 197 | # update attributes in the instance dictionary 198 | # print(attributes_dict[attribute]) 199 | value = attributes_dict[attribute]( 200 | value) # type casting 201 | # print(attribute, value) 202 | setattr(instance_dict, attribute, value) 203 | storage.save() 204 | 205 | def emptyline(self): 206 | pass 207 | 208 | def precmd(self, line): 209 | # make the app work non-interactively 210 | if not sys.stdin.isatty(): 211 | print() 212 | 213 | checks = re.search(r"^(\w*)\.(\w+)(?:\(([^)]*)\))$", line) 214 | if checks: 215 | class_name = checks.group(1) 216 | command = checks.group(2) 217 | args = checks.group(3) 218 | 219 | if args is None: 220 | line = f"{command} {class_name}" 221 | return '' 222 | else: 223 | # print(args) 224 | args_checks = re.search(r"^\"([^\"]*)\"(?:, (.*))?$", args) 225 | # print(args_checks.group(1), args_checks.group(2)) 226 | instance_id = args_checks[1] 227 | 228 | if args_checks.group(2) is None: 229 | line = f"{command} {class_name} {instance_id}" 230 | else: 231 | attribute_part = args_checks.group(2) 232 | # print(attribute_part) 233 | line = f"{command} {class_name} {instance_id} \ 234 | {attribute_part}" 235 | return '' 236 | 237 | return cmd.Cmd.precmd(self, line) 238 | # return '' 239 | 240 | def do_count(self, line): 241 | '''Usage: 1. count | 2. .count() 242 | Function: Counts all the instances of the class 243 | ''' 244 | count = 0 245 | for key in storage.all().keys(): 246 | class_name, instance_id = key.split(".") 247 | if line == class_name: 248 | count += 1 249 | print(count) 250 | 251 | 252 | if __name__ == '__main__': 253 | HBNBCommand().cmdloop() 254 | -------------------------------------------------------------------------------- /tests/test_console.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | """Defines unittests for console.py. 3 | 4 | Unittest classes: 5 | TestHBNBCommand_prompting 6 | TestHBNBCommand_help 7 | TestHBNBCommand_exit 8 | TestHBNBCommand_create 9 | TestHBNBCommand_show 10 | TestHBNBCommand_all 11 | TestHBNBCommand_destroy 12 | TestHBNBCommand_update 13 | """ 14 | import os 15 | import sys 16 | import unittest 17 | from models import storage 18 | from models.engine.file_storage import FileStorage 19 | from console import HBNBCommand 20 | from io import StringIO 21 | from unittest.mock import patch 22 | 23 | 24 | class TestHBNBCommand_prompting(unittest.TestCase): 25 | """Unittests for testing prompting of the HBNB command interpreter.""" 26 | 27 | def test_prompt_string(self): 28 | self.assertEqual("(hbnb) ", HBNBCommand.prompt) 29 | 30 | def test_empty_line(self): 31 | with patch("sys.stdout", new=StringIO()) as output: 32 | self.assertFalse(HBNBCommand().onecmd("")) 33 | self.assertEqual("", output.getvalue().strip()) 34 | 35 | 36 | class TestHBNBCommand_help(unittest.TestCase): 37 | """Unittests for testing help messages of the HBNB command interpreter.""" 38 | 39 | def test_help_quit(self): 40 | h = "Quit command to exit the program." 41 | with patch("sys.stdout", new=StringIO()) as output: 42 | self.assertFalse(HBNBCommand().onecmd("help quit")) 43 | self.assertEqual(h, output.getvalue().strip()) 44 | 45 | def test_help_create(self): 46 | h = ("Usage: create \n " 47 | "Create a new class instance and print its id.") 48 | with patch("sys.stdout", new=StringIO()) as output: 49 | self.assertFalse(HBNBCommand().onecmd("help create")) 50 | self.assertEqual(h, output.getvalue().strip()) 51 | 52 | def test_help_EOF(self): 53 | h = "EOF signal to exit the program." 54 | with patch("sys.stdout", new=StringIO()) as output: 55 | self.assertFalse(HBNBCommand().onecmd("help EOF")) 56 | self.assertEqual(h, output.getvalue().strip()) 57 | 58 | def test_help_show(self): 59 | h = ("Usage: show or .show()\n " 60 | "Display the string representation of a class instance of" 61 | " a given id.") 62 | with patch("sys.stdout", new=StringIO()) as output: 63 | self.assertFalse(HBNBCommand().onecmd("help show")) 64 | self.assertEqual(h, output.getvalue().strip()) 65 | 66 | def test_help_destroy(self): 67 | h = ("Usage: destroy or .destroy()\n " 68 | "Delete a class instance of a given id.") 69 | with patch("sys.stdout", new=StringIO()) as output: 70 | self.assertFalse(HBNBCommand().onecmd("help destroy")) 71 | self.assertEqual(h, output.getvalue().strip()) 72 | 73 | def test_help_all(self): 74 | h = ("Usage: all or all or .all()\n " 75 | "Display string representations of all instances of a given class" 76 | ".\n If no class is specified, displays all instantiated " 77 | "objects.") 78 | with patch("sys.stdout", new=StringIO()) as output: 79 | self.assertFalse(HBNBCommand().onecmd("help all")) 80 | self.assertEqual(h, output.getvalue().strip()) 81 | 82 | def test_help_count(self): 83 | h = ("Usage: count or .count()\n " 84 | "Retrieve the number of instances of a given class.") 85 | with patch("sys.stdout", new=StringIO()) as output: 86 | self.assertFalse(HBNBCommand().onecmd("help count")) 87 | self.assertEqual(h, output.getvalue().strip()) 88 | 89 | def test_help_update(self): 90 | h = ("Usage: update or" 91 | "\n .update(, , ) or\n .update(, )\n " 93 | "Update a class instance of a given id by adding or updating\n " 94 | " a given attribute key/value pair or dictionary.") 95 | with patch("sys.stdout", new=StringIO()) as output: 96 | self.assertFalse(HBNBCommand().onecmd("help update")) 97 | self.assertEqual(h, output.getvalue().strip()) 98 | 99 | def test_help(self): 100 | h = ("Documented commands (type help ):\n" 101 | "========================================\n" 102 | "EOF all count create destroy help quit show update") 103 | with patch("sys.stdout", new=StringIO()) as output: 104 | self.assertFalse(HBNBCommand().onecmd("help")) 105 | self.assertEqual(h, output.getvalue().strip()) 106 | 107 | 108 | class TestHBNBCommand_exit(unittest.TestCase): 109 | """Unittests for testing exiting from the HBNB command interpreter.""" 110 | 111 | def test_quit_exits(self): 112 | with patch("sys.stdout", new=StringIO()) as output: 113 | self.assertTrue(HBNBCommand().onecmd("quit")) 114 | 115 | def test_EOF_exits(self): 116 | with patch("sys.stdout", new=StringIO()) as output: 117 | self.assertTrue(HBNBCommand().onecmd("EOF")) 118 | 119 | 120 | class TestHBNBCommand_create(unittest.TestCase): 121 | """Unittests for testing create from the HBNB command interpreter.""" 122 | 123 | @classmethod 124 | def setUp(self): 125 | try: 126 | os.rename("file.json", "tmp") 127 | except IOError: 128 | pass 129 | FileStorage.__objects = {} 130 | 131 | @classmethod 132 | def tearDown(self): 133 | try: 134 | os.remove("file.json") 135 | except IOError: 136 | pass 137 | try: 138 | os.rename("tmp", "file.json") 139 | except IOError: 140 | pass 141 | 142 | def test_create_missing_class(self): 143 | correct = "** class name missing **" 144 | with patch("sys.stdout", new=StringIO()) as output: 145 | self.assertFalse(HBNBCommand().onecmd("create")) 146 | self.assertEqual(correct, output.getvalue().strip()) 147 | 148 | def test_create_invalid_class(self): 149 | correct = "** class doesn't exist **" 150 | with patch("sys.stdout", new=StringIO()) as output: 151 | self.assertFalse(HBNBCommand().onecmd("create MyModel")) 152 | self.assertEqual(correct, output.getvalue().strip()) 153 | 154 | def test_create_invalid_syntax(self): 155 | correct = "*** Unknown syntax: MyModel.create()" 156 | with patch("sys.stdout", new=StringIO()) as output: 157 | self.assertFalse(HBNBCommand().onecmd("MyModel.create()")) 158 | self.assertEqual(correct, output.getvalue().strip()) 159 | correct = "*** Unknown syntax: BaseModel.create()" 160 | with patch("sys.stdout", new=StringIO()) as output: 161 | self.assertFalse(HBNBCommand().onecmd("BaseModel.create()")) 162 | self.assertEqual(correct, output.getvalue().strip()) 163 | 164 | def test_create_object(self): 165 | with patch("sys.stdout", new=StringIO()) as output: 166 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 167 | self.assertLess(0, len(output.getvalue().strip())) 168 | testKey = "BaseModel.{}".format(output.getvalue().strip()) 169 | self.assertIn(testKey, storage.all().keys()) 170 | with patch("sys.stdout", new=StringIO()) as output: 171 | self.assertFalse(HBNBCommand().onecmd("create User")) 172 | self.assertLess(0, len(output.getvalue().strip())) 173 | testKey = "User.{}".format(output.getvalue().strip()) 174 | self.assertIn(testKey, storage.all().keys()) 175 | with patch("sys.stdout", new=StringIO()) as output: 176 | self.assertFalse(HBNBCommand().onecmd("create State")) 177 | self.assertLess(0, len(output.getvalue().strip())) 178 | testKey = "State.{}".format(output.getvalue().strip()) 179 | self.assertIn(testKey, storage.all().keys()) 180 | with patch("sys.stdout", new=StringIO()) as output: 181 | self.assertFalse(HBNBCommand().onecmd("create City")) 182 | self.assertLess(0, len(output.getvalue().strip())) 183 | testKey = "City.{}".format(output.getvalue().strip()) 184 | self.assertIn(testKey, storage.all().keys()) 185 | with patch("sys.stdout", new=StringIO()) as output: 186 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 187 | self.assertLess(0, len(output.getvalue().strip())) 188 | testKey = "Amenity.{}".format(output.getvalue().strip()) 189 | self.assertIn(testKey, storage.all().keys()) 190 | with patch("sys.stdout", new=StringIO()) as output: 191 | self.assertFalse(HBNBCommand().onecmd("create Place")) 192 | self.assertLess(0, len(output.getvalue().strip())) 193 | testKey = "Place.{}".format(output.getvalue().strip()) 194 | self.assertIn(testKey, storage.all().keys()) 195 | with patch("sys.stdout", new=StringIO()) as output: 196 | self.assertFalse(HBNBCommand().onecmd("create Review")) 197 | self.assertLess(0, len(output.getvalue().strip())) 198 | testKey = "Review.{}".format(output.getvalue().strip()) 199 | self.assertIn(testKey, storage.all().keys()) 200 | 201 | 202 | class TestHBNBCommand_show(unittest.TestCase): 203 | """Unittests for testing show from the HBNB command interpreter""" 204 | 205 | @classmethod 206 | def setUp(self): 207 | try: 208 | os.rename("file.json", "tmp") 209 | except IOError: 210 | pass 211 | FileStorage.__objects = {} 212 | 213 | @classmethod 214 | def tearDown(self): 215 | try: 216 | os.remove("file.json") 217 | except IOError: 218 | pass 219 | try: 220 | os.rename("tmp", "file.json") 221 | except IOError: 222 | pass 223 | 224 | def test_show_missing_class(self): 225 | correct = "** class name missing **" 226 | with patch("sys.stdout", new=StringIO()) as output: 227 | self.assertFalse(HBNBCommand().onecmd("show")) 228 | self.assertEqual(correct, output.getvalue().strip()) 229 | with patch("sys.stdout", new=StringIO()) as output: 230 | self.assertFalse(HBNBCommand().onecmd(".show()")) 231 | self.assertEqual(correct, output.getvalue().strip()) 232 | 233 | def test_show_invalid_class(self): 234 | correct = "** class doesn't exist **" 235 | with patch("sys.stdout", new=StringIO()) as output: 236 | self.assertFalse(HBNBCommand().onecmd("show MyModel")) 237 | self.assertEqual(correct, output.getvalue().strip()) 238 | with patch("sys.stdout", new=StringIO()) as output: 239 | self.assertFalse(HBNBCommand().onecmd("MyModel.show()")) 240 | self.assertEqual(correct, output.getvalue().strip()) 241 | 242 | def test_show_missing_id_space_notation(self): 243 | correct = "** instance id missing **" 244 | with patch("sys.stdout", new=StringIO()) as output: 245 | self.assertFalse(HBNBCommand().onecmd("show BaseModel")) 246 | self.assertEqual(correct, output.getvalue().strip()) 247 | with patch("sys.stdout", new=StringIO()) as output: 248 | self.assertFalse(HBNBCommand().onecmd("show User")) 249 | self.assertEqual(correct, output.getvalue().strip()) 250 | with patch("sys.stdout", new=StringIO()) as output: 251 | self.assertFalse(HBNBCommand().onecmd("show State")) 252 | self.assertEqual(correct, output.getvalue().strip()) 253 | with patch("sys.stdout", new=StringIO()) as output: 254 | self.assertFalse(HBNBCommand().onecmd("show City")) 255 | self.assertEqual(correct, output.getvalue().strip()) 256 | with patch("sys.stdout", new=StringIO()) as output: 257 | self.assertFalse(HBNBCommand().onecmd("show Amenity")) 258 | self.assertEqual(correct, output.getvalue().strip()) 259 | with patch("sys.stdout", new=StringIO()) as output: 260 | self.assertFalse(HBNBCommand().onecmd("show Place")) 261 | self.assertEqual(correct, output.getvalue().strip()) 262 | with patch("sys.stdout", new=StringIO()) as output: 263 | self.assertFalse(HBNBCommand().onecmd("show Review")) 264 | self.assertEqual(correct, output.getvalue().strip()) 265 | 266 | def test_show_missing_id_dot_notation(self): 267 | correct = "** instance id missing **" 268 | with patch("sys.stdout", new=StringIO()) as output: 269 | self.assertFalse(HBNBCommand().onecmd("BaseModel.show()")) 270 | self.assertEqual(correct, output.getvalue().strip()) 271 | with patch("sys.stdout", new=StringIO()) as output: 272 | self.assertFalse(HBNBCommand().onecmd("User.show()")) 273 | self.assertEqual(correct, output.getvalue().strip()) 274 | with patch("sys.stdout", new=StringIO()) as output: 275 | self.assertFalse(HBNBCommand().onecmd("State.show()")) 276 | self.assertEqual(correct, output.getvalue().strip()) 277 | with patch("sys.stdout", new=StringIO()) as output: 278 | self.assertFalse(HBNBCommand().onecmd("City.show()")) 279 | self.assertEqual(correct, output.getvalue().strip()) 280 | with patch("sys.stdout", new=StringIO()) as output: 281 | self.assertFalse(HBNBCommand().onecmd("Amenity.show()")) 282 | self.assertEqual(correct, output.getvalue().strip()) 283 | with patch("sys.stdout", new=StringIO()) as output: 284 | self.assertFalse(HBNBCommand().onecmd("Place.show()")) 285 | self.assertEqual(correct, output.getvalue().strip()) 286 | with patch("sys.stdout", new=StringIO()) as output: 287 | self.assertFalse(HBNBCommand().onecmd("Review.show()")) 288 | self.assertEqual(correct, output.getvalue().strip()) 289 | 290 | def test_show_no_instance_found_space_notation(self): 291 | correct = "** no instance found **" 292 | with patch("sys.stdout", new=StringIO()) as output: 293 | self.assertFalse(HBNBCommand().onecmd("show BaseModel 1")) 294 | self.assertEqual(correct, output.getvalue().strip()) 295 | with patch("sys.stdout", new=StringIO()) as output: 296 | self.assertFalse(HBNBCommand().onecmd("show User 1")) 297 | self.assertEqual(correct, output.getvalue().strip()) 298 | with patch("sys.stdout", new=StringIO()) as output: 299 | self.assertFalse(HBNBCommand().onecmd("show State 1")) 300 | self.assertEqual(correct, output.getvalue().strip()) 301 | with patch("sys.stdout", new=StringIO()) as output: 302 | self.assertFalse(HBNBCommand().onecmd("show City 1")) 303 | self.assertEqual(correct, output.getvalue().strip()) 304 | with patch("sys.stdout", new=StringIO()) as output: 305 | self.assertFalse(HBNBCommand().onecmd("show Amenity 1")) 306 | self.assertEqual(correct, output.getvalue().strip()) 307 | with patch("sys.stdout", new=StringIO()) as output: 308 | self.assertFalse(HBNBCommand().onecmd("show Place 1")) 309 | self.assertEqual(correct, output.getvalue().strip()) 310 | with patch("sys.stdout", new=StringIO()) as output: 311 | self.assertFalse(HBNBCommand().onecmd("show Review 1")) 312 | self.assertEqual(correct, output.getvalue().strip()) 313 | 314 | def test_show_no_instance_found_dot_notation(self): 315 | correct = "** no instance found **" 316 | with patch("sys.stdout", new=StringIO()) as output: 317 | self.assertFalse(HBNBCommand().onecmd("BaseModel.show(1)")) 318 | self.assertEqual(correct, output.getvalue().strip()) 319 | with patch("sys.stdout", new=StringIO()) as output: 320 | self.assertFalse(HBNBCommand().onecmd("User.show(1)")) 321 | self.assertEqual(correct, output.getvalue().strip()) 322 | with patch("sys.stdout", new=StringIO()) as output: 323 | self.assertFalse(HBNBCommand().onecmd("State.show(1)")) 324 | self.assertEqual(correct, output.getvalue().strip()) 325 | with patch("sys.stdout", new=StringIO()) as output: 326 | self.assertFalse(HBNBCommand().onecmd("City.show(1)")) 327 | self.assertEqual(correct, output.getvalue().strip()) 328 | with patch("sys.stdout", new=StringIO()) as output: 329 | self.assertFalse(HBNBCommand().onecmd("Amenity.show(1)")) 330 | self.assertEqual(correct, output.getvalue().strip()) 331 | with patch("sys.stdout", new=StringIO()) as output: 332 | self.assertFalse(HBNBCommand().onecmd("Place.show(1)")) 333 | self.assertEqual(correct, output.getvalue().strip()) 334 | with patch("sys.stdout", new=StringIO()) as output: 335 | self.assertFalse(HBNBCommand().onecmd("Review.show(1)")) 336 | self.assertEqual(correct, output.getvalue().strip()) 337 | 338 | def test_show_objects_space_notation(self): 339 | with patch("sys.stdout", new=StringIO()) as output: 340 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 341 | testID = output.getvalue().strip() 342 | with patch("sys.stdout", new=StringIO()) as output: 343 | obj = storage.all()["BaseModel.{}".format(testID)] 344 | command = "show BaseModel {}".format(testID) 345 | self.assertFalse(HBNBCommand().onecmd(command)) 346 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 347 | with patch("sys.stdout", new=StringIO()) as output: 348 | self.assertFalse(HBNBCommand().onecmd("create User")) 349 | testID = output.getvalue().strip() 350 | with patch("sys.stdout", new=StringIO()) as output: 351 | obj = storage.all()["User.{}".format(testID)] 352 | command = "show User {}".format(testID) 353 | self.assertFalse(HBNBCommand().onecmd(command)) 354 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 355 | with patch("sys.stdout", new=StringIO()) as output: 356 | self.assertFalse(HBNBCommand().onecmd("create State")) 357 | testID = output.getvalue().strip() 358 | with patch("sys.stdout", new=StringIO()) as output: 359 | obj = storage.all()["State.{}".format(testID)] 360 | command = "show State {}".format(testID) 361 | self.assertFalse(HBNBCommand().onecmd(command)) 362 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 363 | with patch("sys.stdout", new=StringIO()) as output: 364 | self.assertFalse(HBNBCommand().onecmd("create Place")) 365 | testID = output.getvalue().strip() 366 | with patch("sys.stdout", new=StringIO()) as output: 367 | obj = storage.all()["Place.{}".format(testID)] 368 | command = "show Place {}".format(testID) 369 | self.assertFalse(HBNBCommand().onecmd(command)) 370 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 371 | with patch("sys.stdout", new=StringIO()) as output: 372 | self.assertFalse(HBNBCommand().onecmd("create City")) 373 | testID = output.getvalue().strip() 374 | with patch("sys.stdout", new=StringIO()) as output: 375 | obj = storage.all()["City.{}".format(testID)] 376 | command = "show City {}".format(testID) 377 | self.assertFalse(HBNBCommand().onecmd(command)) 378 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 379 | with patch("sys.stdout", new=StringIO()) as output: 380 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 381 | testID = output.getvalue().strip() 382 | with patch("sys.stdout", new=StringIO()) as output: 383 | obj = storage.all()["Amenity.{}".format(testID)] 384 | command = "show Amenity {}".format(testID) 385 | self.assertFalse(HBNBCommand().onecmd(command)) 386 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 387 | with patch("sys.stdout", new=StringIO()) as output: 388 | self.assertFalse(HBNBCommand().onecmd("create Review")) 389 | testID = output.getvalue().strip() 390 | with patch("sys.stdout", new=StringIO()) as output: 391 | obj = storage.all()["Review.{}".format(testID)] 392 | command = "show Review {}".format(testID) 393 | self.assertFalse(HBNBCommand().onecmd(command)) 394 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 395 | 396 | def test_show_objects_space_notation(self): 397 | with patch("sys.stdout", new=StringIO()) as output: 398 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 399 | testID = output.getvalue().strip() 400 | with patch("sys.stdout", new=StringIO()) as output: 401 | obj = storage.all()["BaseModel.{}".format(testID)] 402 | command = "BaseModel.show({})".format(testID) 403 | self.assertFalse(HBNBCommand().onecmd(command)) 404 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 405 | with patch("sys.stdout", new=StringIO()) as output: 406 | self.assertFalse(HBNBCommand().onecmd("create User")) 407 | testID = output.getvalue().strip() 408 | with patch("sys.stdout", new=StringIO()) as output: 409 | obj = storage.all()["User.{}".format(testID)] 410 | command = "User.show({})".format(testID) 411 | self.assertFalse(HBNBCommand().onecmd(command)) 412 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 413 | with patch("sys.stdout", new=StringIO()) as output: 414 | self.assertFalse(HBNBCommand().onecmd("create State")) 415 | testID = output.getvalue().strip() 416 | with patch("sys.stdout", new=StringIO()) as output: 417 | obj = storage.all()["State.{}".format(testID)] 418 | command = "State.show({})".format(testID) 419 | self.assertFalse(HBNBCommand().onecmd(command)) 420 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 421 | with patch("sys.stdout", new=StringIO()) as output: 422 | self.assertFalse(HBNBCommand().onecmd("create Place")) 423 | testID = output.getvalue().strip() 424 | with patch("sys.stdout", new=StringIO()) as output: 425 | obj = storage.all()["Place.{}".format(testID)] 426 | command = "Place.show({})".format(testID) 427 | self.assertFalse(HBNBCommand().onecmd(command)) 428 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 429 | with patch("sys.stdout", new=StringIO()) as output: 430 | self.assertFalse(HBNBCommand().onecmd("create City")) 431 | testID = output.getvalue().strip() 432 | with patch("sys.stdout", new=StringIO()) as output: 433 | obj = storage.all()["City.{}".format(testID)] 434 | command = "City.show({})".format(testID) 435 | self.assertFalse(HBNBCommand().onecmd(command)) 436 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 437 | with patch("sys.stdout", new=StringIO()) as output: 438 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 439 | testID = output.getvalue().strip() 440 | with patch("sys.stdout", new=StringIO()) as output: 441 | obj = storage.all()["Amenity.{}".format(testID)] 442 | command = "Amenity.show({})".format(testID) 443 | self.assertFalse(HBNBCommand().onecmd(command)) 444 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 445 | with patch("sys.stdout", new=StringIO()) as output: 446 | self.assertFalse(HBNBCommand().onecmd("create Review")) 447 | testID = output.getvalue().strip() 448 | with patch("sys.stdout", new=StringIO()) as output: 449 | obj = storage.all()["Review.{}".format(testID)] 450 | command = "Review.show({})".format(testID) 451 | self.assertFalse(HBNBCommand().onecmd(command)) 452 | self.assertEqual(obj.__str__(), output.getvalue().strip()) 453 | 454 | 455 | class TestHBNBCommand_destroy(unittest.TestCase): 456 | """Unittests for testing destroy from the HBNB command interpreter.""" 457 | 458 | @classmethod 459 | def setUp(self): 460 | try: 461 | os.rename("file.json", "tmp") 462 | except IOError: 463 | pass 464 | FileStorage.__objects = {} 465 | 466 | @classmethod 467 | def tearDown(self): 468 | try: 469 | os.remove("file.json") 470 | except IOError: 471 | pass 472 | try: 473 | os.rename("tmp", "file.json") 474 | except IOError: 475 | pass 476 | storage.reload() 477 | 478 | def test_destroy_missing_class(self): 479 | correct = "** class name missing **" 480 | with patch("sys.stdout", new=StringIO()) as output: 481 | self.assertFalse(HBNBCommand().onecmd("destroy")) 482 | self.assertEqual(correct, output.getvalue().strip()) 483 | with patch("sys.stdout", new=StringIO()) as output: 484 | self.assertFalse(HBNBCommand().onecmd(".destroy()")) 485 | self.assertEqual(correct, output.getvalue().strip()) 486 | 487 | def test_destroy_invalid_class(self): 488 | correct = "** class doesn't exist **" 489 | with patch("sys.stdout", new=StringIO()) as output: 490 | self.assertFalse(HBNBCommand().onecmd("destroy MyModel")) 491 | self.assertEqual(correct, output.getvalue().strip()) 492 | with patch("sys.stdout", new=StringIO()) as output: 493 | self.assertFalse(HBNBCommand().onecmd("MyModel.destroy()")) 494 | self.assertEqual(correct, output.getvalue().strip()) 495 | 496 | def test_destroy_id_missing_space_notation(self): 497 | correct = "** instance id missing **" 498 | with patch("sys.stdout", new=StringIO()) as output: 499 | self.assertFalse(HBNBCommand().onecmd("destroy BaseModel")) 500 | self.assertEqual(correct, output.getvalue().strip()) 501 | with patch("sys.stdout", new=StringIO()) as output: 502 | self.assertFalse(HBNBCommand().onecmd("destroy User")) 503 | self.assertEqual(correct, output.getvalue().strip()) 504 | with patch("sys.stdout", new=StringIO()) as output: 505 | self.assertFalse(HBNBCommand().onecmd("destroy State")) 506 | self.assertEqual(correct, output.getvalue().strip()) 507 | with patch("sys.stdout", new=StringIO()) as output: 508 | self.assertFalse(HBNBCommand().onecmd("destroy City")) 509 | self.assertEqual(correct, output.getvalue().strip()) 510 | with patch("sys.stdout", new=StringIO()) as output: 511 | self.assertFalse(HBNBCommand().onecmd("destroy Amenity")) 512 | self.assertEqual(correct, output.getvalue().strip()) 513 | with patch("sys.stdout", new=StringIO()) as output: 514 | self.assertFalse(HBNBCommand().onecmd("destroy Place")) 515 | self.assertEqual(correct, output.getvalue().strip()) 516 | with patch("sys.stdout", new=StringIO()) as output: 517 | self.assertFalse(HBNBCommand().onecmd("destroy Review")) 518 | self.assertEqual(correct, output.getvalue().strip()) 519 | 520 | def test_destroy_id_missing_dot_notation(self): 521 | correct = "** instance id missing **" 522 | with patch("sys.stdout", new=StringIO()) as output: 523 | self.assertFalse(HBNBCommand().onecmd("BaseModel.destroy()")) 524 | self.assertEqual(correct, output.getvalue().strip()) 525 | with patch("sys.stdout", new=StringIO()) as output: 526 | self.assertFalse(HBNBCommand().onecmd("User.destroy()")) 527 | self.assertEqual(correct, output.getvalue().strip()) 528 | with patch("sys.stdout", new=StringIO()) as output: 529 | self.assertFalse(HBNBCommand().onecmd("State.destroy()")) 530 | self.assertEqual(correct, output.getvalue().strip()) 531 | with patch("sys.stdout", new=StringIO()) as output: 532 | self.assertFalse(HBNBCommand().onecmd("City.destroy()")) 533 | self.assertEqual(correct, output.getvalue().strip()) 534 | with patch("sys.stdout", new=StringIO()) as output: 535 | self.assertFalse(HBNBCommand().onecmd("Amenity.destroy()")) 536 | self.assertEqual(correct, output.getvalue().strip()) 537 | with patch("sys.stdout", new=StringIO()) as output: 538 | self.assertFalse(HBNBCommand().onecmd("Place.destroy()")) 539 | self.assertEqual(correct, output.getvalue().strip()) 540 | with patch("sys.stdout", new=StringIO()) as output: 541 | self.assertFalse(HBNBCommand().onecmd("Review.destroy()")) 542 | self.assertEqual(correct, output.getvalue().strip()) 543 | 544 | def test_destroy_invalid_id_space_notation(self): 545 | correct = "** no instance found **" 546 | with patch("sys.stdout", new=StringIO()) as output: 547 | self.assertFalse(HBNBCommand().onecmd("destroy BaseModel 1")) 548 | self.assertEqual(correct, output.getvalue().strip()) 549 | with patch("sys.stdout", new=StringIO()) as output: 550 | self.assertFalse(HBNBCommand().onecmd("destroy User 1")) 551 | self.assertEqual(correct, output.getvalue().strip()) 552 | with patch("sys.stdout", new=StringIO()) as output: 553 | self.assertFalse(HBNBCommand().onecmd("destroy State 1")) 554 | self.assertEqual(correct, output.getvalue().strip()) 555 | with patch("sys.stdout", new=StringIO()) as output: 556 | self.assertFalse(HBNBCommand().onecmd("destroy City 1")) 557 | self.assertEqual(correct, output.getvalue().strip()) 558 | with patch("sys.stdout", new=StringIO()) as output: 559 | self.assertFalse(HBNBCommand().onecmd("destroy Amenity 1")) 560 | self.assertEqual(correct, output.getvalue().strip()) 561 | with patch("sys.stdout", new=StringIO()) as output: 562 | self.assertFalse(HBNBCommand().onecmd("destroy Place 1")) 563 | self.assertEqual(correct, output.getvalue().strip()) 564 | with patch("sys.stdout", new=StringIO()) as output: 565 | self.assertFalse(HBNBCommand().onecmd("destroy Review 1")) 566 | self.assertEqual(correct, output.getvalue().strip()) 567 | 568 | def test_destroy_invalid_id_dot_notation(self): 569 | correct = "** no instance found **" 570 | with patch("sys.stdout", new=StringIO()) as output: 571 | self.assertFalse(HBNBCommand().onecmd("BaseModel.destroy(1)")) 572 | self.assertEqual(correct, output.getvalue().strip()) 573 | with patch("sys.stdout", new=StringIO()) as output: 574 | self.assertFalse(HBNBCommand().onecmd("User.destroy(1)")) 575 | self.assertEqual(correct, output.getvalue().strip()) 576 | with patch("sys.stdout", new=StringIO()) as output: 577 | self.assertFalse(HBNBCommand().onecmd("State.destroy(1)")) 578 | self.assertEqual(correct, output.getvalue().strip()) 579 | with patch("sys.stdout", new=StringIO()) as output: 580 | self.assertFalse(HBNBCommand().onecmd("City.destroy(1)")) 581 | self.assertEqual(correct, output.getvalue().strip()) 582 | with patch("sys.stdout", new=StringIO()) as output: 583 | self.assertFalse(HBNBCommand().onecmd("Amenity.destroy(1)")) 584 | self.assertEqual(correct, output.getvalue().strip()) 585 | with patch("sys.stdout", new=StringIO()) as output: 586 | self.assertFalse(HBNBCommand().onecmd("Place.destroy(1)")) 587 | self.assertEqual(correct, output.getvalue().strip()) 588 | with patch("sys.stdout", new=StringIO()) as output: 589 | self.assertFalse(HBNBCommand().onecmd("Review.destroy(1)")) 590 | self.assertEqual(correct, output.getvalue().strip()) 591 | 592 | def test_destroy_objects_space_notation(self): 593 | with patch("sys.stdout", new=StringIO()) as output: 594 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 595 | testID = output.getvalue().strip() 596 | with patch("sys.stdout", new=StringIO()) as output: 597 | obj = storage.all()["BaseModel.{}".format(testID)] 598 | command = "destroy BaseModel {}".format(testID) 599 | self.assertFalse(HBNBCommand().onecmd(command)) 600 | self.assertNotIn(obj, storage.all()) 601 | with patch("sys.stdout", new=StringIO()) as output: 602 | self.assertFalse(HBNBCommand().onecmd("create User")) 603 | testID = output.getvalue().strip() 604 | with patch("sys.stdout", new=StringIO()) as output: 605 | obj = storage.all()["User.{}".format(testID)] 606 | command = "show User {}".format(testID) 607 | self.assertFalse(HBNBCommand().onecmd(command)) 608 | self.assertNotIn(obj, storage.all()) 609 | with patch("sys.stdout", new=StringIO()) as output: 610 | self.assertFalse(HBNBCommand().onecmd("create State")) 611 | testID = output.getvalue().strip() 612 | with patch("sys.stdout", new=StringIO()) as output: 613 | obj = storage.all()["State.{}".format(testID)] 614 | command = "show State {}".format(testID) 615 | self.assertFalse(HBNBCommand().onecmd(command)) 616 | self.assertNotIn(obj, storage.all()) 617 | with patch("sys.stdout", new=StringIO()) as output: 618 | self.assertFalse(HBNBCommand().onecmd("create Place")) 619 | testID = output.getvalue().strip() 620 | with patch("sys.stdout", new=StringIO()) as output: 621 | obj = storage.all()["Place.{}".format(testID)] 622 | command = "show Place {}".format(testID) 623 | self.assertFalse(HBNBCommand().onecmd(command)) 624 | self.assertNotIn(obj, storage.all()) 625 | with patch("sys.stdout", new=StringIO()) as output: 626 | self.assertFalse(HBNBCommand().onecmd("create City")) 627 | testID = output.getvalue().strip() 628 | with patch("sys.stdout", new=StringIO()) as output: 629 | obj = storage.all()["City.{}".format(testID)] 630 | command = "show City {}".format(testID) 631 | self.assertFalse(HBNBCommand().onecmd(command)) 632 | self.assertNotIn(obj, storage.all()) 633 | with patch("sys.stdout", new=StringIO()) as output: 634 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 635 | testID = output.getvalue().strip() 636 | with patch("sys.stdout", new=StringIO()) as output: 637 | obj = storage.all()["Amenity.{}".format(testID)] 638 | command = "show Amenity {}".format(testID) 639 | self.assertFalse(HBNBCommand().onecmd(command)) 640 | self.assertNotIn(obj, storage.all()) 641 | with patch("sys.stdout", new=StringIO()) as output: 642 | self.assertFalse(HBNBCommand().onecmd("create Review")) 643 | testID = output.getvalue().strip() 644 | with patch("sys.stdout", new=StringIO()) as output: 645 | obj = storage.all()["Review.{}".format(testID)] 646 | command = "show Review {}".format(testID) 647 | self.assertFalse(HBNBCommand().onecmd(command)) 648 | self.assertNotIn(obj, storage.all()) 649 | 650 | def test_destroy_objects_dot_notation(self): 651 | with patch("sys.stdout", new=StringIO()) as output: 652 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 653 | testID = output.getvalue().strip() 654 | with patch("sys.stdout", new=StringIO()) as output: 655 | obj = storage.all()["BaseModel.{}".format(testID)] 656 | command = "BaseModel.destroy({})".format(testID) 657 | self.assertFalse(HBNBCommand().onecmd(command)) 658 | self.assertNotIn(obj, storage.all()) 659 | with patch("sys.stdout", new=StringIO()) as output: 660 | self.assertFalse(HBNBCommand().onecmd("create User")) 661 | testID = output.getvalue().strip() 662 | with patch("sys.stdout", new=StringIO()) as output: 663 | obj = storage.all()["User.{}".format(testID)] 664 | command = "User.destroy({})".format(testID) 665 | self.assertFalse(HBNBCommand().onecmd(command)) 666 | self.assertNotIn(obj, storage.all()) 667 | with patch("sys.stdout", new=StringIO()) as output: 668 | self.assertFalse(HBNBCommand().onecmd("create State")) 669 | testID = output.getvalue().strip() 670 | with patch("sys.stdout", new=StringIO()) as output: 671 | obj = storage.all()["State.{}".format(testID)] 672 | command = "State.destroy({})".format(testID) 673 | self.assertFalse(HBNBCommand().onecmd(command)) 674 | self.assertNotIn(obj, storage.all()) 675 | with patch("sys.stdout", new=StringIO()) as output: 676 | self.assertFalse(HBNBCommand().onecmd("create Place")) 677 | testID = output.getvalue().strip() 678 | with patch("sys.stdout", new=StringIO()) as output: 679 | obj = storage.all()["Place.{}".format(testID)] 680 | command = "Place.destroy({})".format(testID) 681 | self.assertFalse(HBNBCommand().onecmd(command)) 682 | self.assertNotIn(obj, storage.all()) 683 | with patch("sys.stdout", new=StringIO()) as output: 684 | self.assertFalse(HBNBCommand().onecmd("create City")) 685 | testID = output.getvalue().strip() 686 | with patch("sys.stdout", new=StringIO()) as output: 687 | obj = storage.all()["City.{}".format(testID)] 688 | command = "City.destroy({})".format(testID) 689 | self.assertFalse(HBNBCommand().onecmd(command)) 690 | self.assertNotIn(obj, storage.all()) 691 | with patch("sys.stdout", new=StringIO()) as output: 692 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 693 | testID = output.getvalue().strip() 694 | with patch("sys.stdout", new=StringIO()) as output: 695 | obj = storage.all()["Amenity.{}".format(testID)] 696 | command = "Amenity.destroy({})".format(testID) 697 | self.assertFalse(HBNBCommand().onecmd(command)) 698 | self.assertNotIn(obj, storage.all()) 699 | with patch("sys.stdout", new=StringIO()) as output: 700 | self.assertFalse(HBNBCommand().onecmd("create Review")) 701 | testID = output.getvalue().strip() 702 | with patch("sys.stdout", new=StringIO()) as output: 703 | obj = storage.all()["Review.{}".format(testID)] 704 | command = "Review.destory({})".format(testID) 705 | self.assertFalse(HBNBCommand().onecmd(command)) 706 | self.assertNotIn(obj, storage.all()) 707 | 708 | 709 | class TestHBNBCommand_all(unittest.TestCase): 710 | """Unittests for testing all of the HBNB command interpreter.""" 711 | 712 | @classmethod 713 | def setUp(self): 714 | try: 715 | os.rename("file.json", "tmp") 716 | except IOError: 717 | pass 718 | FileStorage.__objects = {} 719 | 720 | @classmethod 721 | def tearDown(self): 722 | try: 723 | os.remove("file.json") 724 | except IOError: 725 | pass 726 | try: 727 | os.rename("tmp", "file.json") 728 | except IOError: 729 | pass 730 | 731 | def test_all_invalid_class(self): 732 | correct = "** class doesn't exist **" 733 | with patch("sys.stdout", new=StringIO()) as output: 734 | self.assertFalse(HBNBCommand().onecmd("all MyModel")) 735 | self.assertEqual(correct, output.getvalue().strip()) 736 | with patch("sys.stdout", new=StringIO()) as output: 737 | self.assertFalse(HBNBCommand().onecmd("MyModel.all()")) 738 | self.assertEqual(correct, output.getvalue().strip()) 739 | 740 | def test_all_objects_space_notation(self): 741 | with patch("sys.stdout", new=StringIO()) as output: 742 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 743 | self.assertFalse(HBNBCommand().onecmd("create User")) 744 | self.assertFalse(HBNBCommand().onecmd("create State")) 745 | self.assertFalse(HBNBCommand().onecmd("create Place")) 746 | self.assertFalse(HBNBCommand().onecmd("create City")) 747 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 748 | self.assertFalse(HBNBCommand().onecmd("create Review")) 749 | with patch("sys.stdout", new=StringIO()) as output: 750 | self.assertFalse(HBNBCommand().onecmd("all")) 751 | self.assertIn("BaseModel", output.getvalue().strip()) 752 | self.assertIn("User", output.getvalue().strip()) 753 | self.assertIn("State", output.getvalue().strip()) 754 | self.assertIn("Place", output.getvalue().strip()) 755 | self.assertIn("City", output.getvalue().strip()) 756 | self.assertIn("Amenity", output.getvalue().strip()) 757 | self.assertIn("Review", output.getvalue().strip()) 758 | 759 | def test_all_objects_dot_notation(self): 760 | with patch("sys.stdout", new=StringIO()) as output: 761 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 762 | self.assertFalse(HBNBCommand().onecmd("create User")) 763 | self.assertFalse(HBNBCommand().onecmd("create State")) 764 | self.assertFalse(HBNBCommand().onecmd("create Place")) 765 | self.assertFalse(HBNBCommand().onecmd("create City")) 766 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 767 | self.assertFalse(HBNBCommand().onecmd("create Review")) 768 | with patch("sys.stdout", new=StringIO()) as output: 769 | self.assertFalse(HBNBCommand().onecmd(".all()")) 770 | self.assertIn("BaseModel", output.getvalue().strip()) 771 | self.assertIn("User", output.getvalue().strip()) 772 | self.assertIn("State", output.getvalue().strip()) 773 | self.assertIn("Place", output.getvalue().strip()) 774 | self.assertIn("City", output.getvalue().strip()) 775 | self.assertIn("Amenity", output.getvalue().strip()) 776 | self.assertIn("Review", output.getvalue().strip()) 777 | 778 | def test_all_single_object_space_notation(self): 779 | with patch("sys.stdout", new=StringIO()) as output: 780 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 781 | self.assertFalse(HBNBCommand().onecmd("create User")) 782 | self.assertFalse(HBNBCommand().onecmd("create State")) 783 | self.assertFalse(HBNBCommand().onecmd("create Place")) 784 | self.assertFalse(HBNBCommand().onecmd("create City")) 785 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 786 | self.assertFalse(HBNBCommand().onecmd("create Review")) 787 | with patch("sys.stdout", new=StringIO()) as output: 788 | self.assertFalse(HBNBCommand().onecmd("all BaseModel")) 789 | self.assertIn("BaseModel", output.getvalue().strip()) 790 | self.assertNotIn("User", output.getvalue().strip()) 791 | with patch("sys.stdout", new=StringIO()) as output: 792 | self.assertFalse(HBNBCommand().onecmd("all User")) 793 | self.assertIn("User", output.getvalue().strip()) 794 | self.assertNotIn("BaseModel", output.getvalue().strip()) 795 | with patch("sys.stdout", new=StringIO()) as output: 796 | self.assertFalse(HBNBCommand().onecmd("all State")) 797 | self.assertIn("State", output.getvalue().strip()) 798 | self.assertNotIn("BaseModel", output.getvalue().strip()) 799 | with patch("sys.stdout", new=StringIO()) as output: 800 | self.assertFalse(HBNBCommand().onecmd("all City")) 801 | self.assertIn("City", output.getvalue().strip()) 802 | self.assertNotIn("BaseModel", output.getvalue().strip()) 803 | with patch("sys.stdout", new=StringIO()) as output: 804 | self.assertFalse(HBNBCommand().onecmd("all Amenity")) 805 | self.assertIn("Amenity", output.getvalue().strip()) 806 | self.assertNotIn("BaseModel", output.getvalue().strip()) 807 | with patch("sys.stdout", new=StringIO()) as output: 808 | self.assertFalse(HBNBCommand().onecmd("all Place")) 809 | self.assertIn("Place", output.getvalue().strip()) 810 | self.assertNotIn("BaseModel", output.getvalue().strip()) 811 | with patch("sys.stdout", new=StringIO()) as output: 812 | self.assertFalse(HBNBCommand().onecmd("all Review")) 813 | self.assertIn("Review", output.getvalue().strip()) 814 | self.assertNotIn("BaseModel", output.getvalue().strip()) 815 | 816 | def test_all_single_object_dot_notation(self): 817 | with patch("sys.stdout", new=StringIO()) as output: 818 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 819 | self.assertFalse(HBNBCommand().onecmd("create User")) 820 | self.assertFalse(HBNBCommand().onecmd("create State")) 821 | self.assertFalse(HBNBCommand().onecmd("create Place")) 822 | self.assertFalse(HBNBCommand().onecmd("create City")) 823 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 824 | self.assertFalse(HBNBCommand().onecmd("create Review")) 825 | with patch("sys.stdout", new=StringIO()) as output: 826 | self.assertFalse(HBNBCommand().onecmd("BaseModel.all()")) 827 | self.assertIn("BaseModel", output.getvalue().strip()) 828 | self.assertNotIn("User", output.getvalue().strip()) 829 | with patch("sys.stdout", new=StringIO()) as output: 830 | self.assertFalse(HBNBCommand().onecmd("User.all()")) 831 | self.assertIn("User", output.getvalue().strip()) 832 | self.assertNotIn("BaseModel", output.getvalue().strip()) 833 | with patch("sys.stdout", new=StringIO()) as output: 834 | self.assertFalse(HBNBCommand().onecmd("State.all()")) 835 | self.assertIn("State", output.getvalue().strip()) 836 | self.assertNotIn("BaseModel", output.getvalue().strip()) 837 | with patch("sys.stdout", new=StringIO()) as output: 838 | self.assertFalse(HBNBCommand().onecmd("City.all()")) 839 | self.assertIn("City", output.getvalue().strip()) 840 | self.assertNotIn("BaseModel", output.getvalue().strip()) 841 | with patch("sys.stdout", new=StringIO()) as output: 842 | self.assertFalse(HBNBCommand().onecmd("Amenity.all()")) 843 | self.assertIn("Amenity", output.getvalue().strip()) 844 | self.assertNotIn("BaseModel", output.getvalue().strip()) 845 | with patch("sys.stdout", new=StringIO()) as output: 846 | self.assertFalse(HBNBCommand().onecmd("Place.all()")) 847 | self.assertIn("Place", output.getvalue().strip()) 848 | self.assertNotIn("BaseModel", output.getvalue().strip()) 849 | with patch("sys.stdout", new=StringIO()) as output: 850 | self.assertFalse(HBNBCommand().onecmd("Review.all()")) 851 | self.assertIn("Review", output.getvalue().strip()) 852 | self.assertNotIn("BaseModel", output.getvalue().strip()) 853 | 854 | 855 | class TestHBNBCommand_update(unittest.TestCase): 856 | """Unittests for testing update from the HBNB command interpreter.""" 857 | 858 | @classmethod 859 | def setUp(self): 860 | try: 861 | os.rename("file.json", "tmp") 862 | except IOError: 863 | pass 864 | FileStorage.__objects = {} 865 | 866 | @classmethod 867 | def tearDown(self): 868 | try: 869 | os.remove("file.json") 870 | except IOError: 871 | pass 872 | try: 873 | os.rename("tmp", "file.json") 874 | except IOError: 875 | pass 876 | 877 | def test_update_missing_class(self): 878 | correct = "** class name missing **" 879 | with patch("sys.stdout", new=StringIO()) as output: 880 | self.assertFalse(HBNBCommand().onecmd("update")) 881 | self.assertEqual(correct, output.getvalue().strip()) 882 | with patch("sys.stdout", new=StringIO()) as output: 883 | self.assertFalse(HBNBCommand().onecmd(".update()")) 884 | self.assertEqual(correct, output.getvalue().strip()) 885 | 886 | def test_update_invalid_class(self): 887 | correct = "** class doesn't exist **" 888 | with patch("sys.stdout", new=StringIO()) as output: 889 | self.assertFalse(HBNBCommand().onecmd("update MyModel")) 890 | self.assertEqual(correct, output.getvalue().strip()) 891 | with patch("sys.stdout", new=StringIO()) as output: 892 | self.assertFalse(HBNBCommand().onecmd("MyModel.update()")) 893 | self.assertEqual(correct, output.getvalue().strip()) 894 | 895 | def test_update_missing_id_space_notation(self): 896 | correct = "** instance id missing **" 897 | with patch("sys.stdout", new=StringIO()) as output: 898 | self.assertFalse(HBNBCommand().onecmd("update BaseModel")) 899 | self.assertEqual(correct, output.getvalue().strip()) 900 | with patch("sys.stdout", new=StringIO()) as output: 901 | self.assertFalse(HBNBCommand().onecmd("update User")) 902 | self.assertEqual(correct, output.getvalue().strip()) 903 | with patch("sys.stdout", new=StringIO()) as output: 904 | self.assertFalse(HBNBCommand().onecmd("update State")) 905 | self.assertEqual(correct, output.getvalue().strip()) 906 | with patch("sys.stdout", new=StringIO()) as output: 907 | self.assertFalse(HBNBCommand().onecmd("update City")) 908 | self.assertEqual(correct, output.getvalue().strip()) 909 | with patch("sys.stdout", new=StringIO()) as output: 910 | self.assertFalse(HBNBCommand().onecmd("update Amenity")) 911 | self.assertEqual(correct, output.getvalue().strip()) 912 | with patch("sys.stdout", new=StringIO()) as output: 913 | self.assertFalse(HBNBCommand().onecmd("update Place")) 914 | self.assertEqual(correct, output.getvalue().strip()) 915 | with patch("sys.stdout", new=StringIO()) as output: 916 | self.assertFalse(HBNBCommand().onecmd("update Review")) 917 | self.assertEqual(correct, output.getvalue().strip()) 918 | 919 | def test_update_missing_id_dot_notation(self): 920 | correct = "** instance id missing **" 921 | with patch("sys.stdout", new=StringIO()) as output: 922 | self.assertFalse(HBNBCommand().onecmd("BaseModel.update()")) 923 | self.assertEqual(correct, output.getvalue().strip()) 924 | with patch("sys.stdout", new=StringIO()) as output: 925 | self.assertFalse(HBNBCommand().onecmd("User.update()")) 926 | self.assertEqual(correct, output.getvalue().strip()) 927 | with patch("sys.stdout", new=StringIO()) as output: 928 | self.assertFalse(HBNBCommand().onecmd("State.update()")) 929 | self.assertEqual(correct, output.getvalue().strip()) 930 | with patch("sys.stdout", new=StringIO()) as output: 931 | self.assertFalse(HBNBCommand().onecmd("City.update()")) 932 | self.assertEqual(correct, output.getvalue().strip()) 933 | with patch("sys.stdout", new=StringIO()) as output: 934 | self.assertFalse(HBNBCommand().onecmd("Amenity.update()")) 935 | self.assertEqual(correct, output.getvalue().strip()) 936 | with patch("sys.stdout", new=StringIO()) as output: 937 | self.assertFalse(HBNBCommand().onecmd("Place.update()")) 938 | self.assertEqual(correct, output.getvalue().strip()) 939 | with patch("sys.stdout", new=StringIO()) as output: 940 | self.assertFalse(HBNBCommand().onecmd("Review.update()")) 941 | self.assertEqual(correct, output.getvalue().strip()) 942 | 943 | def test_update_invalid_id_space_notation(self): 944 | correct = "** no instance found **" 945 | with patch("sys.stdout", new=StringIO()) as output: 946 | self.assertFalse(HBNBCommand().onecmd("update BaseModel 1")) 947 | self.assertEqual(correct, output.getvalue().strip()) 948 | with patch("sys.stdout", new=StringIO()) as output: 949 | self.assertFalse(HBNBCommand().onecmd("update User 1")) 950 | self.assertEqual(correct, output.getvalue().strip()) 951 | with patch("sys.stdout", new=StringIO()) as output: 952 | self.assertFalse(HBNBCommand().onecmd("update State 1")) 953 | self.assertEqual(correct, output.getvalue().strip()) 954 | with patch("sys.stdout", new=StringIO()) as output: 955 | self.assertFalse(HBNBCommand().onecmd("update City 1")) 956 | self.assertEqual(correct, output.getvalue().strip()) 957 | with patch("sys.stdout", new=StringIO()) as output: 958 | self.assertFalse(HBNBCommand().onecmd("update Amenity 1")) 959 | self.assertEqual(correct, output.getvalue().strip()) 960 | with patch("sys.stdout", new=StringIO()) as output: 961 | self.assertFalse(HBNBCommand().onecmd("update Place 1")) 962 | self.assertEqual(correct, output.getvalue().strip()) 963 | with patch("sys.stdout", new=StringIO()) as output: 964 | self.assertFalse(HBNBCommand().onecmd("update Review 1")) 965 | self.assertEqual(correct, output.getvalue().strip()) 966 | 967 | def test_update_invalid_id_dot_notation(self): 968 | correct = "** no instance found **" 969 | with patch("sys.stdout", new=StringIO()) as output: 970 | self.assertFalse(HBNBCommand().onecmd("BaseModel.update(1)")) 971 | self.assertEqual(correct, output.getvalue().strip()) 972 | with patch("sys.stdout", new=StringIO()) as output: 973 | self.assertFalse(HBNBCommand().onecmd("User.update(1)")) 974 | self.assertEqual(correct, output.getvalue().strip()) 975 | with patch("sys.stdout", new=StringIO()) as output: 976 | self.assertFalse(HBNBCommand().onecmd("State.update(1)")) 977 | self.assertEqual(correct, output.getvalue().strip()) 978 | with patch("sys.stdout", new=StringIO()) as output: 979 | self.assertFalse(HBNBCommand().onecmd("City.update(1)")) 980 | self.assertEqual(correct, output.getvalue().strip()) 981 | with patch("sys.stdout", new=StringIO()) as output: 982 | self.assertFalse(HBNBCommand().onecmd("Amenity.update(1)")) 983 | self.assertEqual(correct, output.getvalue().strip()) 984 | with patch("sys.stdout", new=StringIO()) as output: 985 | self.assertFalse(HBNBCommand().onecmd("Place.update(1)")) 986 | self.assertEqual(correct, output.getvalue().strip()) 987 | with patch("sys.stdout", new=StringIO()) as output: 988 | self.assertFalse(HBNBCommand().onecmd("Review.update(1)")) 989 | self.assertEqual(correct, output.getvalue().strip()) 990 | 991 | def test_update_missing_attr_name_space_notation(self): 992 | correct = "** attribute name missing **" 993 | with patch("sys.stdout", new=StringIO()) as output: 994 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 995 | testId = output.getvalue().strip() 996 | testCmd = "update BaseModel {}".format(testId) 997 | with patch("sys.stdout", new=StringIO()) as output: 998 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 999 | self.assertEqual(correct, output.getvalue().strip()) 1000 | with patch("sys.stdout", new=StringIO()) as output: 1001 | self.assertFalse(HBNBCommand().onecmd("create User")) 1002 | testId = output.getvalue().strip() 1003 | testCmd = "update User {}".format(testId) 1004 | with patch("sys.stdout", new=StringIO()) as output: 1005 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1006 | self.assertEqual(correct, output.getvalue().strip()) 1007 | with patch("sys.stdout", new=StringIO()) as output: 1008 | self.assertFalse(HBNBCommand().onecmd("create State")) 1009 | testId = output.getvalue().strip() 1010 | testCmd = "update State {}".format(testId) 1011 | with patch("sys.stdout", new=StringIO()) as output: 1012 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1013 | self.assertEqual(correct, output.getvalue().strip()) 1014 | with patch("sys.stdout", new=StringIO()) as output: 1015 | self.assertFalse(HBNBCommand().onecmd("create City")) 1016 | testId = output.getvalue().strip() 1017 | testCmd = "update City {}".format(testId) 1018 | with patch("sys.stdout", new=StringIO()) as output: 1019 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1020 | self.assertEqual(correct, output.getvalue().strip()) 1021 | with patch("sys.stdout", new=StringIO()) as output: 1022 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 1023 | testId = output.getvalue().strip() 1024 | testCmd = "update Amenity {}".format(testId) 1025 | with patch("sys.stdout", new=StringIO()) as output: 1026 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1027 | self.assertEqual(correct, output.getvalue().strip()) 1028 | with patch("sys.stdout", new=StringIO()) as output: 1029 | self.assertFalse(HBNBCommand().onecmd("create Place")) 1030 | testId = output.getvalue().strip() 1031 | testCmd = "update Place {}".format(testId) 1032 | with patch("sys.stdout", new=StringIO()) as output: 1033 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1034 | self.assertEqual(correct, output.getvalue().strip()) 1035 | 1036 | def test_update_missing_attr_name_dot_notation(self): 1037 | correct = "** attribute name missing **" 1038 | with patch("sys.stdout", new=StringIO()) as output: 1039 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 1040 | testId = output.getvalue().strip() 1041 | testCmd = "BaseModel.update({})".format(testId) 1042 | with patch("sys.stdout", new=StringIO()) as output: 1043 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1044 | self.assertEqual(correct, output.getvalue().strip()) 1045 | with patch("sys.stdout", new=StringIO()) as output: 1046 | self.assertFalse(HBNBCommand().onecmd("create User")) 1047 | testId = output.getvalue().strip() 1048 | testCmd = "User.update({})".format(testId) 1049 | with patch("sys.stdout", new=StringIO()) as output: 1050 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1051 | self.assertEqual(correct, output.getvalue().strip()) 1052 | with patch("sys.stdout", new=StringIO()) as output: 1053 | self.assertFalse(HBNBCommand().onecmd("create State")) 1054 | testId = output.getvalue().strip() 1055 | testCmd = "State.update({})".format(testId) 1056 | with patch("sys.stdout", new=StringIO()) as output: 1057 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1058 | self.assertEqual(correct, output.getvalue().strip()) 1059 | with patch("sys.stdout", new=StringIO()) as output: 1060 | self.assertFalse(HBNBCommand().onecmd("create City")) 1061 | testId = output.getvalue().strip() 1062 | testCmd = "City.update({})".format(testId) 1063 | with patch("sys.stdout", new=StringIO()) as output: 1064 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1065 | self.assertEqual(correct, output.getvalue().strip()) 1066 | with patch("sys.stdout", new=StringIO()) as output: 1067 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 1068 | testId = output.getvalue().strip() 1069 | testCmd = "Amenity.update({})".format(testId) 1070 | with patch("sys.stdout", new=StringIO()) as output: 1071 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1072 | self.assertEqual(correct, output.getvalue().strip()) 1073 | with patch("sys.stdout", new=StringIO()) as output: 1074 | self.assertFalse(HBNBCommand().onecmd("create Place")) 1075 | testId = output.getvalue().strip() 1076 | testCmd = "Place.update({})".format(testId) 1077 | with patch("sys.stdout", new=StringIO()) as output: 1078 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1079 | self.assertEqual(correct, output.getvalue().strip()) 1080 | 1081 | def test_update_missing_attr_value_space_notation(self): 1082 | correct = "** value missing **" 1083 | with patch("sys.stdout", new=StringIO()) as output: 1084 | HBNBCommand().onecmd("create BaseModel") 1085 | testId = output.getvalue().strip() 1086 | with patch("sys.stdout", new=StringIO()) as output: 1087 | testCmd = "update BaseModel {} attr_name".format(testId) 1088 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1089 | self.assertEqual(correct, output.getvalue().strip()) 1090 | with patch("sys.stdout", new=StringIO()) as output: 1091 | HBNBCommand().onecmd("create User") 1092 | testId = output.getvalue().strip() 1093 | with patch("sys.stdout", new=StringIO()) as output: 1094 | testCmd = "update User {} attr_name".format(testId) 1095 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1096 | self.assertEqual(correct, output.getvalue().strip()) 1097 | with patch("sys.stdout", new=StringIO()) as output: 1098 | HBNBCommand().onecmd("create State") 1099 | testId = output.getvalue().strip() 1100 | with patch("sys.stdout", new=StringIO()) as output: 1101 | testCmd = "update State {} attr_name".format(testId) 1102 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1103 | self.assertEqual(correct, output.getvalue().strip()) 1104 | with patch("sys.stdout", new=StringIO()) as output: 1105 | HBNBCommand().onecmd("create City") 1106 | testId = output.getvalue().strip() 1107 | with patch("sys.stdout", new=StringIO()) as output: 1108 | testCmd = "update City {} attr_name".format(testId) 1109 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1110 | self.assertEqual(correct, output.getvalue().strip()) 1111 | with patch("sys.stdout", new=StringIO()) as output: 1112 | HBNBCommand().onecmd("create Amenity") 1113 | testId = output.getvalue().strip() 1114 | with patch("sys.stdout", new=StringIO()) as output: 1115 | testCmd = "update Amenity {} attr_name".format(testId) 1116 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1117 | self.assertEqual(correct, output.getvalue().strip()) 1118 | with patch("sys.stdout", new=StringIO()) as output: 1119 | HBNBCommand().onecmd("create Place") 1120 | testId = output.getvalue().strip() 1121 | with patch("sys.stdout", new=StringIO()) as output: 1122 | testCmd = "update Place {} attr_name".format(testId) 1123 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1124 | self.assertEqual(correct, output.getvalue().strip()) 1125 | with patch("sys.stdout", new=StringIO()) as output: 1126 | HBNBCommand().onecmd("create Review") 1127 | testId = output.getvalue().strip() 1128 | with patch("sys.stdout", new=StringIO()) as output: 1129 | testCmd = "update Review {} attr_name".format(testId) 1130 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1131 | self.assertEqual(correct, output.getvalue().strip()) 1132 | 1133 | def test_update_missing_attr_value_dot_notation(self): 1134 | correct = "** value missing **" 1135 | with patch("sys.stdout", new=StringIO()) as output: 1136 | HBNBCommand().onecmd("create BaseModel") 1137 | testId = output.getvalue().strip() 1138 | with patch("sys.stdout", new=StringIO()) as output: 1139 | testCmd = "BaseModel.update({}, attr_name)".format(testId) 1140 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1141 | self.assertEqual(correct, output.getvalue().strip()) 1142 | with patch("sys.stdout", new=StringIO()) as output: 1143 | HBNBCommand().onecmd("create User") 1144 | testId = output.getvalue().strip() 1145 | with patch("sys.stdout", new=StringIO()) as output: 1146 | testCmd = "User.update({}, attr_name)".format(testId) 1147 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1148 | self.assertEqual(correct, output.getvalue().strip()) 1149 | with patch("sys.stdout", new=StringIO()) as output: 1150 | HBNBCommand().onecmd("create State") 1151 | testId = output.getvalue().strip() 1152 | with patch("sys.stdout", new=StringIO()) as output: 1153 | testCmd = "State.update({}, attr_name)".format(testId) 1154 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1155 | self.assertEqual(correct, output.getvalue().strip()) 1156 | with patch("sys.stdout", new=StringIO()) as output: 1157 | HBNBCommand().onecmd("create City") 1158 | testId = output.getvalue().strip() 1159 | with patch("sys.stdout", new=StringIO()) as output: 1160 | testCmd = "City.update({}, attr_name)".format(testId) 1161 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1162 | self.assertEqual(correct, output.getvalue().strip()) 1163 | with patch("sys.stdout", new=StringIO()) as output: 1164 | HBNBCommand().onecmd("create Amenity") 1165 | testId = output.getvalue().strip() 1166 | with patch("sys.stdout", new=StringIO()) as output: 1167 | testCmd = "Amenity.update({}, attr_name)".format(testId) 1168 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1169 | self.assertEqual(correct, output.getvalue().strip()) 1170 | with patch("sys.stdout", new=StringIO()) as output: 1171 | HBNBCommand().onecmd("create Place") 1172 | testId = output.getvalue().strip() 1173 | with patch("sys.stdout", new=StringIO()) as output: 1174 | testCmd = "Place.update({}, attr_name)".format(testId) 1175 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1176 | self.assertEqual(correct, output.getvalue().strip()) 1177 | with patch("sys.stdout", new=StringIO()) as output: 1178 | HBNBCommand().onecmd("create Review") 1179 | testId = output.getvalue().strip() 1180 | with patch("sys.stdout", new=StringIO()) as output: 1181 | testCmd = "Review.update({}, attr_name)".format(testId) 1182 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1183 | self.assertEqual(correct, output.getvalue().strip()) 1184 | 1185 | def test_update_valid_string_attr_space_notation(self): 1186 | with patch("sys.stdout", new=StringIO()) as output: 1187 | HBNBCommand().onecmd("create BaseModel") 1188 | testId = output.getvalue().strip() 1189 | testCmd = "update BaseModel {} attr_name 'attr_value'".format(testId) 1190 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1191 | test_dict = storage.all()["BaseModel.{}".format(testId)].__dict__ 1192 | self.assertEqual("attr_value", test_dict["attr_name"]) 1193 | 1194 | with patch("sys.stdout", new=StringIO()) as output: 1195 | HBNBCommand().onecmd("create User") 1196 | testId = output.getvalue().strip() 1197 | testCmd = "update User {} attr_name 'attr_value'".format(testId) 1198 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1199 | test_dict = storage.all()["User.{}".format(testId)].__dict__ 1200 | self.assertEqual("attr_value", test_dict["attr_name"]) 1201 | 1202 | with patch("sys.stdout", new=StringIO()) as output: 1203 | HBNBCommand().onecmd("create State") 1204 | testId = output.getvalue().strip() 1205 | testCmd = "update State {} attr_name 'attr_value'".format(testId) 1206 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1207 | test_dict = storage.all()["State.{}".format(testId)].__dict__ 1208 | self.assertEqual("attr_value", test_dict["attr_name"]) 1209 | 1210 | with patch("sys.stdout", new=StringIO()) as output: 1211 | HBNBCommand().onecmd("create City") 1212 | testId = output.getvalue().strip() 1213 | testCmd = "update City {} attr_name 'attr_value'".format(testId) 1214 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1215 | test_dict = storage.all()["City.{}".format(testId)].__dict__ 1216 | self.assertEqual("attr_value", test_dict["attr_name"]) 1217 | 1218 | with patch("sys.stdout", new=StringIO()) as output: 1219 | HBNBCommand().onecmd("create Place") 1220 | testId = output.getvalue().strip() 1221 | testCmd = "update Place {} attr_name 'attr_value'".format(testId) 1222 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1223 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1224 | self.assertEqual("attr_value", test_dict["attr_name"]) 1225 | 1226 | with patch("sys.stdout", new=StringIO()) as output: 1227 | HBNBCommand().onecmd("create Amenity") 1228 | testId = output.getvalue().strip() 1229 | testCmd = "update Amenity {} attr_name 'attr_value'".format(testId) 1230 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1231 | test_dict = storage.all()["Amenity.{}".format(testId)].__dict__ 1232 | self.assertEqual("attr_value", test_dict["attr_name"]) 1233 | 1234 | with patch("sys.stdout", new=StringIO()) as output: 1235 | HBNBCommand().onecmd("create Review") 1236 | testId = output.getvalue().strip() 1237 | testCmd = "update Review {} attr_name 'attr_value'".format(testId) 1238 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1239 | test_dict = storage.all()["Review.{}".format(testId)].__dict__ 1240 | self.assertTrue("attr_value", test_dict["attr_name"]) 1241 | 1242 | def test_update_valid_string_attr_dot_notation(self): 1243 | with patch("sys.stdout", new=StringIO()) as output: 1244 | HBNBCommand().onecmd("create BaseModel") 1245 | tId = output.getvalue().strip() 1246 | testCmd = "BaseModel.update({}, attr_name, 'attr_value')".format(tId) 1247 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1248 | test_dict = storage.all()["BaseModel.{}".format(tId)].__dict__ 1249 | self.assertEqual("attr_value", test_dict["attr_name"]) 1250 | 1251 | with patch("sys.stdout", new=StringIO()) as output: 1252 | HBNBCommand().onecmd("create User") 1253 | tId = output.getvalue().strip() 1254 | testCmd = "User.update({}, attr_name, 'attr_value')".format(tId) 1255 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1256 | test_dict = storage.all()["User.{}".format(tId)].__dict__ 1257 | self.assertEqual("attr_value", test_dict["attr_name"]) 1258 | 1259 | with patch("sys.stdout", new=StringIO()) as output: 1260 | HBNBCommand().onecmd("create State") 1261 | tId = output.getvalue().strip() 1262 | testCmd = "State.update({}, attr_name, 'attr_value')".format(tId) 1263 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1264 | test_dict = storage.all()["State.{}".format(tId)].__dict__ 1265 | self.assertEqual("attr_value", test_dict["attr_name"]) 1266 | 1267 | with patch("sys.stdout", new=StringIO()) as output: 1268 | HBNBCommand().onecmd("create City") 1269 | tId = output.getvalue().strip() 1270 | testCmd = "City.update({}, attr_name, 'attr_value')".format(tId) 1271 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1272 | test_dict = storage.all()["City.{}".format(tId)].__dict__ 1273 | self.assertEqual("attr_value", test_dict["attr_name"]) 1274 | 1275 | with patch("sys.stdout", new=StringIO()) as output: 1276 | HBNBCommand().onecmd("create Place") 1277 | tId = output.getvalue().strip() 1278 | testCmd = "Place.update({}, attr_name, 'attr_value')".format(tId) 1279 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1280 | test_dict = storage.all()["Place.{}".format(tId)].__dict__ 1281 | self.assertEqual("attr_value", test_dict["attr_name"]) 1282 | 1283 | with patch("sys.stdout", new=StringIO()) as output: 1284 | HBNBCommand().onecmd("create Amenity") 1285 | tId = output.getvalue().strip() 1286 | testCmd = "Amenity.update({}, attr_name, 'attr_value')".format(tId) 1287 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1288 | test_dict = storage.all()["Amenity.{}".format(tId)].__dict__ 1289 | self.assertEqual("attr_value", test_dict["attr_name"]) 1290 | 1291 | with patch("sys.stdout", new=StringIO()) as output: 1292 | HBNBCommand().onecmd("create Review") 1293 | tId = output.getvalue().strip() 1294 | testCmd = "Review.update({}, attr_name, 'attr_value')".format(tId) 1295 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1296 | test_dict = storage.all()["Review.{}".format(tId)].__dict__ 1297 | self.assertEqual("attr_value", test_dict["attr_name"]) 1298 | 1299 | def test_update_valid_int_attr_space_notation(self): 1300 | with patch("sys.stdout", new=StringIO()) as output: 1301 | HBNBCommand().onecmd("create Place") 1302 | testId = output.getvalue().strip() 1303 | testCmd = "update Place {} max_guest 98".format(testId) 1304 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1305 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1306 | self.assertEqual(98, test_dict["max_guest"]) 1307 | 1308 | def test_update_valid_int_attr_dot_notation(self): 1309 | with patch("sys.stdout", new=StringIO()) as output: 1310 | HBNBCommand().onecmd("create Place") 1311 | tId = output.getvalue().strip() 1312 | testCmd = "Place.update({}, max_guest, 98)".format(tId) 1313 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1314 | test_dict = storage.all()["Place.{}".format(tId)].__dict__ 1315 | self.assertEqual(98, test_dict["max_guest"]) 1316 | 1317 | def test_update_valid_float_attr_space_notation(self): 1318 | with patch("sys.stdout", new=StringIO()) as output: 1319 | HBNBCommand().onecmd("create Place") 1320 | testId = output.getvalue().strip() 1321 | testCmd = "update Place {} latitude 7.2".format(testId) 1322 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1323 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1324 | self.assertEqual(7.2, test_dict["latitude"]) 1325 | 1326 | def test_update_valid_float_attr_dot_notation(self): 1327 | with patch("sys.stdout", new=StringIO()) as output: 1328 | HBNBCommand().onecmd("create Place") 1329 | tId = output.getvalue().strip() 1330 | testCmd = "Place.update({}, latitude, 7.2)".format(tId) 1331 | self.assertFalse(HBNBCommand().onecmd(testCmd)) 1332 | test_dict = storage.all()["Place.{}".format(tId)].__dict__ 1333 | self.assertEqual(7.2, test_dict["latitude"]) 1334 | 1335 | def test_update_valid_dictionary_space_notation(self): 1336 | with patch("sys.stdout", new=StringIO()) as output: 1337 | HBNBCommand().onecmd("create BaseModel") 1338 | testId = output.getvalue().strip() 1339 | testCmd = "update BaseModel {} ".format(testId) 1340 | testCmd += "{'attr_name': 'attr_value'}" 1341 | HBNBCommand().onecmd(testCmd) 1342 | test_dict = storage.all()["BaseModel.{}".format(testId)].__dict__ 1343 | self.assertEqual("attr_value", test_dict["attr_name"]) 1344 | 1345 | with patch("sys.stdout", new=StringIO()) as output: 1346 | HBNBCommand().onecmd("create User") 1347 | testId = output.getvalue().strip() 1348 | testCmd = "update User {} ".format(testId) 1349 | testCmd += "{'attr_name': 'attr_value'}" 1350 | HBNBCommand().onecmd(testCmd) 1351 | test_dict = storage.all()["User.{}".format(testId)].__dict__ 1352 | self.assertEqual("attr_value", test_dict["attr_name"]) 1353 | 1354 | with patch("sys.stdout", new=StringIO()) as output: 1355 | HBNBCommand().onecmd("create State") 1356 | testId = output.getvalue().strip() 1357 | testCmd = "update State {} ".format(testId) 1358 | testCmd += "{'attr_name': 'attr_value'}" 1359 | HBNBCommand().onecmd(testCmd) 1360 | test_dict = storage.all()["State.{}".format(testId)].__dict__ 1361 | self.assertEqual("attr_value", test_dict["attr_name"]) 1362 | 1363 | with patch("sys.stdout", new=StringIO()) as output: 1364 | HBNBCommand().onecmd("create City") 1365 | testId = output.getvalue().strip() 1366 | testCmd = "update City {} ".format(testId) 1367 | testCmd += "{'attr_name': 'attr_value'}" 1368 | HBNBCommand().onecmd(testCmd) 1369 | test_dict = storage.all()["City.{}".format(testId)].__dict__ 1370 | self.assertEqual("attr_value", test_dict["attr_name"]) 1371 | 1372 | with patch("sys.stdout", new=StringIO()) as output: 1373 | HBNBCommand().onecmd("create Place") 1374 | testId = output.getvalue().strip() 1375 | testCmd = "update Place {} ".format(testId) 1376 | testCmd += "{'attr_name': 'attr_value'}" 1377 | HBNBCommand().onecmd(testCmd) 1378 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1379 | self.assertEqual("attr_value", test_dict["attr_name"]) 1380 | 1381 | with patch("sys.stdout", new=StringIO()) as output: 1382 | HBNBCommand().onecmd("create Amenity") 1383 | testId = output.getvalue().strip() 1384 | testCmd = "update Amenity {} ".format(testId) 1385 | testCmd += "{'attr_name': 'attr_value'}" 1386 | HBNBCommand().onecmd(testCmd) 1387 | test_dict = storage.all()["Amenity.{}".format(testId)].__dict__ 1388 | self.assertEqual("attr_value", test_dict["attr_name"]) 1389 | 1390 | with patch("sys.stdout", new=StringIO()) as output: 1391 | HBNBCommand().onecmd("create Review") 1392 | testId = output.getvalue().strip() 1393 | testCmd = "update Review {} ".format(testId) 1394 | testCmd += "{'attr_name': 'attr_value'}" 1395 | HBNBCommand().onecmd(testCmd) 1396 | test_dict = storage.all()["Review.{}".format(testId)].__dict__ 1397 | self.assertEqual("attr_value", test_dict["attr_name"]) 1398 | 1399 | def test_update_valid_dictionary_dot_notation(self): 1400 | with patch("sys.stdout", new=StringIO()) as output: 1401 | HBNBCommand().onecmd("create BaseModel") 1402 | testId = output.getvalue().strip() 1403 | testCmd = "BaseModel.update({}".format(testId) 1404 | testCmd += "{'attr_name': 'attr_value'})" 1405 | HBNBCommand().onecmd(testCmd) 1406 | test_dict = storage.all()["BaseModel.{}".format(testId)].__dict__ 1407 | self.assertEqual("attr_value", test_dict["attr_name"]) 1408 | 1409 | with patch("sys.stdout", new=StringIO()) as output: 1410 | HBNBCommand().onecmd("create User") 1411 | testId = output.getvalue().strip() 1412 | testCmd = "User.update({}, ".format(testId) 1413 | testCmd += "{'attr_name': 'attr_value'})" 1414 | HBNBCommand().onecmd(testCmd) 1415 | test_dict = storage.all()["User.{}".format(testId)].__dict__ 1416 | self.assertEqual("attr_value", test_dict["attr_name"]) 1417 | 1418 | with patch("sys.stdout", new=StringIO()) as output: 1419 | HBNBCommand().onecmd("create State") 1420 | testId = output.getvalue().strip() 1421 | testCmd = "State.update({}, ".format(testId) 1422 | testCmd += "{'attr_name': 'attr_value'})" 1423 | HBNBCommand().onecmd(testCmd) 1424 | test_dict = storage.all()["State.{}".format(testId)].__dict__ 1425 | self.assertEqual("attr_value", test_dict["attr_name"]) 1426 | 1427 | with patch("sys.stdout", new=StringIO()) as output: 1428 | HBNBCommand().onecmd("create City") 1429 | testId = output.getvalue().strip() 1430 | testCmd = "City.update({}, ".format(testId) 1431 | testCmd += "{'attr_name': 'attr_value'})" 1432 | HBNBCommand().onecmd(testCmd) 1433 | test_dict = storage.all()["City.{}".format(testId)].__dict__ 1434 | self.assertEqual("attr_value", test_dict["attr_name"]) 1435 | 1436 | with patch("sys.stdout", new=StringIO()) as output: 1437 | HBNBCommand().onecmd("create Place") 1438 | testId = output.getvalue().strip() 1439 | testCmd = "Place.update({}, ".format(testId) 1440 | testCmd += "{'attr_name': 'attr_value'})" 1441 | HBNBCommand().onecmd(testCmd) 1442 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1443 | self.assertEqual("attr_value", test_dict["attr_name"]) 1444 | 1445 | with patch("sys.stdout", new=StringIO()) as output: 1446 | HBNBCommand().onecmd("create Amenity") 1447 | testId = output.getvalue().strip() 1448 | testCmd = "Amenity.update({}, ".format(testId) 1449 | testCmd += "{'attr_name': 'attr_value'})" 1450 | HBNBCommand().onecmd(testCmd) 1451 | test_dict = storage.all()["Amenity.{}".format(testId)].__dict__ 1452 | self.assertEqual("attr_value", test_dict["attr_name"]) 1453 | 1454 | with patch("sys.stdout", new=StringIO()) as output: 1455 | HBNBCommand().onecmd("create Review") 1456 | testId = output.getvalue().strip() 1457 | testCmd = "Review.update({}, ".format(testId) 1458 | testCmd += "{'attr_name': 'attr_value'})" 1459 | HBNBCommand().onecmd(testCmd) 1460 | test_dict = storage.all()["Review.{}".format(testId)].__dict__ 1461 | self.assertEqual("attr_value", test_dict["attr_name"]) 1462 | 1463 | def test_update_valid_dictionary_with_int_space_notation(self): 1464 | with patch("sys.stdout", new=StringIO()) as output: 1465 | HBNBCommand().onecmd("create Place") 1466 | testId = output.getvalue().strip() 1467 | testCmd = "update Place {} ".format(testId) 1468 | testCmd += "{'max_guest': 98})" 1469 | HBNBCommand().onecmd(testCmd) 1470 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1471 | self.assertEqual(98, test_dict["max_guest"]) 1472 | 1473 | def test_update_valid_dictionary_with_int_dot_notation(self): 1474 | with patch("sys.stdout", new=StringIO()) as output: 1475 | HBNBCommand().onecmd("create Place") 1476 | testId = output.getvalue().strip() 1477 | testCmd = "Place.update({}, ".format(testId) 1478 | testCmd += "{'max_guest': 98})" 1479 | HBNBCommand().onecmd(testCmd) 1480 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1481 | self.assertEqual(98, test_dict["max_guest"]) 1482 | 1483 | def test_update_valid_dictionary_with_float_space_notation(self): 1484 | with patch("sys.stdout", new=StringIO()) as output: 1485 | HBNBCommand().onecmd("create Place") 1486 | testId = output.getvalue().strip() 1487 | testCmd = "update Place {} ".format(testId) 1488 | testCmd += "{'latitude': 9.8})" 1489 | HBNBCommand().onecmd(testCmd) 1490 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1491 | self.assertEqual(9.8, test_dict["latitude"]) 1492 | 1493 | def test_update_valid_dictionary_with_float_dot_notation(self): 1494 | with patch("sys.stdout", new=StringIO()) as output: 1495 | HBNBCommand().onecmd("create Place") 1496 | testId = output.getvalue().strip() 1497 | testCmd = "Place.update({}, ".format(testId) 1498 | testCmd += "{'latitude': 9.8})" 1499 | HBNBCommand().onecmd(testCmd) 1500 | test_dict = storage.all()["Place.{}".format(testId)].__dict__ 1501 | self.assertEqual(9.8, test_dict["latitude"]) 1502 | 1503 | 1504 | class TestHBNBCommand_count(unittest.TestCase): 1505 | """Unittests for testing count method of HBNB comand interpreter.""" 1506 | 1507 | @classmethod 1508 | def setUp(self): 1509 | try: 1510 | os.rename("file.json", "tmp") 1511 | except IOError: 1512 | pass 1513 | FileStorage._FileStorage__objects = {} 1514 | 1515 | @classmethod 1516 | def tearDown(self): 1517 | try: 1518 | os.remove("file.json") 1519 | except IOError: 1520 | pass 1521 | try: 1522 | os.rename("tmp", "file.json") 1523 | except IOError: 1524 | pass 1525 | 1526 | def test_count_invalid_class(self): 1527 | with patch("sys.stdout", new=StringIO()) as output: 1528 | self.assertFalse(HBNBCommand().onecmd("MyModel.count()")) 1529 | self.assertEqual("0", output.getvalue().strip()) 1530 | 1531 | def test_count_object(self): 1532 | with patch("sys.stdout", new=StringIO()) as output: 1533 | self.assertFalse(HBNBCommand().onecmd("create BaseModel")) 1534 | with patch("sys.stdout", new=StringIO()) as output: 1535 | self.assertFalse(HBNBCommand().onecmd("BaseModel.count()")) 1536 | self.assertEqual("1", output.getvalue().strip()) 1537 | with patch("sys.stdout", new=StringIO()) as output: 1538 | self.assertFalse(HBNBCommand().onecmd("create User")) 1539 | with patch("sys.stdout", new=StringIO()) as output: 1540 | self.assertFalse(HBNBCommand().onecmd("User.count()")) 1541 | self.assertEqual("1", output.getvalue().strip()) 1542 | with patch("sys.stdout", new=StringIO()) as output: 1543 | self.assertFalse(HBNBCommand().onecmd("create State")) 1544 | with patch("sys.stdout", new=StringIO()) as output: 1545 | self.assertFalse(HBNBCommand().onecmd("State.count()")) 1546 | self.assertEqual("1", output.getvalue().strip()) 1547 | with patch("sys.stdout", new=StringIO()) as output: 1548 | self.assertFalse(HBNBCommand().onecmd("create Place")) 1549 | with patch("sys.stdout", new=StringIO()) as output: 1550 | self.assertFalse(HBNBCommand().onecmd("Place.count()")) 1551 | self.assertEqual("1", output.getvalue().strip()) 1552 | with patch("sys.stdout", new=StringIO()) as output: 1553 | self.assertFalse(HBNBCommand().onecmd("create City")) 1554 | with patch("sys.stdout", new=StringIO()) as output: 1555 | self.assertFalse(HBNBCommand().onecmd("City.count()")) 1556 | self.assertEqual("1", output.getvalue().strip()) 1557 | with patch("sys.stdout", new=StringIO()) as output: 1558 | self.assertFalse(HBNBCommand().onecmd("create Amenity")) 1559 | with patch("sys.stdout", new=StringIO()) as output: 1560 | self.assertFalse(HBNBCommand().onecmd("Amenity.count()")) 1561 | self.assertEqual("1", output.getvalue().strip()) 1562 | with patch("sys.stdout", new=StringIO()) as output: 1563 | self.assertFalse(HBNBCommand().onecmd("create Review")) 1564 | with patch("sys.stdout", new=StringIO()) as output: 1565 | self.assertFalse(HBNBCommand().onecmd("Review.count()")) 1566 | self.assertEqual("1", output.getvalue().strip()) 1567 | 1568 | 1569 | if __name__ == "__main__": 1570 | unittest.main() 1571 | --------------------------------------------------------------------------------