def setUp(self) -> None: print("SET UP") with app.app_context(): example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) example2 = User() example2.firstname = 'Admin' example2.lastname = 'Admin' example2.email = '*****@*****.**' example2.dateofbirth = datetime.datetime(2020, 10, 5) example2.is_admin = True example2.set_password('admin') db.session.add(example2) db.session.commit() payload = {'email': '*****@*****.**', 'password': '******'} form = LoginForm(data=payload) self.client.post('/users/login', data=form.data, follow_redirects=True)
def setUp(self) -> None: with app.app_context(): # Create an user with no stories q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() # Create another user q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin2' example.lastname = 'Admin2' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() # Create a not recent story by Admin2 example = Story() example.text = 'This is a story about the end of the world' example.date = datetime.datetime.strptime('2012-12-12', '%Y-%m-%d') example.author_id = 2 example.figures = 'story#world' example.is_draft = False db.session.add(example) db.session.commit() # Create a recent story saved as draft by Admin2 example = Story() example.text = 'This story is just a draft' example.date = datetime.datetime.now() example.author_id = 2 example.figures = 'story#draft' example.is_draft = True db.session.add(example) db.session.commit() # Create a recent story by Admin example = Story() example.text = 'Just another story' example.date = datetime.datetime.now() example.author_id = 1 example.figures = 'dice#example' example.is_draft = False db.session.add(example) db.session.commit()
def _init_database(db): ''' Initializes the database for testing. ''' example1 = User() example1.username = '******' example1.firstname = 'First1' example1.lastname = 'Last1' example1.email = '*****@*****.**' example1.dateofbirth = datetime.datetime(2020, 10, 5) example1.is_admin = False example1.set_password('test1123') db.session.add(example1) example2 = User() example2.username = '******' example2.firstname = 'First2' example2.lastname = 'Last2' example2.email = '*****@*****.**' example2.dateofbirth = datetime.datetime(2020, 10, 5) example2.is_admin = False example2.set_password('test2123') db.session.add(example2) example3 = User() example3.username = '******' example3.firstname = 'First3' example3.lastname = 'Last3' example3.email = '*****@*****.**' example3.dateofbirth = datetime.datetime(2020, 10, 5) example3.is_admin = False example3.set_password('test3123') db.session.add(example3) db.session.commit()
def setUp(self) -> None: with app.app_context(): # user for login example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) # dummy user dummy_user = User() dummy_user.firstname = 'Dummy' dummy_user.lastname = 'Dummy' dummy_user.email = '*****@*****.**' dummy_user.dateofbirth = datetime.datetime(2020, 10, 5) dummy_user.is_admin = True dummy_user.set_password('admin') db.session.add(dummy_user) db.session.commit() dummy_id = User.query.filter( User.email == '*****@*****.**').first().id test_story = Story() test_story.text = "Test story from admin user" test_story.author_id = 1 test_story.is_draft = 0 test_story.figures = "#Test#admin#" dummy_story = Story() dummy_story.text = "Test story from dummy user" dummy_story.author_id = dummy_id dummy_story.is_draft = 0 dummy_story.figures = "#Test#dummy#" db.session.add(test_story) db.session.add(dummy_story) db.session.commit() payload = {'email': '*****@*****.**', 'password': '******'} form = LoginForm(data=payload) self.client.post('/users/login', data=form.data, follow_redirects=True)
def restart_db_tables(db, app): with app.app_context(): db.init_app(app) db.drop_all(app=app) db.create_all(app=app) example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() example = Story() example.text = 'Trial story of example admin user :)' example.likes = 42 example.author_id = 1 example.roll = { 'dice': ['bike', 'tulip', 'happy', 'cat', 'ladder', 'rain'] } example.date = datetime.datetime(2019, 11, 5) db.session.add(example) db.session.commit()
def signup(): form = UserForm() if request.method == 'POST': email = form.data['email'] q = db.session.query(User).filter(User.email == email) check = q.first() if check is None: user = User() user.firstname = form.data['firstname'] user.lastname = form.data['lastname'] user.email = form.data['email'] user.dateofbirth = form.data['dateofbirth'] user.set_password(form.data['password']) db.session.add(user) db.session.commit() login_user(user) return redirect("/") else: form = UserForm() return render_template( 'signup.html', form=form, error=True, message="The email was used before. Please change the email!") if request.method == 'GET': return render_template('signup.html', form=form)
def setUp(self) -> None: with app.app_context(): # user for login example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() # reacted story test_story = Story() test_story.text = "Test story from admin user" test_story.author_id = 1 test_story.is_draft = 0 test_story.figures = "#Test#admin#" db.session.add(test_story) db.session.commit() # login payload = {'email': '*****@*****.**', 'password': '******'} form = LoginForm(data=payload) self.client.post('/users/login', data=form.data, follow_redirects=True)
def populate_user(): new_user = User() new_user.email = "*****@*****.**" new_user.phone = '3333333333' new_user.firstname = "firstname_test" new_user.lastname = "lastname_test" new_user.password = "******" new_user.dateofbirth = datetime.date(2020, 10, 5) new_user.role = "customer" return new_user
def setUp(self) -> None: with app.app_context(): # create an user Admin example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2010, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit()
def add_user(email, phone, firstname, lastname, password, date, role): new_user = User() new_user.email = email new_user.phone = phone new_user.firstname = firstname new_user.lastname = lastname new_user.password = password new_user.role = role new_user.dateofbirth = date db.session.add(new_user) db.session.commit() return db.session.query(User).filter(User.email == email).first()
def create_app(debug=False): app = Flask(__name__) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # DEBUGGING AND TESTING app.config['SQLALCHEMY_ECHO'] = False app.config['TESTING'] = debug app.config['LOGIN_DISABLED'] = True app.config['WTF_CSRF_ENABLED'] = False for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) # create a first admin user with app.app_context(): q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() q = db.session.query(Story).filter(Story.id == 1) story = q.first() if story is None: example = Story() example.text = 'Trial story of example admin user :)' example.likes = 42 example.author_id = 1 example.dicenumber = 6 example.roll = { 'dice': ['bike', 'tulip', 'happy', 'cat', 'ladder', 'rain'] } example.date = datetime.datetime(2019, 11, 5) db.session.add(example) db.session.commit() return app
def insert_admin(db, app): with app.app_context(): admin = db.session.query(User).filter_by( email='*****@*****.**').first() if admin is None: example = User() example.email = '*****@*****.**' example.phone = '3333333333' example.firstname = 'Admin' example.lastname = 'Admin' example.set_password('admin') example.dateofbirth = datetime.date(2020, 10, 5) example.is_admin = True example.role = 'admin' db.session.add(example) db.session.commit()
def insert_ha(db, app): with app.app_context(): ha = db.session.query(User).filter_by( email='*****@*****.**').first() if ha is None: example = User() example.email = '*****@*****.**' example.phone = '3333333333' example.firstname = 'ha' example.lastname = 'ha' example.set_password('ha') example.dateofbirth = datetime.date(2020, 10, 5) example.is_admin = True example.role = 'ha' db.session.add(example) db.session.commit()
def new_user(strava_token=None): user = User() user.email = '*****@*****.**' user.firstname = "A" user.lastname = "Tester" user.strava_token = 0 user.age = 0 user.weight = 0 user.max_hr = 0 user.rest_hr = 0 user.vo2max = 0 user.set_password('test') if strava_token is not None: user.strava_token = strava_token db.session.add(user) db.session.commit() return user
def create_app(): app = Flask(__name__) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///gooutsafe.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) # create a first admin user with app.app_context(): q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() q = db.session.query(Restaurant).filter(Restaurant.id == 1) restaurant = q.first() if restaurant is None: example = Restaurant() example.name = 'Trial Restaurant' example.likes = 42 example.phone = 555123456 example.lat = 43.720586 example.lon = 10.408347 db.session.add(example) db.session.commit() return app
def create_app(): app = Flask(__name__) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db' for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) # create a first admin user with app.app_context(): q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() q = db.session.query(Story).filter(Story.id == 1) story = q.first() if story is None: example = Story() example.text = 'Trial story of example admin user :)' example.likes = 42 example.author_id = 1 print(example) db.session.add(example) db.session.commit() return app
def setUp(self) -> None: with app.app_context(): # user for login example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() # reacted story test_story = Story() test_story.text = "Test story from admin user" test_story.author_id = 1 test_story.is_draft = 0 test_story.figures = "#admin#cat#" db.session.add(test_story) db.session.commit()
def test_email_sender(self): global _app if _app is None: tested_app = create_app(debug=True) _app = tested_app else: tested_app = _app restart_db_tables(db, tested_app) with tested_app.test_client() as client: with client.session_transaction() as session: example2 = User() example2.firstname = 'Daniele' example2.lastname = 'Arioli' example2.email = '*****@*****.**' example2.dateofbirth = datetime(2020, 10, 5) example2.is_admin = True example2.set_password('admin') db.session.add(example2) db.session.commit() self.assertTrue(send_emails())
def test_die_init(self): example = User() example.id = random.randint(0, 2048) example.firstname = 'userwall' example.lastname = 'theWall' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('daddysflownacrosstheocean') some_stories = [ 'story1', 'story2', 'story3', 'story4', 'story5', 'story6' ] wall = Wall(example) for s in some_stories: story = Story() story.id = random.randint(0, 2048) story.text = s story.likes = 0 story.dislikes = 0 wall.add_story(story) wall.storyLimit = len(wall.stories) story = Story() story.id = random.randint(0, 2048) story.text = 'an extra story' story.likes = 0 story.dislikes = 0 wall.add_story(story) wall.add_story(story) self.assertEqual(len(wall.stories), wall.storyLimit)
def test_story_digest_format(): u = User() u.username = '******' u.email = '*****@*****.**' u.firstname = 'Firstname' u.lastname = 'Lastname' date = dt.datetime.now() s = Story() s.author = u s.text = 'Lorem ipsum dolor sit amet' s.date = date s.likes = 42 s.dislikes = 69 s.dice_set = ['lorem', 'ipsum', 'dolor', 'sit', 'amet'] s.deleted = False s.is_draft = False lines = digests.story_digest(s).split('\n') assert lines[0] == 'author: Firstname Lastname (Username)' assert lines[1] == 'roll: lorem, ipsum, dolor, sit, amet' assert lines[2] == f'date: {date}' assert lines[3] == 'story: Lorem ipsum dolor sit amet' assert lines[4] == 'likes: 42 -- dislikes: 69'
def create_app(tests=False): app = Flask(__name__) app.config["WTF_CSRF_SECRET_KEY"] = "A SECRET KEY" app.config["SECRET_KEY"] = "ANOTHER ONE" if tests is False: app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///gooutsafe.db" else: app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///tests/gooutsafe.db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) # create a first admin user with app.app_context(): # create the user roles q = db.session.query(Role).filter(Role.id == 1) role = q.first() if role is None: role = Role() role.value = "ADMIN" role.label = "Admin role" db.session.add(role) role = Role() role.value = "OPERATOR" role.label = "Operator role" db.session.add(role) role = Role() role.value = "CUSTOMER" role.label = "Customer role" db.session.add(role) role = Role() role.value = "HEALTH" role.label = "Health role" db.session.add(role) db.session.commit() # an Admin user q = db.session.query(User).filter(User.email == "*****@*****.**") user = q.first() if user is None: admin_user = User() admin_user.firstname = "Admin" admin_user.lastname = "Admin" admin_user.email = "*****@*****.**" admin_user.phone = "3334455678" admin_user.dateofbirth = datetime.datetime(2020, 10, 5) admin_user.is_admin = True admin_user.set_password("admin") admin_user.role_id = 1 db.session.add(admin_user) db.session.commit() # an operator q = db.session.query(User).filter(User.email == "*****@*****.**") user = q.first() if user is None: first_operator = User() first_operator.firstname = "Ham" first_operator.lastname = "Burger" first_operator.email = "*****@*****.**" first_operator.phone = "222333567" first_operator.is_admin = False first_operator.set_password("operator") first_operator.role_id = 2 db.session.add(first_operator) db.session.commit() # a customer q = db.session.query(User).filter(User.email == "*****@*****.**") user = q.first() if user is None: first_customer = User() first_customer.firstname = "John" first_customer.lastname = "Doe" first_customer.email = "*****@*****.**" first_customer.phone = "111234765" first_customer.is_admin = False first_customer.set_password("customer") first_customer.role_id = 3 db.session.add(first_customer) db.session.commit() # health autority q = db.session.query(User).filter( User.email == "*****@*****.**") user = q.first() if user is None: health_authority = User() health_authority.firstname = "Health" health_authority.lastname = "Authority" health_authority.email = "*****@*****.**" health_authority.phone = "321456783" health_authority.is_admin = False health_authority.set_password("nocovid") health_authority.role_id = 4 db.session.add(health_authority) db.session.commit() # a restaurant q = db.session.query(Restaurant).filter(Restaurant.id == 1) restaurant = q.first() if restaurant is None: # load the first operator q = db.session.query(User).filter( User.email == "*****@*****.**") user = q.first() first_restaurant = Restaurant() first_restaurant.name = "Trial Restaurant" first_restaurant.likes = 42 first_restaurant.phone = 555123456 first_restaurant.covid_measures = "Distance between tables 2mt; Menù touch; Alcohol Gel; Only Electronic Payment" first_restaurant.lat = 43.720586 first_restaurant.lon = 10.408347 first_restaurant.owner_id = user.id db.session.add(first_restaurant) db.session.commit() # a table q = db.session.query(RestaurantTable).filter(RestaurantTable.id == 1) table = q.first() if table is None: # insert the first table q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() first_table = RestaurantTable() first_table.restaurant_id = restaurant.id first_table.name = "Table 1" first_table.max_seats = 6 first_table.available = True db.session.add(first_table) db.session.commit() # another table q = db.session.query(RestaurantTable).filter(RestaurantTable.id == 2) table = q.first() if table is None: # insert the first table q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() second_table = RestaurantTable() second_table.restaurant_id = restaurant.id second_table.name = "Table 2" second_table.max_seats = 4 second_table.available = True db.session.add(second_table) db.session.commit() # insert some opening hours q = (db.session.query(OpeningHours).filter( OpeningHours.restaurant_id == 1).filter( OpeningHours.week_day == 0)) openinghour = q.first() if openinghour is None: q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() first_opening_hours = OpeningHours() first_opening_hours.restaurant_id = restaurant.id first_opening_hours.week_day = 0 first_opening_hours.open_lunch = datetime.time(hour=12) first_opening_hours.close_lunch = datetime.time(hour=15) first_opening_hours.open_dinner = datetime.time(hour=20) first_opening_hours.close_dinner = datetime.time(hour=22) db.session.add(first_opening_hours) db.session.commit() # insert some opening hours q = (db.session.query(OpeningHours).filter( OpeningHours.restaurant_id == 1).filter( OpeningHours.week_day == 2)) openinghour = q.first() if openinghour is None: q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() second_opening_hours = OpeningHours() second_opening_hours.restaurant_id = restaurant.id second_opening_hours.week_day = 2 second_opening_hours.open_lunch = datetime.time(hour=12) second_opening_hours.close_lunch = datetime.time(hour=15) second_opening_hours.open_dinner = datetime.time(hour=20) second_opening_hours.close_dinner = datetime.time(hour=22) db.session.add(second_opening_hours) db.session.commit() # insert some opening hours q = (db.session.query(OpeningHours).filter( OpeningHours.restaurant_id == 1).filter( OpeningHours.week_day == 4)) openinghour = q.first() if openinghour is None: q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() third_opening_hours = OpeningHours() third_opening_hours.restaurant_id = restaurant.id third_opening_hours.week_day = 4 third_opening_hours.open_lunch = datetime.time(hour=12) third_opening_hours.close_lunch = datetime.time(hour=15) third_opening_hours.open_dinner = datetime.time(hour=20) third_opening_hours.close_dinner = datetime.time(hour=22) db.session.add(third_opening_hours) db.session.commit() # a reservation q = db.session.query(Reservation).filter(Reservation.id == 1) reservation = q.first() if reservation is None: # insert the first table q = db.session.query(User).filter( User.email == "*****@*****.**") customer = q.first() q = db.session.query(RestaurantTable).filter( RestaurantTable.id == 1) table = q.first() q = db.session.query(Restaurant).filter(Restaurant.id == 1) restaurant = q.first() first_reservation = Reservation() first_reservation.reservation_date = datetime.datetime(2020, 10, 28, hour=12) first_reservation.reservation_end = ( first_reservation.reservation_date + datetime.timedelta(minutes=restaurant.avg_time)) first_reservation.customer_id = customer.id first_reservation.table_id = table.id first_reservation.people_number = 2 db.session.add(first_reservation) db.session.commit() # insert a review q = db.session.query(Review).filter_by(id=1).first() if q is None: review = Review() q = db.session.query(Restaurant).filter( Restaurant.name == "Trial Restaurant") restaurant = q.first() q = db.session.query(User).filter( User.email == "*****@*****.**") user = q.first() review.restaurant_id = restaurant.id review.reviewer_id = user.id review.review = "ciao" review.stars = decimal.Decimal(4.5) db.session.add(review) db.session.commit() # CALCULATE_RATING_RESTAURANTS return app
def create_app(test=False): app = Flask(__name__, static_url_path='/static') app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///storytellers.db' if test: app.config['TESTING'] = True app.config['CELERY_ALWAYS_EAGER'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False celery = celeryApp.make_celery(app) celeryApp.celery = celery for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) db.create_all(app=app) with app.app_context(): # Create first admin user. q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() example = Story() example.title = 'My first story!' example.rolls_outcome = '[["bike", "static/Mountain/bike.PNG"], ["bus", "static/Mountain/bus.PNG"]]' example.text = 'With my bike, I am faster than a bus!!!!' example.theme = 'Mountain' example.published = 1 example.likes = 42 example.dislikes = 5 example.author_id = 1 db.session.add(example) db.session.commit() # Create dice sets if missing. themes = retrieve_themes() if not themes: die1 = Die( ['angry', 'bag', 'bike', 'bird', 'crying', 'moonandstars'], "N/A") die2 = Die(['bus', 'coffee', 'happy', 'letter', 'paws', 'plate'], "N/A") die3 = Die( ['caravan', 'clock', 'drink', 'mouth', 'tulip', 'whale'], "N/A") die4 = Die( ['baloon', 'bananas', 'cat', 'icecream', 'pencil', 'phone'], "N/A") dice_set = DiceSet([die1, die2, die3], "Mountain") store_dice_set(dice_set) dice_set = DiceSet([die2, die3, die4], "Late night") store_dice_set(dice_set) dice_set = DiceSet([die3, die1, die4], "Travelers") store_dice_set(dice_set) dice_set = DiceSet([die2, die1, die4], "Youth") store_dice_set(dice_set) die = Die(["1", "2", "3"], "test_theme") dice_set = DiceSet([die], "test_theme") return app
def setUp(self) -> None: print("SET UP") with app.app_context(): # Add Admin user example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) # Add another user for testing example = User() example.firstname = 'Test' example.lastname = 'Man' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 6) example.is_admin = False example.set_password('test') db.session.add(example) # Add some stories for user 1 example = Story() example.text = 'Trial story of example admin user :)' example.author_id = 1 example.figures = '#example#admin#' example.is_draft = False db.session.add(example) db.session.commit() example = Story() example.text = 'Another story!' example.author_id = 1 example.is_draft = True example.figures = '#another#story#' db.session.add(example) db.session.commit() # Add reactions for user 1 like = Counter() like.reaction_type_id = 1 like.story_id = 1 like.counter = 23 dislike = Counter() dislike.reaction_type_id = 2 dislike.story_id = 1 dislike.counter = 5 db.session.add(like) db.session.add(dislike) db.session.commit() # login payload = {'email': '*****@*****.**', 'password': '******'} form = LoginForm(data=payload) self.client.post('/users/login', data=form.data, follow_redirects=True)
def create_app(test=False, database=DATABASE_NAME, login_disabled=False, test_telegram=False): ''' Prepares initializes the application and its utilities. ''' app = Flask(__name__) Bootstrap(app) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SECRET_KEY'] = 'ANOTHER ONE' app.config['CELERY_BROKER_URL'] = 'redis://*****:*****@localhost' # The address of the SMTP server app.config['SMTP_SERVER_ADDRESS'] = 'localhost' # The port of the SMTP server app.config['SMTP_SERVER_PORT'] = 8025 app.config['CELERY_TIMEZONE'] = 'Europe/Rome' app.config['PERMANENT_SESSION_LIFETIME'] = dt.timedelta(minutes=120) app.config['SQLALCHEMY_DATABASE_URI'] = database app.config['LOGIN_DISABLED'] = login_disabled app.config['CELERYBEAT_SCHEDULE'] = { 'monthly-digest': { 'task': 'monolith.task.send_digest', # Scheduled for the first day of each month 'schedule': crontab(day_of_month='1'), # Scheduled every 10 seconds # 'schedule': 10.0, } } if test: app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['CELERY_ALWAYS_EAGER'] = True app.config['SMTP_SERVER_ADDRESS'] = 'localhost' app.config['SMTP_SERVER_PORT'] = 8025 # Disables periodic task app.config['CELERYBEAT_SCHEDULE'] = {} if test_telegram: app.config['TELEGRAM_TESTING'] = True # Celery initialization celery = celeryapp.create_celery_app(app) celeryapp.celery = celery # Initialization of the DB and login manager db.init_app(app) login_manager.init_app(app) login_manager.login_view = '/login' db.create_all(app=app) if not test or (test and test_telegram): # initialize Telegram create_bot(mock=test_telegram) updater = Updater(token, use_context=True) dp = updater.dispatcher # Add functions to the dispatcher. # When a function such as start is launched on telegram it will run the # corresponding function dp.add_handler(CommandHandler('start', on_start)) dp.add_handler(CommandHandler('login', on_login)) updater.start_polling() app.config['TELEGRAM_UPDATER'] = updater # Required to avoid circular dependencies from monolith.views import blueprints for bp in blueprints: app.register_blueprint(bp) bp.app = app # Registration of the error handlers from monolith.views import errors app.register_error_handler(400, errors.bad_request) app.register_error_handler(401, errors.unauthorized) app.register_error_handler(403, errors.forbidden) app.register_error_handler(404, errors.page_not_found) app.register_error_handler(410, errors.gone) # Creation of an admin user with app.app_context(): q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.username = '******' example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = dt.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() return app
def test_maker_message(self): global _app if _app is None: tested_app = create_app(debug=True) _app = tested_app else: tested_app = _app restart_db_tables(db, tested_app) with tested_app.test_client() as client: with client.session_transaction() as session: # push in the users_table 3 users user_a = User() user_a.firstname = 'user_a' user_a.email = '*****@*****.**' user_a.set_password('test') user_b = User() user_b.firstname = 'user_b' user_b.lastname = 'surname_b' user_b.email = '*****@*****.**' user_b.set_password('test') user_c = User() user_c.firstname = 'user_c' user_c.lastname = 'surname_c' user_c.email = '*****@*****.**' user_c.set_password('test') user_d = User() user_d.firstname = 'user_d' user_d.lastname = 'surname_d' user_d.email = '*****@*****.**' user_d.set_password('test') db.session.add(user_a) db.session.add(user_b) db.session.add(user_c) db.session.add(user_d) db.session.commit() # Get users ID user_a_id = User.query.filter_by( email=user_a.email).first().get_id() user_b_id = User.query.filter_by( email=user_b.email).first().get_id() user_c_id = User.query.filter_by( email=user_c.email).first().get_id() user_d_id = User.query.filter_by( email=user_d.email).first().get_id() with client.session_transaction() as session: follow_ab = _create_follow(user_a_id, user_b_id) follow_ac = _create_follow(user_a_id, user_c_id) follow_ad = _create_follow(user_a_id, user_d_id) follow_bc = _create_follow(user_b_id, user_c_id) db.session.add(follow_ab) db.session.add(follow_ac) db.session.add(follow_ad) db.session.add(follow_bc) story_b_1 = make_story(user_b_id, "story_b_1") story_b_2 = make_story(user_b_id, "story_b_2") story_b_3 = make_story(user_b_id, "story_b_3", 66, 9) story_b_4 = make_story(user_b_id, "story_b_4", 5, 1) story_c_1 = make_story(user_c_id, "story_c_1") story_c_2 = make_story(user_c_id, "story_c_2", 1000, 162) story_c_3 = make_story(user_c_id, "story_c_3") db.session.add(story_b_1) db.session.add(story_b_2) db.session.add(story_b_3) db.session.add(story_b_4) db.session.add(story_c_1) db.session.add(story_c_2) db.session.add(story_c_3) db.session.commit() res = maker_message(user_a) print(res) correct = "Hello user_a,\n\nhere you can find what's new on the wall of Sweaggers' SocialDice!\n\n - user_b surname_b posts 4 new stories.\n - user_c surname_c posts 3 new stories.\n\nSee you on SocialDice,\nSweaggers Team" self.assertEqual(res, correct) res = maker_message(user_d) correct = "Hello user_d,\n\nYou have no news for today, take a look and add new writers on Sweaggers' SocialDice!" self.assertEqual(res, correct)
def test_delete_wrong_author_story_index(self): global _app if _app is None: tested_app = create_app(debug=True) _app = tested_app else: tested_app = _app restart_db_tables(db, tested_app) with tested_app.test_client() as client: # login reply = login(client, '*****@*****.**', 'admin') self.assertEqual(reply.status_code, 200) # add reaction to a story reply = client.get('/stories/reaction/1/1') self.assertEqual(reply.status_code, 200) users = User.query.all() self.assertEqual(len(users), 1) story = db.session.query(Story).filter_by(id=1).first() self.assertNotEqual(story, None) # logout reply = logout(client) self.assertEqual(reply.status_code, 200) # signup user1 = User() user1.firstname = "Mario" user1.lastname = "Rossi" user1.email = "*****@*****.**" user1.dateofbirth = "1994" user1.password = user1.set_password("12345") reply = signup(client, user1) self.assertEqual(reply.status_code, 200) users = User.query.all() self.assertEqual(len(users), 2) story = db.session.query(Story).filter_by(id=1).first() self.assertNotEqual(story, None) stories = Story.query.filter_by(id=1).all() self.assertEqual(len(stories), 1) reactions = Reaction.query.filter_by(story_id=1).all() self.assertEqual(len(reactions), 1) story = db.session.query(Story).filter_by(id=1).first() self.assertNotEqual(story, None) reactions = Reaction.query.filter_by(story_id=1).all() self.assertEqual(len(reactions), 1) # add reaction to a story reply = client.get('/stories/reaction/1/1') self.assertEqual(reply.status_code, 200) reply = client.post('stories/1/remove/index', follow_redirects=True) self.assertEqual(reply.status_code, 200) story = db.session.query(Story).filter_by(id=1).first() self.assertNotEqual(story, None) # logout reply = logout(client) self.assertEqual(reply.status_code, 200)
def test_json_wall(self): app = test_app.test_client() with app.session_transaction() as sess: db.drop_all() db.create_all() q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'userwall' example.lastname = 'theWall' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('daddysflownacrosstheocean') db.session.add(example) db.session.commit() q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() q = db.session.query(Story).filter(Story.author_id == user.id) story = q.first() if story is None: example = Story() example.text = 'We dont need no education We dont need no...All in all you re just another brick in the wall' example.likes = 42 example.dislikes = 1 example.dicenumber = 6 example.author_id = user.id db.session.add(example) example = Story() example.text = 'Leaving just a memory...Snapshot in the family album...Daddy what else did you leave for me?' example.likes = 42 example.dislikes = 0 example.dicenumber = 4 example.author_id = user.id db.session.add(example) db.session.commit() q = db.session.query(Story).filter(Story.author_id == user.id) stories = [] thewalltest = Wall(user) for s in q: s: Story thewalltest.add_story(s) stories.append({ 'story_id': s.id, 'text': s.text, 'likes': s.likes, 'dislikes': s.dislikes }) reply = app.get('/thewall/' + str(user.id)) body = json.loads(str(reply.data, 'utf8')) self.assertEqual( body, { "id": user.id, "firstname": user.firstname, "lastname": user.lastname, "email": user.email, "stories": stories # thewalltest.stories }) wall_repl = Wall() wall_repl.acquire_from_json(reply) self.assertEqual(thewalltest.id, wall_repl.id, "Json acquire fail")
def create_app(): app = Flask(__name__) app.config['WTF_CSRF_SECRET_KEY'] = 'A SECRET KEY' app.config['SECRET_KEY'] = 'ANOTHER ONE' #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@postgres:5432/postgres' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URI'] app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Flask-Mail configuration app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = 587 app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = '******' app.config['MAIL_PASSWORD'] = '******' app.config['MAIL_DEFAULT_SENDER'] = '*****@*****.**' for bp in blueprints: app.register_blueprint(bp) bp.app = app db.init_app(app) login_manager.init_app(app) try: db.create_all(app=app) except Exception as e: print(e) # TODO THIS SECTION MUST BE REMOVED, ONLY FOR DEMO # already tested EndPoints are used to create examples app.config['WTF_CSRF_ENABLED'] = False with app.app_context(): q = db.session.query(User).filter(User.email == '*****@*****.**') adm = q.first() if adm is None: try: # create a first admin user # test for a user defined in database.db example = User() example.email = '*****@*****.**' example.phone = '3333333333' example.firstname = 'Admin' example.lastname = 'Admin' example.set_password('admin') example.dateofbirth = datetime.date(2020, 10, 5) example.role = 'admin' example.is_admin = True db.session.add(example) db.session.commit() test_client = app.test_client() insert_ha(db, app) for user in customers_example: create_user_EP(test_client,**user) for user in restaurant_owner_example: create_user_EP(test_client,**user) for usr_idx,restaurant in enumerate(restaurant_example): user_login_EP(test_client, restaurant_owner_example[usr_idx]['email'], restaurant_owner_example[usr_idx]['password']) create_restaurant_EP(test_client,restaurant) user_logout_EP(test_client) except Exception as e: print(e) app.config['WTF_CSRF_ENABLED'] = True return app
def setUp(self) -> None: with app.app_context(): # Create admin user (if not present) q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Admin' example.lastname = 'Admin' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2020, 10, 5) example.is_admin = True example.set_password('admin') db.session.add(example) db.session.commit() # Create non admin user (if not present) q = db.session.query(User).filter(User.email == '*****@*****.**') user = q.first() if user is None: example = User() example.firstname = 'Abc' example.lastname = 'Abc' example.email = '*****@*****.**' example.dateofbirth = datetime.datetime(2010, 10, 5) example.is_admin = False example.set_password('abc') db.session.add(example) db.session.commit() # Create the first story, default from teacher's code q = db.session.query(Story).filter(Story.id == 1) story = q.first() if story is None: example = Story() example.text = 'Trial story of example admin user :)' example.author_id = 1 example.figures = '#example#admin#' example.is_draft = False db.session.add(example) db.session.commit() # Create a story of a different user q = db.session.query(Story).filter(Story.id == 2) story = q.first() if story is None: example = Story() example.text = 'You won\'t modify this story' example.author_id = 2 example.figures = '#modify#story#' example.is_draft = False db.session.add(example) db.session.commit() # Create a draft for the logged user q = db.session.query(Story).filter(Story.id == 3) story = q.first() if story is None: example = Story() example.text = 'This is an example of draft' example.author_id = 1 example.figures = '#example#draft#' example.is_draft = True db.session.add(example) db.session.commit() # Create a draft of a different user q = db.session.query(Story).filter(Story.id == 4) story = q.first() if story is None: example = Story() example.text = 'This is an example of draft that you can\'t modify' example.date = datetime.datetime.strptime('2018-12-30', '%Y-%m-%d') example.author_id = 2 example.figures = '#example#draft#' example.is_draft = True db.session.add(example) db.session.commit() payload = {'email': '*****@*****.**', 'password': '******'} form = LoginForm(data=payload) self.client.post('/users/login', data=form.data, follow_redirects=True)
def test_followers_list(self): global _app if _app is None: tested_app = create_app(debug=True) _app = tested_app else: tested_app = _app restart_db_tables(db, tested_app) with tested_app.test_client() as client: with client.session_transaction() as session: # push in the users_table 3 users user_a = User() user_a.firstname = "Pippo" user_a.lastname = "Pippo" user_a.email = '*****@*****.**' user_a.set_password('test') user_b = User() user_b.firstname = "Pluto" user_b.lastname = "Mouse" user_b.email = '*****@*****.**' user_b.set_password('test') user_c = User() user_c.email = '*****@*****.**' user_c.set_password('test') db.session.add(user_a) db.session.add(user_b) db.session.add(user_c) db.session.commit() # Get users ID user_a_id = User.query.filter_by( email=user_a.email).first().get_id() user_b_id = User.query.filter_by( email=user_b.email).first().get_id() # login as user_1 login(client, user_a.email, 'test') # call /follow/user_id_2 # assert True, redirtect to user_2 wall reply = client.post('/follow/' + str(user_b_id)) data = "/wall/" + str(user_b_id) self.assertTrue(_is_follower(user_a_id, user_b_id)) self.assertIn(data, str(reply.data)) # get followed list reply = client.get("/followed/list") self.assertIn(user_b.firstname, str(reply.data)) # get followed number reply = client.get("/followed") assert b'"followed_num":1' in reply.data # logout user1 logout(client) # login as user2 login(client, user_b.email, 'test') # get followers list reply = client.get("/followers/list") self.assertIn(user_a.firstname, str(reply.data)) # get followers number reply = client.get("/followers") assert b'"followers_num":1' in reply.data