From 1cab6bc886ff58e3bf160b7652d06d328ee2921f Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 30 Oct 2025 16:44:26 -0400 Subject: [PATCH 01/56] Sets up task list API project, includes migrations --- migrations/README | 1 + migrations/alembic.ini | 50 +++++++++++++++++ migrations/env.py | 113 ++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++ 4 files changed, 188 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako 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"} From d3793c9128fdc8089807a8e3ff6fc27eb645935d Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 30 Oct 2025 17:22:41 -0400 Subject: [PATCH 02/56] Completes attributes for Task model --- app/models/task.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..192ded22b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,10 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from typing import Optional +from datetime import datetime class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + description: Mapped[str] + completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) \ No newline at end of file From d22d79ed504de2f1cbd562e7b3bc61b2c04060d9 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 30 Oct 2025 17:30:06 -0400 Subject: [PATCH 03/56] First migration after creating Task class --- migrations/versions/5871594ca6ec_.py | 39 ++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 migrations/versions/5871594ca6ec_.py diff --git a/migrations/versions/5871594ca6ec_.py b/migrations/versions/5871594ca6ec_.py new file mode 100644 index 000000000..5e95e0331 --- /dev/null +++ b/migrations/versions/5871594ca6ec_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 5871594ca6ec +Revises: +Create Date: 2025-10-30 17:28:19.595294 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '5871594ca6ec' +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=True), + 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 ### From 3615b4dcebdb02cede46df4523aaeb8ca72ea900 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 30 Oct 2025 17:33:02 -0400 Subject: [PATCH 04/56] Implements from_dict class method for Task, but need to figure out how to connect completed_at to is_complete --- app/models/task.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/app/models/task.py b/app/models/task.py index 192ded22b..a52518314 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -7,4 +7,12 @@ class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] description: Mapped[str] - completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) \ No newline at end of file + completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + + @classmethod + def from_dict(cls, task_data): + new_task = Task(title=task_data['title'], + description=task_data['description'], + completed_at=task_data['completed_at']) + + return new_task \ No newline at end of file From e0c8a6f85365aa2febc959a36a11d94a214fcdc5 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 07:42:24 -0400 Subject: [PATCH 05/56] implements class method from_dict and instance method to_dict, removes decorators for these tests and passes --- app/models/task.py | 18 ++++++++++++++++-- tests/test_wave_01.py | 6 ------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index a52518314..0cf197a7f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,8 +11,22 @@ class Task(db.Model): @classmethod def from_dict(cls, task_data): + if not task_data['is_complete']: + task_data['is_complete'] = None new_task = Task(title=task_data['title'], description=task_data['description'], - completed_at=task_data['completed_at']) + completed_at=task_data['is_complete'] + ) - return new_task \ No newline at end of file + return new_task + + def to_dict(self): + task_dict = {} + if self.completed_at is None: + task_dict['is_complete'] = False + + task_dict['id'] = self.id + task_dict['title'] = self.title + task_dict['description'] = self.description + + return task_dict \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fac95a0a3..72f7fb89e 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,6 @@ from app.db import db import pytest -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict(): #Arrange new_task = Task(id = 1, title="Make My Bed", @@ -19,7 +18,6 @@ def test_task_to_dict(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict_missing_id(): #Arrange new_task = Task(title="Make My Bed", @@ -36,7 +34,6 @@ def test_task_to_dict_missing_id(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict_missing_title(): #Arrange new_task = Task(id = 1, @@ -53,7 +50,6 @@ def test_task_to_dict_missing_title(): assert task_dict["description"] == "Start the day off right!" assert task_dict["is_complete"] == False -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict(): #Arrange task_dict = { @@ -70,7 +66,6 @@ def test_task_from_dict(): assert task_obj.description == "Start the day off right!" assert task_obj.completed_at is None -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict_no_title(): #Arrange task_dict = { @@ -82,7 +77,6 @@ def test_task_from_dict_no_title(): with pytest.raises(KeyError, match = 'title'): Task.from_dict(task_dict) -@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict_no_description(): #Arrange task_dict = { From 9cd3719e80eb923a55199570ebcd4728926c569b Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 07:56:24 -0400 Subject: [PATCH 06/56] registers task bp in app, creates skeleton task routes for get, post, put, and delete --- app/__init__.py | 2 ++ app/models/task.py | 11 +++++++---- app/routes/task_routes.py | 24 +++++++++++++++++++++++- tests/test_wave_01.py | 1 - 4 files changed, 32 insertions(+), 6 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..617440a9b 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from .db import db, migrate from .models import task, goal +from .routes.task_routes import bp as tasks_bp import os def create_app(config=None): @@ -18,5 +19,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 0cf197a7f..6871561d5 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -13,15 +13,18 @@ class Task(db.Model): def from_dict(cls, task_data): if not task_data['is_complete']: task_data['is_complete'] = None - new_task = Task(title=task_data['title'], - description=task_data['description'], - completed_at=task_data['is_complete'] - ) + + new_task = Task( + title=task_data['title'], + description=task_data['description'], + completed_at=task_data['is_complete'] + ) return new_task def to_dict(self): task_dict = {} + if self.completed_at is None: task_dict['is_complete'] = False diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..aa6d247e2 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,23 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint + +bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') + +@bp.get('') +def get_all_tasks(): + pass + +@bp.get('/') +def get_one_task_by_id(task_id): + pass + +@bp.post('') +def create_task(): + pass + +@bp.put('/') +def update_task(task_id): + pass + +@bp.delete('/') +def delete_task(task_id): + pass \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 72f7fb89e..b0d4ba490 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -88,7 +88,6 @@ def test_task_from_dict_no_description(): with pytest.raises(KeyError, match = 'description'): Task.from_dict(task_dict) -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") From d19585b15ac6977fd547676d7e89839f7b27040c Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 08:14:00 -0400 Subject: [PATCH 07/56] creates route_utilities to make a validate_model helper function, implements get all tasks route, tests passing --- app/routes/route_utilities.py | 19 +++++++++++++++++++ app/routes/task_routes.py | 14 ++++++++++++-- tests/test_wave_01.py | 2 -- 3 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 app/routes/route_utilities.py diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..9ab4e8f21 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,19 @@ +from flask import abort, make_response +from ..db import db + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + + except: + response = {'message': f'{cls.__name__} {model_id} invalid'} + abort(make_response(response, 400)) + + query = db.select(cls).where(cls.id == model_id) + model = db.session.scalar(query) + + if not model: + response = {'message': f'{cls.__name__} {model_id} not found'} + abort(make_response(response, 404)) + + return model \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index aa6d247e2..ef696cae0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,10 +1,20 @@ -from flask import Blueprint +from flask import abort, Blueprint, make_response, request +from app.models.task import Task +from ..db import db +from app.routes.route_utilities import validate_model bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @bp.get('') def get_all_tasks(): - pass + query = db.select(Task) + tasks = db.session.scalars(query) + + task_list = [] + for task in tasks: + task_list.append(task.to_dict()) + + return task_list @bp.get('/') def get_one_task_by_id(task_id): diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index b0d4ba490..ccb1414af 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -97,8 +97,6 @@ def test_get_tasks_no_saved_tasks(client): assert response.status_code == 200 assert response_body == [] - -@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") From 0c92b2989c5a69de97c1881ae2f2568fe5b1348f Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 08:30:07 -0400 Subject: [PATCH 08/56] Implements routes for get all tasks and get one task by id, handles invalid and non existent id --- app/routes/task_routes.py | 3 ++- tests/test_wave_01.py | 9 +-------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ef696cae0..ba8ac2fc6 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -18,7 +18,8 @@ def get_all_tasks(): @bp.get('/') def get_one_task_by_id(task_id): - pass + task = validate_model(Task, task_id) + return task.to_dict() @bp.post('') def create_task(): diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index ccb1414af..2bdb7bb24 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -115,7 +115,6 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -130,8 +129,6 @@ def test_get_task(client, one_task): "is_complete": False } - -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -139,11 +136,7 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {'message': 'Task 1 not found'} @pytest.mark.skip(reason="No way to test this feature yet") From ebc03a56487839ac7bdef0c79436bb18a40a93d1 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 08:51:26 -0400 Subject: [PATCH 09/56] Implements create task route, but the from_dict function is a bit funky. all the tests are passing --- app/models/task.py | 7 +++++-- app/routes/task_routes.py | 16 +++++++++++++++- tests/test_wave_01.py | 5 ----- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 6871561d5..6b0c2c6bb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,7 +11,10 @@ class Task(db.Model): @classmethod def from_dict(cls, task_data): - if not task_data['is_complete']: + if 'is_complete' not in task_data.keys(): + task_data['is_complete'] = None + + if task_data['is_complete'] is False: task_data['is_complete'] = None new_task = Task( @@ -24,7 +27,7 @@ def from_dict(cls, task_data): def to_dict(self): task_dict = {} - + if self.completed_at is None: task_dict['is_complete'] = False diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ba8ac2fc6..8b50daf8e 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -23,7 +23,21 @@ def get_one_task_by_id(task_id): @bp.post('') def create_task(): - pass + request_body = request.get_json() + + try: + new_task = Task.from_dict(request_body) + + except KeyError as error: # Missing keys + response = {'details': "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_task) + db.session.commit() + + new_task_dict = new_task.to_dict() + + return new_task_dict, 201 @bp.put('/') def update_task(task_id): diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 2bdb7bb24..0fc906ab2 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -138,8 +138,6 @@ def test_get_task_not_found(client): assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} - -@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -231,7 +229,6 @@ def test_delete_task_not_found(client): assert db.session.scalars(db.select(Task)).all() == [] -@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={ @@ -247,8 +244,6 @@ def test_create_task_must_contain_title(client): } assert db.session.scalars(db.select(Task)).all() == [] - -@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 1809340214144565db5a5694a3c769af6fea9af3 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 09:01:38 -0400 Subject: [PATCH 10/56] implements update task routes, passes all tests for put route --- app/routes/task_routes.py | 11 +++++++++-- tests/test_wave_01.py | 12 +----------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 8b50daf8e..1140a885d 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, make_response, request +from flask import abort, Blueprint, make_response, request, Response from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model @@ -41,7 +41,14 @@ def create_task(): @bp.put('/') def update_task(task_id): - pass + task = validate_model(Task, task_id) + request_body = request.get_json() + + task.title = request_body['title'] + task.description = request_body['description'] + db.session.commit() + + return Response(status=204, mimetype='application/json') @bp.delete('/') def delete_task(task_id): diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 0fc906ab2..620b2c941 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -114,7 +114,6 @@ def test_get_tasks_one_saved_tasks(client, one_task): } ] - def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -163,7 +162,6 @@ def test_create_task(client): assert new_task.description == "Test Description" assert new_task.completed_at == None -@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={ @@ -181,9 +179,6 @@ def test_update_task(client, one_task): assert task.description == "Updated Test Description" assert task.completed_at == None - - -@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={ @@ -194,12 +189,7 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - + assert response_body == {'message': 'Task 1 not found'} @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): From dc216e3236fe821cbfd2a12ae1cd2bbb41a20db2 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 09:03:48 -0400 Subject: [PATCH 11/56] Implements delete task route, all tests pass with appropriate error message asserts implemented. --- app/routes/task_routes.py | 7 ++++++- tests/test_wave_01.py | 9 +-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 1140a885d..d2a917816 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -52,4 +52,9 @@ def update_task(task_id): @bp.delete('/') def delete_task(task_id): - pass \ No newline at end of file + task = validate_model(Task, task_id) + + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 620b2c941..dc0bd8ad5 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -191,7 +191,6 @@ def test_update_task_not_found(client): assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -202,7 +201,6 @@ def test_delete_task(client, one_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query) == None -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -210,12 +208,7 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - + assert response_body == {'message': 'Task 1 not found'} assert db.session.scalars(db.select(Task)).all() == [] From 81d74c896e2d55e1def3635cebff59b155d3bb93 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 09:05:32 -0400 Subject: [PATCH 12/56] Deletes extra whitespace lines. Finished wave 1 but the from_dict class method for tasks is a bit weird (the if statements) - will revisit. --- tests/test_wave_01.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dc0bd8ad5..3d0091d7d 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -211,7 +211,6 @@ def test_delete_task_not_found(client): assert response_body == {'message': 'Task 1 not found'} assert db.session.scalars(db.select(Task)).all() == [] - def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ From f0bd81b982c7c88e32c832c3eb6ee16085c03ed0 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 09:29:04 -0400 Subject: [PATCH 13/56] adds a message to the end of route_utilities about dir() and __dir__, which could help with generalizing the route helper function to create an instance of a class from a dictionary so I don't have to define to_dict and from_dict for both models. --- app/models/task.py | 5 +---- app/routes/route_utilities.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 6b0c2c6bb..361687205 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -11,10 +11,7 @@ class Task(db.Model): @classmethod def from_dict(cls, task_data): - if 'is_complete' not in task_data.keys(): - task_data['is_complete'] = None - - if task_data['is_complete'] is False: + if 'is_complete' not in task_data.keys() or task_data['is_complete'] is False: task_data['is_complete'] = None new_task = Task( diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 9ab4e8f21..5a7e52267 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -16,4 +16,16 @@ def validate_model(cls, model_id): response = {'message': f'{cls.__name__} {model_id} not found'} abort(make_response(response, 404)) - return model \ No newline at end of file + return model + +def create_instance(cls, data): + pass + +# create an instance of model_class +# for each key, value in data_dict: +# if the key corresponds to a valid model attribute: +# set that attribute on the instance +# handle any special-case logic (like completed_at) +# return the instance + +# involves dir() and __dir__ for the class definition. dir() returns a list of the object's attributes, and __dir__ within class definition lets us customize output of dir(). will save this for later wave when I make the goal model. \ No newline at end of file From 5d3fc522a3f6ed6c7306a4d151351d9c4b19f382 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 15:40:02 -0400 Subject: [PATCH 14/56] Implements sorting for get all tasks route --- app/routes/task_routes.py | 9 ++++++++- tests/test_wave_02.py | 4 ---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d2a917816..c8e464d25 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,14 +2,21 @@ from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model +from sqlalchemy import desc, asc bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @bp.get('') def get_all_tasks(): query = db.select(Task) - tasks = db.session.scalars(query) + sort_param = request.args.get('sort') + if sort_param == 'asc' or sort_param is None: + query = query.order_by(Task.title) + elif sort_param == 'desc': + query = query.order_by(Task.title.desc()) + + tasks = db.session.scalars(query) task_list = [] for task in tasks: task_list.append(task.to_dict()) diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..62611a3c4 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,5 @@ import pytest - -@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") @@ -28,8 +26,6 @@ def test_get_tasks_sorted_asc(client, three_tasks): "is_complete": False} ] - -@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 b696355b85e366dfd7fbab5b67657a52d82d4eaf Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 16:47:37 -0400 Subject: [PATCH 15/56] Implements mark_complete method, passes wave 3 tests with it. --- app/routes/task_routes.py | 12 +++++++++++- tests/test_wave_03.py | 12 +----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index c8e464d25..81c3966fe 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,7 +2,8 @@ from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model -from sqlalchemy import desc, asc +from datetime import datetime +from sqlalchemy import update bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @@ -64,4 +65,13 @@ def delete_task(task_id): db.session.delete(task) db.session.commit() + return Response(status=204, mimetype='application/json') + +@bp.patch('//mark_complete') +def mark_task_complete(task_id): + task = validate_model(Task, task_id) + + task.completed_at = datetime.now().date() + db.session.commit() + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..4f9182886 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,8 +5,6 @@ from app.db import db import pytest - -@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -45,8 +43,6 @@ def test_mark_incomplete_on_complete_task(client, completed_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at == None - -@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -85,8 +81,6 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at == None - -@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") @@ -94,11 +88,7 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {'message': 'Task 1 not found'} @pytest.mark.skip(reason="No way to test this feature yet") From 0d1ad37ecefc4b6ea4f614c7067336b0d26d6c25 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 16:50:38 -0400 Subject: [PATCH 16/56] Implements mark_incompleete and passes tests. I feel like I can combine these routes with a endpoint? --- app/routes/task_routes.py | 9 +++++++++ tests/test_wave_03.py | 11 +---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 81c3966fe..d89a20881 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -74,4 +74,13 @@ def mark_task_complete(task_id): task.completed_at = datetime.now().date() db.session.commit() + return Response(status=204, mimetype='application/json') + +@bp.patch('//mark_incomplete') +def mark_task_incomplete(task_id): + task = validate_model(Task, task_id) + + task.completed_at = None + db.session.commit() + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 4f9182886..1ba303a6c 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -31,8 +31,6 @@ def test_mark_complete_on_incomplete_task(client, one_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at - -@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") @@ -70,7 +68,6 @@ def test_mark_complete_on_completed_task(client, completed_task): query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at -@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") @@ -90,8 +87,6 @@ def test_mark_complete_missing_task(client): assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} - -@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") @@ -99,8 +94,4 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {'message': 'Task 1 not found'} \ No newline at end of file From 61a6d6a39933539d6a9e023fbbe4ef12488a8af1 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 16:52:31 -0400 Subject: [PATCH 17/56] Combined mark complete and incomplete in same route --- app/routes/task_routes.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d89a20881..a8e257200 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -67,20 +67,16 @@ def delete_task(task_id): return Response(status=204, mimetype='application/json') -@bp.patch('//mark_complete') -def mark_task_complete(task_id): +@bp.patch('//') +def mark_task_complete(task_id, complete_or_incomplete): task = validate_model(Task, task_id) - task.completed_at = datetime.now().date() - db.session.commit() - - return Response(status=204, mimetype='application/json') - -@bp.patch('//mark_incomplete') -def mark_task_incomplete(task_id): - task = validate_model(Task, task_id) + if complete_or_incomplete == 'mark_complete': + task.completed_at = datetime.now().date() + + else: + task.completed_at = None - task.completed_at = None db.session.commit() return Response(status=204, mimetype='application/json') \ No newline at end of file From 6e30cfced704b2cc304bbfdfeb9bb7989580e0d3 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 17:08:18 -0400 Subject: [PATCH 18/56] Separated mark incomplete and mark complete back into two separate endpoints --- app/routes/task_routes.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index a8e257200..9d969e63c 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,7 +3,6 @@ from ..db import db from app.routes.route_utilities import validate_model from datetime import datetime -from sqlalchemy import update bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @@ -67,15 +66,19 @@ def delete_task(task_id): return Response(status=204, mimetype='application/json') -@bp.patch('//') -def mark_task_complete(task_id, complete_or_incomplete): +@bp.patch('//mark_incomplete') +def mark_task_complete(task_id): task = validate_model(Task, task_id) + task.completed_at = None - if complete_or_incomplete == 'mark_complete': - task.completed_at = datetime.now().date() - - else: - task.completed_at = None + db.session.commit() + + return Response(status=204, mimetype='application/json') + +@bp.patch('//mark_complete') +def mark_task_incomplete(task_id): + task = validate_model(Task, task_id) + task.completed_at = datetime.now().date() db.session.commit() From 10078182fa20c32dc3b612ecf00f3290b6f24279 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Fri, 31 Oct 2025 17:55:47 -0400 Subject: [PATCH 19/56] Fixed complete/incomplete (I had them swapped), successfully posts to the slack channel!!! Yay!!! --- app/routes/task_routes.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 9d969e63c..f357aacd0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,6 +3,8 @@ from ..db import db from app.routes.route_utilities import validate_model from datetime import datetime +import os +import requests bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @@ -67,7 +69,7 @@ def delete_task(task_id): return Response(status=204, mimetype='application/json') @bp.patch('//mark_incomplete') -def mark_task_complete(task_id): +def mark_task_incomplete(task_id): task = validate_model(Task, task_id) task.completed_at = None @@ -76,10 +78,19 @@ def mark_task_complete(task_id): return Response(status=204, mimetype='application/json') @bp.patch('//mark_complete') -def mark_task_incomplete(task_id): +def mark_task_complete(task_id): task = validate_model(Task, task_id) task.completed_at = datetime.now().date() db.session.commit() + slack_token = os.environ["SLACK_BOT_TOKEN"] + channel_and_message = { + 'channel': 'task-notifications', + 'text': f'Someone just completed the task {task.title}' + } + headers = { + 'Authorization': slack_token + } + requests.post('https://slack.com/api/chat.postMessage', data=channel_and_message, json=channel_and_message, headers=headers) return Response(status=204, mimetype='application/json') \ No newline at end of file From cb4f79edcd077671dbd0dc588292e9bf76faab42 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 09:46:59 -0500 Subject: [PATCH 20/56] Implements Goal model, to_dict, from_dict methods for Goal. Will create a model_utilities to generalize the to and from dict methods --- app/models/goal.py | 19 +++++++++++++++++++ tests/test_wave_05.py | 7 ------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..0b0c4e1f9 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,24 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from typing import Optional +from datetime import datetime class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + + @classmethod + def from_dict(cls, goal_data): + new_goal = Goal( + title=goal_data['title'] + ) + + return new_goal + + def to_dict(self): + goal_dict = {} + + goal_dict['id'] = self.id + goal_dict['title'] = self.title + + return goal_dict \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b7cc330ae..91b960cda 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,6 @@ from app.models.goal import Goal import pytest -@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict(): #Arrange new_goal = Goal(id=1, title="Seize the Day!") @@ -13,7 +12,6 @@ def test_goal_to_dict(): assert goal_dict["id"] == 1 assert goal_dict["title"] == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict_no_id(): #Arrange new_goal = Goal(title="Seize the Day!") @@ -25,7 +23,6 @@ def test_goal_to_dict_no_id(): assert goal_dict["id"] is None assert goal_dict["title"] == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict_no_title(): #Arrange new_goal = Goal(id=1) @@ -37,9 +34,6 @@ def test_goal_to_dict_no_title(): assert goal_dict["id"] == 1 assert goal_dict["title"] is None - - -@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict(): #Arrange goal_dict = { @@ -52,7 +46,6 @@ def test_goal_from_dict(): #Assert assert goal_obj.title == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict_no_title(): #Arrange goal_dict = { From 30cda81e1a5162bc4682b4105fee66dde5c81f82 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 09:50:36 -0500 Subject: [PATCH 21/56] Registers goal model bp, implements get one goal by id, implements migration for new table in db for goals --- app/__init__.py | 2 ++ app/routes/goal_routes.py | 15 ++++++++++++- migrations/versions/ae438a556073_.py | 32 ++++++++++++++++++++++++++++ tests/test_wave_05.py | 2 -- 4 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 migrations/versions/ae438a556073_.py diff --git a/app/__init__.py b/app/__init__.py index 617440a9b..6e447bbf7 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 bp as tasks_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -20,5 +21,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/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..1e025ce5d 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,14 @@ -from flask import Blueprint \ No newline at end of file +from flask import abort, Blueprint, make_response, request, Response +from app.models.goal import Goal +from ..db import db +from app.routes.route_utilities import validate_model +from datetime import datetime +import os +import requests + +bp = Blueprint('goals_bp', __name__, url_prefix='/goals') + +@bp.get('/') +def get_one_task_by_id(goal_id): + goal = validate_model(Goal, goal_id) + return goal.to_dict() \ No newline at end of file diff --git a/migrations/versions/ae438a556073_.py b/migrations/versions/ae438a556073_.py new file mode 100644 index 000000000..470c55c9d --- /dev/null +++ b/migrations/versions/ae438a556073_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: ae438a556073 +Revises: 5871594ca6ec +Create Date: 2025-11-02 09:49:33.716237 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'ae438a556073' +down_revision = '5871594ca6ec' +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 91b960cda..f29a5ed8f 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -83,8 +83,6 @@ def test_get_goals_one_saved_goal(client, one_goal): } ] - -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") From ddb83623fdc880ba38ad46291bb4723445911644 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 12:45:42 -0500 Subject: [PATCH 22/56] Creates model utilities file, updates goal routes and tests for wave 5 --- app/models/model_utilities.py | 3 ++ app/routes/goal_routes.py | 55 +++++++++++++++++++++++- tests/test_wave_05.py | 80 +++++++++++------------------------ 3 files changed, 80 insertions(+), 58 deletions(-) create mode 100644 app/models/model_utilities.py diff --git a/app/models/model_utilities.py b/app/models/model_utilities.py new file mode 100644 index 000000000..acde37ff5 --- /dev/null +++ b/app/models/model_utilities.py @@ -0,0 +1,3 @@ +# Create a model instance from a dict + +# Create a dict from a model instance \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 1e025ce5d..4e1378f2d 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -8,7 +8,58 @@ bp = Blueprint('goals_bp', __name__, url_prefix='/goals') +@bp.get('') +def get_all_goals(): + query = db.select(Goal) + goals = db.session.scalars(query) + + response = [] + for goal in goals: + response.append(goal.to_dict()) + + return response + @bp.get('/') -def get_one_task_by_id(goal_id): +def get_one_goal_by_id(goal_id): + goal = validate_model(Goal, goal_id) + return goal.to_dict() + +@bp.post('') +def create_goal(): + request_body = request.get_json() + + try: + new_goal = Goal.from_dict(request_body) + + except KeyError as error: # Missing keys + response = {'details': "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_goal) + db.session.commit() + + new_goal_dict = new_goal.to_dict() + + return new_goal_dict, 201 + +@bp.patch('/') +def mark_task_incomplete(goal_id): goal = validate_model(Goal, goal_id) - return goal.to_dict() \ No newline at end of file + request_body = request.get_json() + + goal.title = request_body['title'] + + db.session.commit() + + response_body = goal.to_dict() + + return response_body, 201 + +@bp.delete('/') +def delete_goal(goal_id): + goal = validate_model(Goal, goal_id) + + db.session.delete(goal) + db.session.commit() + + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index f29a5ed8f..b20997c54 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -55,8 +55,6 @@ def test_goal_from_dict_no_title(): with pytest.raises(KeyError, match = 'title'): Goal.from_dict(goal_dict) - -@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -66,8 +64,6 @@ def test_get_goals_no_saved_goals(client): assert response.status_code == 200 assert response_body == [] - -@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") @@ -95,23 +91,14 @@ def test_get_goal(client, one_goal): "title": "Build a habit of going outside daily" } - -@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") - # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- - - -@pytest.mark.skip(reason="No way to test this feature yet") + assert response.status_code == 404 + assert "message" in response_body + assert response_body == {'message': 'Goal 1 not found'} + def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -126,35 +113,28 @@ def test_create_goal(client): "title": "My New Goal" } - -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- + response = client.patch("/goals/1", json={ + "title": "My New Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 201 + assert response_body == { + "id": 1, + "title": "My New Title" + } -@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- - - # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + response = client.delete("/goals/1") + assert response.status_code == 404 + response_body = response.get_json() + assert "message" in response_body + assert response_body == {'message': 'Goal 1 not found'} -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -168,28 +148,16 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "message" in response_body + assert response_body == {'message': 'Goal 1 not found'} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - - -@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") - - # Act - # ---- Complete Act Here ---- - - # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + response = client.delete("/goals/1") + assert response.status_code == 404 + response_body = response.get_json() + assert "message" in response_body + assert response_body == {'message': 'Goal 1 not found'} -@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 7411f0a248c91fcbad65185e77cc2f3ef8a40e98 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 15:07:14 -0500 Subject: [PATCH 23/56] Establishes one to many relationship for goal to tasks, migration included --- app/models/goal.py | 3 ++- app/models/task.py | 5 +++- migrations/versions/dae463354287_.py | 34 ++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 migrations/versions/dae463354287_.py diff --git a/app/models/goal.py b/app/models/goal.py index 0b0c4e1f9..3f5a8d92a 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,4 +1,4 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db from typing import Optional from datetime import datetime @@ -6,6 +6,7 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] + tasks: Mapped[list['Task']] = relationship(back_populates='goal') @classmethod def from_dict(cls, goal_data): diff --git a/app/models/task.py b/app/models/task.py index 361687205..6e863f471 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,4 +1,5 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey from ..db import db from typing import Optional from datetime import datetime @@ -8,6 +9,8 @@ class Task(db.Model): title: Mapped[str] description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey('goal.id')) + goal: Mapped[Optional['Goal']] = relationship(back_populates='tasks') @classmethod def from_dict(cls, task_data): diff --git a/migrations/versions/dae463354287_.py b/migrations/versions/dae463354287_.py new file mode 100644 index 000000000..93f4dc8be --- /dev/null +++ b/migrations/versions/dae463354287_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: dae463354287 +Revises: ae438a556073 +Create Date: 2025-11-02 15:06:43.191168 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'dae463354287' +down_revision = 'ae438a556073' +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 ### From 16f95311c6e480e63e66e241ae5912e307f998b4 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 15:33:12 -0500 Subject: [PATCH 24/56] implements send list of tasks id to assign to goal --- app/routes/goal_routes.py | 22 +++++++++++++++++++++- tests/test_wave_06.py | 4 ---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 4e1378f2d..437a10006 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,5 +1,6 @@ from flask import abort, Blueprint, make_response, request, Response from app.models.goal import Goal +from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model from datetime import datetime @@ -62,4 +63,23 @@ def delete_goal(goal_id): db.session.delete(goal) db.session.commit() - return Response(status=204, mimetype='application/json') \ No newline at end of file + return Response(status=204, mimetype='application/json') + +@bp.post('//tasks') +def send_list_of_task_ids_to_goal(goal_id): + request_body = request.get_json() + goal = validate_model(Goal, goal_id) + + goal.tasks = [] + + for task_id in request_body['task_ids']: + task = validate_model(Task, task_id) + task.goal_id = goal_id + + db.session.commit() + + request_body['id'] = goal.id + + return request_body, 200 + + diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 727fce93a..73320b1b1 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,8 +2,6 @@ from app.db import db import pytest - -@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={ @@ -24,8 +22,6 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): query = db.select(Goal).where(Goal.id == 1) assert len(db.session.scalar(query).tasks) == 3 - -@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ From 740983ab4dcff8ed36fbb5fbf5c1b6f831886082 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 15:44:39 -0500 Subject: [PATCH 25/56] implements get tasks from a goal id --- app/routes/goal_routes.py | 15 +++++++++++++++ tests/test_wave_06.py | 4 ---- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 437a10006..c88f5189c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -82,4 +82,19 @@ def send_list_of_task_ids_to_goal(goal_id): return request_body, 200 +@bp.get('//tasks') +def get_tasks_from_goal_id(goal_id): + goal = validate_model(Goal, goal_id) + + query = db.select(Task).where(Task.goal_id == goal_id) + tasks = db.session.scalars(query) + + response = goal.to_dict() + response['tasks'] = [] + + for task in tasks: + task_dict = task.to_dict() + task_dict['goal_id'] = goal.id + response['tasks'].append(task_dict) + return response \ No newline at end of file diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 73320b1b1..4c90e937a 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -55,8 +55,6 @@ def test_get_tasks_for_specific_goal_no_goal(client): # **Complete test with assertion about response body*************** # ***************************************************************** - -@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") @@ -72,8 +70,6 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): "tasks": [] } - -@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") From a6ad135eb570617d65879820beed57247aedb30a Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Sun, 2 Nov 2025 15:48:58 -0500 Subject: [PATCH 26/56] Adjusts task to_dict method to include goal id --- app/models/task.py | 3 +++ tests/test_wave_06.py | 10 +--------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 6e863f471..fb4fe4a5f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -30,6 +30,9 @@ def to_dict(self): if self.completed_at is None: task_dict['is_complete'] = False + + if self.goal_id: + task_dict['goal_id'] = self.goal_id task_dict['id'] = self.id task_dict['title'] = self.title diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 4c90e937a..047e565cb 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -40,8 +40,6 @@ def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belong query = db.select(Goal).where(Goal.id == 1) assert len(db.session.scalar(query).tasks) == 2 - -@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") @@ -49,11 +47,7 @@ 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") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {'message': 'Goal 1 not found'} def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act @@ -93,8 +87,6 @@ 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") 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 f1b5163fbe58c1822fe2aed0342bb2657227bcb7 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:02:01 -0500 Subject: [PATCH 27/56] Implements create_model method to generalize creating a model from a dictionary, passes all tests --- app/routes/goal_routes.py | 17 ++--------------- app/routes/route_utilities.py | 19 ++++++++++--------- app/routes/task_routes.py | 17 ++--------------- tests/test_wave_07.py | 12 +++--------- 4 files changed, 17 insertions(+), 48 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index c88f5189c..c82a5ca0c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,7 +2,7 @@ from app.models.goal import Goal from app.models.task import Task from ..db import db -from app.routes.route_utilities import validate_model +from app.routes.route_utilities import validate_model, create_model from datetime import datetime import os import requests @@ -28,20 +28,7 @@ def get_one_goal_by_id(goal_id): @bp.post('') def create_goal(): request_body = request.get_json() - - try: - new_goal = Goal.from_dict(request_body) - - except KeyError as error: # Missing keys - response = {'details': "Invalid data"} - abort(make_response(response, 400)) - - db.session.add(new_goal) - db.session.commit() - - new_goal_dict = new_goal.to_dict() - - return new_goal_dict, 201 + return create_model(Goal, request_body) @bp.patch('/') def mark_task_incomplete(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 5a7e52267..7c330763f 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -18,14 +18,15 @@ def validate_model(cls, model_id): return model -def create_instance(cls, data): - pass +def create_model(cls, model_data): + try: + new_model = cls.from_dict(model_data) + + except KeyError as error: + response = {'details': f'Invalid data'} + abort(make_response(response, 400)) -# create an instance of model_class -# for each key, value in data_dict: -# if the key corresponds to a valid model attribute: -# set that attribute on the instance -# handle any special-case logic (like completed_at) -# return the instance + db.session.add(new_model) + db.session.commit() -# involves dir() and __dir__ for the class definition. dir() returns a list of the object's attributes, and __dir__ within class definition lets us customize output of dir(). will save this for later wave when I make the goal model. \ No newline at end of file + return new_model.to_dict(), 201 \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index f357aacd0..ee6f1683b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,7 @@ from flask import abort, Blueprint, make_response, request, Response from app.models.task import Task from ..db import db -from app.routes.route_utilities import validate_model +from app.routes.route_utilities import validate_model, create_model from datetime import datetime import os import requests @@ -33,20 +33,7 @@ def get_one_task_by_id(task_id): @bp.post('') def create_task(): request_body = request.get_json() - - try: - new_task = Task.from_dict(request_body) - - except KeyError as error: # Missing keys - response = {'details': "Invalid data"} - abort(make_response(response, 400)) - - db.session.add(new_task) - db.session.commit() - - new_task_dict = new_task.to_dict() - - return new_task_dict, 201 + return create_model(Task, request_body) @bp.put('/') def update_task(task_id): diff --git a/tests/test_wave_07.py b/tests/test_wave_07.py index 7e7cef55a..2f0edf6be 100644 --- a/tests/test_wave_07.py +++ b/tests/test_wave_07.py @@ -84,7 +84,6 @@ def test_route_utilities_validate_model_with_goal_missing_id(client, one_goal): # **Complete test with assertion about status code response body*************** # ***************************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_task(client): #Arrange request_body = { @@ -103,7 +102,6 @@ def test_route_utilities_create_model_with_task(client): assert response[0]["is_complete"] == False assert response[1] == 201 -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_task_missing_title(client): #Arrange request_body = { @@ -119,8 +117,6 @@ def test_route_utilities_create_model_with_task_missing_title(client): assert response.status_code == 400 assert response.get_json() == {"details": "Invalid data"} - -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_goal(client): #Arrange request_body = { @@ -135,7 +131,6 @@ def test_route_utilities_create_model_with_goal(client): assert response[0]["title"] == "Seize the Day!" assert response[1] == 201 -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_create_model_with_goal_missing_title(client): #Arrange request_body = { @@ -145,7 +140,6 @@ def test_route_utilities_create_model_with_goal_missing_title(client): with pytest.raises(HTTPException) as e: create_model(Goal, request_body) - raise Exception("Complete test with assertion status code and response body") - # ***************************************************************************** - # **Complete test with assertion about status code response body*************** - # ***************************************************************************** + response = e.value.get_response() + assert response.status_code == 400 + assert response.get_json() == {"details": "Invalid data"} From b2d63bf008617e2b9cdf556938fdecc77a20ddde Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:08:08 -0500 Subject: [PATCH 28/56] Clean up import statements --- app/models/goal.py | 2 -- app/routes/goal_routes.py | 5 +---- app/routes/task_routes.py | 2 +- 3 files changed, 2 insertions(+), 7 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 3f5a8d92a..e65c3133b 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,7 +1,5 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db -from typing import Optional -from datetime import datetime class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index c82a5ca0c..08cd25dc8 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,11 +1,8 @@ -from flask import abort, Blueprint, make_response, request, Response +from flask import Blueprint, request, Response from app.models.goal import Goal from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model, create_model -from datetime import datetime -import os -import requests bp = Blueprint('goals_bp', __name__, url_prefix='/goals') diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ee6f1683b..df3c3b3c8 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, make_response, request, Response +from flask import abort, Blueprint, request, Response from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model, create_model From 46ca6779ba3a175374e4b0c3f22aeeb6d48ddff6 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:11:36 -0500 Subject: [PATCH 29/56] more import cleanup --- app/routes/task_routes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index df3c3b3c8..54c29e991 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,4 +1,4 @@ -from flask import abort, Blueprint, request, Response +from flask import Blueprint, request, Response from app.models.task import Task from ..db import db from app.routes.route_utilities import validate_model, create_model From 6814fa35d943da796082d3535afafc61f0170693 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:14:52 -0500 Subject: [PATCH 30/56] get all tasks list comprehension --- app/routes/task_routes.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 54c29e991..dfc89957c 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -19,11 +19,7 @@ def get_all_tasks(): query = query.order_by(Task.title.desc()) tasks = db.session.scalars(query) - task_list = [] - for task in tasks: - task_list.append(task.to_dict()) - - return task_list + return [task.to_dict() for task in tasks] @bp.get('/') def get_one_task_by_id(task_id): From 7fcc9c2c5c2d43ed60d29121ac3dea84108915e8 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:20:06 -0500 Subject: [PATCH 31/56] list comprehension for get_tasks_from_goal_id route --- app/routes/goal_routes.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 08cd25dc8..0a384e2c8 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -74,11 +74,9 @@ def get_tasks_from_goal_id(goal_id): tasks = db.session.scalars(query) response = goal.to_dict() - response['tasks'] = [] + response['tasks'] = [task.to_dict() for task in tasks] for task in tasks: - task_dict = task.to_dict() - task_dict['goal_id'] = goal.id - response['tasks'].append(task_dict) + task['goal_id'] = goal.id return response \ No newline at end of file From b1c67156164c6dce1c8c10fac2ae1c5bf7e26ec4 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:23:15 -0500 Subject: [PATCH 32/56] patch method was titled incorrectly --- app/routes/goal_routes.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 08cd25dc8..f344fd257 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -28,17 +28,15 @@ def create_goal(): return create_model(Goal, request_body) @bp.patch('/') -def mark_task_incomplete(goal_id): +def update_goal_title(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() - + goal.title = request_body['title'] db.session.commit() - response_body = goal.to_dict() - - return response_body, 201 + return Response(status=204, mimetype='application/json') @bp.delete('/') def delete_goal(goal_id): From a1296e3c0e7323e12b220d8e17f108b7e8ee76fd Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:24:39 -0500 Subject: [PATCH 33/56] list comprehension for get all goals route --- app/routes/goal_routes.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 0a384e2c8..0f10aafbf 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -10,12 +10,8 @@ def get_all_goals(): query = db.select(Goal) goals = db.session.scalars(query) - - response = [] - for goal in goals: - response.append(goal.to_dict()) - return response + return [goal.to_dict() for goal in goals] @bp.get('/') def get_one_goal_by_id(goal_id): From 16f1c1c0896c1f2da1fd419f0887c89e1f80b9a3 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:33:49 -0500 Subject: [PATCH 34/56] Implements wave 7 assert statements and cleans up comments --- tests/test_wave_07.py | 62 +++++++++---------------------------------- 1 file changed, 13 insertions(+), 49 deletions(-) diff --git a/tests/test_wave_07.py b/tests/test_wave_07.py index 2f0edf6be..0aeab6bd3 100644 --- a/tests/test_wave_07.py +++ b/tests/test_wave_07.py @@ -4,14 +4,11 @@ from app.models.task import Task from app.routes.route_utilities import create_model, validate_model -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_task(client, three_tasks): - #Act task_1 = validate_model(Task, 1) task_2 = validate_model(Task, 2) task_3 = validate_model(Task, 3) - #Assert assert task_1.id == 1 assert task_1.title == "Water the garden 🌷" assert task_1.description == "" @@ -23,93 +20,65 @@ def test_route_utilities_validate_model_with_task(client, three_tasks): assert task_3.id == 3 assert task_3.title == "Pay my outstanding tickets 😭" - -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_task_invalid_id(client, three_tasks): - #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) as e: result_task = validate_model(Task, "One") - # Test that the correct status code and response message are returned response = e.value.get_response() assert response.status_code == 400 + assert response.get_json() == {"message": "Task One invalid"} - raise Exception("Complete test with an assertion about the response body") - # ***************************************************************************** - # ** Complete test with an assertion about the response body **************** - # ***************************************************************************** - -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_task_missing_id(client, three_tasks): - #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Task, 4) - raise Exception("Complete test with assertion status code and response body") - # ***************************************************************************** - # **Complete test with assertion about status code response body*************** - # ***************************************************************************** + response = e.value.get_response() + assert response.status_code == 404 + assert response.get_json() == {'message': 'Task 4 not found'} - -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_goal(client, one_goal): - #Act goal_1 = validate_model(Goal, 1) - #Assert assert goal_1.id == 1 assert goal_1.title == "Build a habit of going outside daily" -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_goal_invalid_id(client, one_goal): - #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Goal, "One") - raise Exception("Complete test with assertion status code and response body") - # ***************************************************************************** - # **Complete test with assertion about status code response body*************** - # ***************************************************************************** + response = e.value.get_response() + assert response.status_code == 400 + assert response.get_json() == {"message": "Goal One invalid"} -@pytest.mark.skip(reason="No way to test this feature yet") def test_route_utilities_validate_model_with_goal_missing_id(client, one_goal): - #Act & Assert with pytest.raises(HTTPException) as e: result_task = validate_model(Goal, 4) - raise Exception("Complete test with assertion status code and response body") - # ***************************************************************************** - # **Complete test with assertion about status code response body*************** - # ***************************************************************************** + response = e.value.get_response() + assert response.status_code == 404 + assert response.get_json() == {'message': 'Goal 4 not found'} def test_route_utilities_create_model_with_task(client): - #Arrange request_body = { "title": "Make the bed", "description": "", "completed_at": None } - - #Act + response = create_model(Task, request_body) - #Assert - assert response[0]["id"] == 1 #create_model returns a tuple + assert response[0]["id"] == 1 assert response[0]["title"] == "Make the bed" assert response[0]["description"] == "" assert response[0]["is_complete"] == False assert response[1] == 201 def test_route_utilities_create_model_with_task_missing_title(client): - #Arrange request_body = { "description": "", "completed_at": None } - #Act with pytest.raises(HTTPException) as e: create_model(Task, request_body) @@ -118,25 +87,20 @@ def test_route_utilities_create_model_with_task_missing_title(client): assert response.get_json() == {"details": "Invalid data"} def test_route_utilities_create_model_with_goal(client): - #Arrange request_body = { "title": "Seize the Day!" } - #Act response = create_model(Goal, request_body) - #Assert - assert response[0]["id"] == 1 #create_model returns a tuple + assert response[0]["id"] == 1 assert response[0]["title"] == "Seize the Day!" assert response[1] == 201 def test_route_utilities_create_model_with_goal_missing_title(client): - #Arrange request_body = { } - #Act with pytest.raises(HTTPException) as e: create_model(Goal, request_body) From 89c1804ff3dea7480d4ac4f880120948cf6105c1 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Mon, 3 Nov 2025 15:39:19 -0500 Subject: [PATCH 35/56] Updates wave 5 test to match updated patch method --- tests/test_wave_05.py | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b20997c54..d0cbf9d77 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -117,14 +117,8 @@ def test_update_goal(client, one_goal): response = client.patch("/goals/1", json={ "title": "My New Title" }) - response_body = response.get_json() - # Assert - assert response.status_code == 201 - assert response_body == { - "id": 1, - "title": "My New Title" - } + assert response.status_code == 204 def test_update_goal_not_found(client): From ab5576382ea755f3f3accfbc90244ad370abf553 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 15:35:58 -0500 Subject: [PATCH 36/56] Adds tasks attribute to Goal, adds goal_id and goal attributes to Task --- app/models/goal.py | 18 +++++++----------- app/models/task.py | 5 ++++- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 0b0c4e1f9..bb6684a44 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,4 +1,4 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db from typing import Optional from datetime import datetime @@ -6,19 +6,15 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] + tasks: Mapped[list["Task"]] = relationship(back_populates="goal") @classmethod def from_dict(cls, goal_data): - new_goal = Goal( - title=goal_data['title'] - ) - + new_goal = cls(title=goal_data['title']) return new_goal def to_dict(self): - goal_dict = {} - - goal_dict['id'] = self.id - goal_dict['title'] = self.title - - return goal_dict \ No newline at end of file + return { + 'id': self.id, + 'title': self.title + } \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 361687205..8653f89ec 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,4 +1,5 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey from ..db import db from typing import Optional from datetime import datetime @@ -8,6 +9,8 @@ class Task(db.Model): title: Mapped[str] description: Mapped[str] completed_at: Mapped[Optional[datetime]] = mapped_column(nullable=True) + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional['Goal']] = relationship(back_populates="tasks") @classmethod def from_dict(cls, task_data): From 6adb2dd00b95f1c4441404021946e30b93854bdf Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 15:40:27 -0500 Subject: [PATCH 37/56] Registers goal routes bp --- app/__init__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 617440a9b..28bf3c67c 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 bp as tasks_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -11,14 +12,12 @@ def create_app(config=None): app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') if config: - # Merge `config` into the app's configuration - # to override the app's default settings for testing app.config.update(config) db.init_app(app) migrate.init_app(app, db) - # Register Blueprints here app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app From 5c7c412d8ad61bd8e63859b410b6b25877622c16 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 15:58:17 -0500 Subject: [PATCH 38/56] create_model route helper, goal routes for create, get all, and delete one by id --- app/routes/goal_routes.py | 25 ++++++++++++++++++++++++- app/routes/route_utilities.py | 19 ++++++++++--------- 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..78cbc8f03 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,24 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response +from ..models.goal import Goal +from ..db import db +from .route_utilities import validate_model, create_model + +bp = Blueprint('goals_bp', __name__, url_prefix='/goals') + +@bp.get('') +def get_all_goals(): + query = db.select(Goal) + goals = db.session.scalars(query) + return [goal.to_dict() for goal in goals] + +@bp.post('') +def create_goal(): + goal_data = request.get_json() + return create_model(Goal, goal_data) + +@bp.delete('') +def delete_goal(goal_id): + goal = validate_model(Goal, goal_id) + db.session.delete(goal) + db.session.commit() + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 5a7e52267..7c330763f 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -18,14 +18,15 @@ def validate_model(cls, model_id): return model -def create_instance(cls, data): - pass +def create_model(cls, model_data): + try: + new_model = cls.from_dict(model_data) + + except KeyError as error: + response = {'details': f'Invalid data'} + abort(make_response(response, 400)) -# create an instance of model_class -# for each key, value in data_dict: -# if the key corresponds to a valid model attribute: -# set that attribute on the instance -# handle any special-case logic (like completed_at) -# return the instance + db.session.add(new_model) + db.session.commit() -# involves dir() and __dir__ for the class definition. dir() returns a list of the object's attributes, and __dir__ within class definition lets us customize output of dir(). will save this for later wave when I make the goal model. \ No newline at end of file + return new_model.to_dict(), 201 \ No newline at end of file From 067a983b54ce57a5d10d4bd27687444afacb2c5b Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:13:19 -0500 Subject: [PATCH 39/56] post task ids to goal route implemented, passes tests --- app/routes/goal_routes.py | 22 +++++++++++++++++++++- tests/test_wave_06.py | 4 ---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 78cbc8f03..86d78e6f0 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,5 +1,6 @@ from flask import Blueprint, request, Response from ..models.goal import Goal +from ..models.task import Task from ..db import db from .route_utilities import validate_model, create_model @@ -21,4 +22,23 @@ def delete_goal(goal_id): goal = validate_model(Goal, goal_id) db.session.delete(goal) db.session.commit() - return Response(status=204, mimetype='application/json') \ No newline at end of file + return Response(status=204, mimetype='application/json') + +@bp.post('//tasks') +def post_task_ids_to_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + goal.tasks = [] + + for id in request_body['task_ids']: + task = validate_model(Task, id) + task.goal_id = goal.id + + db.session.commit() + + response = { + 'id': goal.id, + 'task_ids': [task.id for task in goal.tasks] + } + return response, 200 \ No newline at end of file diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 727fce93a..73320b1b1 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,8 +2,6 @@ from app.db import db import pytest - -@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={ @@ -24,8 +22,6 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): query = db.select(Goal).where(Goal.id == 1) assert len(db.session.scalar(query).tasks) == 3 - -@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ From d9739cb83bf9792d18baaa339e2a80d009fc86aa Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:29:47 -0500 Subject: [PATCH 40/56] updates wave 6 methods because I thought I really messed them up --- app/models/goal.py | 7 ++++--- app/models/task.py | 6 +++++- app/routes/goal_routes.py | 6 ++++++ tests/test_wave_06.py | 14 +------------- 4 files changed, 16 insertions(+), 17 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index bb6684a44..e18fe6f44 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -15,6 +15,7 @@ def from_dict(cls, goal_data): def to_dict(self): return { - 'id': self.id, - 'title': self.title - } \ No newline at end of file + 'id': self.id, + 'title': self.title, + 'tasks': [task.to_dict() for task in self.tasks] + } \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 8653f89ec..4bdd337dd 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -20,7 +20,8 @@ def from_dict(cls, task_data): new_task = Task( title=task_data['title'], description=task_data['description'], - completed_at=task_data['is_complete'] + completed_at=task_data['is_complete'], + goal_id=task_data.get('goal_id', None) ) return new_task @@ -31,6 +32,9 @@ def to_dict(self): if self.completed_at is None: task_dict['is_complete'] = False + if self.goal_id: + task_dict['goal_id'] = self.goal_id + task_dict['id'] = self.id task_dict['title'] = self.title task_dict['description'] = self.description diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 86d78e6f0..0a4eeed49 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -41,4 +41,10 @@ def post_task_ids_to_goal(goal_id): 'id': goal.id, 'task_ids': [task.id for task in goal.tasks] } + return response, 200 + +@bp.get('//tasks') +def get_tasks_for_specific_goal(goal_id): + goal = validate_model(Goal, goal_id) + response = goal.to_dict() return response, 200 \ No newline at end of file diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 73320b1b1..047e565cb 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -40,8 +40,6 @@ def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belong query = db.select(Goal).where(Goal.id == 1) assert len(db.session.scalar(query).tasks) == 2 - -@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") @@ -49,14 +47,8 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert response_body == {'message': 'Goal 1 not found'} - 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") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -72,8 +64,6 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): "tasks": [] } - -@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") @@ -97,8 +87,6 @@ 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") 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 468abc7bece8f13f988b5a1f846cae9fe45307f2 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:39:03 -0500 Subject: [PATCH 41/56] deleted a double line --- app/models/task.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index f699eaa14..914835f53 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -32,9 +32,6 @@ def to_dict(self): if self.completed_at is None: task_dict['is_complete'] = False - if self.goal_id: - task_dict['goal_id'] = self.goal_id - if self.goal_id: task_dict['goal_id'] = self.goal_id From 2f9fe6af33acc9f16c72e919337b5dec3be9f7e6 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:43:56 -0500 Subject: [PATCH 42/56] writes the patch method to update goal title --- app/models/goal.py | 3 +-- app/routes/goal_routes.py | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index 01b19c655..492fe0a6a 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -14,6 +14,5 @@ def from_dict(cls, goal_data): def to_dict(self): return { 'id': self.id, - 'title': self.title, - 'tasks': [task.to_dict() for task in self.tasks] + 'title': self.title } \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index a8b11d9e0..02f80b4a7 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -6,16 +6,29 @@ bp = Blueprint('goals_bp', __name__, url_prefix='/goals') +@bp.post('') +def create_goal(): + goal_data = request.get_json() + return create_model(Goal, goal_data) + @bp.get('') def get_all_goals(): query = db.select(Goal) goals = db.session.scalars(query) return [goal.to_dict() for goal in goals] -@bp.post('') -def create_goal(): - goal_data = request.get_json() - return create_model(Goal, goal_data) +@bp.get('/') +def get_goal_by_id(goal_id): + goal = validate_model(Goal, goal_id) + return goal.to_dict() + +@bp.patch('/') +def update_goal_title(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + goal.title = request_body['title'] + db.session.commit() + return Response(status=204, mimetype='application/json') @bp.delete('') def delete_goal(goal_id): From 61aa81922cb02befcc42c65f35e1ae757834a914 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:46:09 -0500 Subject: [PATCH 43/56] generalizes patch to include more than one attribute to update --- app/routes/goal_routes.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 02f80b4a7..e0cda070a 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -26,8 +26,13 @@ def get_goal_by_id(goal_id): def update_goal_title(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() - goal.title = request_body['title'] + + for attribute, value in request_body: + if hasattr(goal, attribute): + getattr(goal, attribute) = value + db.session.commit() + return Response(status=204, mimetype='application/json') @bp.delete('') From 478dedcd6ab1e82316502457b45a19376da2d696 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:51:02 -0500 Subject: [PATCH 44/56] fixes reassigning attribute value when making patch request --- app/routes/goal_routes.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index e0cda070a..829a7f9d6 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -26,10 +26,10 @@ def get_goal_by_id(goal_id): def update_goal_title(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() - + for attribute, value in request_body: if hasattr(goal, attribute): - getattr(goal, attribute) = value + goal[attribute] = value db.session.commit() From cf9727656b7025ef332126c32d0708cd0e362e65 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 16:56:28 -0500 Subject: [PATCH 45/56] minor fix to for attr, value in request_body.items() goal patch method --- app/routes/goal_routes.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 829a7f9d6..36c81cb5e 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -27,9 +27,9 @@ def update_goal_title(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() - for attribute, value in request_body: + for attribute, value in request_body.items(): if hasattr(goal, attribute): - goal[attribute] = value + goal.attribute = value db.session.commit() @@ -65,4 +65,5 @@ def post_task_ids_to_goal(goal_id): def get_tasks_for_specific_goal(goal_id): goal = validate_model(Goal, goal_id) response = goal.to_dict() + response['tasks'] = [task.to_dict() for task in goal.tasks] return response, 200 From c15d21f388977fde6922ea5a551059ee93c95ca8 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Tue, 4 Nov 2025 17:22:50 -0500 Subject: [PATCH 46/56] implements get_models_with_filters that also sorts the query by title. works for both goal and task and passes all tests after refactoring. --- app/routes/goal_routes.py | 6 ++---- app/routes/route_utilities.py | 22 ++++++++++++++++++++-- app/routes/task_routes.py | 13 ++----------- 3 files changed, 24 insertions(+), 17 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 36c81cb5e..25e2decb4 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -2,7 +2,7 @@ from ..models.goal import Goal from ..models.task import Task from ..db import db -from .route_utilities import validate_model, create_model +from .route_utilities import validate_model, create_model, get_models_with_filters bp = Blueprint('goals_bp', __name__, url_prefix='/goals') @@ -13,9 +13,7 @@ def create_goal(): @bp.get('') def get_all_goals(): - query = db.select(Goal) - goals = db.session.scalars(query) - return [goal.to_dict() for goal in goals] + return get_models_with_filters(Goal, request.args) @bp.get('/') def get_goal_by_id(goal_id): diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 7c330763f..4d63bff20 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,4 +1,4 @@ -from flask import abort, make_response +from flask import abort, make_response, request from ..db import db def validate_model(cls, model_id): @@ -29,4 +29,22 @@ def create_model(cls, model_data): db.session.add(new_model) db.session.commit() - return new_model.to_dict(), 201 \ No newline at end of file + return new_model.to_dict(), 201 + +def get_models_with_filters(cls, filters=None): + query = db.select(cls) + + if filters: + for attr, value in filters.items(): + if hasattr(cls, attr): + query = query.where(getattr(cls, attr).ilike(f'%{value}%')) + + elif attr == 'sort': + if value == 'desc': + query = query.order_by(cls.title.desc()) + else: + query = query.order_by(cls.title) + + models = db.session.scalars(query) + models_response = [model.to_dict() for model in models] + return models_response \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index dfc89957c..061e3b9d7 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, request, Response from app.models.task import Task from ..db import db -from app.routes.route_utilities import validate_model, create_model +from app.routes.route_utilities import validate_model, create_model, get_models_with_filters from datetime import datetime import os import requests @@ -10,16 +10,7 @@ @bp.get('') def get_all_tasks(): - query = db.select(Task) - - sort_param = request.args.get('sort') - if sort_param == 'asc' or sort_param is None: - query = query.order_by(Task.title) - elif sort_param == 'desc': - query = query.order_by(Task.title.desc()) - - tasks = db.session.scalars(query) - return [task.to_dict() for task in tasks] + return get_models_with_filters(Task, request.args) @bp.get('/') def get_one_task_by_id(task_id): From 23c44c8e600f8dd6706a8e72ee68965f2410d039 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 15:16:39 -0500 Subject: [PATCH 47/56] adds three goals fixture for optional feature testing --- tests/conftest.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index a01499583..cff08ff68 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -104,4 +104,12 @@ def one_task_belongs_to_one_goal(app, one_goal, one_task): task = db.session.scalar(task_query) goal = db.session.scalar(goal_query) goal.tasks.append(task) + db.session.commit() + +@pytest.fixture +def three_goals(app): + goal_1 = Goal(title='Prioritize Self Care 🧖‍♀️') + goal_2 = Goal(title='Perfect My Wind Down Routine 🌙') + goal_3 = Goal(title='Tidy Spaces, Tidy Mind 🫧') + db.session.add_all([goal_1, goal_2, goal_3]) db.session.commit() \ No newline at end of file From b0bfe9c7d888af4996ae54f5a0b0092c13fee65e Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 15:17:14 -0500 Subject: [PATCH 48/56] expands upon get_models_with_filters to include logic to sort by any column in either direction --- app/routes/route_utilities.py | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 4d63bff20..3aecea781 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -33,18 +33,22 @@ def create_model(cls, model_data): def get_models_with_filters(cls, filters=None): query = db.select(cls) - - if filters: - for attr, value in filters.items(): - if hasattr(cls, attr): - query = query.where(getattr(cls, attr).ilike(f'%{value}%')) - - elif attr == 'sort': - if value == 'desc': - query = query.order_by(cls.title.desc()) - else: - query = query.order_by(cls.title) + if filters: + sort_by = filters.get('sort_by', 'title') + direction = filters.get('sort', None) + + for attribute, value in filters.items(): + if hasattr(cls, attribute): + query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) + + if hasattr(cls, sort_by): + sort_column = getattr(cls, sort_by) + if direction == 'desc': + query = query.order_by(sort_column.desc()) + else: + query = query.order_by(sort_column) + models = db.session.scalars(query) models_response = [model.to_dict() for model in models] return models_response \ No newline at end of file From 4daac792c8f65408213880bf7918a788cbb5d3b3 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 15:17:39 -0500 Subject: [PATCH 49/56] writes tests to test filtering and sorting method --- app/routes/task_routes.py | 2 +- tests/test_query_params_refactor.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 tests/test_query_params_refactor.py diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 061e3b9d7..0807825c5 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -10,7 +10,7 @@ @bp.get('') def get_all_tasks(): - return get_models_with_filters(Task, request.args) + return get_models_with_filters(Task, request.args), 200 @bp.get('/') def get_one_task_by_id(task_id): diff --git a/tests/test_query_params_refactor.py b/tests/test_query_params_refactor.py new file mode 100644 index 000000000..2659e1e1e --- /dev/null +++ b/tests/test_query_params_refactor.py @@ -0,0 +1,21 @@ +def test_get_tasks_sorted_by_id_asc(client, three_tasks): + response = client.get('/tasks?sort=asc&sort_by=id') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['id'] == 1 + assert response_body[1]['id'] == 2 + assert response_body[2]['id'] == 3 + +def test_get_tasks_sorted_by_id_desc(client, three_tasks): + response = client.get('/tasks?sort=desc&sort_by=id') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['id'] == 3 + assert response_body[1]['id'] == 2 + assert response_body[2]['id'] == 1 + +def test_get_goals_sorted_by_id_asc(client, ) \ No newline at end of file From c882bda298ecc7b2ed32a715ff1aad30bddb9936 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 15:33:19 -0500 Subject: [PATCH 50/56] finishes tests for query params to determine sort direction and by which column to sort by --- app/routes/route_utilities.py | 5 ++- tests/test_query_params_refactor.py | 70 ++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 3aecea781..bcbf1c0d1 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -33,7 +33,7 @@ def create_model(cls, model_data): def get_models_with_filters(cls, filters=None): query = db.select(cls) - + if filters: sort_by = filters.get('sort_by', 'title') direction = filters.get('sort', None) @@ -48,6 +48,9 @@ def get_models_with_filters(cls, filters=None): query = query.order_by(sort_column.desc()) else: query = query.order_by(sort_column) + + else: + query = query.order_by(cls.title) models = db.session.scalars(query) models_response = [model.to_dict() for model in models] diff --git a/tests/test_query_params_refactor.py b/tests/test_query_params_refactor.py index 2659e1e1e..0d49d0df0 100644 --- a/tests/test_query_params_refactor.py +++ b/tests/test_query_params_refactor.py @@ -18,4 +18,72 @@ def test_get_tasks_sorted_by_id_desc(client, three_tasks): assert response_body[1]['id'] == 2 assert response_body[2]['id'] == 1 -def test_get_goals_sorted_by_id_asc(client, ) \ No newline at end of file +def test_get_tasks_sort_by_default(client, three_tasks): + response = client.get('/tasks') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['title'] == 'Answer forgotten email 📧' + assert response_body[1]['title'] == 'Pay my outstanding tickets 😭' + assert response_body[2]['title'] == 'Water the garden 🌷' + +def test_get_goals_sorted_by_id_asc(client, three_goals): + response = client.get('/goals?sort=asc&sort_by=id') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['id'] == 1 + assert response_body[1]['id'] == 2 + assert response_body[2]['id'] == 3 + +def test_get_goals_sorted_by_id_desc(client, three_goals): + response = client.get('/goals?sort=desc&sort_by=id') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['id'] == 3 + assert response_body[1]['id'] == 2 + assert response_body[2]['id'] == 1 + +def test_get_goals_sorted_by_title_asc(client, three_goals): + response = client.get('/goals?sort=asc&sort_by=title') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['title'] == 'Perfect My Wind Down Routine 🌙' + assert response_body[1]['title'] == 'Prioritize Self Care 🧖‍♀️' + assert response_body[2]['title'] == 'Tidy Spaces, Tidy Mind 🫧' + +def test_get_goals_sorted_by_title_desc(client, three_goals): + response = client.get('/goals?sort=desc&sort_by=title') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['title'] == 'Tidy Spaces, Tidy Mind 🫧' + assert response_body[1]['title'] == 'Prioritize Self Care 🧖‍♀️' + assert response_body[2]['title'] == 'Perfect My Wind Down Routine 🌙' + +def test_get_goals_sort_by_default(client, three_goals): + response = client.get('/goals') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['title'] == 'Perfect My Wind Down Routine 🌙' + assert response_body[1]['title'] == 'Prioritize Self Care 🧖‍♀️' + assert response_body[2]['title'] == 'Tidy Spaces, Tidy Mind 🫧' + +def test_get_goals_sorted_by_id_default_direction(client, three_goals): + response = client.get('/goals?sort_by=id') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 3 + assert response_body[0]['id'] == 1 + assert response_body[1]['id'] == 2 + assert response_body[2]['id'] == 3 \ No newline at end of file From c5367e647c34560f1ba0b0913188ecdec201544f Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 18:41:09 -0500 Subject: [PATCH 51/56] added more tests to test_query_params_refactor for 100% test coverage --- tests/test_query_params_refactor.py | 37 ++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/tests/test_query_params_refactor.py b/tests/test_query_params_refactor.py index 0d49d0df0..bb40cce6b 100644 --- a/tests/test_query_params_refactor.py +++ b/tests/test_query_params_refactor.py @@ -28,7 +28,23 @@ def test_get_tasks_sort_by_default(client, three_tasks): assert response_body[1]['title'] == 'Pay my outstanding tickets 😭' assert response_body[2]['title'] == 'Water the garden 🌷' -def test_get_goals_sorted_by_id_asc(client, three_goals): +def test_get_tasks_filter_title(client, three_tasks): + response = client.get('/tasks?title=email') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]['title'] == 'Answer forgotten email 📧' + +def test_get_tasks_filter_description(client, one_task): + response = client.get('/tasks?description=day') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]['description'] == 'Notice something new every day' + +def test_get_goals_sort_by_id_asc(client, three_goals): response = client.get('/goals?sort=asc&sort_by=id') response_body = response.get_json() @@ -38,7 +54,7 @@ def test_get_goals_sorted_by_id_asc(client, three_goals): assert response_body[1]['id'] == 2 assert response_body[2]['id'] == 3 -def test_get_goals_sorted_by_id_desc(client, three_goals): +def test_get_goals_sort_by_id_desc(client, three_goals): response = client.get('/goals?sort=desc&sort_by=id') response_body = response.get_json() @@ -48,7 +64,7 @@ def test_get_goals_sorted_by_id_desc(client, three_goals): assert response_body[1]['id'] == 2 assert response_body[2]['id'] == 1 -def test_get_goals_sorted_by_title_asc(client, three_goals): +def test_get_goals__by_title_asc(client, three_goals): response = client.get('/goals?sort=asc&sort_by=title') response_body = response.get_json() @@ -58,7 +74,7 @@ def test_get_goals_sorted_by_title_asc(client, three_goals): assert response_body[1]['title'] == 'Prioritize Self Care 🧖‍♀️' assert response_body[2]['title'] == 'Tidy Spaces, Tidy Mind 🫧' -def test_get_goals_sorted_by_title_desc(client, three_goals): +def test_get_goals_sort_by_title_desc(client, three_goals): response = client.get('/goals?sort=desc&sort_by=title') response_body = response.get_json() @@ -78,7 +94,7 @@ def test_get_goals_sort_by_default(client, three_goals): assert response_body[1]['title'] == 'Prioritize Self Care 🧖‍♀️' assert response_body[2]['title'] == 'Tidy Spaces, Tidy Mind 🫧' -def test_get_goals_sorted_by_id_default_direction(client, three_goals): +def test_get_goals_sort_by_id_default_direction(client, three_goals): response = client.get('/goals?sort_by=id') response_body = response.get_json() @@ -86,4 +102,13 @@ def test_get_goals_sorted_by_id_default_direction(client, three_goals): assert len(response_body) == 3 assert response_body[0]['id'] == 1 assert response_body[1]['id'] == 2 - assert response_body[2]['id'] == 3 \ No newline at end of file + assert response_body[2]['id'] == 3 + +def test_get_goals_filter_by_title(client, three_goals): + response = client.get('/goals?title=in') + response_body = response.get_json() + + assert response.status_code == 200 + assert len(response_body) == 2 + assert response_body[0]['title'] == 'Perfect My Wind Down Routine 🌙' + assert response_body[1]['title'] == 'Tidy Spaces, Tidy Mind 🫧' \ No newline at end of file From 15883a2710244190fdb437372ea810960a934eea Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 19:15:45 -0500 Subject: [PATCH 52/56] final run through of methods to make sure they all worked, updated the patch goal to actually be a put like the readme says --- app/models/model_utilities.py | 3 --- app/models/task.py | 4 +++- app/routes/goal_routes.py | 6 ++---- app/routes/route_utilities.py | 4 ++-- 4 files changed, 7 insertions(+), 10 deletions(-) delete mode 100644 app/models/model_utilities.py diff --git a/app/models/model_utilities.py b/app/models/model_utilities.py deleted file mode 100644 index acde37ff5..000000000 --- a/app/models/model_utilities.py +++ /dev/null @@ -1,3 +0,0 @@ -# Create a model instance from a dict - -# Create a dict from a model instance \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 914835f53..7c4cdc0a8 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -29,8 +29,10 @@ def from_dict(cls, task_data): def to_dict(self): task_dict = {} - if self.completed_at is None: + if self.completed_at is None or self.completed_at is False: task_dict['is_complete'] = False + else: + task_dict['is_complete'] = True if self.goal_id: task_dict['goal_id'] = self.goal_id diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 25e2decb4..f31801d08 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -20,14 +20,12 @@ def get_goal_by_id(goal_id): goal = validate_model(Goal, goal_id) return goal.to_dict() -@bp.patch('/') +@bp.put('/') def update_goal_title(goal_id): goal = validate_model(Goal, goal_id) request_body = request.get_json() - for attribute, value in request_body.items(): - if hasattr(goal, attribute): - goal.attribute = value + goal.title = request_body['title'] db.session.commit() diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index bcbf1c0d1..9ca7888a7 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,4 +1,4 @@ -from flask import abort, make_response, request +from flask import abort, make_response from ..db import db def validate_model(cls, model_id): @@ -22,7 +22,7 @@ def create_model(cls, model_data): try: new_model = cls.from_dict(model_data) - except KeyError as error: + except KeyError: response = {'details': f'Invalid data'} abort(make_response(response, 400)) From 5abd3a3e48bb1fd5a1be1a2a8839255e3f71ef08 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 19:58:52 -0500 Subject: [PATCH 53/56] updated tests to show that the put and patch methods persisted data --- tests/test_wave_01.py | 40 +--------------------------------------- tests/test_wave_02.py | 4 ---- tests/test_wave_03.py | 16 ---------------- tests/test_wave_05.py | 30 +++++++----------------------- tests/test_wave_06.py | 10 ---------- 5 files changed, 8 insertions(+), 92 deletions(-) diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 3d0091d7d..bfe48cc4f 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -3,15 +3,12 @@ import pytest def test_task_to_dict(): - #Arrange new_task = Task(id = 1, title="Make My Bed", description="Start the day off right!", completed_at=None) - #Act task_dict = new_task.to_dict() - #Assert assert len(task_dict) == 4 assert task_dict["id"] == 1 assert task_dict["title"] == "Make My Bed" @@ -19,15 +16,12 @@ def test_task_to_dict(): assert task_dict["is_complete"] == False def test_task_to_dict_missing_id(): - #Arrange new_task = Task(title="Make My Bed", description="Start the day off right!", completed_at=None) - #Act task_dict = new_task.to_dict() - #Assert assert len(task_dict) == 4 assert task_dict["id"] is None assert task_dict["title"] == "Make My Bed" @@ -35,15 +29,12 @@ def test_task_to_dict_missing_id(): assert task_dict["is_complete"] == False def test_task_to_dict_missing_title(): - #Arrange new_task = Task(id = 1, description="Start the day off right!", completed_at=None) - - #Act + task_dict = new_task.to_dict() - #Assert assert len(task_dict) == 4 assert task_dict["id"] == 1 assert task_dict["title"] is None @@ -51,58 +42,47 @@ def test_task_to_dict_missing_title(): assert task_dict["is_complete"] == False def test_task_from_dict(): - #Arrange task_dict = { "title": "Make My Bed", "description": "Start the day off right!", "is_complete": False } - #Act task_obj = Task.from_dict(task_dict) - #Assert assert task_obj.title == "Make My Bed" assert task_obj.description == "Start the day off right!" assert task_obj.completed_at is None def test_task_from_dict_no_title(): - #Arrange task_dict = { "description": "Start the day off right!", "is_complete": False } - #Act & Assert with pytest.raises(KeyError, match = 'title'): Task.from_dict(task_dict) def test_task_from_dict_no_description(): - #Arrange task_dict = { "title": "Make My Bed", "is_complete": False } - #Act & Assert with pytest.raises(KeyError, match = 'description'): Task.from_dict(task_dict) def test_get_tasks_no_saved_tasks(client): - # Act response = client.get("/tasks") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == [] def test_get_tasks_one_saved_tasks(client, one_task): - # Act response = client.get("/tasks") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 1 assert response_body == [ @@ -115,11 +95,9 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] def test_get_task(client, one_task): - # Act response = client.get("/tasks/1") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == { "id": 1, @@ -129,23 +107,19 @@ def test_get_task(client, one_task): } def test_get_task_not_found(client): - # Act response = client.get("/tasks/1") response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} def test_create_task(client): - # Act response = client.post("/tasks", json={ "title": "A Brand New Task", "description": "Test Description", }) response_body = response.get_json() - # Assert assert response.status_code == 201 assert response_body == { "id": 1, @@ -163,13 +137,11 @@ def test_create_task(client): assert new_task.completed_at == None def test_update_task(client, one_task): - # Act response = client.put("/tasks/1", json={ "title": "Updated Task Title", "description": "Updated Test Description", }) - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) @@ -180,45 +152,37 @@ def test_update_task(client, one_task): assert task.completed_at == None def test_update_task_not_found(client): - # Act response = client.put("/tasks/1", json={ "title": "Updated Task Title", "description": "Updated Test Description", }) response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} def test_delete_task(client, one_task): - # Act response = client.delete("/tasks/1") - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query) == None def test_delete_task_not_found(client): - # Act response = client.delete("/tasks/1") response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} assert db.session.scalars(db.select(Task)).all() == [] def test_create_task_must_contain_title(client): - # Act response = client.post("/tasks", json={ "description": "Test Description" }) response_body = response.get_json() - # Assert assert response.status_code == 400 assert "details" in response_body assert response_body == { @@ -227,13 +191,11 @@ def test_create_task_must_contain_title(client): assert db.session.scalars(db.select(Task)).all() == [] def test_create_task_must_contain_description(client): - # Act response = client.post("/tasks", json={ "title": "A Brand New Task" }) response_body = response.get_json() - # Assert assert response.status_code == 400 assert "details" in response_body assert response_body == { diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index 62611a3c4..b6b545748 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,11 +1,9 @@ import pytest def test_get_tasks_sorted_asc(client, three_tasks): - # Act response = client.get("/tasks?sort=asc") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 3 assert response_body == [ @@ -27,11 +25,9 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] def test_get_tasks_sorted_desc(client, three_tasks): - # Act response = client.get("/tasks?sort=desc") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 3 assert response_body == [ diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 1ba303a6c..26e813317 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -6,7 +6,6 @@ import pytest def test_mark_complete_on_incomplete_task(client, one_task): - # Arrange """ The future Wave 4 adds special functionality to this route, so for this test, we need to set-up "mocking." @@ -22,27 +21,21 @@ def test_mark_complete_on_incomplete_task(client, one_task): with patch("requests.post") as mock_get: mock_get.return_value.status_code = 200 - # Act response = client.patch("/tasks/1/mark_complete") - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at def test_mark_incomplete_on_complete_task(client, completed_task): - # Act response = client.patch("/tasks/1/mark_incomplete") - - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at == None def test_mark_complete_on_completed_task(client, completed_task): - # Arrange """ The future Wave 4 adds special functionality to this route, so for this test, we need to set-up "mocking." @@ -58,40 +51,31 @@ def test_mark_complete_on_completed_task(client, completed_task): with patch("requests.post") as mock_get: mock_get.return_value.status_code = 200 - # Act response = client.patch("/tasks/1/mark_complete") - - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at def test_mark_incomplete_on_incomplete_task(client, one_task): - # Act response = client.patch("/tasks/1/mark_incomplete") - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) assert db.session.scalar(query).completed_at == None def test_mark_complete_missing_task(client): - # Act response = client.patch("/tasks/1/mark_complete") response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} def test_mark_incomplete_missing_task(client): - # Act response = client.patch("/tasks/1/mark_incomplete") response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Task 1 not found'} \ No newline at end of file diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index d0cbf9d77..94ab844ad 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -2,13 +2,10 @@ import pytest def test_goal_to_dict(): - #Arrange new_goal = Goal(id=1, title="Seize the Day!") - #Act goal_dict = new_goal.to_dict() - #Assert assert goal_dict["id"] == 1 assert goal_dict["title"] == "Seize the Day!" @@ -35,41 +32,31 @@ def test_goal_to_dict_no_title(): assert goal_dict["title"] is None def test_goal_from_dict(): - #Arrange goal_dict = { "title": "Seize the Day!", } - #Act goal_obj = Goal.from_dict(goal_dict) - #Assert assert goal_obj.title == "Seize the Day!" def test_goal_from_dict_no_title(): - #Arrange goal_dict = { } - - #Act & Assert with pytest.raises(KeyError, match = 'title'): Goal.from_dict(goal_dict) def test_get_goals_no_saved_goals(client): - # Act response = client.get("/goals") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == [] def test_get_goals_one_saved_goal(client, one_goal): - # Act response = client.get("/goals") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 1 assert response_body == [ @@ -80,11 +67,9 @@ def test_get_goals_one_saved_goal(client, one_goal): ] def test_get_goal(client, one_goal): - # Act response = client.get("/goals/1") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == { "id": 1, @@ -100,13 +85,11 @@ def test_get_goal_not_found(client): assert response_body == {'message': 'Goal 1 not found'} def test_create_goal(client): - # Act response = client.post("/goals", json={ "title": "My New Goal" }) response_body = response.get_json() - # Assert assert response.status_code == 201 assert response_body == { "id": 1, @@ -114,12 +97,18 @@ def test_create_goal(client): } def test_update_goal(client, one_goal): - response = client.patch("/goals/1", json={ + response = client.put("/goals/1", json={ "title": "My New Title" }) assert response.status_code == 204 + + # check that the goal was updated + response = client.get('goals/1') + response_body = response.get_json() + assert response.status_code == 200 + assert response_body['title'] == 'My New Title' def test_update_goal_not_found(client): response = client.delete("/goals/1") @@ -130,10 +119,7 @@ def test_update_goal_not_found(client): assert response_body == {'message': 'Goal 1 not found'} def test_delete_goal(client, one_goal): - # Act response = client.delete("/goals/1") - - # Assert assert response.status_code == 204 # Check that the goal was deleted @@ -153,11 +139,9 @@ def test_delete_goal_not_found(client): assert response_body == {'message': 'Goal 1 not found'} def test_create_goal_missing_title(client): - # Act response = client.post("/goals", json={}) response_body = response.get_json() - # Assert assert response.status_code == 400 assert response_body == { "details": "Invalid data" diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 047e565cb..010148080 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -3,13 +3,11 @@ import pytest def test_post_task_ids_to_goal(client, one_goal, three_tasks): - # Act response = client.post("/goals/1/tasks", json={ "task_ids": [1, 2, 3] }) response_body = response.get_json() - # Assert assert response.status_code == 200 assert "id" in response_body assert "task_ids" in response_body @@ -23,13 +21,11 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(db.session.scalar(query).tasks) == 3 def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belongs_to_one_goal, three_tasks): - # Act response = client.post("/goals/1/tasks", json={ "task_ids": [2, 4] }) response_body = response.get_json() - # Assert assert response.status_code == 200 assert "id" in response_body assert "task_ids" in response_body @@ -41,20 +37,16 @@ def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belong assert len(db.session.scalar(query).tasks) == 2 def test_get_tasks_for_specific_goal_no_goal(client): - # Act response = client.get("/goals/1/tasks") response_body = response.get_json() - # Assert assert response.status_code == 404 assert response_body == {'message': 'Goal 1 not found'} def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): - # Act response = client.get("/goals/1/tasks") response_body = response.get_json() - # Assert assert response.status_code == 200 assert "tasks" in response_body assert len(response_body["tasks"]) == 0 @@ -65,11 +57,9 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): - # Act response = client.get("/goals/1/tasks") response_body = response.get_json() - # Assert assert response.status_code == 200 assert "tasks" in response_body assert len(response_body["tasks"]) == 1 From e1962033dbb0cfe830e0eeeb27e4e3690af1bcb4 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Wed, 5 Nov 2025 20:15:56 -0500 Subject: [PATCH 54/56] moved slack post message to its own helper function in route utilities --- app/routes/route_utilities.py | 19 +++++++++++++++++-- app/routes/task_routes.py | 17 +++-------------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index 9ca7888a7..bc508fc95 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -1,5 +1,7 @@ -from flask import abort, make_response +from flask import abort, make_response, Response from ..db import db +import os +import requests def validate_model(cls, model_id): try: @@ -54,4 +56,17 @@ def get_models_with_filters(cls, filters=None): models = db.session.scalars(query) models_response = [model.to_dict() for model in models] - return models_response \ No newline at end of file + return models_response + +def send_slack_message(task): + slack_token = os.environ["SLACK_BOT_TOKEN"] + channel_and_message = { + 'channel': 'task-notifications', + 'text': f'Someone just completed the task {task.title}' + } + headers = { + 'Authorization': slack_token + } + requests.post('https://slack.com/api/chat.postMessage', data=channel_and_message, json=channel_and_message, headers=headers) + + return Response(status=204, mimetype='application/json') \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 0807825c5..db702d3c6 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,10 +1,8 @@ from flask import Blueprint, request, Response from app.models.task import Task from ..db import db -from app.routes.route_utilities import validate_model, create_model, get_models_with_filters +from app.routes.route_utilities import validate_model, create_model, get_models_with_filters, send_slack_message from datetime import datetime -import os -import requests bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') @@ -57,14 +55,5 @@ def mark_task_complete(task_id): task.completed_at = datetime.now().date() db.session.commit() - slack_token = os.environ["SLACK_BOT_TOKEN"] - channel_and_message = { - 'channel': 'task-notifications', - 'text': f'Someone just completed the task {task.title}' - } - headers = { - 'Authorization': slack_token - } - requests.post('https://slack.com/api/chat.postMessage', data=channel_and_message, json=channel_and_message, headers=headers) - - return Response(status=204, mimetype='application/json') \ No newline at end of file + + return send_slack_message(task) \ No newline at end of file From 05a1453b2e9ec09286cf9d6aed3d67934acd5b29 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 6 Nov 2025 19:16:03 -0500 Subject: [PATCH 55/56] adds if not slack token line to send_slack_message helper function --- app/routes/route_utilities.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index bc508fc95..ab1663162 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -60,6 +60,9 @@ def get_models_with_filters(cls, filters=None): def send_slack_message(task): slack_token = os.environ["SLACK_BOT_TOKEN"] + if not slack_token: + return Response(status=204, mimetype='application/json') + channel_and_message = { 'channel': 'task-notifications', 'text': f'Someone just completed the task {task.title}' From 947dfd347e4ccb0b4ece42fbacc7e35ef85afab5 Mon Sep 17 00:00:00 2001 From: Riley Drellishak Date: Thu, 6 Nov 2025 19:18:06 -0500 Subject: [PATCH 56/56] another update to the slack token get --- app/routes/route_utilities.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py index ab1663162..649294d3d 100644 --- a/app/routes/route_utilities.py +++ b/app/routes/route_utilities.py @@ -59,7 +59,7 @@ def get_models_with_filters(cls, filters=None): return models_response def send_slack_message(task): - slack_token = os.environ["SLACK_BOT_TOKEN"] + slack_token = os.environ.get("SLACK_BOT_TOKEN") if not slack_token: return Response(status=204, mimetype='application/json')