def test_get_row_if_exists(self): user_name = "cris" user_email = "*****@*****.**" created_time = datetime.now() user_phone = "858-2867-3567" user_description = "cultured man" user_school_year = "Third" user_major = "Data Science" # check if it the method detects no users query_object = crud.get_row_if_exists( User, self.session, **{'email': user_email}) self.assertEqual(query_object is None, True) # add the user user_object = crud.add_user( user_name, user_email, created_time, user_phone, user_description, user_school_year, user_major, self.session) # check if it the method detects an user query_object = crud.get_row_if_exists( User, self.session, **{'email': user_email}) self.assertEqual(query_object == user_object, True)
def test_update_field(self): # create an user user_name = "cris" user_email = "*****@*****.**" created_time = datetime.now() user_phone = "858-2867-3567" user_description = "cultured man" user_school_year = "Third" user_major = "Data Science" user_object = crud.add_user( user_name, user_email, created_time, user_phone, user_description, user_school_year, user_major, self.session) # change description crud.update_field( User, self.session, {'email': '*****@*****.**'}, {'description':'google man'}) user_object = crud.get_row_if_exists( User, self.session, **{'email': '*****@*****.**'}) self.assertEqual(user_object.description == 'google man', True)
def test_add_user(self): user_name = "cris" user_email = "*****@*****.**" created_time = datetime.now() user_phone = "858-2867-3567" user_description = "cultured man" user_school_year = "Third" user_major = "Data Science" user_object = crud.add_user(user_name, user_email, created_time, user_phone, user_description, user_school_year, user_major, self.session) # check if the return object has correct information self.assertEqual(user_object.email, user_email) self.assertEqual(user_object.name, user_name) self.assertEqual(user_object.date_created, created_time) self.assertEqual(user_object.phone, user_phone) self.assertEqual(user_object.description, user_description) self.assertEqual(user_object.school_year, user_school_year) self.assertEqual(user_object.major, user_major) # check if the user is loaded into the database query_object = crud.get_row_if_exists(User, self.session, **{'email': user_email}) self.assertEqual(query_object == user_object, True)
def test_add_attribute(self): name, category = others[0], "other" attribute_object = crud.add_attribute( name, category, self.session) # check if the return object has correct information self.assertEqual(attribute_object.name, name) self.assertEqual(attribute_object.category, category) # check if the attribute is loaded into the database query_object = crud.get_row_if_exists( Attribute, self.session, **{'name': name, 'category': category}) self.assertEqual(query_object == attribute_object, True) # one thing in the database number_of_rows = self.session.query(Attribute).count() self.assertEqual(number_of_rows == 1, True) # check duplicate handling attribute_object = crud.add_attribute( name, category, self.session) number_of_rows = self.session.query(Attribute).count() self.assertEqual(number_of_rows == 1, True)
def login(): """Create anti-forgery state token.""" if request.method == 'OPTIONS': return generateResponse() access_token = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(32)) login_session["access_token"] = access_token requested_json = request.json # check in with db to see if user is new session = current_app.config['DB_CONNECTION'] user = get_row_if_exists(User, session, **{'email': requested_json['email']}) if not user: # User doesn't exist # maybe also do: , 'access_token': access_token json_response = {'newUser': True} response = generateResponse(json_response) response.set_cookie('access_token', access_token) return response path_name = "/".join(["user"+str(user.id), 'profile', "headshot.jpg"]) login_session["user_id"] = user.id json_response = {'name': requested_json['name'], 'email': requested_json['email'], 'access_token': access_token, 'message': 'Successfully created room.', 'description': user.description, 'phone': user.phone, 'schoolYear': user.school_year, 'major': user.major, 'profile_photo': path_name } response = generateResponse(json_response) response.set_cookie('access_token', access_token) return response
def test_edit_profile(client, app, email, login_first, corrupt_cookie, json_query, correct_response, database_entry, correct_status_code): """ Test Edit Profile Assumption: user has to log in to edit the profile & the profile has to exist """ # if the tests requires previous log in, do it if login_first: client.post("/login", data=json.dumps({"email": email}), content_type="application/json") if corrupt_cookie: # corrupt the client's cookie => to create you have to destroy cookie_map = {cookie.name: cookie for cookie in client.cookie_jar} cookie_map[ "access_token"].value = "fake token to see whether the engineer is dumb" rv = client.post("/profile", **json_query) response_data = json.loads(rv.data) for key, value in correct_response.items(): assert response_data[key] == value # verify database user = get_row_if_exists(User, app.config["DB_CONNECTION"], **{"email": email}) for key, value in database_entry.items(): assert user.serialize[key] == value assert rv.status_code == correct_status_code
def test_get_recent_rooms(client, app): """Test get recent rooms with mock database simple test: list all the rooms => correct number of rooms in sorted chronological order """ rv = client.get("/getRecentRoomIds") room_ids = json.loads(rv.data) # case 1: check it returns number of data in mock db assert len(room_ids) == 2 room_1 = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": room_ids[0]}) room_2 = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": room_ids[1]}) # case 1: check it is in descending order of dates assert room_1.date_created > room_2.date_created
def test_write_room(self): # create an user user_name = "cris" user_email = "*****@*****.**" created_time = datetime.now() user_phone = "858-2867-3567" user_description = "cultured man" user_school_year = "Third" user_major = "Data Science" user_object = crud.add_user(user_name, user_email, created_time, user_phone, user_description, user_school_year, user_major, self.session) # the input json should be the same as output json from room_json except for id test_json = { 'name': '75 Big Rock Cove St. Middletown', 'address': '75 Big Rock Cove St. Middletown, NY 10940', 'distance': '20 mins', 'pricePerMonth': 500, 'from_month': 'June/18', 'to_month': 'July/18', 'early_date': '06/01/18', 'late_date': '06/12/18', 'roomType': 'Single', 'other': [], 'facilities': [], 'leaserName': 'cris', 'leaserEmail': '*****@*****.**', 'leaserPhone': '858-2867-3567', 'leaserSchoolYear': 'Third', 'leaserMajor': 'Data Science', 'photos': ['photo1', 'photo2'], 'profilePhoto': 'profile_photo', 'negotiable': True, 'numBaths': 2.5, 'numBeds': 2, 'roomDescription': 'dream house in a life time' } crud.write_room(test_json, self.session, True) room_object = crud.get_row_if_exists(Room, self.session, **{'id': 1}) self.assertEqual(room_object is not None, True) result_json = crud.room_json(room_object, self.session, True) test_json['roomId'] = 1 self.assertEqual(result_json == test_json, True)
def test_post_rooms(client, app, new_room_json, login_first, corrupt_cookie, check_s3, correct_response, verify_database, correct_status_code, post_content_type): if login_first: client.post("/login", data=json.dumps({"email": "*****@*****.**"}), content_type="application/json") if corrupt_cookie: # corrupt the client's cookie => to create you have to destroy cookie_map = {cookie.name: cookie for cookie in client.cookie_jar} cookie_map[ "access_token"].value = "fake token to see whether the engineer is dumb" new_room_json['photos'] = [] valid_photos_cnt = 0 for p_file in new_room_json["photo_files"]: with open(p_file, 'rb') as f: file_object = io.BytesIO(f.read()) new_room_json['photos'].append((file_object, f.name)) valid_photos_cnt += 1 if verify_image( file_object) != "error" else 0 # get room id inferred by # of rows, assuming no deletes happening for test sake room_id = get_insert_id(Room, app.config["DB_CONNECTION"]) if check_s3: app.config["OFFLINE_TESTING"] = False rv = client.post("/postRoom", data=new_room_json, content_type=post_content_type) response_data = json.loads(rv.data) for key, value in correct_response.items(): assert response_data[key] == value assert rv.status_code == correct_status_code room = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": room_id}) if verify_database: room_json_test = room_json(room, app.config["DB_CONNECTION"], True) for key, value in json.loads(new_room_json["json"]).items(): assert room_json_test[key] == value else: assert room is None if check_s3: images_uploaded = get_images("test_user1", extra_path=str(room_id) + "/") assert len(images_uploaded) == valid_photos_cnt # delete test folder delete_folder("test_user1", "houseit")
def test_add_address(self): address = "75 Big Rock Cove St.Middletown, NY 10940" distance = "20 mins" address_object = crud.add_address(distance, address, self.session) # check if the return object has correct information self.assertEqual(address_object.distance, distance) self.assertEqual(address_object.address, address) # check if the address is loaded into the database query_object = crud.get_row_if_exists( Address, self.session, **{ 'distance': distance, 'address': address }) self.assertEqual(query_object == address_object, True) # one thing in the database number_of_rows = self.session.query(Address).count() self.assertEqual(number_of_rows == 1, True)
def test_add_move_in(self): early_date = datetime(2018, 6, 1) late_date = datetime(2018, 8, 1) move_in_object = crud.add_move_in(early_date, late_date, self.session) # check if return object has correct info self.assertEqual(move_in_object.early_date, early_date) self.assertEqual(move_in_object.late_date, late_date) # check if move in is loaded in db query_object = crud.get_row_if_exists( Move_In, self.session, **{ 'early_date': early_date, 'late_date': late_date }) self.assertEqual(query_object == move_in_object, True) # check that there's only one thing in db number_of_rows = self.session.query(Move_In).count() self.assertEqual(number_of_rows == 1, True)
def test_add_stay_period(self): from_month = datetime(2018, 6, 1) to_month = datetime(2018, 7, 1) stay_period_object = crud.add_stay_period(from_month, to_month, self.session) # check if the return object has correct information self.assertEqual(stay_period_object.from_month, from_month) self.assertEqual(stay_period_object.to_month, to_month) # check if the stay period is loaded into the database query_object = crud.get_row_if_exists( Stay_Period, self.session, **{ 'from_month': from_month, 'to_month': to_month }) self.assertEqual(query_object == stay_period_object, True) # one thing in the database number_of_rows = self.session.query(Stay_Period).count() self.assertEqual(number_of_rows == 1, True)
def create_user(): session = current_app.config['DB_CONNECTION'] if request.method == 'OPTIONS': return generateResponse() requested_json = request.json if get_row_if_exists(User, session, **{'email': requested_json['email']}): message, status = 'Already Created', 200 return generateResponse(elem=message, status=status) user = add_user(requested_json['name'], requested_json['email'], datetime.now(), requested_json['phone'], requested_json["description"], requested_json["schoolYear"], requested_json["major"], session) login_session["user_id"] = user.id icon_path = './assets/profile_default_icons/' selected_icon = random.choice( os.listdir(icon_path)) path_name = "/".join(["user"+str(user.id), 'profile', "headshot.jpg"]) upload_file_wname(icon_path+selected_icon, 'houseit', path_name) json_response = {'name': requested_json['name'], 'email': requested_json['email'], 'access_token': login_session["access_token"], 'message': 'Successfully created room.', 'description': user.description, 'phone': user.phone, 'schoolYear': user.school_year, 'major': user.major, 'profile_photo': path_name } response = generateResponse(json_response, 201) response.set_cookie('access_token', login_session["access_token"]) return response
def login(): """Login function and create anti-forgery state token. content_type: application/json example of valid json request format: "google_login_token":blah blah blah """ session = current_app.config["DB_CONNECTION"] # PART1: Secure measure to verify identity # first check if the origin is allowed if request.remote_addr not in current_app.config["ALLOWED_ORIGINS"]: response = generate_message(MESSAGE_WRONG_ORIGIN, 401) return response # pre-flight for CORS communication if request.method == "OPTIONS": return generate_response() # if user has already logged in, tell them and return the user data since they might be wanting to re fetch data if is_loggedin(login_session): # use user id stored in login session user = get_row_if_exists(User, session, **{"id": login_session["user_id"]}) json_response = generate_user_login_data(user) json_response["message"] = MESSAGE_ALREADY_LOGIN return json_response # check requested json, see if the json contains required login info # first check if json exists from request checked_json, response, requested_json = check_json_form( request, MESSAGE_BAD_JSON, MESSAGE_LOGIN_NO_JSON) if checked_json != True: return response # second check if json conatins enough info try: google_login_token = requested_json["google_login_token"] # check if json contains valid info(ucsd email and google auth token) status_code, message, user_email = verify_email( google_login_token, current_app.config["ALLOWED_DOMAINS"], current_app.config["GAUTH_AUDIENCE"]) # if not valid, troll them(very likely to be a hacker) if status_code != 200: response = generate_message(message, status_code) return response except KeyError: # if in online test mode or production mode, return invalid response if current_app.config["OFFLINE_TESTING"] != True: response = generate_message(MESSAGE_LOGIN_NO_GTOKEN, 400) return response user_email = requested_json["email"] # else just continue the flow for offline testing # this is needed to ensure the email loaded eventually to the database is valid, if user continues to create an account login_session["login_user_email"] = user_email # PART2: Check whether user is new and return corresponding response # access token will be issued only after user's identity is verified access_token = "".join( random.choice(string.ascii_uppercase + string.digits) for x in range(32)) login_session["access_token"] = access_token # check in with db to see if user is new # Assumption: user email is a unique identifier user = get_row_if_exists(User, session, **{"email": user_email}) if not user: # User doesn't exist json_response = {"newUser": True, "message": MESSAGE_LOGIN_NEW_USER} response = generate_response(json_response) response.set_cookie("access_token", access_token) return response login_session["user_id"] = user.id json_response = generate_user_login_data(user) response = generate_response(json_response) response.set_cookie("access_token", access_token) return response
def test_favorite(client, app, action, room_id, login_first, add_first, verify_database, correct_response, correct_status_code): if login_first: if action == "super edge case": login_email = "*****@*****.**" action = "add" else: login_email = "*****@*****.**" client.post("/login", data=json.dumps({"email": login_email}), content_type="application/json") if add_first and correct_status_code == 200: # post first, generate deterministic data since create houses randomly generate listings for new_room_json in correct_response["favorites"]: photos = [] for p_file in [ "app/assets/room_mock_images/1.jpg", "app/assets/room_mock_images/2.jpg" ]: with open(p_file, 'rb') as f: file_object = io.BytesIO(f.read()) photos.append((file_object, f.name)) rv = client.post("/postRoom", data={ "json": json.dumps(new_room_json), "photos": photos }, content_type="multipart/form-data") response_data = json.loads(rv.data) # manually add favorites user = get_row_if_exists(User, app.config["DB_CONNECTION"], **{"id": 1}) room = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": 3}) add_favorite(room, user, app.config["DB_CONNECTION"]) room = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": 4}) add_favorite(room, user, app.config["DB_CONNECTION"]) if action == "get": rv = client.get("/favorite") response_data = json.loads(rv.data) if correct_response["favorites"] == []: assert response_data["favorites"] == correct_response["favorites"] else: for idx, new_room_json in enumerate(correct_response["favorites"]): for key, value in new_room_json.items(): assert response_data["favorites"][idx][key] == value else: if action is None: rv = client.post("/favorite", data=json.dumps({"room_id": room_id}), content_type="application/json") else: # if add twice, add it first if action == "add twice": user = get_row_if_exists(User, app.config["DB_CONNECTION"], **{"id": 1}) room = get_row_if_exists(Room, app.config["DB_CONNECTION"], **{"id": 1}) add_favorite(room, user, app.config["DB_CONNECTION"]) action = "add" if action == "delete twice": remove_entry(Favorite, 1, app.config["DB_CONNECTION"]) action = "delete" rv = client.post("/favorite", data=json.dumps({ "action": action, "room_id": room_id }), content_type="application/json") response_data = json.loads(rv.data) for key, value in correct_response.items(): assert response_data[key] == value if action == "add": favorite = get_row_if_exists(Favorite, app.config["DB_CONNECTION"], **{"id": str(room_id)}) if verify_database: assert favorite.id == 1 assert favorite.room.id == 1 else: assert favorite is None elif action == "delete": favorite = get_row_if_exists(Favorite, app.config["DB_CONNECTION"], **{"id": str(room_id)}) if not verify_database: assert favorite.id == 1 assert favorite.room.id == 1 else: assert favorite is None assert rv.status_code == correct_status_code
def test_write_room(self): # create an user user_name = "cris" user_email = "*****@*****.**" created_time = datetime.now() user_phone = "858-2867-3567" user_description = "cultured man" user_school_year = "Third" user_major = "Data Science" user_object = crud.add_user( user_name, user_email, created_time, user_phone, user_description, user_school_year, user_major, self.session) # the input json should be the same as output json from room_json except for id test_json = {"name": "75 Big Rock Cove St. Middletown", "address": "75 Big Rock Cove St. Middletown, NY 10940", "distance": "20 mins", "pricePerMonth": 500, "fromMonth": "June/18", "toMonth": "July/18", "earlyDate": "06/01/18", "lateDate": "06/12/18", "roomType": "Single", "other": [], "facilities": [], "photos": ["photo1", "photo2"], "profilePhoto": "profile_photo", "negotiable": True, "numBaths": 2.5, "numBeds": 2, "roomDescription": "dream house in a life time"} test_res_json = {"name": "75 Big Rock Cove St. Middletown", "address": "75 Big Rock Cove St. Middletown, NY 10940", "distance": "20 mins", "pricePerMonth": 500, "fromMonth": "June/18", "toMonth": "July/18", "earlyDate": "06/01/18", "lateDate": "06/12/18", "roomType": "Single", "other": [], "facilities": [], "photos": ["photo1", "photo2"], "profilePhoto": "profile_photo", "negotiable": True, "numBaths": 2.5, "numBeds": 2, "roomDescription": "dream house in a life time", "leaserName": user_name, "leaserEmail": user_email, "leaserPhone": user_phone, "leaserSchoolYear": user_school_year, "leaserMajor": user_major, } crud.write_room(transform_json_underscore(test_json), user_object.id, self.session, True) room_object = crud.get_row_if_exists( Room, self.session, **{"id": 1}) self.assertEqual(room_object is not None, True) result_json = crud.room_json( room_object, self.session, True) test_res_json["roomId"] = 1 self.assertEqual(result_json == test_res_json, True)