def test_evaluate_achievement_for_yearly_evaluation_case2(self): achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=3, achievement_evaluation="yearly") user = create_user() achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement["evaluation"]) print(achievement_date) next_year = achievement_date + datetime.timedelta(534) print(next_year) create_achievement_user(user, achievement, achievement_date, level=1) create_variable("invite_users", variable_group="day") create_goals(achievement, goal_goal="3*level", goal_operator="geq", goal_group_by_key=False) clear_all_caches() # Not achieved in first year but in the second year print("Yearly evaluation Case 2") Value.increase_value(variable_name="invite_users", user=user, value=5, key=None, at_datetime=achievement_date) achievement_result = Achievement.evaluate(user, achievement.id, achievement_date) print("achievement result: ", achievement_result) next_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, evaluation_type="yearly", dt=next_year + datetime.timedelta(10)) Value.increase_value(variable_name="invite_users", user=user, value=15, key=None, at_datetime=next_date) achievement_result1 = Achievement.evaluate(user, achievement.id, next_date) print("achievement result1: ", achievement_result1) self.assertEqual(achievement_result["achievement_date"], achievement_date) self.assertEqual(achievement_result1["achievement_date"], next_date) self.assertNotEqual(next_year, next_date) self.assertIn('1', achievement_result["levels_achieved"]) self.assertIn('1', achievement_result1["new_levels"]) self.assertIn('2', achievement_result1["new_levels"]) self.assertIn('3', achievement_result1["new_levels"])
def increase_multi_values(request): try: doc = request.json_body except: raise APIError(400, "invalid_json", "no valid json body") ret = {} for user_id, values in doc.items(): user = User.get_user(user_id) if not user: raise APIError(404, "user_not_found", "user %s not found" % (user_id, )) for variable_name, values_and_keys in values.items(): for value_and_key in values_and_keys: variable = Variable.get_variable_by_name(variable_name) if asbool(get_settings().get("enable_user_authentication", False)): if not Variable.may_increase(variable, request, user_id): raise APIError( 403, "forbidden", "You may not increase the variable %s for user %s." % (variable_name, user_id)) if not variable: raise APIError(404, "variable_not_found", "variable %s not found" % (variable_name, )) if not 'value' in value_and_key: raise APIError(400, "variable_not_found", "illegal value for %s" % (variable_name, )) value = value_and_key['value'] key = value_and_key.get('key', '') Value.increase_value(variable_name, user, value, key) output = _get_progress(achievements_for_user=user, requesting_user=request.user) output = copy.deepcopy(output) to_delete = list() for i in range(len(output["achievements"])): if len(output["achievements"][i]["new_levels"]) > 0: if "levels" in output["achievements"][i]: del output["achievements"][i]["levels"] if "priority" in output["achievements"][i]: del output["achievements"][i]["priority"] if "goals" in output["achievements"][i]: del output["achievements"][i]["goals"] else: to_delete.append(i) for i in sorted(to_delete, reverse=True): del output["achievements"][i] if len(output["achievements"]) > 0: ret[user_id] = output return ret
def test_get_reward_and_properties_for_achievement(self): user = create_user() achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=3) achievementproperty = AchievementProperty() achievementproperty.name = "xp" DBSession.add(achievementproperty) DBSession.flush() achievements_achievementproperty = AchievementAchievementProperty() achievements_achievementproperty.achievement_id = achievement.id achievements_achievementproperty.property_id = achievementproperty.id achievements_achievementproperty.value = "5" achievements_achievementproperty.from_level = None DBSession.add(achievements_achievementproperty) DBSession.flush() create_achievement_rewards(achievement=achievement) achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement.evaluation) create_achievement_user(user=user, achievement=achievement, achievement_date=achievement_date, level=1) create_variable("invite_users", "none") Value.increase_value(variable_name="invite_users", user=user, value=4, key="5", at_datetime=achievement_date) create_goals( achievement=achievement, goal_condition= """{"term": {"type": "literal", "variable": "invite_users"}}""", goal_group_by_key=True, goal_operator="geq", goal_goal="1*level") clear_all_caches() result = Achievement.evaluate(user, achievement.id, achievement_date) print("reward_achievement_result:", result) self.assertEqual(len(result["new_levels"]["2"]["rewards"]), 0) self.assertEqual(len(result["new_levels"]["3"]["rewards"]), 1) self.assertEqual(len(result["new_levels"]["2"]["properties"]), 1) self.assertEqual(len(result["new_levels"]["3"]["properties"]), 1)
def test_evaluate_achievement_for_weekly_evaluation_case3(self): achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=3, achievement_evaluation="weekly") user = create_user() achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement["evaluation"]) create_achievement_user(user, achievement, achievement_date, level=1) create_variable("invite_users", variable_group="day") create_goals(achievement, goal_goal="3*level", goal_operator="geq", goal_group_by_key=False) clear_all_caches() # User has not achieved in first week and achieved after few days in a same week print("Weekly evaluation Case 3") Value.increase_value(variable_name="invite_users", user=user, value=5, key=None, at_datetime=achievement_date) achievement_result = Achievement.evaluate(user, achievement.id, achievement_date) print(achievement_result) next_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, evaluation_type="weekly", dt=achievement_date + datetime.timedelta(3)) Value.increase_value(variable_name="invite_users", user=user, value=10, key=None, at_datetime=next_date) achievement_result1 = Achievement.evaluate(user, achievement.id, next_date) print("achievement result1: ", achievement_result1) self.assertEqual(achievement_result["achievement_date"], achievement_date) self.assertEqual(achievement_result1["achievement_date"], next_date) self.assertEqual(achievement_date, next_date) self.assertIn('1', achievement_result["levels_achieved"]) self.assertIn('2', achievement_result1["new_levels"]) self.assertIn('3', achievement_result1["new_levels"])
def test_increase_value(self): user = create_user() variable = create_variable(variable_name="participate", variable_group="day") value1 = Value.increase_value(variable.name, user, value=3, key="5") value2 = Value.increase_value(variable.name, user, value=3, key="5") value3 = Value.increase_value(variable.name, user, value=6, key="7") # Correct cases self.assertGreater(value2, value1) self.assertEqual(value3, value2)
def increase_value(request): """increase a value for the user""" user_id = int(request.matchdict["user_id"]) try: value = float(request.POST["value"]) except: try: doc = request.json_body value = doc["value"] except: raise APIError(400, "invalid_value", "Invalid value provided") key = request.matchdict["key"] if ( "key" in request.matchdict and request.matchdict["key"] is not None) else "" variable_name = request.matchdict["variable_name"] user = User.get_user(user_id) if not user: raise APIError(404, "user_not_found", "user not found") variable = Variable.get_variable_by_name(variable_name) if not variable: raise APIError(404, "variable_not_found", "variable not found") if asbool(get_settings().get("enable_user_authentication", False)): if not Variable.may_increase(variable, request, user_id): raise APIError(403, "forbidden", "You may not increase the variable for this user.") Value.increase_value(variable_name, user, value, key) output = _get_progress(achievements_for_user=user, requesting_user=request.user) output = copy.deepcopy(output) to_delete = list() for i in range(len(output["achievements"])): if len(output["achievements"][i]["new_levels"]) > 0: if "levels" in output["achievements"][i]: del output["achievements"][i]["levels"] if "priority" in output["achievements"][i]: del output["achievements"][i]["priority"] if "goals" in output["achievements"][i]: del output["achievements"][i]["goals"] else: to_delete.append(i) for i in sorted(to_delete, reverse=True): del output["achievements"][i] return output
def increase_data(request): dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\file.csv" params = request.GET if request.method == 'POST': if 'upload' in request.POST: dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\values_data.csv" content = request.POST['file'].file content = content.read() content = content.decode('utf-8', 'ignore') my_dict = p.get_book(file_type="csv", file_content=content, delimiter=';') my_dict.save_as(dir_name, delimiter=';') with open(dir_name) as f: keys_data = f.readline().rstrip().split(";") params.update({'id': request.POST['achievement_id']}) return render_to_response( 'gengine.app:templates/index/increase_data.jinja2', { 'keys_data': keys_data, 'params': params }, request=request) elif 'value' in request.POST: user_id = request.POST["user_id"] variable = request.POST["variable"] value = request.POST["value"] user_id_value = request.POST["user_id_value"] achievement_id = request.POST['achievement_id'] res_id_user = User.get_by_id(user_id, user_id_value) Value.increaseByValue(variable, res_id_user, value) Achievement.update_user_value(achievement_id, res_id_user) return HTTPFound(request.route_url('increase_data', _query=params)) else: user_id = request.POST["user_id"] variable = request.POST["variable"] achievement_id = params["id"] Value.increase(achievement_id, variable, user_id, dir_name) return HTTPFound(request.route_url('leaderboard', _query=params)) else: with open(dir_name) as f: keys = f.readline().rstrip().split(";") achievements = Achievement.get_all_achievements() return {'achievements': achievements, 'params': params, 'keys': keys}
def goal(request): params = request.GET dir_name = os.path.dirname( os.path.abspath(__file__)) + "\\csv_uploads\\file.csv" if request.method == 'POST': user_id = params["user_id"] variable = request.POST["variable"] goal_name = request.POST["goal_name"] goal_goal = request.POST["goal_goal"] achievement_id = params["id"] goal_condition = request.POST["goal_condition"] Variable.add_variable(variable) Goal.add_goal(goal_name, goal_condition, goal_goal, achievement_id) Value.increase(achievement_id, variable, user_id, dir_name) return HTTPFound(request.route_url('leaderboard', _query=params)) else: with open(dir_name) as f: keys = f.readline().rstrip().split(";") return {'keys': keys, 'params': params}
def test_evaluate_achievement_for_participate(self): achievement = create_achievement( achievement_name="participate_achievement", achievement_relevance="own", achievement_maxlevel=4) user = create_user() achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement.evaluation) current_level = 1 achievement_user = AchievementSubject() achievement_user.user_id = user.id achievement_user.achievement_id = achievement.id achievement_user.achievement_date = achievement_date achievement_user.level = current_level DBSession.add(achievement_user) DBSession.flush() variable = create_variable("participate", variable_group="day") Value.increase_value(variable_name=variable.name, user=user, value=1, key="5") create_goals( achievement, goal_condition= """{"term": {"key": ["5","7"], "type": "literal", "key_operator": "IN", "variable": "participate"}}""", goal_group_by_key=True, goal_operator="geq", goal_goal="1*level") clear_all_caches() level = Achievement.evaluate(user, achievement.id, achievement_date).get("level") Value.increase_value(variable_name="participate", user=user, value=1, key="7", at_datetime=achievement_date) level2 = Achievement.evaluate(user, achievement.id, achievement_date).get("level") Value.increase_value(variable_name="participate", user=user, value=5, key="5", at_datetime=achievement_date) level1 = Achievement.evaluate(user, achievement.id, achievement_date).get("level") self.assertEqual(level, 1) self.assertEqual(level2, 1) self.assertEqual(level1, 4)
def test_evaluate_achievement_for_invite_users(self): achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=10) user = create_user() achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement.evaluation) create_achievement_user(user=user, achievement=achievement, achievement_date=achievement_date, level=1) update_connection().execute(t_values.delete()) create_variable("invite_users", variable_group="day") Value.increase_value(variable_name="invite_users", user=user, value=1, key=None, at_datetime=achievement_date) create_goals(achievement, goal_goal="1*level", goal_operator="geq", goal_group_by_key=False) clear_all_caches() level = Achievement.evaluate(user, achievement.id, achievement_date).get("level") print("level: ", level) Value.increase_value(variable_name="invite_users", user=user, value=8, key=None, at_datetime=achievement_date) level1 = Achievement.evaluate(user, achievement.id, achievement_date).get("level") print("level1 ", level1) Value.increase_value(variable_name="invite_users", user=user, value=5, key=None, at_datetime=achievement_date) level2 = Achievement.evaluate(user, achievement.id, achievement_date).get("level") print("level2: ", level2) self.assertEqual(level, 1) self.assertEqual(level1, 9) self.assertEqual(level2, 10)
def create_value( user_id=undefined, variable_id=undefined, var_value=undefined, key="", ): value = Value() value.user_id = user_id value.variable_id = variable_id value.value = var_value value.key = key DBSession.add(value) DBSession.flush() return value
def test_increase_value_null_key(self): user = create_user() variable = create_variable(variable_name="login", variable_group="day") value1 = Value.increase_value(variable.name, user, value=1, key=None) self.assertIs(value1, 1)
def test_evaluate_goal(self): user = create_user() create_variable(variable_name="invite_users", variable_group="day") Value.increase_value(variable_name="invite_users", user=user, value=6, key=None) Value.increase_value(variable_name="invite_users", user=user, value=7, key=None) create_variable(variable_name="participate", variable_group="day") Value.increase_value(variable_name="participate", user=user, value=6, key="5") Value.increase_value(variable_name="participate", user=user, value=3, key="7") Value.increase_value(variable_name="participate", user=user, value=5, key="7") # Goal Participate with group_by = False achievement = create_achievement( achievement_name="participate_achievement") goal = create_goals(achievement, goal_group_by_key=False, goal_goal="3*level") achievement_date = Achievement.get_datetime_for_evaluation_type( User.get_user(user.id)["timezone"], achievement["evaluation"]) evaluation_result = Goal.evaluate(goal, achievement, achievement_date, user, level=4, goal_eval_cache_before=False, execute_triggers=True) print(evaluation_result) # True cases self.assertGreaterEqual(evaluation_result["value"], 12) self.assertEqual(evaluation_result["achieved"], True) # Goal Participate with group_by = True goal2 = create_goals(achievement, goal_group_by_key=True, goal_goal="3*level") evaluation_result2 = Goal.evaluate(goal2, achievement, achievement_date, user, level=4, goal_eval_cache_before=False, execute_triggers=True) print(evaluation_result2) self.assertLessEqual(evaluation_result2["value"], 12) self.assertEqual(evaluation_result2["achieved"], False) # Goal invite_users achievement1 = create_achievement( achievement_name="invite_users_achievement") goal1 = create_goals(achievement1, goal_goal="4*level") achievement_date1 = Achievement.get_datetime_for_evaluation_type( User.get_user(user.id)["timezone"], achievement1["evaluation"]) evaluation_result1 = Goal.evaluate(goal1, achievement1, achievement_date1, user, level=2, goal_eval_cache_before=False, execute_triggers=True) print(evaluation_result1) self.assertGreaterEqual(evaluation_result1["value"], 8) self.assertEqual(evaluation_result1["achieved"], True)
def test_compute_progress(self): user = create_user() create_variable(variable_name="invite_users", variable_group="day") Value.increase_value(variable_name="invite_users", user=user, value=6, key=None) Value.increase_value(variable_name="invite_users", user=user, value=7, key=None) create_variable(variable_name="participate", variable_group="day") Value.increase_value(variable_name="participate", user=user, value=2, key="5") Value.increase_value(variable_name="participate", user=user, value=3, key="7") Value.increase_value(variable_name="participate", user=user, value=5, key="7") achievement = create_achievement( achievement_name="invite_users_achievement") goal = create_goals(achievement) # goal is for invite_users, its group_by_key is false, progress is sum of all the values achievement_date = Achievement.get_datetime_for_evaluation_type( User.get_user(user.id)["timezone"], achievement["evaluation"]) users_progress_goal = Goal.compute_progress( goal=goal, achievement=achievement, user=user, evaluation_date=achievement_date) goal_evaluation = { e["user_id"]: e["value"] for e in users_progress_goal } print(goal_evaluation) self.assertLessEqual(goal_evaluation.get(user.id), 13) # For goal1, since its group_by_key is True, it'll add the values of the same key achievement1 = create_achievement( achievement_name="participate_achievement") goal1 = create_goals(achievement1) achievement_date1 = Achievement.get_datetime_for_evaluation_type( User.get_user(user.id)["timezone"], achievement1["evaluation"]) users_progress_goal1 = Goal.compute_progress( goal=goal1, achievement=achievement1, user=user, evaluation_date=achievement_date1) goal_evaluation1 = { e["user_id"]: e["value"] for e in users_progress_goal1 } print(goal_evaluation1) self.assertLess(goal_evaluation1.get(user.id), 10) # Check with group_by_key for goals participate = False goal2 = create_goals(achievement1, goal_group_by_key=False) users_progress_goal1 = Goal.compute_progress( goal=goal2, achievement=achievement1, user=user, evaluation_date=achievement_date1) goal_evaluation2 = { e["user_id"]: e["value"] for e in users_progress_goal1 } print(goal_evaluation2) self.assertLessEqual(goal_evaluation2.get(user.id), 10)
def test_get_leaderboard(self): achievement = create_achievement( achievement_name="invite_users_achievement") goals = create_goals(achievement) # Create multiple users for a goal user1 = create_user() user2 = create_user(lat=85.59, lng=65.75, country="USA", region="Lethal crosside", city="New York", timezone="US/Eastern", language="en", additional_public_data={ "first_name": "Michael", "last_name": "Clarke" }) # Create Third user user3 = create_user(lat=12.1, lng=12.2, country="RO", region="Transylvania", city="Cluj-Napoca", timezone="Europe/Bucharest", language="en", additional_public_data={ "first_name": "Rudolf", "last_name": "Red Nose" }, friends=[1, 2]) # Create Fourth user user4 = create_user(lat=25.56, lng=15.89, country="AU", region="Sydney", city="New South Wales", timezone="Australia/Sydney", language="en", additional_public_data={ "first_name": "Steve", "last_name": "Waugh" }, friends=[3]) achievement_date_for_user1 = Achievement.get_datetime_for_evaluation_type( User.get_user(user1.id)["timezone"], achievement["evaluation"]) achievement_date_for_user2 = Achievement.get_datetime_for_evaluation_type( User.get_user(user2.id)["timezone"], achievement["evaluation"]) achievement_date_for_user3 = Achievement.get_datetime_for_evaluation_type( User.get_user(user3.id)["timezone"], achievement["evaluation"]) achievement_date_for_user4 = Achievement.get_datetime_for_evaluation_type( User.get_user(user4.id)["timezone"], achievement["evaluation"]) print(achievement_date_for_user4) create_goal_evaluation_cache( goal_id=goals.id, gec_achievement_date=achievement_date_for_user1, gec_user_id=user1.id, gec_value=22.00, gec_achieved=True) create_goal_evaluation_cache( goal_id=goals.id, gec_achievement_date=achievement_date_for_user2, gec_user_id=user2.id, gec_value=8.00, gec_achieved=True) create_goal_evaluation_cache( goal_id=goals.id, gec_achievement_date=achievement_date_for_user3, gec_user_id=user3.id, gec_value=15.00, gec_achieved=True) # Test for finding leaderboard in case where goal has been evaluated for all given users # First get list of friends (user_ids) of given user user_ids = Achievement.get_relevant_users_by_achievement_and_user( achievement, user3.id) # Get leaderboard positions = Goal.get_leaderboard(goals, achievement_date_for_user3, user_ids) print(positions) self.assertEqual(positions[0]["value"], 22.00) self.assertEqual(positions[1]["value"], 15.00) self.assertEqual(positions[2]["value"], 8.00) # Test for Goal is not evaluated for few user_ids create_variable(variable_name="invite_users", variable_group="day") Value.increase_value(variable_name="invite_users", user=user4, value=6, key=None) Value.increase_value(variable_name="invite_users", user=user4, value=9, key=None) user_ids = Achievement.get_relevant_users_by_achievement_and_user( achievement, user4.id) positions = Goal.get_leaderboard(goals, achievement_date_for_user4, user_ids) print(positions) self.assertEqual(positions[0]["value"], 15.00)
def increase_value(request): """increase a value for the subject""" subject_id = int(request.matchdict["subject_id"]) try: value = float(request.POST["value"]) except: try: doc = request.json_body value = doc["value"] except: raise APIError(400, "invalid_value", "Invalid value provided") key = request.matchdict["key"] if ( "key" in request.matchdict and request.matchdict["key"] is not None) else "" variable_name = request.matchdict["variable_name"] subject = Subject.get_subject(subject_id) if not subject: raise APIError(404, "subject_not_found", "subject not found") variable = Variable.get_variable_by_name(variable_name) if not variable: raise APIError(404, "variable_not_found", "variable not found") if asbool(get_settings().get("enable_user_authentication", False)): if not AuthUser.may_increase(variable, request, subject_id): raise APIError( 403, "forbidden", "You may not increase the variable for this subject.") Value.increase_value(variable_name, subject["id"], value, key, at_datetime=dt_now()) try: achievement_history = int(request.GET["achievement_history"]) except: achievement_history = 2 output = _get_progress(achievements_for_subject=subject, requesting_subject=request.subject, achievement_history=achievement_history) output = copy.deepcopy(output) to_delete = list() for i in range(len(output["achievements"])): if len(output["achievements"][i]["new_levels"]) > 0: if "levels" in output["achievements"][i]: del output["achievements"][i]["levels"] if "priority" in output["achievements"][i]: del output["achievements"][i]["priority"] if "goals" in output["achievements"][i]: del output["achievements"][i]["goals"] else: to_delete.append(i) for i in sorted(to_delete, reverse=True): del output["achievements"][i] return output
def test_evaluate_achievement_for_monthly_evaluation_case2(self): achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=3, achievement_evaluation="monthly") user = create_user() achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement["evaluation"]) print(achievement_date) next_month = achievement_date + datetime.timedelta(31) print(next_month) create_achievement_user(user, achievement, achievement_date, level=1) create_variable("invite_users", variable_group="day") create_goals(achievement, goal_goal="3*level", goal_operator="geq", goal_group_by_key=False) clear_all_caches() # User has NOT achieved in this month but in the next month print("Monthly evaluation Case 2") Value.increase_value(variable_name="invite_users", user=user, value=5, key=None, at_datetime=achievement_date) achievement_result = Achievement.evaluate(user, achievement.id, achievement_date) print("achievement result: ", achievement_result) next_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, evaluation_type="monthly", dt=next_month + datetime.timedelta(days=10)) Value.increase_value(variable_name="invite_users", user=user, value=10, key=None, at_datetime=next_date) achievement_result1 = Achievement.evaluate(user, achievement.id, next_date) print("achievement result1: ", achievement_result1) self.assertEqual(achievement_result["achievement_date"], achievement_date) self.assertEqual(achievement_result1["achievement_date"], next_date) self.assertGreaterEqual( next_month, next_date) # next_month can be the 1st, 2nd, 3rd of 4th (February) self.assertIn('1', achievement_result["levels_achieved"]) self.assertIn('1', achievement_result1["new_levels"]) self.assertIn('2', achievement_result1["new_levels"]) self.assertIn('3', achievement_result1["new_levels"])
def test_multiple_goals_of_same_achievement(self): user = create_user() achievement = create_achievement( achievement_name="participate_achievement", achievement_maxlevel=3) create_achievement_rewards(achievement=achievement) achievement_date = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement.evaluation) create_goals( achievement=achievement, goal_condition= """{"term": {"key": ["5","7"], "type": "literal", "key_operator": "IN", "variable": "participate_seminar"}}""", goal_group_by_key=False, goal_operator="geq", goal_goal="2*level", goal_name="goal_participate_seminar") create_goals( achievement=achievement, goal_condition= """{"term": {"type": "literal", "variable": "participate_talk"}}""", goal_group_by_key=False, goal_operator="geq", goal_goal="1*level", goal_name="goal_participate_talk") clear_all_caches() create_achievement_user(user=user, achievement=achievement, achievement_date=achievement_date, level=1) variable1 = create_variable("participate_seminar", variable_group=None) variable2 = create_variable("participate_talk", variable_group=None) Value.increase_value(variable1.name, user, "2", "5", at_datetime=achievement_date) Value.increase_value(variable1.name, user, "3", "7", at_datetime=achievement_date) Value.increase_value(variable2.name, user, "3", key=None, at_datetime=achievement_date) result = Achievement.evaluate(user, achievement.id, achievement_date) print("multiple_goals_of_same_achievement:", result) Value.increase_value(variable1.name, user, "2", "7", at_datetime=achievement_date) result1 = Achievement.evaluate(user, achievement.id, achievement_date) print(result1) Value.increase_value(variable2.name, user, "2", key=None, at_datetime=achievement_date) result2 = Achievement.evaluate(user, achievement.id, achievement_date) print(result2) self.assertEqual(len(result["levels"]["3"]["rewards"]), 1) self.assertEqual(result["levels"]["1"]["goals"]["1"]["goal_goal"], 2) self.assertEqual(result["levels"]["3"]["goals"]["2"]["goal_goal"], 3) self.assertEqual(result1["levels"]["2"]["goals"]["1"]["goal_goal"], 4) self.assertEqual(result1["levels"]["3"]["goals"]["2"]["goal_goal"], 3) self.assertEqual(result2["levels"]["2"]["goals"]["1"]["goal_goal"], 4) self.assertEqual(result2["levels"]["3"]["goals"]["2"]["goal_goal"], 3)
def cycle(user, km, dt): Value.increase_value(variable_name="cycling", subject_id=user.id, value=km, key=None, at_datetime=dt)
def test_simple_invite_users(self): create_subjecttypes() create_subjects() create_variables() create_achievements() klaus = DBSession.query(Subject).filter_by(name="Klaus").first() invite_users_achievement = DBSession.query(Achievement).filter_by( name="invite_users").first() # First step: increase by 1, level 1 will not be achieved Value.increase_value(variable_name="invite_users", subject_id=klaus.id, value=1, key=None, at_datetime=default_dt()) evaluation = Achievement.evaluate( compared_subject=klaus, achievement_id=invite_users_achievement.id, achievement_date=AchievementDate.compute( evaluation_timezone=invite_users_achievement. evaluation_timezone, evaluation_type=invite_users_achievement.evaluation, evaluation_shift=invite_users_achievement.evaluation_shift, context_datetime=default_dt()), context_subject_id=None, execute_triggers=False) self.assertEqual(evaluation["level"], 0) self.assertEqual(evaluation["progress"], 1.0) # Now increase by 3, level 1 will achieved, progress 4.0 Value.increase_value(variable_name="invite_users", subject_id=klaus.id, value=3, key=None, at_datetime=default_dt()) evaluation = Achievement.evaluate( compared_subject=klaus, achievement_id=invite_users_achievement.id, achievement_date=AchievementDate.compute( evaluation_timezone=invite_users_achievement. evaluation_timezone, evaluation_type=invite_users_achievement.evaluation, evaluation_shift=invite_users_achievement.evaluation_shift, context_datetime=default_dt()), context_subject_id=None, execute_triggers=False) self.assertEqual(evaluation["level"], 1) self.assertEqual(evaluation["progress"], 4.0) # Now lets test the maximum level (100) Value.increase_value(variable_name="invite_users", subject_id=klaus.id, value=300, key=None, at_datetime=default_dt()) evaluation = Achievement.evaluate( compared_subject=klaus, achievement_id=invite_users_achievement.id, achievement_date=AchievementDate.compute( evaluation_timezone=invite_users_achievement. evaluation_timezone, evaluation_type=invite_users_achievement.evaluation, evaluation_shift=invite_users_achievement.evaluation_shift, context_datetime=default_dt()), context_subject_id=None, execute_triggers=False) self.assertEqual(evaluation["level"], 100) self.assertEqual(evaluation["progress"], 304.0)
def test_friends_leaderboard(self): user1 = create_user() # Create Second user user2 = create_user( lat=85.59, lng=65.75, #country="DE", #region="Roland", #city="New York", timezone="US/Eastern", language="en", additional_public_data={ "first_name": "Michael", "last_name": "Clarke" }) # Create Third user user3 = create_user( lat=12.1, lng=12.2, #country="RO", #region="Transylvania", #city="Cluj-Napoca", timezone="Europe/Bucharest", language="en", additional_public_data={ "first_name": "Rudolf", "last_name": "Red Nose" }, friends=[1, 2]) # Create Fourth user user4 = create_user( lat=25.56, lng=15.89, #country="AU", #region="Sydney", #city="New South Wales", timezone="Australia/Sydney", language="en", additional_public_data={ "first_name": "Steve", "last_name": "Waugh" }, friends=[3]) achievement = create_achievement( achievement_name="invite_users_achievement", achievement_relevance="friends", achievement_maxlevel=3, achievement_evaluation="weekly") print(achievement.evaluation_timezone) achievement_date1 = Achievement.get_datetime_for_evaluation_type( achievement.evaluation_timezone, achievement.evaluation) print("Achievement date for first user:"******"invite_users", variable_group="day") create_goals(achievement, goal_goal=None, goal_operator="geq", goal_group_by_key=False) Value.increase_value(variable_name="invite_users", user=user1, value=12, key=None, at_datetime=achievement_date1) Value.increase_value(variable_name="invite_users", user=user2, value=2, key=None, at_datetime=achievement_date1) Value.increase_value(variable_name="invite_users", user=user3, value=11, key=None, at_datetime=achievement_date1) Value.increase_value(variable_name="invite_users", user=user4, value=6, key=None, at_datetime=achievement_date1) clear_all_caches() print("test for multiple users") # Evaluate achievement for friends of user 3 achievement1 = Achievement.evaluate(user3, achievement.id, achievement_date1) print(achievement1["goals"][1]["leaderboard"]) # user 3 has to friends: user 1 and user 2 self.assertEqual( user1["id"], achievement1["goals"][1]["leaderboard"][0]["user"]["id"]) self.assertEqual( user3["id"], achievement1["goals"][1]["leaderboard"][1]["user"]["id"]) self.assertEqual( user2["id"], achievement1["goals"][1]["leaderboard"][2]["user"]["id"]) self.assertEqual(12.0, achievement1["goals"][1]["leaderboard"][0]["value"]) self.assertEqual(11.0, achievement1["goals"][1]["leaderboard"][1]["value"]) self.assertEqual(2.0, achievement1["goals"][1]["leaderboard"][2]["value"])