diff --git a/__pycache__/database.cpython-312.pyc b/__pycache__/database.cpython-312.pyc new file mode 100644 index 000000000000..a41e9406feb3 Binary files /dev/null and b/__pycache__/database.cpython-312.pyc differ diff --git a/app.py b/app.py new file mode 100644 index 000000000000..5f5ac3986be5 --- /dev/null +++ b/app.py @@ -0,0 +1,137 @@ +import streamlit as st +from controllers.user_controller import create_user, authenticate_user +from controllers.category_controller import create_category, get_categories +from controllers.product_controller import create_product, get_products +from controllers.shopping_list_controller import create_shopping_list, get_shopping_lists, add_item_to_list, get_list_items, get_shopping_list_by_id +from controllers.stock_controller import add_to_stock, get_stock, remove_from_stock + +def main(): + st.title("Lista de Compras") + + if 'user' not in st.session_state: + st.session_state.user = None + + if st.session_state.user: + st.write(f"Bem-vindo, {st.session_state.user['username']}!") + if st.button("Logout"): + st.session_state.user = None + st.rerun() + + st.header("Categorias") + category_name = st.text_input("Nova Categoria") + if st.button("Adicionar Categoria"): + if create_category(category_name) is not None: + st.success("Categoria adicionada com sucesso!") + else: + st.error("Erro ao adicionar categoria.") + + st.header("Produtos") + product_name = st.text_input("Novo Produto") + categories = get_categories() + category_id = st.selectbox("Categoria", [c['id'] for c in categories], format_func=lambda x: [c['name'] for c in categories if c['id'] == x][0]) + if st.button("Adicionar Produto"): + if create_product(product_name, category_id) is not None: + st.success("Produto adicionado com sucesso!") + else: + st.error("Erro ao adicionar produto.") + + st.header("Minhas Listas de Compras") + + st.subheader("Criar Nova Lista") + list_name = st.text_input("Nome da Nova Lista") + if st.button("Criar"): + list_id = create_shopping_list(list_name, st.session_state.user['id']) + if list_id: + st.success(f"Lista '{list_name}' criada com sucesso!") + else: + st.error("Erro ao criar lista.") + + st.subheader("Importar Lista") + shared_link = st.text_input("Link da Lista Compartilhada") + if st.button("Importar"): + try: + shared_list_id = int(shared_link.split("=")[-1]) + shared_list = get_shopping_list_by_id(shared_list_id) + if shared_list: + new_list_id = create_shopping_list(f"Importada - {shared_list['name']}", st.session_state.user['id']) + if new_list_id: + items = get_list_items(shared_list_id) + for item in items: + add_item_to_list(new_list_id, item['product_id'], item['quantity']) + st.success("Lista importada com sucesso!") + else: + st.error("Erro ao importar lista.") + else: + st.error("Lista compartilhada não encontrada.") + except: + st.error("Link inválido.") + + shopping_lists = get_shopping_lists(st.session_state.user['id']) + selected_list_id = st.selectbox("Selecione uma lista", [l['id'] for l in shopping_lists], format_func=lambda x: [l['name'] for l in shopping_lists if l['id'] == x][0]) + + if selected_list_id: + st.header(f"Itens da Lista") + + share_url = f"http://localhost:8501/?list_id={selected_list_id}" + st.write(f"Link para compartilhar: `{share_url}`") + + products = get_products() + product_id = st.selectbox("Produto", [p['id'] for p in products], format_func=lambda x: [p['name'] for p in products if p['id'] == x][0]) + quantity = st.number_input("Quantidade", min_value=1, value=1) + if st.button("Adicionar Item"): + if add_item_to_list(selected_list_id, product_id, quantity): + st.success("Item adicionado com sucesso!") + else: + st.error("Erro ao adicionar item.") + + items = get_list_items(selected_list_id) + for item in items: + col1, col2 = st.columns([3, 1]) + with col1: + st.write(f"- {item['name']} (Quantidade: {item['quantity']})") + with col2: + if st.button("Comprar", key=f"buy_{item['id']}"): + if add_to_stock(st.session_state.user['id'], item['product_id'], item['quantity']): + st.success(f"{item['name']} adicionado ao estoque!") + else: + st.error("Erro ao adicionar ao estoque.") + + st.header("Meu Estoque") + stock_items = get_stock(st.session_state.user['id']) + for item in stock_items: + col1, col2, col3 = st.columns([2, 1, 1]) + with col1: + st.write(f"- {item['name']} (Quantidade: {item['quantity']})") + with col2: + quantity_to_remove = st.number_input("Quantidade a remover", min_value=1, max_value=item['quantity'], value=1, key=f"remove_qty_{item['id']}") + with col3: + if st.button("Dar Baixa", key=f"remove_{item['id']}"): + if remove_from_stock(item['id'], quantity_to_remove): + st.success("Baixa realizada com sucesso!") + st.rerun() + else: + st.error("Erro ao dar baixa no estoque.") + + else: + choice = st.selectbox("Login ou Cadastro", ["Login", "Cadastro"]) + if choice == "Login": + username = st.text_input("Usuário") + password = st.text_input("Senha", type="password") + if st.button("Login"): + user = authenticate_user(username, password) + if user: + st.session_state.user = user + st.rerun() + else: + st.error("Usuário ou senha inválidos") + else: + username = st.text_input("Usuário") + password = st.text_input("Senha", type="password") + if st.button("Cadastrar"): + if create_user(username, password) is not None: + st.success("Usuário criado com sucesso! Faça o login.") + else: + st.error("Este nome de usuário já existe.") + +if __name__ == "__main__": + main() diff --git a/controllers/__init__.py b/controllers/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/controllers/__pycache__/__init__.cpython-312.pyc b/controllers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 000000000000..211f7225891c Binary files /dev/null and b/controllers/__pycache__/__init__.cpython-312.pyc differ diff --git a/controllers/__pycache__/category_controller.cpython-312.pyc b/controllers/__pycache__/category_controller.cpython-312.pyc new file mode 100644 index 000000000000..cea021390bcd Binary files /dev/null and b/controllers/__pycache__/category_controller.cpython-312.pyc differ diff --git a/controllers/__pycache__/product_controller.cpython-312.pyc b/controllers/__pycache__/product_controller.cpython-312.pyc new file mode 100644 index 000000000000..cca4e5e5b672 Binary files /dev/null and b/controllers/__pycache__/product_controller.cpython-312.pyc differ diff --git a/controllers/__pycache__/shopping_list_controller.cpython-312.pyc b/controllers/__pycache__/shopping_list_controller.cpython-312.pyc new file mode 100644 index 000000000000..5c2e16098cb9 Binary files /dev/null and b/controllers/__pycache__/shopping_list_controller.cpython-312.pyc differ diff --git a/controllers/__pycache__/stock_controller.cpython-312.pyc b/controllers/__pycache__/stock_controller.cpython-312.pyc new file mode 100644 index 000000000000..099726678203 Binary files /dev/null and b/controllers/__pycache__/stock_controller.cpython-312.pyc differ diff --git a/controllers/__pycache__/user_controller.cpython-312.pyc b/controllers/__pycache__/user_controller.cpython-312.pyc new file mode 100644 index 000000000000..59f69c44b287 Binary files /dev/null and b/controllers/__pycache__/user_controller.cpython-312.pyc differ diff --git a/controllers/category_controller.py b/controllers/category_controller.py new file mode 100644 index 000000000000..ff8b41117948 --- /dev/null +++ b/controllers/category_controller.py @@ -0,0 +1,21 @@ +from database import get_db_connection + +def create_category(name): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("INSERT INTO categories (name) VALUES (?)", (name,)) + conn.commit() + return cursor.lastrowid + except: + return None + finally: + conn.close() + +def get_categories(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute("SELECT * FROM categories") + categories = cursor.fetchall() + conn.close() + return categories diff --git a/controllers/product_controller.py b/controllers/product_controller.py new file mode 100644 index 000000000000..560bece76fc6 --- /dev/null +++ b/controllers/product_controller.py @@ -0,0 +1,25 @@ +from database import get_db_connection + +def create_product(name, category_id): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("INSERT INTO products (name, category_id) VALUES (?, ?)", (name, category_id)) + conn.commit() + return cursor.lastrowid + except: + return None + finally: + conn.close() + +def get_products(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + SELECT p.id, p.name, c.name as category_name + FROM products p + JOIN categories c ON p.category_id = c.id + """) + products = cursor.fetchall() + conn.close() + return products diff --git a/controllers/shopping_list_controller.py b/controllers/shopping_list_controller.py new file mode 100644 index 000000000000..1a6c95fa6318 --- /dev/null +++ b/controllers/shopping_list_controller.py @@ -0,0 +1,54 @@ +from database import get_db_connection + +def create_shopping_list(name, user_id): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("INSERT INTO shopping_lists (name, user_id) VALUES (?, ?)", (name, user_id)) + conn.commit() + return cursor.lastrowid + except: + return None + finally: + conn.close() + +def get_shopping_lists(user_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute("SELECT * FROM shopping_lists WHERE user_id = ?", (user_id,)) + lists = cursor.fetchall() + conn.close() + return lists + +def add_item_to_list(shopping_list_id, product_id, quantity): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("INSERT INTO shopping_list_items (shopping_list_id, product_id, quantity) VALUES (?, ?, ?)", (shopping_list_id, product_id, quantity)) + conn.commit() + return True + except: + return False + finally: + conn.close() + +def get_list_items(shopping_list_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + SELECT sli.id, p.id as product_id, p.name, sli.quantity + FROM shopping_list_items sli + JOIN products p ON sli.product_id = p.id + WHERE sli.shopping_list_id = ? + """, (shopping_list_id,)) + items = cursor.fetchall() + conn.close() + return items + +def get_shopping_list_by_id(list_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute("SELECT * FROM shopping_lists WHERE id = ?", (list_id,)) + shopping_list = cursor.fetchone() + conn.close() + return shopping_list diff --git a/controllers/stock_controller.py b/controllers/stock_controller.py new file mode 100644 index 000000000000..411e45074711 --- /dev/null +++ b/controllers/stock_controller.py @@ -0,0 +1,51 @@ +from database import get_db_connection + +def add_to_stock(user_id, product_id, quantity): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("SELECT * FROM stock WHERE user_id = ? AND product_id = ?", (user_id, product_id)) + item = cursor.fetchone() + if item: + new_quantity = item['quantity'] + quantity + cursor.execute("UPDATE stock SET quantity = ? WHERE id = ?", (new_quantity, item['id'])) + else: + cursor.execute("INSERT INTO stock (user_id, product_id, quantity) VALUES (?, ?, ?)", (user_id, product_id, quantity)) + conn.commit() + return True + except: + return False + finally: + conn.close() + +def get_stock(user_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + SELECT s.id, p.name, s.quantity + FROM stock s + JOIN products p ON s.product_id = p.id + WHERE s.user_id = ? + """, (user_id,)) + stock = cursor.fetchall() + conn.close() + return stock + +def remove_from_stock(stock_id, quantity_to_remove): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute("SELECT * FROM stock WHERE id = ?", (stock_id,)) + item = cursor.fetchone() + if item: + new_quantity = item['quantity'] - quantity_to_remove + if new_quantity > 0: + cursor.execute("UPDATE stock SET quantity = ? WHERE id = ?", (new_quantity, stock_id)) + else: + cursor.execute("DELETE FROM stock WHERE id = ?", (stock_id,)) + conn.commit() + return True + except: + return False + finally: + conn.close() diff --git a/controllers/user_controller.py b/controllers/user_controller.py new file mode 100644 index 000000000000..e59c7de5af53 --- /dev/null +++ b/controllers/user_controller.py @@ -0,0 +1,28 @@ +import sqlite3 +from werkzeug.security import generate_password_hash, check_password_hash +from database import get_db_connection + +def create_user(username, password): + conn = get_db_connection() + cursor = conn.cursor() + try: + cursor.execute( + "INSERT INTO users (username, password) VALUES (?, ?)", + (username, generate_password_hash(password)) + ) + conn.commit() + return cursor.lastrowid + except sqlite3.IntegrityError: + return None + finally: + conn.close() + +def authenticate_user(username, password): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute("SELECT * FROM users WHERE username = ?", (username,)) + user = cursor.fetchone() + conn.close() + if user and check_password_hash(user['password'], password): + return user + return None diff --git a/database.py b/database.py new file mode 100644 index 000000000000..f58454f105ae --- /dev/null +++ b/database.py @@ -0,0 +1,73 @@ +import sqlite3 +import os + +def get_db_connection(): + db_name = 'test_shopping_list.db' if os.environ.get('TESTING') else 'shopping_list.db' + conn = sqlite3.connect(db_name) + conn.row_factory = sqlite3.Row + return conn + +def create_tables(): + conn = get_db_connection() + cursor = conn.cursor() + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + password TEXT NOT NULL + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS categories ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL UNIQUE + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS products ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + category_id INTEGER, + FOREIGN KEY (category_id) REFERENCES categories (id) + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS shopping_lists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + user_id INTEGER, + FOREIGN KEY (user_id) REFERENCES users (id) + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS shopping_list_items ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + shopping_list_id INTEGER, + product_id INTEGER, + quantity INTEGER NOT NULL, + FOREIGN KEY (shopping_list_id) REFERENCES shopping_lists (id), + FOREIGN KEY (product_id) REFERENCES products (id) + ) + ''') + + cursor.execute(''' + CREATE TABLE IF NOT EXISTS stock ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER, + product_id INTEGER, + quantity INTEGER NOT NULL, + FOREIGN KEY (user_id) REFERENCES users (id), + FOREIGN KEY (product_id) REFERENCES products (id) + ) + ''') + + conn.commit() + conn.close() + +if __name__ == '__main__': + create_tables() diff --git a/models/__init__.py b/models/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/models/category.py b/models/category.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/models/product.py b/models/product.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/models/shopping_list.py b/models/shopping_list.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/models/stock.py b/models/stock.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/models/user.py b/models/user.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 000000000000..a635c5c03182 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +pythonpath = . diff --git a/shopping_list.db b/shopping_list.db new file mode 100644 index 000000000000..970fcdf4340d Binary files /dev/null and b/shopping_list.db differ diff --git a/streamlit_app.py b/streamlit_app.py deleted file mode 100644 index ac305b93bffd..000000000000 --- a/streamlit_app.py +++ /dev/null @@ -1,38 +0,0 @@ -from collections import namedtuple -import altair as alt -import math -import pandas as pd -import streamlit as st - -""" -# Welcome to Streamlit! - -Edit `/streamlit_app.py` to customize this app to your heart's desire :heart: - -If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community -forums](https://discuss.streamlit.io). - -In the meantime, below is an example of what you can do with just a few lines of code: -""" - - -with st.echo(code_location='below'): - total_points = st.slider("Number of points in spiral", 1, 5000, 2000) - num_turns = st.slider("Number of turns in spiral", 1, 100, 9) - - Point = namedtuple('Point', 'x y') - data = [] - - points_per_turn = total_points / num_turns - - for curr_point_num in range(total_points): - curr_turn, i = divmod(curr_point_num, points_per_turn) - angle = (curr_turn + 1) * 2 * math.pi * i / points_per_turn - radius = curr_point_num / total_points - x = radius * math.cos(angle) - y = radius * math.sin(angle) - data.append(Point(x, y)) - - st.altair_chart(alt.Chart(pd.DataFrame(data), height=500, width=500) - .mark_circle(color='#0068c9', opacity=0.5) - .encode(x='x:Q', y='y:Q')) diff --git a/tests/__pycache__/conftest.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/conftest.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..488302a7a332 Binary files /dev/null and b/tests/__pycache__/conftest.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/__pycache__/test_category_controller.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/test_category_controller.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..62c35cd6ca8b Binary files /dev/null and b/tests/__pycache__/test_category_controller.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/__pycache__/test_product_controller.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/test_product_controller.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..060468f0074b Binary files /dev/null and b/tests/__pycache__/test_product_controller.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/__pycache__/test_shopping_list_controller.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/test_shopping_list_controller.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..244690e3b518 Binary files /dev/null and b/tests/__pycache__/test_shopping_list_controller.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/__pycache__/test_stock_controller.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/test_stock_controller.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..fa273e1cf67c Binary files /dev/null and b/tests/__pycache__/test_stock_controller.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/__pycache__/test_user_controller.cpython-312-pytest-8.4.1.pyc b/tests/__pycache__/test_user_controller.cpython-312-pytest-8.4.1.pyc new file mode 100644 index 000000000000..f98e7d408cdd Binary files /dev/null and b/tests/__pycache__/test_user_controller.cpython-312-pytest-8.4.1.pyc differ diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 000000000000..9f4232d7e3e3 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,36 @@ +import pytest +import sqlite3 +import os + +@pytest.fixture(scope='session', autouse=True) +def db_connection(): + db_path = 'test_shopping_list.db' + if os.path.exists(db_path): + os.remove(db_path) + + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, username TEXT UNIQUE, password TEXT)''') + cursor.execute('''CREATE TABLE categories (id INTEGER PRIMARY KEY, name TEXT UNIQUE)''') + cursor.execute('''CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, category_id INTEGER, FOREIGN KEY(category_id) REFERENCES categories(id))''') + cursor.execute('''CREATE TABLE shopping_lists (id INTEGER PRIMARY KEY, name TEXT, user_id INTEGER, FOREIGN KEY(user_id) REFERENCES users(id))''') + cursor.execute('''CREATE TABLE shopping_list_items (id INTEGER PRIMARY KEY, shopping_list_id INTEGER, product_id INTEGER, quantity INTEGER, FOREIGN KEY(shopping_list_id) REFERENCES shopping_lists(id), FOREIGN KEY(product_id) REFERENCES products(id))''') + cursor.execute('''CREATE TABLE stock (id INTEGER PRIMARY KEY, user_id INTEGER, product_id INTEGER, quantity INTEGER, FOREIGN KEY(user_id) REFERENCES users(id), FOREIGN KEY(product_id) REFERENCES products(id))''') + conn.commit() + + yield conn + + conn.close() + if os.path.exists(db_path): + os.remove(db_path) + +@pytest.fixture(autouse=True) +def clean_tables(db_connection): + cursor = db_connection.cursor() + cursor.execute("DELETE FROM users") + cursor.execute("DELETE FROM categories") + cursor.execute("DELETE FROM products") + cursor.execute("DELETE FROM shopping_lists") + cursor.execute("DELETE FROM shopping_list_items") + cursor.execute("DELETE FROM stock") + db_connection.commit() diff --git a/tests/test_category_controller.py b/tests/test_category_controller.py new file mode 100644 index 000000000000..0add46b85506 --- /dev/null +++ b/tests/test_category_controller.py @@ -0,0 +1,18 @@ +import pytest +from controllers.category_controller import create_category, get_categories +import os + +os.environ['TESTING'] = 'true' + +def test_create_category(): + assert create_category("Laticínios") == True + # Tente criar a mesma categoria novamente + assert create_category("Laticínios") == False + +def test_get_categories(): + create_category("Frutas") + create_category("Legumes") + categories = get_categories() + assert len(categories) == 2 + assert categories[0]['name'] == "Frutas" + assert categories[1]['name'] == "Legumes" diff --git a/tests/test_product_controller.py b/tests/test_product_controller.py new file mode 100644 index 000000000000..ef0447d1c37b --- /dev/null +++ b/tests/test_product_controller.py @@ -0,0 +1,20 @@ +import pytest +from controllers.product_controller import create_product, get_products +from controllers.category_controller import create_category +import os + +os.environ['TESTING'] = 'true' + +def test_create_product(): + category_id = create_category("Frutas") + assert create_product("Maçã", category_id) == True + +def test_get_products(): + category_id = create_category("Frutas") + create_product("Maçã", category_id) + create_product("Banana", category_id) + products = get_products() + assert len(products) == 2 + assert products[0]['name'] == "Maçã" + assert products[1]['name'] == "Banana" + assert products[0]['category_name'] == "Frutas" diff --git a/tests/test_shopping_list_controller.py b/tests/test_shopping_list_controller.py new file mode 100644 index 000000000000..7da8b508a77e --- /dev/null +++ b/tests/test_shopping_list_controller.py @@ -0,0 +1,49 @@ +import pytest +from controllers.shopping_list_controller import * +from controllers.user_controller import create_user +from controllers.category_controller import create_category +from controllers.product_controller import create_product +import os + +os.environ['TESTING'] = 'true' + +@pytest.fixture +def setup_data(): + user_id = create_user("testuser", "password") + category_id = create_category("Laticínios") + product_id = create_product("Leite", category_id) + return user_id, category_id, product_id + +def test_create_shopping_list(setup_data): + user_id, _, _ = setup_data + list_id = create_shopping_list("Lista de Teste", user_id) + assert list_id is not None + +def test_get_shopping_lists(setup_data): + user_id, _, _ = setup_data + create_shopping_list("Lista 1", user_id) + create_shopping_list("Lista 2", user_id) + lists = get_shopping_lists(user_id) + assert len(lists) == 2 + +def test_add_item_to_list(setup_data): + user_id, _, product_id = setup_data + list_id = create_shopping_list("Minha Lista", user_id) + assert add_item_to_list(list_id, product_id, 2) == True + +def test_get_list_items(setup_data): + user_id, _, product_id = setup_data + list_id = create_shopping_list("Minha Lista", user_id) + add_item_to_list(list_id, product_id, 3) + items = get_list_items(list_id) + assert len(items) == 1 + assert items[0]['name'] == "Leite" + assert items[0]['quantity'] == 3 + +def test_get_shopping_list_by_id(setup_data): + user_id, _, _ = setup_data + list_id = create_shopping_list("Lista de Teste", user_id) + retrieved_list = get_shopping_list_by_id(list_id) + assert retrieved_list is not None + assert retrieved_list['id'] == list_id + assert retrieved_list['name'] == "Lista de Teste" diff --git a/tests/test_stock_controller.py b/tests/test_stock_controller.py new file mode 100644 index 000000000000..90d714f041dc --- /dev/null +++ b/tests/test_stock_controller.py @@ -0,0 +1,50 @@ +import pytest +from controllers.stock_controller import * +from controllers.user_controller import create_user +from controllers.category_controller import create_category +from controllers.product_controller import create_product +import os + +os.environ['TESTING'] = 'true' + +@pytest.fixture +def setup_data(): + user_id = create_user("testuser", "password") + category_id = create_category("Laticínios") + product_id = create_product("Leite", category_id) + return user_id, category_id, product_id + +def test_add_to_stock(setup_data): + user_id, _, product_id = setup_data + assert add_to_stock(user_id, product_id, 5) == True + stock = get_stock(user_id) + assert len(stock) == 1 + assert stock[0]['quantity'] == 5 + + # Adicionar mais do mesmo produto + add_to_stock(user_id, product_id, 3) + stock = get_stock(user_id) + assert stock[0]['quantity'] == 8 + +def test_get_stock(setup_data): + user_id, _, product_id = setup_data + add_to_stock(user_id, product_id, 10) + stock = get_stock(user_id) + assert len(stock) == 1 + assert stock[0]['name'] == "Leite" + +def test_remove_from_stock(setup_data): + user_id, _, product_id = setup_data + add_to_stock(user_id, product_id, 10) + stock = get_stock(user_id) + stock_id = stock[0]['id'] + + # Remover uma parte + assert remove_from_stock(stock_id, 4) == True + stock = get_stock(user_id) + assert stock[0]['quantity'] == 6 + + # Remover tudo + assert remove_from_stock(stock_id, 6) == True + stock = get_stock(user_id) + assert len(stock) == 0 diff --git a/tests/test_user_controller.py b/tests/test_user_controller.py new file mode 100644 index 000000000000..30cdb7ff2bcd --- /dev/null +++ b/tests/test_user_controller.py @@ -0,0 +1,24 @@ +import pytest +from controllers.user_controller import create_user, authenticate_user +import os + +os.environ['TESTING'] = 'true' + +def test_create_user(): + assert create_user("testuser", "password123") == True + # Tente criar o mesmo usuário novamente + assert create_user("testuser", "password123") == False + +def test_authenticate_user(): + create_user("testuser_auth", "password123") + user = authenticate_user("testuser_auth", "password123") + assert user is not None + assert user['username'] == "testuser_auth" + + # Senha incorreta + user = authenticate_user("testuser_auth", "wrongpassword") + assert user is None + + # Usuário inexistente + user = authenticate_user("nonexistentuser", "password123") + assert user is None