From 5b74876653a253d228c1848a173a3f712107383e Mon Sep 17 00:00:00 2001 From: Leidy Date: Thu, 7 Nov 2024 00:45:48 -0500 Subject: [PATCH 1/6] Wave 1 --- app/__init__.py | 5 +- app/models/task.py | 8 ++ app/routes/task_routes.py | 113 +++++++++++++++++- migrations/README | 1 + migrations/alembic.ini | 50 ++++++++ migrations/env.py | 113 ++++++++++++++++++ migrations/script.py.mako | 24 ++++ .../522ae47ed892_create_tasks_table.py | 42 +++++++ migrations/versions/7baa2b17ed0e_.py | 32 +++++ .../versions/8d285adee3e2_adds_task_model.py | 39 ++++++ migrations/versions/caf8579d11ca_.py | 43 +++++++ requirements.txt | 6 + tests/test_wave_01.py | 36 +++--- 13 files changed, 496 insertions(+), 16 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/522ae47ed892_create_tasks_table.py create mode 100644 migrations/versions/7baa2b17ed0e_.py create mode 100644 migrations/versions/8d285adee3e2_adds_task_model.py create mode 100644 migrations/versions/caf8579d11ca_.py diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..2e481b06a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,13 +1,15 @@ from flask import Flask from .db import db, migrate from .models import task, goal +from .routes.task_routes import tasks_bp import os def create_app(config=None): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') + app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/task_list_api_development' + if config: # Merge `config` into the app's configuration @@ -18,5 +20,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(tasks_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..1e6a23146 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,13 @@ from sqlalchemy.orm import Mapped, mapped_column +from datetime import datetime +from typing import Optional +from sqlalchemy import String, Text, DateTime from ..db import db class Task(db.Model): + __tablename__ = 'task' id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] = mapped_column(nullable=False) # Title column required + description: Mapped[str] = mapped_column(nullable=False) # Description column required + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, default=None) + is_complete: Mapped[Optional[bool]] = False \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..902e2005b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,112 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, abort, make_response, Response +from app.models.task import Task +from ..db import db + +tasks_bp = Blueprint("task_bp", __name__,url_prefix="/tasks") + +@tasks_bp.post("") +def create_task(): + request_body = request.get_json() + + # Check if "title" or "description" keys are missing in the request body + if "title" not in request_body or "description" not in request_body: + return {"details": "Invalid data"}, 400 + + title = request_body["title"] + description = request_body["description"] + completed_at = request_body.get("completed_at") # Use .get() since "completed_at" is optional + + new_task = Task(title=title, description=description, completed_at=completed_at) + + db.session.add(new_task) + db.session.commit() + + response = { + Task.__tablename__: + { + "id": new_task.id, + "title": new_task.title, + "description": new_task.description, + "is_complete": bool(new_task.completed_at) # Convert to boolean for completeness + } + } + return response, 201 + +@tasks_bp.get("") +def get_all_tasks(): + #execute the query statement and retrieve the models + query = db.select(Task) #select records from db Model + tasks = db.session.scalars(query) #retrieve the records + + response = [] + for task in tasks: + response.append( + { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": bool(task.completed_at) + } + ) + return response + +@tasks_bp.get("/") +def get_one_task_by_id(task_id): + task = validate_task_id(task_id) + + return { + Task.__tablename__: { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": bool(task.completed_at) + } + } + +def validate_task_id(task_id): + try: + task_id = int(task_id) + except: + response = {"message": f"Task {task_id} invalid"} + abort(make_response(response, 400)) + + #execute the query statement and retrieve the models + query = db.select(Task).where(Task.id == task_id) #select records with an id = task_id + task = db.session.scalar(query) #retrieve only one record task_id + + if not task: + response = {"message": f"Task {task_id} not found"} + abort(make_response(response, 404)) + + return task + +@tasks_bp.put("/") +def update_one_task_by_id(task_id): + task = validate_task_id(task_id) #record with id = task_id + request_body = request.get_json() + + task.title = request_body["title"] + task.description = request_body["description"] + db.session.commit() #save the changes to db + + return { + Task.__tablename__: { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": bool(task.completed_at) + } + } + +@tasks_bp.delete("/") +def delete_task_by_id(task_id): + task = validate_task_id(task_id) + + #Delete the task + db.session.delete(task) + db.session.commit() + + response = { + "details": f"Task {task.id} \"{task.title}\" successfully deleted" + } + return response, 200 \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..4c9709271 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/522ae47ed892_create_tasks_table.py b/migrations/versions/522ae47ed892_create_tasks_table.py new file mode 100644 index 000000000..71c661011 --- /dev/null +++ b/migrations/versions/522ae47ed892_create_tasks_table.py @@ -0,0 +1,42 @@ +"""Create tasks table + +Revision ID: 522ae47ed892 +Revises: 8d285adee3e2 +Create Date: 2024-11-06 09:29:35.225766 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = '522ae47ed892' +down_revision = '8d285adee3e2' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('tasks', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('task') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('task', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False), + sa.PrimaryKeyConstraint('id', name='task_pkey') + ) + op.drop_table('tasks') + # ### end Alembic commands ### diff --git a/migrations/versions/7baa2b17ed0e_.py b/migrations/versions/7baa2b17ed0e_.py new file mode 100644 index 000000000..bdd7968bb --- /dev/null +++ b/migrations/versions/7baa2b17ed0e_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: 7baa2b17ed0e +Revises: 522ae47ed892 +Create Date: 2024-11-06 12:21:12.872380 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7baa2b17ed0e' +down_revision = '522ae47ed892' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('tasks', schema=None) as batch_op: + batch_op.add_column(sa.Column('is_complete', sa.Boolean(), nullable=True)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('tasks', schema=None) as batch_op: + batch_op.drop_column('is_complete') + + # ### end Alembic commands ### diff --git a/migrations/versions/8d285adee3e2_adds_task_model.py b/migrations/versions/8d285adee3e2_adds_task_model.py new file mode 100644 index 000000000..1cb83a8fd --- /dev/null +++ b/migrations/versions/8d285adee3e2_adds_task_model.py @@ -0,0 +1,39 @@ +"""adds Task model + +Revision ID: 8d285adee3e2 +Revises: +Create Date: 2024-11-05 22:52:33.631895 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '8d285adee3e2' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/migrations/versions/caf8579d11ca_.py b/migrations/versions/caf8579d11ca_.py new file mode 100644 index 000000000..f50ef1e1a --- /dev/null +++ b/migrations/versions/caf8579d11ca_.py @@ -0,0 +1,43 @@ +"""empty message + +Revision ID: caf8579d11ca +Revises: 7baa2b17ed0e +Create Date: 2024-11-07 00:29:19.039720 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'caf8579d11ca' +down_revision = '7baa2b17ed0e' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('tasks') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('tasks', + sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=False), + sa.Column('completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True), + sa.Column('is_complete', sa.BOOLEAN(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('id', name='tasks_pkey') + ) + op.drop_table('task') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index af8fc4cf4..6db0b9eee 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,12 +3,15 @@ blinker==1.7.0 certifi==2024.8.30 charset-normalizer==3.3.2 click==8.1.7 +coverage==7.6.4 +exceptiongroup==1.2.2 Flask==3.0.2 Flask-Migrate==4.0.5 Flask-SQLAlchemy==3.1.1 greenlet==3.0.3 gunicorn==21.2.0 idna==3.10 +importlib_metadata==8.5.0 iniconfig==2.0.0 itsdangerous==2.1.2 Jinja2==3.1.3 @@ -18,9 +21,12 @@ packaging==23.2 pluggy==1.4.0 psycopg2-binary==2.9.9 pytest==8.0.0 +pytest-cov==6.0.0 python-dotenv==1.0.1 requests==2.32.3 SQLAlchemy==2.0.25 +tomli==2.0.2 typing_extensions==4.9.0 urllib3==2.2.3 Werkzeug==3.0.1 +zipp==3.20.2 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..4b61f7777 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -13,7 +13,7 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +##@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_one_saved_tasks(client, one_task): # Act response = client.get("/tasks") @@ -32,7 +32,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -51,7 +51,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -59,14 +59,16 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -93,7 +95,7 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -119,7 +121,7 @@ def test_update_task(client, one_task): assert task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -130,14 +132,17 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Task 1 not found"} + - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -152,7 +157,7 @@ def test_delete_task(client, one_task): assert Task.query.get(1) == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -160,8 +165,11 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Task 1 not found"} + - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -169,7 +177,7 @@ def test_delete_task_not_found(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -186,7 +194,7 @@ def test_create_task_must_contain_title(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ From 4d8fb548e8851b677c94311f56118d12bc2cdf43 Mon Sep 17 00:00:00 2001 From: Leidy Date: Thu, 7 Nov 2024 10:12:15 -0500 Subject: [PATCH 2/6] Wave 2 --- app/routes/task_routes.py | 14 ++++++++++++++ tests/test_wave_01.py | 10 +++++++--- tests/test_wave_02.py | 4 ++-- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 902e2005b..31cb18bf3 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -36,6 +36,20 @@ def create_task(): def get_all_tasks(): #execute the query statement and retrieve the models query = db.select(Task) #select records from db Model + + # Check for sorting parameter and apply + sorting_param = request.args.get("sort", "asc").lower() #asc is default if not provided + + # If sort=desc, order by title descending + if sorting_param.lower() == "desc": + query = query.order_by(Task.title.desc()) + else: + query = query.order_by(Task.title) + # else: + # # No sorting parameter provided, default to ordering by id + # query = query.order_by(Task.id) + + #query = query.order_by(Task.id)#select records tasks = db.session.scalars(query) #retrieve the records response = [] diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 4b61f7777..d90ef8d6b 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -1,5 +1,6 @@ from app.models.task import Task import pytest +from app.db import db #@pytest.mark.skip(reason="No way to test this feature yet") @@ -88,7 +89,8 @@ def test_create_task(client): "is_complete": False } } - new_task = Task.query.get(1) + #new_task = Task.query.get(1) + new_task = db.session.get(Task, 1) # Use Session.get() for SQLAlchemy 2.0 compatibility assert new_task assert new_task.title == "A Brand New Task" assert new_task.description == "Test Description" @@ -115,7 +117,8 @@ def test_update_task(client, one_task): "is_complete": False } } - task = Task.query.get(1) + #task = Task.query.get(1) + task = db.session.get(Task, 1) # Use Session.get() for SQLAlchemy 2.0 compatibility assert task.title == "Updated Task Title" assert task.description == "Updated Test Description" assert task.completed_at == None @@ -154,7 +157,8 @@ def test_delete_task(client, one_task): assert response_body == { "details": 'Task 1 "Go on my daily walk 🏞" successfully deleted' } - assert Task.query.get(1) == None + #assert Task.query.get(1) == None + assert db.session.get(Task, 1) == None # Use Session.get() for SQLAlchemy 2.0 compatibility #@pytest.mark.skip(reason="No way to test this feature yet") diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..c9a76e6b1 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") From fbb4a9a50d28794ba92a2ac21a5962cc0b2c5d02 Mon Sep 17 00:00:00 2001 From: Leidy Date: Thu, 7 Nov 2024 17:39:56 -0500 Subject: [PATCH 3/6] Wave 3 --- app/__init__.py | 3 ++- app/routes/task_routes.py | 27 +++++++++++++++++++++++++++ tests/conftest.py | 12 ++++++------ tests/test_wave_03.py | 30 ++++++++++++++++++++++-------- 4 files changed, 57 insertions(+), 15 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2e481b06a..09976bbd1 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -8,7 +8,8 @@ def create_app(config=None): app = Flask(__name__) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/task_list_api_development' + #app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/task_list_api_development' + app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') if config: diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 31cb18bf3..212a6629c 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, request, abort, make_response, Response from app.models.task import Task +from datetime import datetime from ..db import db tasks_bp = Blueprint("task_bp", __name__,url_prefix="/tasks") @@ -112,6 +113,32 @@ def update_one_task_by_id(task_id): } } +@tasks_bp.patch("//") +def task_status(task_id, task_status): + + task = validate_task_id(task_id) #record with id = task_id + + # Update task status based on the task_status value + if task_status == "mark_complete": + task.completed_at = datetime.now() + + elif task_status == "mark_incomplete": + task.completed_at = None # Set to None to indicate incomplete + else: + # Return error response for invalid task_status + return {"error": "Invalid task status provided"}, 400 + + db.session.commit() #save the changes to db + return { + Task.__tablename__: { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": bool(task.completed_at) + } + } + + @tasks_bp.delete("/") def delete_task_by_id(task_id): task = validate_task_id(task_id) diff --git a/tests/conftest.py b/tests/conftest.py index e370e597b..eec1fa135 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -57,14 +57,14 @@ def one_task(app): def three_tasks(app): db.session.add_all([ Task(title="Water the garden 🌷", - description="", - completed_at=None), + description="", + completed_at=None), Task(title="Answer forgotten email 📧", - description="", - completed_at=None), + description="", + completed_at=None), Task(title="Pay my outstanding tickets 😭", - description="", - completed_at=None) + description="", + completed_at=None) ]) db.session.commit() diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..2af17e17f 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -42,7 +42,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -62,7 +62,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +99,7 @@ def test_mark_complete_on_completed_task(client, completed_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -119,7 +119,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -127,14 +127,16 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +144,20 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** + +def test_invalid_task_status(client,one_task): + # Act + response = client.patch('/tasks/1/invalid_status') + response_data = response.get_json() + + # Assert that the status code is 400 (Bad Request) + assert response.status_code == 400 + assert len(response_data) == 1 + assert response_data == {"error": "Invalid task status provided"} From 3758e81bc771db00bee6071ed07d711c26f58f68 Mon Sep 17 00:00:00 2001 From: Leidy Date: Thu, 7 Nov 2024 21:01:25 -0500 Subject: [PATCH 4/6] Wave 5 --- app/__init__.py | 2 + app/models/goal.py | 2 + app/routes/goal_routes.py | 101 ++++++++++++++++++++++++++- migrations/versions/fb269825c351_.py | 32 +++++++++ tests/test_wave_05.py | 83 ++++++++++++++-------- 5 files changed, 190 insertions(+), 30 deletions(-) create mode 100644 migrations/versions/fb269825c351_.py diff --git a/app/__init__.py b/app/__init__.py index 09976bbd1..b524814ff 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,6 +2,7 @@ from .db import db, migrate from .models import task, goal from .routes.task_routes import tasks_bp +from .routes.goal_routes import goals_bp import os def create_app(config=None): @@ -22,5 +23,6 @@ def create_app(config=None): # Register Blueprints here app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..b4b90233b 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,4 +2,6 @@ from ..db import db class Goal(db.Model): + __tablename__ = 'goal' id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] = mapped_column(nullable=False) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..13552519b 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,100 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, abort, make_response, Response +from app.models.goal import Goal +from ..db import db +goals_bp = Blueprint("goals_bp",__name__,url_prefix="/goals") + +@goals_bp.post("") +def create_goal(): + request_body = request.get_json() + + if "title" not in request_body: + return {"details": "Invalid data"}, 400 + + title = request_body["title"] + new_goal = Goal(title=title) + + db.session.add(new_goal) + db.session.commit() + + response = { + Goal.__tablename__: + { + "id": new_goal.id, + "title": new_goal.title, + } + } + return response, 201 + +@goals_bp.get("") +def get_all_goals(): + #execute the query statement and retrieve the models + query = db.select(Goal) #select records from db Model + + query = query.order_by(Goal.id) + goals = db.session.scalars(query) #retrieve the records + + response = [] + for goal in goals: + response.append( + { + "id": goal.id, + "title": goal.title + } + ) + return response + +def validate_goal(goal_id): + try: + goal_id = int(goal_id) + except: + response = {"message": f"goal {goal_id} invalid"} + abort(make_response(response, 400)) + + #execute the query statement and retrieve the models + query = db.select(Goal).where(Goal.id == goal_id) #select records with an id = goal_id + goal = db.session.scalar(query) #retrieve only one record goal_id + + if not goal: + response = {"message": f"Goal {goal_id} not found"} + abort(make_response(response, 404)) + + return goal + +@goals_bp.get("/") +def get_one_goal(goal_id): + goal = validate_goal(goal_id) + + return { + Goal.__tablename__: { + "id": goal.id, + "title": goal.title, + } + } + +@goals_bp.put("/") +def update_one_goal_by_id(goal_id): + goal = validate_goal(goal_id) #record with id = goal_id + request_body = request.get_json() + + goal.title = request_body["title"] + db.session.commit() #save the changes to db + + return { + Goal.__tablename__: { + "id": goal.id, + "title": goal.title, + } + } + +@goals_bp.delete("/") +def delete_goal_by_id(goal_id): + goal = validate_goal(goal_id) + + #Delete the goal + db.session.delete(goal) + db.session.commit() + + response = { + "details": f"Goal {goal.id} \"{goal.title}\" successfully deleted" + } + return response, 200 \ No newline at end of file diff --git a/migrations/versions/fb269825c351_.py b/migrations/versions/fb269825c351_.py new file mode 100644 index 000000000..bf336c55a --- /dev/null +++ b/migrations/versions/fb269825c351_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: fb269825c351 +Revises: caf8579d11ca +Create Date: 2024-11-07 20:04:14.513914 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fb269825c351' +down_revision = 'caf8579d11ca' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.add_column(sa.Column('title', sa.String(), nullable=False)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..369b21a0d 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,9 @@ import pytest +from app.db import db +from app.models.goal import Goal -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +14,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -29,7 +31,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +48,25 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + #raise Exception("Complete test") # Assert + # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here + # Assert + assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Goal 1 not found"} # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,34 +85,49 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") + #raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title" + } + } + goal = db.session.get(Goal, 1) # Use Session.get() for SQLAlchemy 2.0 compatibility + assert goal.title == "Updated Goal Title" # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") + #raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title", + "description": "Updated Goal Description", + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here + assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Goal 1 not found"} # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -124,27 +144,32 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** + assert db.session.get(Goal, 1) == None # Use Session.get() for SQLAlchemy 2.0 compatibility + # ***************************************************************** -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") - + #raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() - # Assert # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here + # Assert + assert response.status_code == 404 + assert len(response_body) == 1 + assert response_body == {"message": "Goal 1 not found"} + # ---- Complete Assertions Here ---- + assert Goal.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) From a050fd46e33223cc8f4bcd0d892df99bcc4c161a Mon Sep 17 00:00:00 2001 From: Leidy Date: Mon, 11 Nov 2024 20:54:10 -0500 Subject: [PATCH 5/6] Ready to Deploy --- app/__init__.py | 6 +- app/models/goal.py | 33 ++++++- app/models/task.py | 39 +++++++- app/routes/__init__.py | 0 app/routes/goal_routes.py | 116 ++++++++++++------------ app/routes/route_utilities.py | 53 +++++++++++ app/routes/task_routes.py | 129 +++++++++------------------ migrations/versions/2fdb5ec7efa3_.py | 34 +++++++ migrations/versions/5ef7fb6b3cde_.py | 34 +++++++ migrations/versions/90fa02bc3efe_.py | 34 +++++++ migrations/versions/9c392f2eecee_.py | 34 +++++++ migrations/versions/a3f5ad43fb39_.py | 34 +++++++ tests/test_route_utilities.py | 27 ++++++ tests/test_task_model.py | 110 +++++++++++++++++++++++ tests/test_wave_01.py | 1 + tests/test_wave_06.py | 18 ++-- 16 files changed, 541 insertions(+), 161 deletions(-) create mode 100644 app/routes/__init__.py create mode 100644 app/routes/route_utilities.py create mode 100644 migrations/versions/2fdb5ec7efa3_.py create mode 100644 migrations/versions/5ef7fb6b3cde_.py create mode 100644 migrations/versions/90fa02bc3efe_.py create mode 100644 migrations/versions/9c392f2eecee_.py create mode 100644 migrations/versions/a3f5ad43fb39_.py create mode 100644 tests/test_route_utilities.py create mode 100644 tests/test_task_model.py diff --git a/app/__init__.py b/app/__init__.py index b524814ff..a9b1001f3 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,8 +1,8 @@ from flask import Flask from .db import db, migrate from .models import task, goal -from .routes.task_routes import tasks_bp -from .routes.goal_routes import goals_bp +from .routes.task_routes import bp as tasks_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -19,7 +19,7 @@ def create_app(config=None): app.config.update(config) db.init_app(app) - migrate.init_app(app, db) + migrate.init_app(app,db) # Register Blueprints here app.register_blueprint(tasks_bp) diff --git a/app/models/goal.py b/app/models/goal.py index b4b90233b..314a63b4d 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,7 +1,38 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column,relationship from ..db import db +from typing import TYPE_CHECKING, Optional +if TYPE_CHECKING: + from .task import Task class Goal(db.Model): __tablename__ = 'goal' id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] = mapped_column(nullable=False) + tasks: Mapped[Optional[list["Task"]]] = relationship(back_populates="goal") + + @classmethod + def from_dict(cls, data): + """Creates a Task instance from a dictionary""" + + return cls( + title=data["title"], + ) + + def to_dict(self, include_name=True, tasks_ids=False): + """Converts a Task instance to a dictionary""" + goal_dict = { + + "id": self.id, + "title": self.title, + } + + if tasks_ids: + tasks_ids_list = [task.id for task in self.tasks] + goal_dict["task_ids"] = tasks_ids_list + goal_dict.pop("title") + + if include_name: + return {Goal.__name__.lower(): goal_dict} + + return goal_dict + diff --git a/app/models/task.py b/app/models/task.py index 1e6a23146..1f20110b1 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,8 +1,11 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column,relationship from datetime import datetime from typing import Optional -from sqlalchemy import String, Text, DateTime +from sqlalchemy import String, Text, DateTime, ForeignKey from ..db import db +from typing import TYPE_CHECKING +if TYPE_CHECKING: + from .goal import Goal class Task(db.Model): __tablename__ = 'task' @@ -10,4 +13,34 @@ class Task(db.Model): title: Mapped[str] = mapped_column(nullable=False) # Title column required description: Mapped[str] = mapped_column(nullable=False) # Description column required completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, default=None) - is_complete: Mapped[Optional[bool]] = False \ No newline at end of file + is_complete: Mapped[Optional[bool]] = False + goal_id: Mapped[Optional[int]] = mapped_column((ForeignKey("goal.id")), default=None) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") + + @classmethod + def from_dict(cls, data): + """Creates a Task instance from a dictionary""" + + return cls( + title=data["title"], + description=data["description"], + completed_at=data.get("completed_at") # Use .get() since "completed_at" is optional + ) + + def to_dict(self, include_name=True, goal_id=False): + """Converts a Task instance to a dictionary""" + task_dict = { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": bool(self.completed_at) # Convert to boolean for completeness + } + if goal_id: + task_dict["goal_id"] = self.goal.id + + if include_name: + return {Task.__name__.lower(): task_dict} + + return task_dict + + \ No newline at end of file diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 13552519b..2a9137d46 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,9 +1,12 @@ -from flask import Blueprint, request, abort, make_response, Response +from flask import Blueprint, request, abort, jsonify from app.models.goal import Goal +from app.models.task import Task +from app.routes.route_utilities import validate_model from ..db import db -goals_bp = Blueprint("goals_bp",__name__,url_prefix="/goals") -@goals_bp.post("") +bp = Blueprint("bp",__name__,url_prefix="/goals") + +@bp.post("") def create_goal(): request_body = request.get_json() @@ -15,17 +18,11 @@ def create_goal(): db.session.add(new_goal) db.session.commit() - - response = { - Goal.__tablename__: - { - "id": new_goal.id, - "title": new_goal.title, - } - } + + response = new_goal.to_dict() return response, 201 -@goals_bp.get("") +@bp.get("") def get_all_goals(): #execute the query statement and retrieve the models query = db.select(Goal) #select records from db Model @@ -35,60 +32,25 @@ def get_all_goals(): response = [] for goal in goals: - response.append( - { - "id": goal.id, - "title": goal.title - } - ) + response.append(goal.to_dict(include_name=False)) return response -def validate_goal(goal_id): - try: - goal_id = int(goal_id) - except: - response = {"message": f"goal {goal_id} invalid"} - abort(make_response(response, 400)) - - #execute the query statement and retrieve the models - query = db.select(Goal).where(Goal.id == goal_id) #select records with an id = goal_id - goal = db.session.scalar(query) #retrieve only one record goal_id - - if not goal: - response = {"message": f"Goal {goal_id} not found"} - abort(make_response(response, 404)) - - return goal - -@goals_bp.get("/") +@bp.get("/") def get_one_goal(goal_id): - goal = validate_goal(goal_id) + goal = validate_model(Goal,goal_id) + return goal.to_dict() - return { - Goal.__tablename__: { - "id": goal.id, - "title": goal.title, - } - } - -@goals_bp.put("/") +@bp.put("/") def update_one_goal_by_id(goal_id): - goal = validate_goal(goal_id) #record with id = goal_id + goal = validate_model(Goal,goal_id) #record with id = goal_id request_body = request.get_json() - goal.title = request_body["title"] - db.session.commit() #save the changes to db - - return { - Goal.__tablename__: { - "id": goal.id, - "title": goal.title, - } - } + db.session.commit() + return goal.to_dict() -@goals_bp.delete("/") +@bp.delete("/") def delete_goal_by_id(goal_id): - goal = validate_goal(goal_id) + goal = validate_model(Goal,goal_id) #Delete the goal db.session.delete(goal) @@ -97,4 +59,42 @@ def delete_goal_by_id(goal_id): response = { "details": f"Goal {goal.id} \"{goal.title}\" successfully deleted" } - return response, 200 \ No newline at end of file + return response, 200 + +@bp.post("//tasks") +def add_tasks_to_goal(goal_id): + + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + task_ids = request_body.get("task_ids") + if not task_ids: + response = {"details": "Invalid data"} + abort(response, 400) + + #valid_task_ids = [] + for task_id in task_ids: + task = validate_model(Task,task_id) + # assign each task to goal_id + task.goal_id = goal_id + + response_body = goal.to_dict(include_name=False, tasks_ids=True) + db.session.commit() + + return response_body , 200 + +@bp.get("//tasks") +def get_goals_and_tasks(goal_id): + + goal = validate_model(Goal, goal_id) + + # Get associated tasks and convert each to a dictionary + task_dicts = [task.to_dict(include_name=False , goal_id=True) for task in goal.tasks] + + response = { + "id": goal.id, + "title": goal.title, + "tasks": task_dicts # Populate with list of task dictionaries + } + + return response diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..8118089d0 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,53 @@ +from flask import abort, make_response, request +from ..db import db +import os +import requests + +# Slack webhook URL and token from environment variables +SLACK_URL = "https://slack.com/api/chat.postMessage" +SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except ValueError: + response = {"message": f"{cls.__name__} {model_id} invalid"} + abort(make_response(response, 400)) + + #execute the query statement and retrieve the models + query = db.select(cls).where(cls.id == model_id) #select records with an id = model_id + model = db.session.scalar(query) #retrieve only one record model_id + + if not model: + response = {"message": f"{cls.__name__} {model_id} not found"} + abort(make_response(response, 404)) + + return model + +def get_models_with_filters(cls, filters=None): + query = db.select(cls) + + if filters: + for attribute, value in filters.items(): + if hasattr(cls, attribute): + query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) + + models = db.session.scalars(query.order_by(cls.id)) + models_response = [model.to_dict() for model in models] + return models_response + +def send_slack_message(message): + """Sends a message to the Slack channel using the Slack API.""" + + headers = { + "Authorization": f"Bearer {SLACK_TOKEN}", + "Content-Type": "application/json" + } + payload = { + "channel": "tasks-api-notifications", + "text": message + } + response = requests.post(SLACK_URL, headers=headers, json=payload) + response.raise_for_status() # Raise an error if the request fails + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 212a6629c..efc7a08f6 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,127 +1,85 @@ from flask import Blueprint, request, abort, make_response, Response from app.models.task import Task from datetime import datetime +from app.routes.route_utilities import validate_model from ..db import db +from app.routes.route_utilities import send_slack_message -tasks_bp = Blueprint("task_bp", __name__,url_prefix="/tasks") +bp = Blueprint("task_bp", __name__,url_prefix="/tasks") -@tasks_bp.post("") +@bp.post("") def create_task(): request_body = request.get_json() - # Check if "title" or "description" keys are missing in the request body - if "title" not in request_body or "description" not in request_body: - return {"details": "Invalid data"}, 400 - - title = request_body["title"] - description = request_body["description"] - completed_at = request_body.get("completed_at") # Use .get() since "completed_at" is optional - - new_task = Task(title=title, description=description, completed_at=completed_at) + try: + new_task = Task.from_dict(request_body) + except: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) db.session.add(new_task) db.session.commit() - response = { - Task.__tablename__: - { - "id": new_task.id, - "title": new_task.title, - "description": new_task.description, - "is_complete": bool(new_task.completed_at) # Convert to boolean for completeness - } - } - return response, 201 - -@tasks_bp.get("") + return new_task.to_dict(), 201 + +@bp.get("") def get_all_tasks(): - #execute the query statement and retrieve the models + query = db.select(Task) #select records from db Model # Check for sorting parameter and apply - sorting_param = request.args.get("sort", "asc").lower() #asc is default if not provided + sorting_param = request.args.get("sort", "asc") - # If sort=desc, order by title descending - if sorting_param.lower() == "desc": + if sorting_param == "desc": query = query.order_by(Task.title.desc()) else: query = query.order_by(Task.title) - # else: - # # No sorting parameter provided, default to ordering by id - # query = query.order_by(Task.id) - + #query = query.order_by(Task.id)#select records tasks = db.session.scalars(query) #retrieve the records - response = [] + response =[] for task in tasks: - response.append( - { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": bool(task.completed_at) - } - ) + response.append(task.to_dict(include_name=False)) return response -@tasks_bp.get("/") +@bp.get("/") def get_one_task_by_id(task_id): - task = validate_task_id(task_id) - - return { - Task.__tablename__: { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": bool(task.completed_at) - } - } -def validate_task_id(task_id): - try: - task_id = int(task_id) - except: - response = {"message": f"Task {task_id} invalid"} - abort(make_response(response, 400)) - - #execute the query statement and retrieve the models - query = db.select(Task).where(Task.id == task_id) #select records with an id = task_id - task = db.session.scalar(query) #retrieve only one record task_id - - if not task: - response = {"message": f"Task {task_id} not found"} - abort(make_response(response, 404)) + task = validate_model(Task,task_id) - return task + if task.goal_id: + return task.to_dict(goal_id=True) + else: + return task.to_dict() -@tasks_bp.put("/") +@bp.put("/") def update_one_task_by_id(task_id): - task = validate_task_id(task_id) #record with id = task_id - request_body = request.get_json() + task = validate_model(Task,task_id) #record with id = task_id + request_body = request.get_json() + + #Update the task task.title = request_body["title"] task.description = request_body["description"] + db.session.commit() #save the changes to db - return { - Task.__tablename__: { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": bool(task.completed_at) - } - } + return task.to_dict() -@tasks_bp.patch("//") +@bp.patch("//") def task_status(task_id, task_status): - task = validate_task_id(task_id) #record with id = task_id + task = validate_model(Task,task_id) #record with id = task_id # Update task status based on the task_status value if task_status == "mark_complete": task.completed_at = datetime.now() + + # Send Slack notification + send_slack_message(f"Someone just completed the task '{task.title}'") + elif task_status == "mark_incomplete": task.completed_at = None # Set to None to indicate incomplete else: @@ -129,19 +87,12 @@ def task_status(task_id, task_status): return {"error": "Invalid task status provided"}, 400 db.session.commit() #save the changes to db - return { - Task.__tablename__: { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": bool(task.completed_at) - } - } + return task.to_dict() -@tasks_bp.delete("/") +@bp.delete("/") def delete_task_by_id(task_id): - task = validate_task_id(task_id) + task = validate_model(Task,task_id) #Delete the task db.session.delete(task) diff --git a/migrations/versions/2fdb5ec7efa3_.py b/migrations/versions/2fdb5ec7efa3_.py new file mode 100644 index 000000000..072ee592f --- /dev/null +++ b/migrations/versions/2fdb5ec7efa3_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 2fdb5ec7efa3 +Revises: 5ef7fb6b3cde +Create Date: 2024-11-08 12:37:17.196116 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2fdb5ec7efa3' +down_revision = '5ef7fb6b3cde' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint('task_goal_id_fkey', type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.INTEGER(), autoincrement=False, nullable=True)) + batch_op.create_foreign_key('task_goal_id_fkey', 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### diff --git a/migrations/versions/5ef7fb6b3cde_.py b/migrations/versions/5ef7fb6b3cde_.py new file mode 100644 index 000000000..a1a3c1c80 --- /dev/null +++ b/migrations/versions/5ef7fb6b3cde_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 5ef7fb6b3cde +Revises: 9c392f2eecee +Create Date: 2024-11-08 12:14:31.354066 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5ef7fb6b3cde' +down_revision = '9c392f2eecee' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/migrations/versions/90fa02bc3efe_.py b/migrations/versions/90fa02bc3efe_.py new file mode 100644 index 000000000..5af4a6bb8 --- /dev/null +++ b/migrations/versions/90fa02bc3efe_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 90fa02bc3efe +Revises: 2fdb5ec7efa3 +Create Date: 2024-11-09 16:33:42.586310 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '90fa02bc3efe' +down_revision = '2fdb5ec7efa3' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/migrations/versions/9c392f2eecee_.py b/migrations/versions/9c392f2eecee_.py new file mode 100644 index 000000000..050f073bc --- /dev/null +++ b/migrations/versions/9c392f2eecee_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 9c392f2eecee +Revises: a3f5ad43fb39 +Create Date: 2024-11-08 00:10:23.750412 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9c392f2eecee' +down_revision = 'a3f5ad43fb39' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint('task_goal_id_fkey', type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.INTEGER(), autoincrement=False, nullable=True)) + batch_op.create_foreign_key('task_goal_id_fkey', 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### diff --git a/migrations/versions/a3f5ad43fb39_.py b/migrations/versions/a3f5ad43fb39_.py new file mode 100644 index 000000000..9719ca8b6 --- /dev/null +++ b/migrations/versions/a3f5ad43fb39_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: a3f5ad43fb39 +Revises: fb269825c351 +Create Date: 2024-11-07 23:21:39.049501 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a3f5ad43fb39' +down_revision = 'fb269825c351' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/tests/test_route_utilities.py b/tests/test_route_utilities.py new file mode 100644 index 000000000..389c2c1cb --- /dev/null +++ b/tests/test_route_utilities.py @@ -0,0 +1,27 @@ +from werkzeug.exceptions import HTTPException +from app.routes.route_utilities import validate_model +from app.models.task import Task +import pytest + +def test_validate_model_id(one_task: None): + # Act + result_task = validate_model(Task, 1) + + # Assert + assert result_task.id == 1 + assert result_task.title == "Go on my daily walk 🏞" + assert result_task.description == "Notice something new every day" + +def test_validate_model_missing_record(one_task: None): + # Act & Assert + # Calling `validate_model` without being invoked by a route will + # cause an `HTTPException` when an `abort` statement is reached + with pytest.raises(HTTPException): + result_task = validate_model(Task,"3") + +def test_validate_model_invalid_id(one_task: None): + # Act & Assert + # Calling `validate_model` without being invoked by a route will + # cause an `HTTPException` when an `abort` statement is reached + with pytest.raises(HTTPException): + result_task = validate_model(Task,"cat") \ No newline at end of file diff --git a/tests/test_task_model.py b/tests/test_task_model.py new file mode 100644 index 000000000..7ae7f0bb2 --- /dev/null +++ b/tests/test_task_model.py @@ -0,0 +1,110 @@ +from app.models.task import Task +import pytest + +def test_from_dict_returns_model(): + # Arrange + model_data = { + "title": "New Test Task", + "description": "something new to do" + } + + # Act + new_model = Task.from_dict(model_data) + + # Assert + assert new_model.title == "New Test Task" + assert new_model.description == "something new to do" + +def test_from_dict_with_no_title(): + # Arrange + model_data = { + "description": "something new to do" + } + + # Act & Assert + with pytest.raises(KeyError, match = 'title'): + new_model = Task.from_dict(model_data) + +def test_from_dict_with_no_description(): + # Arrange + model_data = { + "title": "New Test Task" + } + + # Act & Assert + with pytest.raises(KeyError, match = 'description'): + new_model = Task.from_dict(model_data) + +def test_from_dict_with_extra_keys(): + # Arrange + model_data = { + "extra": "some stuff", + "title": "New Test Task", + "description": "something new to do", + "another": "last value" + } + + # Act + new_model = Task.from_dict(model_data) + + # Assert + assert new_model.title == "New Test Task" + assert new_model.description == "something new to do" + +def test_to_dict_no_missing_data(): + # Arrange + test_data = Task(id = 1, + title="Test Task", + description="test description task") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result["task"]) == 4 + assert result["task"]["id"] == 1 + assert result["task"]["title"] == "Test Task" + assert result["task"]["description"] == "test description task" + assert "task" in result + +def test_to_dict_missing_id(): + # Arrange + test_data = Task(title="Test Task", + description="test description task") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result["task"]) == 4 + assert result["task"]["id"] is None + assert result["task"]["title"] == "Test Task" + assert result["task"]["description"] == "test description task" + +def test_to_dict_missing_title(): + # Arrange + test_data = Task(id=1, + description="test description task") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result["task"]) == 4 + assert result["task"]["id"] == 1 + assert result["task"]["title"] is None + assert result["task"]["description"] == "test description task" + +def test_to_dict_missing_description(): + # Arrange + test_data = Task(id = 1, + title="Test Task") + + # Act + result = test_data.to_dict() + + # Assert + assert len(result["task"]) == 4 + assert result["task"]["id"] == 1 + assert result["task"]["title"] == "Test Task" + assert result["task"]["description"] is None \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index d90ef8d6b..9d60e13f1 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -63,6 +63,7 @@ def test_get_task_not_found(client): assert len(response_body) == 1 assert response_body == {"message": "Task 1 not found"} + #raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..59a5ea35b 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -23,7 +23,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(Goal.query.get(1).tasks) == 3 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -42,7 +42,7 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on assert len(Goal.query.get(1).tasks) == 2 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act response = client.get("/goals/1/tasks") @@ -51,13 +51,17 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + #raise Exception("Complete test with assertion about response body") + + assert response_body == {"message": "Goal 1 not found"} + + # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -74,7 +78,7 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -99,7 +103,7 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json() From af603de28e3f7119a6f5f00472525835ac725f1d Mon Sep 17 00:00:00 2001 From: Leidy Date: Mon, 11 Nov 2024 21:08:26 -0500 Subject: [PATCH 6/6] fixed comments --- app/models/goal.py | 4 ++-- app/routes/route_utilities.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 314a63b4d..a17a2f153 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -12,14 +12,14 @@ class Goal(db.Model): @classmethod def from_dict(cls, data): - """Creates a Task instance from a dictionary""" + # Creates a Task instance from a dictionary return cls( title=data["title"], ) def to_dict(self, include_name=True, tasks_ids=False): - """Converts a Task instance to a dictionary""" + # Converts a Task instance to a dictionary goal_dict = { "id": self.id, diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 8118089d0..8462514ad 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -37,7 +37,7 @@ def get_models_with_filters(cls, filters=None): return models_response def send_slack_message(message): - """Sends a message to the Slack channel using the Slack API.""" + # Sends a message to the Slack channel using the Slack API. headers = { "Authorization": f"Bearer {SLACK_TOKEN}",