Skip to content

Commit

Permalink
change tests and fix imports
Browse files Browse the repository at this point in the history
  • Loading branch information
akrakman committed Nov 16, 2022
1 parent 3dc82e1 commit a357b1c
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 82 deletions.
23 changes: 10 additions & 13 deletions src/backend/app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
""" This is a module docstring """
""" Handles routing and HTTP Requests """
import json
import dataclasses
from werkzeug.datastructures import MultiDict
Expand All @@ -8,7 +8,6 @@
from pages.mainpage import MainPage
from pages.userpage import UserPage
from dataholders.mainpage_get import GetRequestType, GetRequestParams
#from decorators import login_required

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
Expand All @@ -24,7 +23,7 @@ def login():
username = json_form.get("user", "")
password = json_form.get("password", "")
if user_login.login(username, password):
session["USERNAME"] = username # session variable makes User accessible in the backend
session["USERNAME"] = username # session object makes User accessible in the backend
return f"welcome {username}", 200
return "User not found, please try again", 401
return "", 400
Expand All @@ -47,11 +46,14 @@ def register():
return result.message, 201
return "", 400

@app.route("/<username>", methods=["GET", "POST"])
#@login_required
@app.route("/user/<username>", methods=["GET", "POST"])
def userpage():
"""Handles userpage requests"""
userpage = UserPage()
print(request.get_json(force=True))
if session.get("username", None) is None:
return "user does not exist", 404
username = session.get("username")
userpage = UserPage(username)
if request.method == "POST":
json_form = request.get_json(force=True) # serialize data
# see which field was True and therefore should be changed
Expand All @@ -71,17 +73,12 @@ def userpage():
if not result.status:
return result.message, 400
return result.message, 201
try:
username = session.get("USERNAME") # decorator checks it exists, but just in case
except:
return "", 400
user = userpage.get_user(username)
user = userpage.get_user(username) # get request
return json.dumps(user), username, 201

@app.route("/logout")
def logout():
login = Login()
login.logout()
session.pop("USERNAME", None) # session object is None if pop fails
return "redirect", 201

@app.route("/", methods=["GET", "POST"])
Expand Down
Binary file modified src/backend/database/database_test.db
Binary file not shown.
5 changes: 2 additions & 3 deletions src/backend/database/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ CREATE TABLE Reviews (
);

-- TEST
/*
INSERT INTO Users (user_id, username, password, email, phone, apt_id)
VALUES (1, 'Zongxian', '12345abcde', 'Zongxian@Feng.com', '1234567890', 1);
Expand Down Expand Up @@ -218,6 +219,4 @@ VALUES (11, 2, '2021-09-14', 'Hello there lizard', 1);
INSERT INTO Reviews (apt_id, user_id, date_of_rating, comment, vote)
VALUES (12, 3, '2021-09-15', 'Windows are broken, rent is expensive, door doesnt work. Roof falling in. Bank foreclosing it. ABORT', -1);



*/
15 changes: 1 addition & 14 deletions src/backend/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import sqlite3
from functools import wraps
import config
from app import session

def use_database(func):
"""Decorator to utilize DB connections"""
Expand Down Expand Up @@ -40,16 +39,4 @@ def wrapped(*args, **kwargs):
return func_instance

return wrapped
'''
def login_required(func):
"""Decorator to prevent logged out user entering user page"""
@wraps(func)
def wrapped(*args, **kwargs):
"""Wrapper"""
if session.get("USERNAME", None) is None:
return {"url": "/register"}, 404
return func(*args, **kwargs)
return wrapped
'''

5 changes: 1 addition & 4 deletions src/backend/pages/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from dataclasses import dataclass
import re
from decorators import use_database
#from app import session


@dataclass(frozen=True)
Expand All @@ -16,7 +15,6 @@ class RegisterResult:
class Login:
"""Login class"""

# stored_user = User()
def __init__(self) -> None:
"""Constructor"""

Expand Down Expand Up @@ -61,8 +59,7 @@ def login(self, user_id: str, password: str) -> bool:
return len(user) > 0

def logout(self) -> None:
"""Logout function removes session object"""
#session.pop("USERNAME", None) # session object is None if pop fails
"""Logout"""

def validate_phone(phone: str) -> bool:
"""Used in Login class and in User class"""
Expand Down
36 changes: 18 additions & 18 deletions src/backend/pages/userpage.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
"""Contains the UserPage backend"""
#from pages.login import Login
from pages.login import Login
from dataholders.user import User
from typing import List
from dataholders.apt import Apt
#from app import session
#from decorators import use_database
from decorators import use_database
from pages.login import validate_phone

class UserPage:
"""UserPage class"""

def __init__(self) -> None:
def __init__(self, username: str) -> None:
"""Constructor"""
self.username = username

def get_user(self, username: str) -> User:
user = []
return user
def get_user(self, username: str):
"""Return User object based on username"""
return True

def update_password(self, password: str) -> bool:
"""Updates password based on username"""
# can use Flask-Hashing if we want
return True

def update_email(self, email: str) -> bool:
"""Updates email based on username"""
return True

def get_liked(self, user_id: int) -> List[Apt]:
"""Gets liked apartments based on username"""
apts = []
return apts

#@use_database
@use_database
def update_phone(self, phone: str) -> bool:
"""Update phone number, return true if phone is valid and database is updated"""
'''if not validate_phone(phone):
return False'''
'''if session.get("USERNAME", None) is not None: # checks session object exists
username = session.get("USERNAME") # gets the username from the session object
self.update_phone.cursor.execute(
"UPDATE Users SET phone = ? WHERE (username = ?)", (phone, username),
)
return True'''
return False
"""Updates User's phone number if valid"""
if not validate_phone(phone):
return False
self.update_phone.cursor.execute(
"UPDATE Users SET phone = ? WHERE (username = ?)", (phone, self.username),
)
return True
16 changes: 16 additions & 0 deletions src/backend/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,19 @@ def test_mainpage_post_invalid(client):
sample_review = {"username": "User McUserFace", "comment": "Ho ho ho ho"}
res = client.post("/main", json=sample_review)
assert res.status_code == 400


def test_userpage_not_logged_in(client):
"""Tests userpage is inaccessible to logged out user"""
res = client.get("/user/")
assert res.status_code == 404

def test_userpage_logged_in(client):
"""Tests post request with username"""
with client:
client.post("/user/musk", json={"username": "musk"})
res = client.get("/user/")
assert res.status_code == 201

def test_userpage_status_code(client):
"""Tests all json """
57 changes: 27 additions & 30 deletions src/backend/tests/test_userpage.py
Original file line number Diff line number Diff line change
@@ -1,61 +1,58 @@
"""Test userpage.py"""
import sqlite3
from pages.userpage import UserPage
#from decorators import use_test, use_database
#from pages.login import validate_phone
from app import app
from decorators import use_test
from pages.login import validate_phone

class TestUserPage:
"""Test user page class"""

userpage = UserPage()
username = "test_username"
alt_username = "alt_username"
userpage = UserPage(username)
phone = "012-345-6789"
invalid_phone = "123-3421-322"

#@use_database
def set_up(self):
with app.test_client() as c:
with c.session_transaction() as session:
session["SECRET_KEY"] = "VlpJb4lFReaMsVvPZgzMJA"
result = app.test_client.get('/')

#@use_database
@use_test
def test_update_phone(self):
"""Tests valid and invalid phone numbers"""
#assert validate_phone(self.phone) is True # verify for later tests
#assert validate_phone(self.invalid_phone) is False
#valid = self.test_valid_phone(self.phone)
#invalid = self.test_invalid_phone(self.invalid_phone)
#assert valid is True
#assert invalid is False
assert validate_phone(self.phone) is True # verify for later tests
assert validate_phone(self.invalid_phone) is False
valid = self.test_valid_phone()
invalid = self.test_invalid_phone()
assert valid is True
assert invalid is False
self.cleanup_db()

#@use_database
@use_test
def test_valid_phone(self) -> bool:
"""Test update_phone returns True and User is logged in"""
connection = sqlite3.connect("database/database_test.db")
cursor = connection.cursor()
cursor.execute(
"INSERT INTO Users (username, email, password, phone, apt_id) \
VALUES (?, ?, ?, ?, 0)",
("hello", "hello@gmail.com", "password", "011-899-9013"),
(self.alt_username, "hello@gmail.com", "password", "011-899-9013"),
)
cursor.execute(
"UPDATE Users SET phone = ? WHERE (username = ?)", (self.phone, "hello"),
"UPDATE Users SET phone = ? WHERE (username = ?)", (self.phone, self.alt_username,),
)
result = cursor.execute("SELECT phone FROM Users WHERE (username = ?)", ("hello",)).fetchone()
#update = self.userpage.update_phone(self.valid)
return True

result = cursor.execute("SELECT phone FROM Users WHERE (username = ?)", (self.alt_username,)).fetchone()
update = self.userpage.update_phone(self.phone)
assert result == update
self.cleanup_db()
return update

@use_test
def test_invalid_phone(self) -> bool:
"""Test update_phone returns False"""
update = self.userpage.update_phone(self.invalid_phone)
return True
return self.userpage.update_phone(self.invalid_phone)

@use_test
def cleanup_db(self) -> None:
"""Remove fake data from database"""
connection = sqlite3.connect("database/database_test.db")
cursor = connection.cursor
cursor.execute("DELETE FROM Users WHERE (phone = ?)", (self.phone,))
cursor.execute("DELETE FROM Users WHERE (phone = ?)", (self.invalid_phone,))
cursor = connection.cursor()
cursor.execute("DELETE FROM Users WHERE (username = ?)", (self.username, self.alt_username,))
connection.commit()
connection.close()

3 comments on commit a357b1c

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCoverMissing
app.py1305855%44–46, 52–77, 81–82, 129–130, 133–148, 151–152, 155, 158, 184–193, 199–201
config.py10100% 
decorators.py270100% 
dataholders
   apt.py90100% 
   mainpage_get.py150100% 
   review.py70100% 
   user.py70100% 
pages
   login.py35877%34–49
   mainpage.py1006733%36–52, 60–80, 87–116, 123–152, 164–204, 209–215, 222–244, 249–257, 261–268, 273–279
   userpage.py24675%18, 23, 27, 31–32, 42
TOTAL35513961% 

Tests Skipped Failures Errors Time
43 0 💤 29 ❌ 0 🔥 11.826s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCoverMissing
app.py1305855%44–46, 52–77, 81–82, 129–130, 133–148, 151–152, 155, 158, 184–193, 199–201
config.py10100% 
decorators.py270100% 
dataholders
   apt.py90100% 
   mainpage_get.py150100% 
   review.py70100% 
   user.py70100% 
pages
   login.py35877%34–49
   mainpage.py1006733%36–52, 60–80, 87–116, 123–152, 164–204, 209–215, 222–244, 249–257, 261–268, 273–279
   userpage.py24675%18, 23, 27, 31–32, 42
TOTAL35513961% 

Tests Skipped Failures Errors Time
43 0 💤 29 ❌ 0 🔥 11.911s ⏱️

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coverage

Coverage Report
FileStmtsMissCoverMissing
app.py1305855%44–46, 52–77, 81–82, 129–130, 133–148, 151–152, 155, 158, 184–193, 199–201
config.py10100% 
decorators.py270100% 
dataholders
   apt.py90100% 
   mainpage_get.py150100% 
   review.py70100% 
   user.py70100% 
pages
   login.py35877%34–49
   mainpage.py1006733%36–52, 60–80, 87–116, 123–152, 164–204, 209–215, 222–244, 249–257, 261–268, 273–279
   userpage.py24675%18, 23, 27, 31–32, 42
TOTAL35513961% 

Tests Skipped Failures Errors Time
43 0 💤 29 ❌ 0 🔥 13.074s ⏱️

Please sign in to comment.