Example #1
0
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.fitness = Fitness(self.db, self.user_id)
        self.fitness_dict = {'WorkoutType': 'Running',\
                             'Minutes': 10.0,\
                             'CaloriesBurned': 100.9}
        self.fitness_1 = Fitness(self.db, self.user_id_1)
        self.fitness_dict_1 = {'WorkoutType': 'Sleeping',\
                             'Minutes': 100.0,\
                             'CaloriesBurned': 10.9}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())
Example #2
0
def callback():
    code = request.args.get("code")
    google_provider_cfg = get_google_provider_cfg()
    token_endpoint = google_provider_cfg["token_endpoint"]
    token_url, headers, body = client.prepare_token_request(
        token_endpoint,
        authorization_response=request.url,
        redirect_url=request.base_url,
        code=code,
    )
    token_response = requests.post(
        token_url,
        headers=headers,
        data=body,
        auth=(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET),
    )
    client.parse_request_body_response(json.dumps(token_response.json()))
    userinfo_endpoint = google_provider_cfg["userinfo_endpoint"]
    uri, headers, body = client.add_token(userinfo_endpoint)
    userinfo_response = requests.get(uri, headers=headers, data=body)
    if userinfo_response.json().get("email_verified"):
        unique_id = userinfo_response.json()["sub"]
        users_email = userinfo_response.json()["email"]
        picture = userinfo_response.json()["picture"]
        users_name = userinfo_response.json()["given_name"]
    else:
        return "User email not available or not verified by Google.", 400
    user = User(id_=unique_id, name=users_name, email=users_email, profile_pic=picture)
    if not User.get(unique_id):
        User.create(unique_id, users_name, users_email, picture)
    login_user(user)
    return redirect('/')
def warmup(environ, start_response):
    try:
        User.create(email="*****@*****.**", password="******")
    except EmailTaken:
        # Test user already in the database. No action needed
        pass
    start_response('200 OK', [])
    return ['']
Example #4
0
 def vote(self, voter: User, amount_staked: float, for_against: bool):
     if for_against:
         self._for_map[voter.get_address()] = amount_staked
         self._for_staked += amount_staked
         self._for_count += 1
         self._for_rep += voter.get_rep()
     else:
         self._against_map[voter.get_address()] = amount_staked
         self._against_staked += amount_staked
         self._against_count += 1
         self._against_rep += voter.get_rep()
Example #5
0
 def setUpClass(self):
     """
     Set up the unit test.
     """
     self.db = DB()
     self.email = '*****@*****.**'
     self.password = '******'
     self.fullname = 'ABC'
     
     self.user = User(self.db)
     self.user.create_new_user(self.email, self.password, self.fullname)
     self.user_id = self.user.check_email_match(self.email)
Example #6
0
async def ws(user, token):
    user = User.access(user, token)
    if user is None:
        return 'Invalid token', 403
    else:
        await websocket.accept()
        await stream_updates(websocket, user)
Example #7
0
    def __init__(self,
                 creator: User,
                 data: Database,
                 stock_ticker: str = '',
                 sign: int = 0,
                 margin: float = 0.0,
                 amount_staked: float = 0.0,
                 seconds: int = 0):
        # initializing our own ADTs
        self._creator = creator
        self._key = data.make_bet_key()
        data.bets()[self._key] = self

        # initializing our arguments
        self._stock_ticker = stock_ticker
        self._sign = sign
        self._margin = margin
        self._amount_staked = amount_staked

        # initializing initial and target stock price with some data reader stuff, edit initial price
        self._initial_price = self.get_current_price()
        self._target_price = self._initial_price * (1 +
                                                    self._sign * self._margin)

        # creating necessary data structures
        self._for_map = {creator.get_address(): amount_staked}
        self._against_map = {}
        self._for_count = 1
        self._against_count = 0
        self._for_rep = creator.get_rep()
        self._against_rep = 0.0
        self._for_staked = amount_staked
        self._against_staked = 0.0

        # timing the bet, adjust back for longer time frames after testing
        # current_time = datetime.utcnow()
        # tz = timezone.utc
        # set_time = datetime(year, month, day, 20, 0, 1, 0, tz)
        # timedelta = set_time - current_time
        # self._total_seconds = timedelta.total_seconds()
        self._total_seconds = seconds

        # starting the timer for the voting duration once the bet is initialized
        voting_period = self.voting_period()
        timer = Timer(voting_period, self.timed_payout)
        timer.start()
Example #8
0
def warmups(environ, start_response):
    try:
        User.create(
            email="*****@*****.**",
            password="******"
        )
    except EmailTaken:
        # Test user already in the database. No action needed
        pass
    start_response('200 OK', [])
    logging.info('Starting actions')
    if not Movies.query_movies():
        logging.info('Populating database')
        for page in range(1,11):
            movies = get_OMDB_movies(page_number=page)
            populate_database(movies)
        logging.info('Database was populated')
    else:
        logging.info('Database doesn\'t need to be populated')

    return ['']
Example #9
0
 def test_password_match(self): 
     """
     Test inserting an input in the database
     """
     email = '*****@*****.**'
     password = '******'
     self.assertTrue(isinstance(self.user.check_password_match(email,password),int))
     
     user = User(None)
     email = '*****@*****.**'
     password = '******'
     self.assertEqual(self.user.check_password_match(None,None),-1)
Example #10
0
    def setUpClass(self):
        """
        Set up the unittest.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.sleep = Sleep(self.db, self.user_id)
        self.sleep_1 = Sleep(self.db, self.user_id_1)

        self.sleep_time = datetime.utcnow()
        self.wakeup_time = datetime.utcnow() + timedelta(minutes=1)
        self.sleep_dict = {'Nap': False,\
                           'SleepTime': self.sleep_time,\
                           'WakeupTime': self.wakeup_time}

        self.sleep_time_1 = datetime.utcnow()
        self.wakeup_time_1 = datetime.utcnow() + timedelta(minutes=2)
        self.sleep_dict_1 = {'Nap': False,\
                           'SleepTime': self.sleep_time_1,\
                           'WakeupTime': self.wakeup_time_1}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())
Example #11
0
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABCD'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.goals = Goals(self.db, self.user_id)
        self.diet_goal_dict = {'Type': 'Calories', 'Value': 1000.0}
        self.fitness_goal_dict = {'Type': 'FitnessMinutes', 'Value': 100.0}
        self.sleep_goal_dict = {'Type': 'SleepHours', 'Value': 10.0}

        self.goals.set_goal(self.diet_goal_dict)
        self.goals.set_goal(self.fitness_goal_dict)
        self.goals.set_goal(self.sleep_goal_dict)
Example #12
0
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.email_2 = '*****@*****.**'
        self.password_2 = 'qqq'
        self.fullname_2 = 'ASD'

        self.user_2 = User(self.db)
        self.user_2.create_new_user(self.email_2, self.password_2,
                                    self.fullname_2)
        self.user_id_2 = self.user_2.check_email_match(self.email_2)

        self.diet = Diet(self.db, self.user_id)
        self.diet_1 = Diet(self.db, self.user_id_1)
        self.diet_2 = Diet(self.db, self.user_id_2)


        self.diet_dict = {'Item': 'Apple',\
                         'ServingSize': 1.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}}
        self.diet_dict_1 = {'Item': 'Orange',\
                         'ServingSize': 2.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 105.0,'Protein': 105.0, 'Carbs': 105.0, 'Fat': 105.0, 'Fiber': 105.0}}
        self.diet_dict_2 = {'Item': 'banana',\
                         'ServingSize': 2.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 101.0,'Protein': 101.0, 'Carbs': 101.0, 'Fat': 101.0, 'Fiber': 101.0}}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())
Example #13
0
async def login():
    if current_user.is_authenticated:
        return quart.redirect(url_for('main'))

    if request.method == "POST":
        data = await request.form
        login = data.get("login")
        user = User.load(login)

        error = await user.login(ip=data.get("ip"),
                                 login=login,
                                 password=data.get("password"))
        if not error:
            error = await user.initialize()

        if error:
            return quart.redirect(url_for('login'))
        login_user(user)
        return quart.redirect(quart.url_for('main'))
    else:
        return await quart.render_template('login.html')
Example #14
0
def load_user(user_id: str):
    return User.load(user_id)
Example #15
0
    Parameters
    ----------
    token : str
        Unique user token.

    Returns
    -------
    result : int
        If successful, returns user ID. Otherwise, returns -1.
    """
    msg, code = USER.decode_token(token)
    if code != 200:
        return -1
    return int(msg)


if __name__ == '__main__':
    test = False
    try:
        test = sys.argv[1]
        test = bool(test)
    except:
        test = False

    print(test)
    DB_OBJECT = DB(test)
    USER = User(DB_OBJECT)

    app.run(host="0.0.0.0", port=5000, debug=False)
Example #16
0
class TestFitness(unittest.TestCase):
    """
    Tests for Fitness.py
    """
    @classmethod
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.fitness = Fitness(self.db, self.user_id)
        self.fitness_dict = {'WorkoutType': 'Running',\
                             'Minutes': 10.0,\
                             'CaloriesBurned': 100.9}
        self.fitness_1 = Fitness(self.db, self.user_id_1)
        self.fitness_dict_1 = {'WorkoutType': 'Sleeping',\
                             'Minutes': 100.0,\
                             'CaloriesBurned': 10.9}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())

    def test_0_data_insertion(self):
        """
        Test database insertion for a single user.
        """
        s = self.fitness.insert_in_database(self.fitness_dict,
                                            date_time=self.dt1)
        self.assertTrue(s)

    def test_1_data_insertion_multiple_users(self):
        """
        Test database insertion for multiple users.
        """
        s = self.fitness.insert_in_database(self.fitness_dict,
                                            date_time=self.dt1)
        self.assertEqual(s, True)
        s_1 = self.fitness_1.insert_in_database(self.fitness_dict_1,
                                                date_time=self.dt1)
        self.assertEqual(s_1, True)

    def test_2_incorrect_key(self):
        """
        Test for incorrect keys. The input keys are the columns of the fitness table.
        """
        d = copy.deepcopy(self.fitness_dict)
        del (d['WorkoutType'])
        d['WorkoutTypeS'] = 'Running'
        self.assertFalse(self.fitness.insert_in_database(d))

        d = copy.deepcopy(self.fitness_dict)
        del (d['Minutes'])
        d['MinutesS'] = 10.0
        self.assertFalse(self.fitness.insert_in_database(d))

        d = copy.deepcopy(self.fitness_dict)
        del (d['CaloriesBurned'])
        d['CaloriesBurnedS'] = 100.9
        self.assertFalse(self.fitness.insert_in_database(d))

    def test_3_incorrect_value(self):
        """
        Test for incorrect value data type before inserting in the fitness database.
        """
        d = copy.deepcopy(self.fitness_dict)
        d['WorkoutType'] = 1
        self.assertFalse(self.fitness.insert_in_database(d))

        d = copy.deepcopy(self.fitness_dict)
        d['Minutes'] = 'Running'
        self.assertFalse(self.fitness.insert_in_database(d))

        d = copy.deepcopy(self.fitness_dict)
        d['CaloriesBurned'] = 1
        self.assertFalse(self.fitness.insert_in_database(d))

    def test_4_data_fetching_unix_time_and_insertion(self):
        """
        Test fetching fitness data from database and also check if the UNIX TIMESTAMP is correct.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.fitness.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))
        self.assertTrue(success)
        self.assertEqual(result[0]['Datetime'], self.unix_time)

    def test_6_data_fetching_values_multiple_users(self):
        """
        Test fetching fitness data from database for multiple users.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.fitness.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success)
        self.assertEqual(result[0]['WorkoutType'], 'Running')
        self.assertEqual(result[0]['Minutes'], 10.0)
        self.assertEqual(result[0]['CaloriesBurned'], 100.9)

        result_1, success_1 = self.fitness_1.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success_1)
        self.assertEqual(result_1[0]['WorkoutType'], 'Sleeping')
        self.assertEqual(result_1[0]['Minutes'], 100.0)
        self.assertEqual(result_1[0]['CaloriesBurned'], 10.9)

    def test_7_incorrect_data_fetching(self):
        """
        Test fetching fitness from the database for incorrect date range. The function should return False. 
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.fitness.get_columns_given_range(
            dt1 + timedelta(days=10), dt1 + timedelta(days=11))
        self.assertFalse(success)

    def test_8_data_fetching_multiple(self):
        """
        Test fetching multiple fitness data entries from the database.
        """
        d = {'WorkoutType': 'Running',\
             'Minutes': 10.0,\
             'CaloriesBurned': 100.9}
        _ = self.fitness.insert_in_database(d,
                                            date_time=datetime.utcnow() +
                                            timedelta(days=1) +
                                            timedelta(minutes=1))
        d = {'WorkoutType': 'Jogging',\
             'Minutes': 10.0,\
             'CaloriesBurned': 100.9}
        _ = self.fitness.insert_in_database(d,
                                            date_time=datetime.utcnow() +
                                            timedelta(days=1) +
                                            timedelta(minutes=2))
        d = {'WorkoutType': 'Dancing',\
             'Minutes': 10.0,\
             'CaloriesBurned': 100.9}
        _ = self.fitness.insert_in_database(d,
                                            date_time=datetime.utcnow() +
                                            timedelta(days=1) +
                                            timedelta(minutes=4))
        d1 = date.today() + timedelta(days=1)
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.fitness.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertEqual(len(result), 3)
        self.assertTrue(success)
        self.assertEqual(result[0]['WorkoutType'], 'Running')
        self.assertEqual(result[1]['WorkoutType'], 'Jogging')
        self.assertEqual(result[2]['WorkoutType'], 'Dancing')

    def test_9_incorrect_database(self):
        """
        Test database insertion for a single user with incorrect database. Test case to increase the coverage. 
        """
        fitness = Fitness(None, self.user_id_1)
        s = fitness.insert_in_database(self.fitness_dict, date_time=self.dt1)
        self.assertFalse(s)
Example #17
0
class TestGoals(unittest.TestCase):
    """
    Test for goals.py
    """
    @classmethod
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABCD'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.goals = Goals(self.db, self.user_id)
        self.diet_goal_dict = {'Type': 'Calories', 'Value': 1000.0}
        self.fitness_goal_dict = {'Type': 'FitnessMinutes', 'Value': 100.0}
        self.sleep_goal_dict = {'Type': 'SleepHours', 'Value': 10.0}

        self.goals.set_goal(self.diet_goal_dict)
        self.goals.set_goal(self.fitness_goal_dict)
        self.goals.set_goal(self.sleep_goal_dict)

    def test_alter_goal(self):
        """
        Test altering a goal. Change all the goals and check for correctness.
        """
        self.assertTrue(self.goals.alter_goal('Calories', 99.0))
        self.assertTrue(self.goals.alter_goal('FitnessMinutes', 50.0))
        self.assertTrue(self.goals.alter_goal('SleepHours', 1.99))
        goal, status = self.goals.get_latest_goal(Type='Calories')
        self.assertEqual(goal[0]['Value'], 99.0)
        goal, status = self.goals.get_latest_goal(Type='FitnessMinutes')
        self.assertEqual(goal[0]['Value'], 50.0)
        goal, status = self.goals.get_latest_goal(Type='SleepHours')
        self.assertEqual(goal[0]['Value'], 1.99)

        goals = Goals(None, self.user_id)
        self.assertFalse(goals.alter_goal('Calories', 99.0))

    def test_incorrect_alter_type_goal(self):
        """
        Test for incorrect alter type. The function alter_goal() should return False.
        """
        self.assertFalse(self.goals.alter_goal('CaloriesS', 99.0))
        self.assertFalse(self.goals.alter_goal('FitnessMinutesS', 50.0))
        self.assertFalse(self.goals.alter_goal('SleepHoursS', 1.99))

    def test_incorrect_alter_value_type_goal(self):
        """
        Test for incorrect alter value data type.
        """
        self.assertFalse(self.goals.alter_goal('Calories', 'A'))
        self.assertFalse(self.goals.alter_goal('FitnessMinutes', 50))
        self.assertFalse(self.goals.alter_goal('SleepHours', 'B'))

    def test_get_latest_goal(self):
        """
        Test getting the latest goal of a particular type, Diet, Fitness or Sleep.
        """
        goal, status = self.goals.get_latest_goal(Type='Calories')
        self.assertTrue(status)
        goal, status = self.goals.get_latest_goal(Type='FitnessMinutes')
        self.assertTrue(status)
        goal, status = self.goals.get_latest_goal(Type='SleepHours')
        self.assertTrue(status)

        goals = Goals(None, self.user_id)
        goal, status = goals.get_latest_goal(Type='Calories')
        self.assertFalse(status)

    def test_incorrect_get_latest_goal(self):
        """
        Test incorrect goal type while getting the latest goal of a particular type.
        """
        goal, status = self.goals.get_latest_goal(Type='A')
        self.assertFalse(status)

    def test_get_all_goals(self):
        """
        Test getting all the goals from the table.
        """
        goals, status = self.goals.get_all_goals()
        self.assertTrue(status)

        goals = Goals(None, self.user_id)
        goal, status = goals.get_all_goals()
        self.assertFalse(status)

    def test_get_type_goals(self):
        """
        Test getting all the goals of a particular type. Mostly we will only be interested in the latest goal.
        """
        goal, status = self.goals.get_type_goals('Calories')
        self.assertTrue(status)

        goals = Goals(None, self.user_id)
        goal, status = goals.get_type_goals('Calories')
        self.assertFalse(status)

    def test_incorrect_get_type_goals(self):
        """
        Test for incorrect goal type while getting all the goals of a particular type. Mostly we will only be interested in the latest goal.
        """
        goal, status = self.goals.get_type_goals('A')
        self.assertFalse(status)

    def test_set_goal(self):
        """
        Test setting a goal. Set all the three goals, Diet, Fitness and Sleep.
        """
        self.assertTrue(self.goals.set_goal(self.diet_goal_dict))
        self.assertTrue(self.goals.set_goal(self.fitness_goal_dict))
        self.assertTrue(self.goals.set_goal(self.sleep_goal_dict))

        goals = Goals(None, self.user_id)
        self.assertFalse(goals.set_goal(self.diet_goal_dict))

    def test_incorrect_key_set_goal(self):
        """
        Test for incorrect keys. We send incorrect keys: Typo and Valuo. These keys are the columns in our tables.
        """
        d = {'Typo': 'Calories', 'Valuo': 100.0}
        self.assertFalse(self.goals.set_goal(d))

    def test_incorrect_value_type_set_goal(self):
        """
        Test for incorrect value data types. We use int for the Value instead of float (in python) and double (in mysql).
        """
        d = {'Type': 'Calories', 'Value': 100}
        self.assertFalse(self.goals.set_goal(d))
Example #18
0
class TestUser(unittest.TestCase):
    """
    Tests for user.py
    """

    @classmethod
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()
        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'
        
        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)
        
    def test_create_new_user(self):
        """
        Test inserting an input in the database
        """
        email = f'{get_random_string(4)}@gmail.com'
        password = '******'
        fullname = 'ABCD'
        self.assertTrue(self.user.create_new_user(email,password,fullname))
        
    def test_user_already_exists(self):
        """
        Test inserting an input in the database
        """
        email = '*****@*****.**'
        password = '******'
        fullname = 'ABCD'
        self.assertFalse(self.user.create_new_user(email,password,fullname))
        
    def test_email_match(self):
        """
        Test inserting an input in the database
        """
        email = '*****@*****.**'
        password = '******'
        self.assertTrue(isinstance(self.user.check_email_match(email),int))
        
    def test_incorrect_email_match(self):
        """
        Test inserting an input in the database
        """
        email = '*****@*****.**'
        password = '******'
        self.assertEqual(self.user.check_email_match(email),-1)
        
    def test_password_match(self): 
        """
        Test inserting an input in the database
        """
        email = '*****@*****.**'
        password = '******'
        self.assertTrue(isinstance(self.user.check_password_match(email,password),int))
        
        user = User(None)
        email = '*****@*****.**'
        password = '******'
        self.assertEqual(self.user.check_password_match(None,None),-1)
        
    def test_incorrect_password_match(self):
        """
        Test inserting an input in the database
        """
        email = '*****@*****.**'
        password = '******'
        self.assertEqual(self.user.check_password_match(email,password),-1)
        
    def test_token(self):
        """
        Test the encoding and decoding token functions.
        """
        num = 10
        token, code = self.user.encode_token(num)
        dec_num, dec_code = self.user.decode_token(token)
        self.assertEqual(num, dec_num)
Example #19
0
class TestSleep(unittest.TestCase):
    """
    Tests for Sleep.py
    """
    @classmethod
    def setUpClass(self):
        """
        Set up the unittest.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.sleep = Sleep(self.db, self.user_id)
        self.sleep_1 = Sleep(self.db, self.user_id_1)

        self.sleep_time = datetime.utcnow()
        self.wakeup_time = datetime.utcnow() + timedelta(minutes=1)
        self.sleep_dict = {'Nap': False,\
                           'SleepTime': self.sleep_time,\
                           'WakeupTime': self.wakeup_time}

        self.sleep_time_1 = datetime.utcnow()
        self.wakeup_time_1 = datetime.utcnow() + timedelta(minutes=2)
        self.sleep_dict_1 = {'Nap': False,\
                           'SleepTime': self.sleep_time_1,\
                           'WakeupTime': self.wakeup_time_1}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())

    def test_0_data_insertion(self):
        """
        Test data insertion for sleep for a single user.
        """
        s = self.sleep.insert_in_database(self.sleep_dict, date_time=self.dt1)
        self.assertTrue(s)

    def test_1_data_insertion_multiple_user(self):
        """
        Test data insertion for sleep for multiple users.
        """
        s = self.sleep.insert_in_database(self.sleep_dict, date_time=self.dt1)
        self.assertTrue(s)
        s_1 = self.sleep_1.insert_in_database(self.sleep_dict_1,
                                              date_time=self.dt1)
        self.assertTrue(s_1)

    def test_2_incorrect_key(self):
        """
        Test for incorrect keys.
        """
        d = copy.deepcopy(self.sleep_dict)
        del (d['Nap'])
        d['NapS'] = False
        self.assertFalse(self.sleep.insert_in_database(d))

        d = copy.deepcopy(self.sleep_dict)
        del (d['SleepTime'])
        d['SleepTimeS'] = datetime.utcnow()
        self.assertFalse(self.sleep.insert_in_database(d))

        d = copy.deepcopy(self.sleep_dict)
        del (d['WakeupTime'])
        d['WakeupTimeS'] = datetime.utcnow()
        self.assertFalse(self.sleep.insert_in_database(d))

    def test_3_incorrect_value(self):
        """
        Test for incorrect value data type.
        """
        d = copy.deepcopy(self.sleep_dict)
        d['Nap'] = 10
        self.assertFalse(self.sleep.insert_in_database(d))

        d = copy.deepcopy(self.sleep_dict)
        d['SleepTime'] = 10
        self.assertFalse(self.sleep.insert_in_database(d))

        d = copy.deepcopy(self.sleep_dict)
        d['WakeupTime'] = 10
        self.assertFalse(self.sleep.insert_in_database(d))

    def test_4_data_fetching_unix_time_and_insertion(self):
        """
        Test fetching sleep data from database and the UNIX TIMESTAMP.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.sleep.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))
        self.assertTrue(success)
        self.assertEqual(result[0]['Datetime'], self.unix_time)

    def test_5_data_fetching_value(self):
        """
        Test fetching sleep data from database for multiple users.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.sleep.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))
        self.assertTrue(success)
        self.assertEqual(
            result[0]['SleepTime'],
            round(self.sleep_time.replace(tzinfo=timezone.utc).timestamp()))
        self.assertEqual(
            result[0]['WakeupTime'],
            round(self.wakeup_time.replace(tzinfo=timezone.utc).timestamp()))
        self.assertFalse(result[0]['Nap'])
        self.assertEqual(result[0]['Minutes'], 1)

        result_1, success_1 = self.sleep_1.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success_1)
        self.assertEqual(
            result_1[0]['SleepTime'],
            round(self.sleep_time_1.replace(tzinfo=timezone.utc).timestamp()))
        self.assertEqual(
            result_1[0]['WakeupTime'],
            round(self.wakeup_time_1.replace(tzinfo=timezone.utc).timestamp()))
        self.assertFalse(result_1[0]['Nap'])
        self.assertEqual(result_1[0]['Minutes'], 2)

        sleep = Sleep(None, self.user_id_1)
        result, success = sleep.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))
        self.assertFalse(success)

    def test_6_minutes_computation(self):
        """
        Test the minute computation in sleep.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.sleep.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success)
        self.assertEqual(result[0]['Minutes'], 1)

    def test_7_incorrect_data_fetching(self):
        """
        Test fetching sleep data from database.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.sleep.get_columns_given_range(
            dt1 + timedelta(days=10), dt1 + timedelta(days=11))

        self.assertFalse(success)

    def test_8_data_fetching_multiple(self):
        """
        Test fetching of multiple sleep entries from database.
        """
        d = {
               'Nap': False,\
               'SleepTime': datetime.utcnow() + timedelta(days=1),\
               'WakeupTime': datetime.utcnow() + timedelta(days=1) + timedelta(minutes=1)}
        _ = self.sleep.insert_in_database(d)
        d = {
               'Nap': False,\
               'SleepTime': datetime.utcnow() + timedelta(days=1),\
               'WakeupTime': datetime.utcnow() + timedelta(days=1) + timedelta(minutes=2)}
        _ = self.sleep.insert_in_database(d)
        d = {
               'Nap': False,\
               'SleepTime': datetime.utcnow() + timedelta(days=1),\
               'WakeupTime': datetime.utcnow() + timedelta(days=1) + timedelta(minutes=3)}
        _ = self.sleep.insert_in_database(d)
        d1 = date.today() + timedelta(days=1)
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.sleep.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success)
        self.assertEqual(len(result), 3)
        self.assertEqual(result[0]['Minutes'], 1)
        self.assertEqual(result[1]['Minutes'], 2)
        self.assertEqual(result[2]['Minutes'], 3)

    def test_9_incorrect_database(self):
        """
        Test database insertion for a single user with incorrect database. Test case to increase the coverage. 
        """
        sleep = Sleep(None, self.user_id_1)
        s = sleep.insert_in_database(self.sleep_dict, date_time=self.dt1)
        self.assertFalse(s)
Example #20
0
def load_user(user_id):
    return User.get(user_id)
Example #21
0
def fake_decode_token(token) -> User:
    return User(
        username=token + "fakedecoded", email="*****@*****.**", full_name="John Doe"
    )
Example #22
0
class TestDiet(unittest.TestCase):
    """
    Tests for Diet.py
    """
    @classmethod
    def setUpClass(self):
        """
        Set up the unit test.
        """
        self.db = DB()

        self.email = '*****@*****.**'
        self.password = '******'
        self.fullname = 'ABC'

        self.user = User(self.db)
        self.user.create_new_user(self.email, self.password, self.fullname)
        self.user_id = self.user.check_email_match(self.email)

        self.email_1 = '*****@*****.**'
        self.password_1 = 'klmno'
        self.fullname_1 = 'XYZ'

        self.user_1 = User(self.db)
        self.user_1.create_new_user(self.email_1, self.password_1,
                                    self.fullname_1)
        self.user_id_1 = self.user_1.check_email_match(self.email_1)

        self.email_2 = '*****@*****.**'
        self.password_2 = 'qqq'
        self.fullname_2 = 'ASD'

        self.user_2 = User(self.db)
        self.user_2.create_new_user(self.email_2, self.password_2,
                                    self.fullname_2)
        self.user_id_2 = self.user_2.check_email_match(self.email_2)

        self.diet = Diet(self.db, self.user_id)
        self.diet_1 = Diet(self.db, self.user_id_1)
        self.diet_2 = Diet(self.db, self.user_id_2)


        self.diet_dict = {'Item': 'Apple',\
                         'ServingSize': 1.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}}
        self.diet_dict_1 = {'Item': 'Orange',\
                         'ServingSize': 2.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 105.0,'Protein': 105.0, 'Carbs': 105.0, 'Fat': 105.0, 'Fiber': 105.0}}
        self.diet_dict_2 = {'Item': 'banana',\
                         'ServingSize': 2.0,\
                         'Barcode': False,\
                         'nutri_dict': {'Cals': 101.0,'Protein': 101.0, 'Carbs': 101.0, 'Fat': 101.0, 'Fiber': 101.0}}

        self.dt1 = datetime.utcnow()
        self.unix_time = round(time.time())

    def test_0_data_insertion(self):
        """
        Test database insertion for a single user. 
        """
        s = self.diet.insert_in_database(self.diet_dict, date_time=self.dt1)
        self.assertEqual(s, True)

    def test_1_data_insertion_multiple_users(self):
        """
        Test database insertion for multiple users.
        """
        s = self.diet.insert_in_database(self.diet_dict, date_time=self.dt1)
        self.assertEqual(s, True)
        s_1 = self.diet_1.insert_in_database(self.diet_dict_1,
                                             date_time=self.dt1)
        self.assertEqual(s_1, True)
        s_2 = self.diet_2.insert_in_database(self.diet_dict_2)
        self.assertEqual(s_2, True)

    def test_2_incorrect_key(self):
        """
        Test for incorrect keys. The function should return False if the input dictionary keys are incorrect.
        """
        d = copy.deepcopy(self.diet_dict)
        del (d['Item'])
        d['ItemS'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['ServingSize'])
        d['ServinsSizeS'] = 1.0
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['Barcode'])
        d['BarcodeS'] = False
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict'])
        d['nutri_dictS'] = {
            'Cals': 100.0,
            'Protein': 100.0,
            'Carbs': 100.0,
            'Fat': 100.0,
            'Fiber': 100.0
        }
        self.assertFalse(self.diet.insert_in_database(d))

    def test_3_incorrect_key_1(self):
        """
        Test for incorrect keys in the nutri_dict. The function should return False if the nutrient names is incorrect.
        """
        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict']['Cals'])
        d['nutri_dict']['CalsS'] = 100.0
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict']['Protein'])
        d['nutri_dict']['ProteinS'] = 100.0
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict']['Carbs'])
        d['nutri_dict']['CarbS'] = 100.0
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict']['Fat'])
        d['nutri_dict']['FatS'] = 100.0
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        del (d['nutri_dict']['Fiber'])
        d['nutri_dict']['FiberS'] = 100.0
        self.assertFalse(self.diet.insert_in_database(d))

    def test_4_incorrect_value(self):
        """
        Test for incorrect value data type.
        """
        d = copy.deepcopy(self.diet_dict)
        d['Item'] = 1
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['ServingSize'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['Barcode'] = 1
        self.assertFalse(self.diet.insert_in_database(d))

    def test_5_incorrect_value_1(self):
        """
        Test for incorrect value data type in the nutrients dictionary.
        """
        d = copy.deepcopy(self.diet_dict)
        d['nutri_dict']['Cals'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['nutri_dict']['Protein'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['nutri_dict']['Fiber'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['nutri_dict']['Carbs'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

        d = copy.deepcopy(self.diet_dict)
        d['nutri_dict']['Fat'] = 'Apple'
        self.assertFalse(self.diet.insert_in_database(d))

    def test_6_data_fetching_unix_time_and_insertion(self):
        """
        Test fetching diet data from database and also checks if the UNIX TIMESTAMP is correct.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.diet.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))
        self.assertTrue(success)
        self.assertEqual(result[0]['Datetime'], self.unix_time)

    def test_7_data_fetching_values(self):
        """
        Test fetching diet data from database for multiple users. 
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.diet.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success)
        self.assertEqual(result[0]['Item'], 'Apple')
        self.assertEqual(result[0]['ServingSize'], 1.0)
        self.assertEqual(result[0]['Cals'], 100.0)
        self.assertEqual(result[0]['Fiber'], 100.0)
        self.assertEqual(result[0]['Carbs'], 100.0)
        self.assertEqual(result[0]['Fat'], 100.0)
        self.assertEqual(result[0]['Protein'], 100.0)
        self.assertFalse(result[0]['Barcode'])

        result_1, success_1 = self.diet_1.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success_1)
        self.assertEqual(result_1[0]['Item'], 'Orange')
        self.assertEqual(result_1[0]['ServingSize'], 2.0)
        self.assertEqual(result_1[0]['Cals'], 105.0)
        self.assertEqual(result_1[0]['Fiber'], 105.0)
        self.assertEqual(result_1[0]['Carbs'], 105.0)
        self.assertEqual(result_1[0]['Fat'], 105.0)
        self.assertEqual(result_1[0]['Protein'], 105.0)
        self.assertFalse(result_1[0]['Barcode'])

    def test_8_incorrect_data_fetching(self):
        """
        Test fetching diet data from the database for incorrect date range. The function 
        should return False.
        """
        d1 = date.today()
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.diet.get_columns_given_range(
            dt1 + timedelta(days=10), dt1 + timedelta(days=11))
        self.assertFalse(success)

    def test_9_data_fetching_multiple(self):
        """
        Test fetching multiple diet entries from the database.
        """
        d = {'Item': 'Apple',\
             'ServingSize': 1.0,\
             'Barcode': False,\
             'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}}
        _ = self.diet.insert_in_database(d,
                                         date_time=datetime.utcnow() +
                                         timedelta(days=1) +
                                         timedelta(minutes=1))
        d = {'Item': 'Orange',\
             'ServingSize': 1.0,\
             'Barcode': False,\
             'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}}
        _ = self.diet.insert_in_database(d,
                                         date_time=datetime.utcnow() +
                                         timedelta(days=1) +
                                         timedelta(minutes=2))
        d = {'Item': 'Banana',\
             'ServingSize': 1.0,\
             'Barcode': False,\
             'nutri_dict': {'Cals': 100.0,'Protein': 100.0, 'Carbs': 100.0, 'Fat': 100.0, 'Fiber': 100.0}}
        _ = self.diet.insert_in_database(d,
                                         date_time=datetime.utcnow() +
                                         timedelta(days=1) +
                                         timedelta(minutes=3))
        d1 = date.today() + timedelta(days=1)
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = self.diet.get_columns_given_range(
            dt1, dt1 + timedelta(days=1))

        self.assertTrue(success)
        self.assertEqual(len(result), 3)
        self.assertEqual(result[0]['Item'], 'Apple')
        self.assertEqual(result[1]['Item'], 'Orange')
        self.assertEqual(result[2]['Item'], 'Banana')

    def test_10_incorrect_database(self):
        """
        Test database insertion for a single user with incorrect database. Test case to increase the coverage. 
        """
        diet = Diet(None, self.user_id_2)
        s = diet.insert_in_database(self.diet_dict, date_time=self.dt1)
        self.assertFalse(s)
        d1 = date.today() + timedelta(days=1)
        dt1 = datetime(d1.year, d1.month, d1.day) + timedelta(hours=8)
        result, success = diet.get_columns_given_range(dt1,
                                                       dt1 + timedelta(days=1))
        self.assertFalse(success)
Example #23
0
    def timed_payout(self):
        sleep(self.observation_period())
        self.payout(parse(self._stock_ticker))

    # timer for main method to return updated account balances in test
    def see_balances(self):
        for user, balance in self._for_map.items():
            print(user, " voted for and has: ", balance)

        for user, balance in self._against_map.items():
            print(user, " voted against and has: ")


if __name__ == '__main__':
    database = Database()
    timmy = User(database, 'timmy')
    timmy.update_rep(100.0)
    timmy.update_bank(100.0)
    bet = Bet(timmy, database, 'FB', -1, 0.0, 50.0, 60)
    print(bet.get_current_price())
'''
if __name__ == '__main__':
    database = Database()
    timmy = User(database, 'timmy')
    timmy.update_rep(100.0)
    timmy.update_bank(100.0)
    bet = Bet(timmy, database, 'FB', -1, 0.0, 50.0, 60)
    loop = True
    timer = Timer(60.0, bet.see_balances)
    timer.start()