Example #1
0
    def test_create_new_person_with_drink(self, save_new_user_in_database):
        # Select the first option to create
        test_name = ' TestName '
        drink_option = '1'

        # INPUTS
        # Julio: Repeated name to verify that it is not allowed to repeat name in the list of persons
        # TestName: Unique name
        # 'Y': option to select that I want to add the favorite drink of the new period.
        # '99': Incorrect number for the moment of choosing a drink from the list.
        # drinkOption: Correct number for the moment of choosing a drink from the list
        input_values = ['Julio', test_name, 'Y', '99', drink_option]
        mock_inputs(input_values)

        people = [Person('Julio'), Person('Dani')]
        drinks = [Drink('Water'), Drink('Coffee')]

        save_new_user_in_database.return_value = Person(
            test_name.strip(), drinks[int(drink_option) - 1], 12)

        people = functions.create_new_person(people, drinks)

        self.assertTrue(len(people) == 3)
        self.assertTrue(people[-1].name == test_name.strip())
        self.assertTrue(
            people[-1].favourite_drink.name == drinks[int(drink_option) -
                                                      1].name)
Example #2
0
    def test_add_drink(self):
        new_drink_name = 'Beer'
        drinks = [Drink('Water'), Drink('Coffee')]
        input_values = ['Water', new_drink_name]
        mock_inputs(input_values)

        new_drinks = functions.add_drink(drinks)

        self.assertTrue(len(new_drinks) == 3)
        self.assertTrue(drinks[len(drinks) - 1].name == new_drink_name)
Example #3
0
    def test_add_drink(self, save_new_drink_in_database):
        new_drink_name = 'Beer'
        drink_id = 12
        drinks = [Drink('Water'), Drink('Coffee')]
        input_values = ['Water', new_drink_name]
        mock_inputs(input_values)

        save_new_drink_in_database.return_value = Drink(new_drink_name,
                                                        drink_id=drink_id)

        new_drinks = functions.add_drink(drinks)

        self.assertTrue(len(new_drinks) == 3)
        self.assertTrue(drinks[-1].name == new_drink_name)
        self.assertTrue(drinks[-1].drink_id == drink_id)
Example #4
0
    def test_set_favourite_drink(self):

        # INPUTS
        #   '1': person id in the people list
        #   '2': drink id in the drinks list
        input_values = ['1', '2']
        mock_inputs(input_values)

        people = [Person('Julio'), Person('Dani')]
        drinks = [Drink('Water'), Drink('Coffee')]

        people = functions.set_favourite_drink(people, drinks)

        self.assertTrue(people[0].name == 'Julio')
        self.assertTrue(people[0].favourite_drink.name == drinks[1].name)
        self.assertTrue(people[1].favourite_drink == None)
Example #5
0
def read_rounds(filepath):
    rounds = []
    try:
        with open(filepath, "r") as rounds_file:
            for line in rounds_file.readlines():
                orders = line.strip().split(";")
                date = datetime.strptime(orders[0], texts.DATE_FORMAT)
                brewer = orders[1]
                round_orders = []
                for order in orders[2:]:
                    _order = order.split(",")
                    round_orders.append(
                        Order(Person(_order[0]), Drink(_order[1])))

                rounds.append(Round(round_orders, date, Person(brewer)))
    except FileNotFoundError as filenotfound:
        print(
            f"Could no open the file {filepath}. /nError: {str(filenotfound)}")
        error_opening_file()
    except Exception as e:
        print(
            f"Error opening the file {filepath}. /nError: {str(e)}")
        error_opening_file()

    return rounds
Example #6
0
def web_drinks():
    if request.method == 'GET':
        drinks = get_drinks_from_database()

        return render_template('drinks.html', title='Drinks', drinks=drinks)

    if request.method == 'POST':
        drink_name = request.form.get('drink_name')
        drinks = get_drinks_from_database()
        if len(drink_name) == 0:
            return render_template(
                'drinks.html',
                title='Drinks',
                drinks=drinks,
                error_message='The name of the drink cannot be empty')
        if len(search_drinks_by_name_from_database(drink_name)) > 0:
            return render_template(
                'drinks.html',
                title='Drinks',
                drinks=drinks,
                error_message='There is already a drink with that name')
        new_drink = Drink(drink_name)
        saved_drink = save_new_drink_in_database(new_drink)
        drinks.append(saved_drink)
        return render_template('drinks.html', title='Drinks', drinks=drinks)
    else:
        return "Unsupported HTTP Request Type"
Example #7
0
def get_rounds_from_database(is_open_filter=None):
    rounds = []

    db = Database(Config)

    query = """
       	SELECT r.is_open, r.brewer as brewer_id, r.open_date, r.round_id,
        p.name as brewer_name, p2.name as person_name, d.name as drink_name,
        d.drink_id, p2.person_id, o.order_id
       	FROM BrewOrder as o
       	RIGHT JOIN BrewRound as r
       	ON o.round_id = r.round_id
        INNER JOIN Person as p
        ON p.person_id = r.brewer
       	LEFT JOIN Drink as d
        ON d.drink_id = o.drink_id
        LEFT JOIN Person as p2
        ON p2.person_id = o.person_id
        """

    if is_open_filter != None and isinstance(is_open_filter, bool):
        query += f" WHERE r.is_open={int(is_open_filter)}"

    query += " ORDER BY r.round_id"

    db_rounds = db.run_query(query)

    rounds = []
    if len(db_rounds) != 0:
        curret_round = db_rounds[0]
        round_orders = []
        for idx, order in enumerate(db_rounds):
            if curret_round['round_id'] != order['round_id'] or idx == len(
                    db_rounds):
                rounds.append(
                    Round(
                        round_orders, curret_round['open_date'],
                        Person(curret_round['brewer_name'], None,
                               curret_round['brewer_id']),
                        curret_round['is_open'], curret_round['round_id']))
                curret_round = order
                round_orders = []
            if order['person_name']:
                round_orders.append(
                    Order(
                        Person(order['person_name'],
                               person_id=order['person_id']),
                        Drink(order['drink_name'], order['drink_id']),
                        order['order_id']))

        rounds.append(
            Round(
                round_orders, curret_round['open_date'],
                Person(curret_round['brewer_name'], None,
                       curret_round['brewer_id']), curret_round['is_open'],
                curret_round['round_id']))

    return rounds
Example #8
0
def add_drink(drinks):
    """
    Auxiliary function to ask and add a new drink, in cache and write in the file.
    +Parameters:
        - drinks: list of drinks
    """

    drink = ask_unique_name(drinks, texts.DRINK_NAME)
    if len(drink) != 0:
        drinks.append(Drink(drink))
    return drinks
Example #9
0
def get_drinks_from_database():
    drinks = []

    db = Database(Config)

    db_drinks = db.run_query("""SELECT * FROM Drink""")

    for drink in db_drinks:
        drinks.append(Drink(drink['name'], drink['drink_id']))

    return drinks
Example #10
0
    def test_create_new_person_without_drink(self):
        # Select the first option to create
        testName = ' TestName '

        # INPUTS
        # Julio: Repeated name to verify that it is not allowed to repeat name in the list of persons
        # TestName: Unique name
        # 'N': option to select that I don't want to add the favorite drink of the new period.
        # '99': Incorrect number for the moment of choosing a drink from the list.
        # drinkOption: Correct number for the moment of choosing a drink from the list
        input_values = ['Julio', 'TestName', 'N']
        mock_inputs(input_values)

        people = [Person('Julio'), Person('Dani')]
        drinks = [Drink('Water'), Drink('Coffee')]

        functions.create_new_person(people, drinks)

        self.assertTrue(len(people) == 3)
        self.assertTrue(people[len(people) - 1].name == testName.strip())
        self.assertTrue(people[len(people) - 1].favourite_drink == None)
Example #11
0
def get_drink_by_id_from_database(drink_id):

    db = Database(Config)

    db_drinks = db.run_query(
        f"""SELECT * FROM Drink AS d WHERE d.drink_id = {int(drink_id)} """)

    if len(db_drinks) != 0:
        drink = db_drinks[0]
        return Drink(drink['name'], drink['drink_id'])
    else:
        return None
Example #12
0
def search_drinks_by_name_from_database(drink_name):
    drinks = []

    db = Database(Config)

    db_drinks = db.run_query(
        f"""SELECT * FROM Drink AS d WHERE upper(d.name) = '{drink_name.strip().upper()}' """
    )

    for drink in db_drinks:
        drinks.append(Drink(drink['name'], drink['drink_id']))

    return drinks
Example #13
0
def post_drink(handler, data):
    try:
        new_drink = Drink(data["name"])
        save_new_drink_in_database(new_drink)
        handler.send_response(201)
    except KeyError as e:
        print("JSON KEY ERRORS: " + str(e))
        handler.send_response(400)
    except DatabaseError:
        handler.send_response(500)
        print(texts.DATABASE_ERROR + texts.DRINK_NOT_ADDED)
    finally:
        handler.end_headers()
Example #14
0
def post_people(handler, data):
    try:
        new_person = Person(data['name'], Drink('',
                                                data['favourite_drink_id']))
        save_new_user_in_database(new_person)
        handler.send_response(201)
    except KeyError as e:
        print("JSON KEY ERRORS: " + str(e))
        handler.send_response(400)
    except DatabaseError:
        handler.send_response(500)
        print(texts.DATABASE_ERROR + texts.ROUND_NOT_ADDED)
    finally:
        handler.end_headers()
Example #15
0
    def test_set_favourite_drink(self, update_user_in_database):

        person_id = '1'
        drink_id = '2'

        # INPUTS
        #   '1': person id in the people list
        #   '2': drink id in the drinks list
        input_values = [person_id, drink_id]
        mock_inputs(input_values)

        people = [Person('Julio'), Person('Dani')]
        drinks = [Drink('Water'), Drink('Coffee')]

        update_user_in_database.return_value = Person(
            people[int(person_id) - 1].name, drinks[int(drink_id) - 1].name,
            12)

        people = functions.set_favourite_drink(people, drinks)

        self.assertTrue(people[0].name == 'Julio')
        self.assertTrue(people[0].favourite_drink.name == drinks[1].name)
        self.assertTrue(people[1].favourite_drink == None)
Example #16
0
    def test_add_order_to_round(self, add_order_to_round_in_database):
        selected_person_id = '1'
        selected_drink_id = '1'
        people = [Person('Julio'), Person('Dani')]
        drinks = [Drink('Water'), Drink('Coffee')]
        rounds = [Round(brewer=people[0])]
        new_order = Order(people[int(selected_person_id) - 1],
                          drinks[int(selected_drink_id) - 1])
        orders = [new_order]
        expected_rounds = [Round(orders)]

        input_values = [selected_person_id, selected_drink_id]
        mock_inputs(input_values)

        add_order_to_round_in_database.return_value = new_order

        new_rounds = functions.add_order_to_round(people, drinks, rounds)

        self.assertTrue(new_rounds[-1].orders[-1].drink.name ==
                        expected_rounds[-1].orders[-1].drink.name)

        self.assertTrue(new_rounds[-1].orders[-1].person.name ==
                        expected_rounds[-1].orders[-1].person.name)
Example #17
0
def read_drinks_from_file(filepath):
    drinks = []
    try:
        with open(filepath, "r") as drinks_file:
            for drink in drinks_file.readlines():
                drinks.append(Drink(drink.strip()))
    except FileNotFoundError as filenotfound:
        print(
            f"Could no open the file {filepath}. /nError: {str(filenotfound)}")
        error_opening_file()
    except Exception as e:
        print(f"Error opening the file {filepath}. /nError: {str(e)}")
        error_opening_file()

    return drinks
Example #18
0
def get_person_by_id_from_database(person_id):

    db = Database(Config)

    db_users = db.run_query(
        f"""SELECT p.person_id, p.name as person_name, p.favourite_drink_id, d.name as drink_name
        FROM Person AS p INNER JOIN Drink as d ON p.favourite_drink_id = d.drink_id WHERE p.person_id = {person_id} """
    )

    if len(db_users) != 0:
        user = db_users[0]
        return Person(user['person_name'],
                      Drink(user['drink_name'], user['favourite_drink_id']),
                      user['person_id'])
    else:
        return None
Example #19
0
def get_people_by_favourite_drink_from_database(drink_id):

    db = Database(Config)

    db_people = db.run_query(
        f"""SELECT p.person_id, p.name as person_name, p.favourite_drink_id, d.name as drink_name
        FROM Person AS p INNER JOIN Drink as d ON p.favourite_drink_id = d.drink_id WHERE p.favourite_drink_id = {drink_id} """
    )

    people = []
    for person in db_people:
        people.append(
            Person(person['person_name'],
                   Drink(person['drink_name'], person['favourite_drink_id']),
                   person['person_id']))
    return people
Example #20
0
def post_add_order_to_round(handler, data):
    try:
        open_round = Round(round_id=data['round_id'])
        new_order = Order(Person(person_id=data['person_id']),
                          Drink(drink_id=data['drink_id']))

        add_order_to_round_in_database(open_round, new_order)

        handler.send_response(201)
    except KeyError as e:
        print("JSON KEY ERRORS: " + str(e))
        handler.send_response(400)
    except DatabaseError:
        handler.send_response(500)
        print(texts.DATABASE_ERROR + texts.ROUND_NOT_ADDED)
    finally:
        handler.end_headers()
Example #21
0
def get_people_from_database():
    users = []

    db = Database(Config)

    db_users = db.run_query(
        """SELECT p.person_id, p.name as person_name, p.favourite_drink_id, d.name as drink_name
        FROM Person AS p LEFT JOIN Drink as d ON p.favourite_drink_id = d.drink_id"""
    )

    for user in db_users:
        users.append(
            Person(user['person_name'],
                   Drink(user['drink_name'], user['favourite_drink_id']),
                   user['person_id']))

    return users
Example #22
0
def search_person_by_name(person_name):
    db = Database(Config)

    people = []

    db_users = db.run_query(
        f"""SELECT p.person_id, p.name as person_name, p.favourite_drink_id, d.name as drink_name
        FROM Person AS p INNER JOIN Drink as d ON p.favourite_drink_id = d.drink_id WHERE upper(p.name) = '{person_name.strip().upper()}' """
    )

    if len(db_users) != 0:
        for user in db_users:
            people.append(
                Person(user['person_name'],
                       Drink(user['drink_name'], user['favourite_drink_id']),
                       user['person_id']))

    return people
Example #23
0
def add_drink(drinks):
    """
    Auxiliary function to ask and add a new drink, in cache and write in the file.
    +Parameters:
        - drinks: list of drinks
    """

    drink_name = ask_unique_name(drinks, texts.DRINK_NAME)
    if len(drink_name) != 0:

        try:
            drink_saved = drinks_controller.save_new_drink_in_database(
                Drink(drink_name))
            drinks.append(drink_saved)
        except DatabaseError:
            print(texts.DATABASE_ERROR + texts.DRINK_NOT_ADDED)

    return drinks
Example #24
0
def read_people_from_file(filepath):
    people = []
    try:
        with open(filepath, "r") as people_file:
            for person in people_file.readlines():
                line = person.split(":")
                drink = None
                if line[1].strip() != 'None':
                    drink = Drink(line[1].strip())
                people.append(Person(line[0], drink))
    except FileNotFoundError as filenotfound:
        print(
            f"Could no open the file {filepath}. /nError: {str(filenotfound)}")
        error_opening_file()
    except Exception as e:
        print(f"Error opening the file {filepath}. /nError: {str(e)}")
        error_opening_file()

    return people
Example #25
0
def get_round_by_id(round_id):

    db = Database(Config)

    query = f"""
       	SELECT r.is_open, r.brewer as brewer_id, r.open_date, r.round_id,
        p.name as brewer_name, p2.name as person_name, d.name as drink_name,
        d.drink_id, p2.person_id, o.order_id
       	FROM BrewOrder as o
       	RIGHT JOIN BrewRound as r
       	ON o.round_id = r.round_id
        INNER JOIN Person as p
        ON p.person_id = r.brewer
       	LEFT JOIN Drink as d
        ON d.drink_id = o.drink_id
        LEFT JOIN Person as p2
        ON p2.person_id = o.person_id
        WHERE r.round_id = {round_id}
        """

    db_orders = db.run_query(query)

    if len(db_orders) == 0:
        return None

    round_orders = []
    for order in db_orders:
        if order['person_name']:
            round_orders.append(
                Order(
                    Person(order['person_name'], person_id=order['person_id']),
                    Drink(order['drink_name'], order['drink_id']),
                    order['order_id']))

    rount_to_return = Round(
        round_orders, db_orders[0]['open_date'],
        Person(db_orders[0]['brewer_name'], None, db_orders[0]['brewer_id']),
        db_orders[0]['is_open'], db_orders[0]['round_id'])

    return rount_to_return
Example #26
0
def api_get_drinks():
    if request.method == 'GET':
        drinks = get_drinks_from_database()
        return {'Drinks': [drink.to_json() for drink in drinks]}

    if request.method == 'POST':
        data = request.get_json() or {}
        if 'name' not in data:
            return Response(status=400, response='must include name field')
        if len(search_drinks_by_name_from_database(data['name'])) > 0:
            return Response(status=400,
                            response='there is already a drink with that name')

        new_drink = Drink(data['name'])
        save_drink = save_new_drink_in_database(new_drink)
        response = jsonify(save_drink.to_json())
        response.status_code = 201

        return response

    else:
        return "Unsupported HTTP Request Type"
Example #27
0
def save_new_drink_in_database(new_drink: Drink):
    db = Database(Config)
    new_drink.drink_id = db.run_query(f"""INSERT INTO Drink(name) 
        VALUES ('{new_drink.name}')""")
    return new_drink