def test_profile_user_relationship(self):
		user = User('profileUsername', '*****@*****.**')
		user.save()
		profile = Profile(user)
		profile.save()
		assert(profile.user is not None)
		assert(profile.user.username == 'profileUsername')	
		assert(profile.user.email == '*****@*****.**')
	def test_profile_updates_weight_history_on_new_weight(self):
		user = User('user', '*****@*****.**')
		user.save()		
		new_profile = Profile(user)
		new_profile.set_weight(69.0)
		new_profile.save()
		assert(new_profile.weights.count() == 1)
		assert(new_profile.weights[0].weight == 69.0)
	def test_get_by_id(self):
		# note: 1-to-1 relationship User<=>Profile. Thus we need a User.
		user = User('user', '*****@*****.**')
		user.save()
		new_profile = Profile(user)
		new_profile.save()
		retrieved_profile = Profile.get_by_id(new_profile.id)
		assert(retrieved_profile == new_profile)
	def test_get_polar_data(self):
		user = User('profileUsername', '*****@*****.**')
		user.save()
		profile = Profile(user)
		profile.save()
		polar_user = PolarUserModel(profile.id, profile.username)
		polar_user.save()
		retrieved_polar = profile.get_polar_data()
		assert(retrieved_polar.member_id == 'R4IT_profileUsername')
	def test_profile_birth_date(self):
		user = User('user', '*****@*****.**')
		user.save()
		new_profile = Profile(user)
		new_profile.set_birth_date(1980, 1, 2)
		new_profile.save()
		assert(new_profile.birth_date.year == 1980)
		assert(new_profile.birth_date.month == 1)
		assert(new_profile.birth_date.day == 2)
	def test_profile_data_defaults_to_none(self):
		user = User('user', '*****@*****.**')
		user.save()
		new_profile = Profile(user)
		new_profile.save()
		assert(new_profile.height is None)
		assert(new_profile.weight is None)
		assert(new_profile.birth_date is None) 
		assert(new_profile.weights.count() == 0)
	def test_profile_weight(self):
		user = User('user', '*****@*****.**')
		user.save()
		new_profile = Profile(user)
		new_profile.set_weight(80)
		new_profile.save()
		assert(new_profile.weight == 80)
		new_profile.set_weight(0)
		new_profile.save()
		assert(new_profile.weight is None)
	def test_profile_weight_history_relationship(self):
		user = User('user', '*****@*****.**')
		user.save()		
		new_profile = Profile(user)
		new_profile.set_weight(69.0)
		new_profile.save()
		weight_history_record = ProfileWeightHistory.get_by_id(1)
		assert(weight_history_record is not None)
		assert(weight_history_record.profile_id == new_profile.id)
		assert(weight_history_record.weight == 69.0)
	def test_profile_updates_weight_history_on_several_new_weights(self):	# last is saved
		user = User('user', '*****@*****.**')
		user.save()		
		new_profile = Profile(user)
		new_profile.set_weight(69.0)
		new_profile.set_weight(70.0)
		new_profile.set_weight(71.0)
		new_profile.save()
		assert(new_profile.weights.count() == 1)
		assert(new_profile.weights[0].weight == 71.0)	
	def _init_profile_with_workouts(self):
		user = User('user', '*****@*****.**')
		user.save(commit=False)
		profile = Profile(user)
		profile.save(commit=False)
		cat1 = WorkoutCategoryModel('Running', True)
		cat1.save(commit=False)
		cat2 = WorkoutCategoryModel('Swimming', True)
		cat2.save()
		WorkoutModel(profile.id, cat1, "Run 1", dt.datetime.utcnow() - dt.timedelta(days=3), 1000, 180, 10, None, False).save(commit=False)
		WorkoutModel(profile.id, cat1, "Run 2", dt.datetime.utcnow() - dt.timedelta(days=2), 1000, 180, 10, None, False).save(commit=False)
		WorkoutModel(profile.id, cat2, "Swim 1", dt.datetime.utcnow() - dt.timedelta(days=1), 100, 180, 0, None, False).save()
		return profile
	def _init_profile_with_goals(self):
		user = User('user', '*****@*****.**')
		user.save()
		profile = Profile(user)
		profile.save()
		goal_cat = GoalCategoryModel('demo')
		goal_cat.save()
		previous_start_at = dt.datetime.utcnow() + dt.timedelta(days=-5)
		current_start_at = dt.datetime.utcnow() + dt.timedelta(days=-2)
		later_start_at = dt.datetime.utcnow() + dt.timedelta(days=1)
		GoalModel(profile.id, goal_cat, current_start_at, current_start_at + dt.timedelta(days=4), 0, 10, 11).save() # completed but still active positive-going
		GoalModel(profile.id, goal_cat, later_start_at, later_start_at + dt.timedelta(days=4), 0, 10, 0).save() # not completed, future
		GoalModel(profile.id, goal_cat, previous_start_at, previous_start_at + dt.timedelta(days=4), 0, 5, 4).save() # not completed, pos.going
		return profile
	def test_profile_unique(self, db):
		user = User('user', '*****@*****.**')
		user.save()
		profile1 = Profile(user)
		profile1.save()

		try:
			profile2 = Profile(user)
			profile2.save()

		except:
			db.session.rollback()

		num_profiles = db.session.query(Profile).count()
		assert(num_profiles == 1)
	def test_profile_updates_weight_loss_goals_on_new_weight(self):
		user = User('user', '*****@*****.**')
		user.save()	
		profile = Profile(user)
		profile.set_weight(80)
		profile.save()
		weight_cat = GoalCategoryModel('Weight loss', 'kg')
		weight_cat.save()
		weight_goal = GoalModel(profile.id, weight_cat, dt.datetime.utcnow() - dt.timedelta(days=1), dt.datetime.utcnow() + dt.timedelta(days=1), 80, 70, 79).save()
		weight_goal.save()
		initial_start_value = weight_goal.start_value
		initial_current_value = weight_goal.current_value
		assert(initial_start_value == 80)
		assert(initial_current_value == 79)
		profile.set_weight(78)
		profile.save()
		assert(weight_goal.start_value == 80)
		assert(weight_goal.current_value == 78)		
示例#14
0
def get_auth_profile_or_abort(username, module_name="profile"):
    auth_username = get_jwt_identity()
    if auth_username != username:
        report_error_and_abort(422, module_name, "Profile not found")

    user = User.find_by_username(auth_username)
    if user.profile is None:  # should not be possible to have a user without a profile
        report_error_and_abort(422, module_name, "Profile not found")

    return user.profile
示例#15
0
    def get(self, username, **kwargs):
        auth_username = get_jwt_identity()

        if auth_username != username:
            report_error_and_abort(422, "profile", "Profile not found")

        user = User.find_by_username(auth_username)

        if user.profile is None:  # should not be possible to have a user without a profile
            report_error_and_abort(422, "profile", "Profile not found")

        # load profile from db
        return user.profile, 200
示例#16
0
    def put(self,
            username,
            height=None,
            weight=None,
            birth_date=None,
            **kwargs):
        auth_username = get_jwt_identity()

        if auth_username != username:
            report_error_and_abort(422, "profile", "Profile not found")

        user = User.find_by_username(auth_username)

        if user.profile is None:  # should not be possible to have a user without a profile
            report_error_and_abort(422, "profile", "Profile not found")

        was_updated = False

        if (height is not None):
            user.profile.set_height(height)
            was_updated = True

        if (weight is not None):
            user.profile.set_weight(weight)
            was_updated = True

        if birth_date is not None:
            user.profile.birth_date = birth_date
            was_updated = True

        if was_updated:
            try:
                user.profile.updated_at = dt.datetime.utcnow()
                user.save()
            except:
                db.session.rollback()
                report_error_and_abort(500, "profile",
                                       "Unable to update profile")

        return user.profile, 200
示例#17
0
    def get(self, username, start_at=None, end_at=None):
        auth_username = get_jwt_identity()

        if auth_username != username:
            report_error_and_abort(422, "profile", "Profile not found")

        user = User.find_by_username(auth_username)

        if user.profile is None:  # should not be possible to have a user without a profile
            report_error_and_abort(422, "profile", "Profile not found")

        weight_list = []
        if start_at is not None and end_at is not None:
            start_date = dt.datetime(start_at.year, start_at.month,
                                     start_at.day, 0, 0, 0)
            end_date = dt.datetime(end_at.year, end_at.month, end_at.day, 23,
                                   59, 59, 999999)
            weight_list = user.profile.weights.filter(
                and_(ProfileWeightHistory.created_at > start_date,
                     ProfileWeightHistory.created_at < end_date)).order_by(
                         ProfileWeightHistory.created_at.desc()).all()
        elif start_at is not None:
            start_date = dt.datetime(start_at.year, start_at.month,
                                     start_at.day, 0, 0, 0)
            weight_list = user.profile.weights.filter(
                ProfileWeightHistory.created_at > start_date).order_by(
                    ProfileWeightHistory.created_at.desc()).all()
        elif end_at is not None:
            end_date = dt.datetime(end_at.year, end_at.month, end_at.day, 23,
                                   59, 59, 999999)
            weight_list = user.profile.weights.filter(
                ProfileWeightHistory.created_at < end_date).order_by(
                    ProfileWeightHistory.created_at.desc()).all()
        else:
            weight_list = user.profile.weights.order_by(
                ProfileWeightHistory.created_at.desc()).all()

        return weight_list
示例#18
0
def init_database_test_data():
	print('Deleting database data ...')

	from run4it.app.database import db  # noqa
	from run4it.api.user import User, UserConfirmation # noqa
	from run4it.api.profile import Profile, ProfileWeightHistory  # noqa
	from run4it.api.token import TokenRegistry  # noqa
	from run4it.api.discipline import DisciplineModel # noqa
	from run4it.api.goal import GoalModel, GoalCategoryModel # noqa
	from run4it.api.workout import WorkoutCategoryModel, WorkoutModel #noqa
	from run4it.api.polar import PolarUserModel, PolarWebhookExerciseModel

	# delete most stuff
	rows = User.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from User table'.format(rows))

	rows = Profile.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from Profile table'.format(rows))

	rows = UserConfirmation.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from UserConfirmation table'.format(rows))

	rows = TokenRegistry.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from TokenRegistry table'.format(rows))
	
	rows = ProfileWeightHistory.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from ProfileWeightHistory table'.format(rows))
	
	rows = DisciplineModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from Discipline table'.format(rows))
	
	rows = GoalModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from Goal table'.format(rows))	

	rows = GoalCategoryModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from GoalCategory table'.format(rows))
	
	rows = WorkoutModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from Workout table'.format(rows))

	rows = WorkoutCategoryModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from WorkoutCategory table'.format(rows))
	
	rows = PolarUserModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from PolarUser table'.format(rows))

	rows = PolarWebhookExerciseModel.query.delete(False)
	if rows > 0:
		print('Deleted {0} rows from PolarWebhookExercise table'.format(rows))

	db.session.commit()

	# create test items
	user = User('existing', '*****@*****.**', 'pwd') #not confirmed
	profile = Profile(user)
	user.save(commit=False)
	profile.save(commit=False)
	print("Added {0}".format(user))

	user = User('JonnyIT', '*****@*****.**', 'pwd')
	user.confirmed = True
	profile = Profile(user)
	profile.set_weight(79.1)
	profile.set_height(176)
	profile.set_birth_date(1979, 5, 1)
	user.save(commit=False)
	profile.save(commit=False)
	print("Added {0}".format(user))

	user = User('confirm', '*****@*****.**', 'pwd')
	profile = Profile(user)
	profile.set_weight(70.1)
	user.save(commit=False)
	profile.save(commit=False)
	print("Added {0}".format(user)) 

	confirmation = UserConfirmation('confirm', 'correct')
	confirmation.save(commit=False)
	print("Added {0}".format(confirmation))

	discipline = DisciplineModel('10,000m', 10000)
	discipline.save(commit=False)
	print("Added {0}".format(discipline))
	discipline = DisciplineModel('5,000m', 5000)
	discipline.save(commit=False)
	print("Added {0}".format(discipline))
	discipline = DisciplineModel('1,500m', 1500)
	discipline.save(commit=False)
	print("Added {0}".format(discipline))

	workout_cat_run = WorkoutCategoryModel('Running', True)
	workout_cat_run.save(commit=False)
	print("Added {0}".format(workout_cat_run))
	workout_cat = WorkoutCategoryModel('Cross-country skiing', True)
	workout_cat.save(commit=False)
	print("Added {0}".format(workout_cat))
	workout_cat = WorkoutCategoryModel('Roller skiing', True)
	workout_cat.save(commit=False)
	print("Added {0}".format(workout_cat))
	workout_cat_fitness = WorkoutCategoryModel('Fitness', False)
	workout_cat_fitness.save(commit=False)
	print("Added {0}".format(workout_cat_fitness))
	db.session.commit()

	goalCatCumRun = GoalCategoryModel('Cumulative distance', 'km', 1)
	goalCatCumRun.save(commit=False)
	print("Added {0}".format(goalCatCumRun))
	goalCatWeightLoss = GoalCategoryModel('Weight loss', 'kg')
	goalCatWeightLoss.save(commit=False)
	print("Added {0}".format(goalCatWeightLoss))
	goalCatSkiingCount = GoalCategoryModel('Workout count', '#', 2)
	goalCatSkiingCount.save(commit=False)
	print("Added {0}".format(goalCatSkiingCount))
	goalCatFitnessCount = GoalCategoryModel('Workout count', '#', 4) 
	goalCatFitnessCount.save(commit=False)
	print("Added {0}".format(goalCatFitnessCount))
	goalCatCumClimb = GoalCategoryModel('Cumulative climb', 'm', 1) # running
	goalCatCumClimb.save(commit=False)
	print("Added {0}".format(goalCatCumClimb))
	db.session.commit()

	now = dt.datetime.utcnow()
	next_january = dt.datetime(now.year + 1, 1, 1)
	prev_january = dt.datetime(now.year, 1, 1)
	this_month_first = dt.datetime(now.year, now.month, 1)
	next_month_first = this_month_first + dt.timedelta(days=monthrange(this_month_first.year, this_month_first.month)[1])
	last_day_prev_month = this_month_first + dt.timedelta(days=-1)
	prev_month_first = this_month_first + dt.timedelta(days=-monthrange(last_day_prev_month.year, last_day_prev_month.month)[1])
	prev_monday = dt.datetime(now.year, now.month, now.day) + dt.timedelta(days=-now.weekday())

	# future goal
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatSkiingCount, next_january, next_january + dt.timedelta(days=100), 0, 30, 0)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatCumRun, next_month_first, next_month_first + dt.timedelta(days=monthrange(next_month_first.year, next_month_first.month)[1]), 0, 100, 0)
	goal.save(commit=False)
	print("Added {0}".format(goal))

	# active goals
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatWeightLoss, prev_monday, prev_monday + dt.timedelta(days=8), 79, 76, 77)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatCumRun, this_month_first, next_month_first, 0, 100, 22.666)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatFitnessCount, prev_january, next_january, 0, 20, 4)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatCumClimb, prev_january - dt.timedelta(days=10), next_january, 0, 8848, 2174)
	goal.save(commit=False)
	print("Added {0}".format(goal))

	# expired goals
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatCumRun, prev_month_first, this_month_first, 0, 100, 98)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	goal = GoalModel(User.find_by_username('JonnyIT').profile.id, goalCatWeightLoss, prev_month_first, this_month_first, 82, 80, 79)
	goal.save(commit=False)
	print("Added {0}".format(goal))
	db.session.commit()

	# Workouts
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_run, "Åsen run 3", dt.datetime.utcnow(), 7321, 1921, 430)
	workout.save(commit=False)
	print("Added {0}".format(workout))
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_run, "Åsen run 2", dt.datetime.utcnow()-dt.timedelta(seconds=90000), 3000, 658, 621, 'C:/mydev/run4it_backend/run4it/uploads/gpx/test.tcx', 1)
	workout.save(commit=False)
	print("Added {0}".format(workout))
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_run, "Åsen run 1", dt.datetime.utcnow()-dt.timedelta(seconds=180000), 12345, 658, 1123, 'C:/mydev/run4it_backend/run4it/uploads/gpx/test2.tcx', 1)
	workout.save(commit=False)
	print("Added {0}".format(workout))	
	db.session.commit()
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_fitness, "Fitness 1", dt.datetime.utcnow()-dt.timedelta(days=20), 0, 3600, 0)
	workout.save(commit=False)
	print("Added {0}".format(workout))
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_fitness, "Fitness 2", dt.datetime.utcnow()-dt.timedelta(days=17), 0, 3600, 0)
	workout.save(commit=False)
	print("Added {0}".format(workout))	
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_fitness, "Fitness 3", dt.datetime.utcnow()-dt.timedelta(days=15), 0, 3600, 0)
	workout.save(commit=False)
	print("Added {0}".format(workout))
	workout = WorkoutModel(User.find_by_username('JonnyIT').profile.id, workout_cat_fitness, "Fitness 4", dt.datetime.utcnow(), 0, 3600, 0)
	workout.save(commit=False)
	print("Added {0}".format(workout))
	db.session.commit()	

	print('Application data initialized!')
	return 0
	def test_profile_username(self):
		user = User('profileUsername', '*****@*****.**')
		user.save()
		profile = Profile(user)
		profile.save()
		assert(profile.username == 'profileUsername')