diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..298bb0976 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,15 @@ from flask import Flask +from flask_cors import CORS 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): app = Flask(__name__) + CORS(app) + app.config['CORS_HEADERS'] = 'Content-Type' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') @@ -18,5 +23,7 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..ff54d7b97 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,25 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from .task import Task 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") + + def to_dict(self): + goal_as_dict = { + "id": self.id, + "title": self.title + } + + return goal_as_dict + + @classmethod + def from_dict(cls, task_data): + new_task = cls(title=task_data['title']) + + return new_task diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..1a2f1864a 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,50 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey from ..db import db +from datetime import datetime +from typing import Optional, TYPE_CHECKING + +if TYPE_CHECKING: + from .goal import Goal + class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + description: Mapped[str] + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") + + completed_at: Mapped[Optional[datetime]] + + #converts task instance into dictionary + def to_dict(self): + task_as_dict = {} + task_as_dict["id"]= self.id + task_as_dict["title"]= self.title + task_as_dict["description"]= self.description + task_as_dict["is_complete"]= self.completed_at is not None + + if self.goal_id: + task_as_dict["goal_id"] = self.goal_id + + if self.completed_at: + task_as_dict["completed_at"]= self.completed_at.isoformat() + else: + None + + return task_as_dict + + #creates a task from a dictionary + @classmethod + def from_dict(cls, task_data): + + new_task = cls( + title=task_data['title'], + description=task_data['description'], + completed_at=task_data.get('completed_at'), + goal_id=task_data.get('goal_id') + ) + + return new_task + diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..f2e83a58c 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,89 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request +from app.models.goal import Goal +from app.models.task import Task + +from .route_utilities import * + +bp = Blueprint("goals_bp", __name__, url_prefix="/goals") + +def associate_tasks_with_goal(goal, task_ids): + + for task in goal.tasks: + task.goal_id = None + + #add new tasks + for task_id in task_ids: + task = validate_model(Task, task_id) + task.goal_id = goal.id + + db.session.commit() + + return { + "id": goal.id, + "task_ids": task_ids + }, 200 + +def create_new_task_for_goal(goal, task_data): + task_data["goal_id"] = goal.id + + new_task = Task.from_dict(task_data) + db.session.add(new_task) + db.session.commit + + return new_task.to_dict(), 200 + +@bp.post("", strict_slashes = False) +def create_goal(): + return create_model(Goal, request.get_json()) + +@bp.post("//tasks", strict_slashes = False) +def create_task_with_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + if "task_ids" in request_body: + task_ids = request_body["task_ids"] + return associate_tasks_with_goal(goal, task_ids) + + else: + return create_new_task_for_goal + + +@bp.get("", strict_slashes = False) +def get_all_goals(): + return get_all_items(Goal) + +@bp.get("//tasks") +def get_tasks_by_goal(goal_id): + goal = validate_model(Goal, goal_id) + + return{ + "id": goal.id, + "title": goal.title, + "tasks": [task.to_dict() for task in goal.tasks] + } + +@bp.get("/") +def get_one_goal(goal_id): + return get_one_item(Goal, goal_id) + +@bp.put("/", strict_slashes = False) +def update_entire_goal(goal_id): + updated_goal = update_entire_item(Goal, goal_id, goal_update=True) + return updated_goal.to_dict(), 200 + +@bp.patch("/", strict_slashes = False) +def update_partial_goal(goal_id): + return update_partial_item(Goal, goal_id) + +@bp.patch("//mark_complete", strict_slashes = False) +def mark_complete(goal_id): + return mark_item_complete(Goal, goal_id) + +@bp.patch("//mark_incomplete", strict_slashes = False) +def mark_incomplete(goal_id): + return mark_item_incomplete(Goal, goal_id) + +@bp.delete("/", strict_slashes = False) +def delete_goal(goal_id): + return delete_item(Goal, goal_id) \ No newline at end of file diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..40e977c25 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,138 @@ +from flask import abort, make_response, request, Response +from ..db import db +from datetime import datetime +import os +import requests + +def validate_model(cls, id): + try: + id = int(id) + except ValueError: + response = {"message": f"{cls.__name__} id {id} is invalid"} + abort(make_response(response, 400)) + + query = db.select(cls).where(cls.id == id) + item = db.session.scalar(query) + + if not item: + response = {"message": f"{cls.__name__} {id} not found"} + abort(make_response(response, 404)) + + return item + + +def send_slack_notification(item_title): + slack_token = os.environ.get("SLACK_TOKEN") + if slack_token: + try: + requests.post( + "https://slack.com/api/chat.postMessage", + headers={"Authorization": f"Bearer {slack_token}"}, + json={ + "channel": "slack-api-testing", + "text": f"Someone just completed {item_title}" + } + ) + except Exception as e: + print(f"Slack notification failed: {e}") + + +'''none of these probably go here, but it seemed easier at the time... +& while my code is solid, my brain is delicate & easy to break.''' +def create_model(cls, request_body): + try: + new_item = cls.from_dict(request_body) + + except KeyError: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_item) + db.session.commit() + + return new_item.to_dict(), 201 + +def get_all_items(cls): + query = db.select(cls) + + title_param = request.args.get('title') + if title_param: + query = query.where(cls.title.ilike(f"{title_param}%")) + + sort_param = request.args.get('sort', 'asc') + + if sort_param == "desc": + query = query.order_by(cls.title.desc()) + else: + query = query.order_by(cls.title.asc()) + + items = db.session.scalars(query) + + items_response = [] + for item in items: + items_response.append(item.to_dict()) + return items_response + +def get_one_item(cls, id): + item = validate_model(cls, id) + + return item.to_dict() + +def update_entire_item(cls, id, goal_update=False): + item = validate_model(cls, id) + request_body = request.get_json() + + item.title = request_body["title"] + if not goal_update: + item.description = request_body["description"] + db.session.commit() + + return item + +def update_partial_item(cls, id): + item = validate_model(cls, id) + request_body = request.get_json() + + if 'title' in request_body: + item.title = request_body['title'] + + if 'description' in request_body: + item.description = request_body['description'] + + if 'is_complete' in request_body: + if request_body['is_complete']: + item.completed_at = datetime.now() + else: + item.completed_at = None + + db.session.commit() + + return Response(status=204, mimetype="application/json") + +def mark_item_complete(cls, id): + item = validate_model(cls, id) + + item.completed_at = datetime.now() + + db.session.commit() + + send_slack_notification(item.title) + + return Response(status=204, mimetype="application/json") + +def mark_item_incomplete(cls, id): + item = validate_model(cls, id) + + item.completed_at = None + + db.session.commit() + + return Response(status=204, mimetype="application/json") + +def delete_item(cls, id): + item = validate_model(cls, id) + + db.session.delete(item) + db.session.commit() + + 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 3aae38d49..d60ce30c0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,44 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint +from app.models.task import Task +from .route_utilities import * + + +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") + +@bp.post("", strict_slashes = False) +def create_task(): + return create_model(Task, request.get_json()) + +@bp.get("", strict_slashes = False) +def get_all_tasks(): + return get_all_items(Task) + +@bp.get("/") +def get_one_task(task_id): + return get_one_item(Task, task_id) + +@bp.put("/", strict_slashes = False) +def update_entire_task(task_id): + update_entire_item(Task, task_id) + return Response(status=204, mimetype="application/json") + +@bp.patch("/", strict_slashes = False) +def update_partial_task(task_id): + return update_partial_item(Task, task_id) + +@bp.patch("//mark_complete", strict_slashes = False) +def mark_complete(task_id): + return mark_item_complete(Task, task_id) + +@bp.patch("//mark_incomplete", strict_slashes = False) +def mark_incomplete(task_id): + return mark_item_incomplete(Task, task_id) + +@bp.delete("/", strict_slashes = False) +def delete_task(task_id): + return delete_item(Task, task_id) + + + + + \ No newline at end of file diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..4c9709271 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/2757c45a454d_.py b/migrations/versions/2757c45a454d_.py new file mode 100644 index 000000000..fd837caff --- /dev/null +++ b/migrations/versions/2757c45a454d_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 2757c45a454d +Revises: +Create Date: 2025-11-02 17:28:18.761529 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2757c45a454d' +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 ### diff --git a/migrations/versions/7bca6cfb3447_goals_model.py b/migrations/versions/7bca6cfb3447_goals_model.py new file mode 100644 index 000000000..eb8c6c658 --- /dev/null +++ b/migrations/versions/7bca6cfb3447_goals_model.py @@ -0,0 +1,32 @@ +"""goals model + +Revision ID: 7bca6cfb3447 +Revises: 2757c45a454d +Create Date: 2025-11-05 16:05:37.492139 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '7bca6cfb3447' +down_revision = '2757c45a454d' +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/migrations/versions/b7e49467e695_created_one_to_many_relationship_.py b/migrations/versions/b7e49467e695_created_one_to_many_relationship_.py new file mode 100644 index 000000000..a7617c3bf --- /dev/null +++ b/migrations/versions/b7e49467e695_created_one_to_many_relationship_.py @@ -0,0 +1,34 @@ +"""created one-to-many relationship between goals & tasks + +Revision ID: b7e49467e695 +Revises: 7bca6cfb3447 +Create Date: 2025-11-05 20:11:15.827601 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'b7e49467e695' +down_revision = '7bca6cfb3447' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index b989cae17..55f258d15 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,7 @@ charset-normalizer==3.4.1 click==8.1.8 coverage==7.6.12 Flask==3.1.0 +flask-cors==6.0.2 Flask-Migrate==4.1.0 Flask-SQLAlchemy==3.1.1 gunicorn==23.0.0 diff --git a/seed.py b/seed.py new file mode 100644 index 000000000..8ac6686ae --- /dev/null +++ b/seed.py @@ -0,0 +1,100 @@ +from app import create_app, db +from app.models.task import Task +from app.models.goal import Goal +from datetime import datetime +from dotenv import load_dotenv + +load_dotenv() +app = create_app() + +with app.app_context(): + print("Clearing existing data...") + # Delete all existing data + Task.query.delete() + Goal.query.delete() + db.session.commit() + + print("Creating goals...") + # Create goals + goal1 = Goal(title="Get Fit") + goal2 = Goal(title="Learn Python") + goal3 = Goal(title="Travel More") + + db.session.add_all([goal1, goal2, goal3]) + db.session.commit() + + print("Creating tasks...") + # Tasks for "Get Fit" goal + task1 = Task( + title="Run 5k 🏃", + description="Morning run in the park", + goal_id=goal1.id + ) + task2 = Task( + title="Do 50 pushups 💪", + description="Daily strength training", + goal_id=goal1.id, + completed_at=datetime.now() # This one is complete + ) + task3 = Task( + title="Eat healthy meals 🥗", + description="Meal prep on Sundays", + goal_id=goal1.id + ) + + # Tasks for "Learn Python" goal + task4 = Task( + title="Build a Flask API 💻", + description="Complete task list project", + goal_id=goal2.id + ) + task5 = Task( + title="Read Python docs 📚", + description="Study advanced topics", + goal_id=goal2.id + ) + task6 = Task( + title="Practice algorithms 🧠", + description="Solve coding challenges", + goal_id=goal2.id, + completed_at=datetime.now() # This one is complete + ) + + # Tasks for "Travel More" goal + task7 = Task( + title="Book flight to Japan ✈️", + description="Research dates and prices", + goal_id=goal3.id + ) + task8 = Task( + title="Learn basic Japanese 🇯🇵", + description="Common phrases and etiquette", + goal_id=goal3.id + ) + + # Tasks without a goal + task9 = Task( + title="Call dentist 🦷", + description="Schedule cleaning appointment" + ) + task10 = Task( + title="Pay utility bills 💸", + description="Due by end of month" + ) + task11 = Task( + title="Water plants 🌱", + description="Check soil moisture first", + completed_at=datetime.now() # This one is complete + ) + + db.session.add_all([ + task1, task2, task3, task4, task5, task6, + task7, task8, task9, task10, task11 + ]) + db.session.commit() + + print("✅ Database seeded successfully!") + print(f" Created {Goal.query.count()} goals") + print(f" Created {Task.query.count()} tasks") + print(f" - {Task.query.filter(Task.completed_at.isnot(None)).count()} completed") + print(f" - {Task.query.filter(Task.goal_id.isnot(None)).count()} assigned to goals") \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fac95a0a3..2b57d4b6e 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,7 @@ from app.db import db import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_to_dict(): #Arrange new_task = Task(id = 1, title="Make My Bed", @@ -19,7 +19,7 @@ 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") +#@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 +36,7 @@ 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") +#@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 +53,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict(): #Arrange task_dict = { @@ -70,7 +70,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict_no_title(): #Arrange task_dict = { @@ -82,7 +82,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_task_from_dict_no_description(): #Arrange task_dict = { @@ -94,7 +94,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -105,7 +105,7 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_one_saved_tasks(client, one_task): # Act response = client.get("/tasks") @@ -124,7 +124,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -140,7 +140,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -148,14 +148,10 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -181,7 +177,7 @@ 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") +#@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={ @@ -201,7 +197,7 @@ def test_update_task(client, one_task): -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -212,14 +208,10 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -230,7 +222,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -238,16 +230,14 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 1 not found"} - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert db.session.scalars(db.select(Task)).all() == [] assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -264,7 +254,7 @@ 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") +#@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={ diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..c9a76e6b1 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..aa24537ee 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -6,7 +6,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -34,7 +34,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -46,7 +46,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -74,7 +74,7 @@ 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") +#@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") @@ -86,7 +86,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert db.session.scalar(query).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -94,14 +94,10 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "Task 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") +#@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") @@ -109,8 +105,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"} diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b7cc330ae..adbbcd5e9 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,7 @@ from app.models.goal import Goal import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict(): #Arrange new_goal = Goal(id=1, title="Seize the Day!") @@ -13,7 +13,7 @@ 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") +#@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 +25,7 @@ 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") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_to_dict_no_title(): #Arrange new_goal = Goal(id=1) @@ -39,7 +39,7 @@ def test_goal_to_dict_no_title(): -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict(): #Arrange goal_dict = { @@ -52,7 +52,7 @@ def test_goal_from_dict(): #Assert assert goal_obj.title == "Seize the Day!" -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_goal_from_dict_no_title(): #Arrange goal_dict = { @@ -63,7 +63,7 @@ def test_goal_from_dict_no_title(): Goal.from_dict(goal_dict) -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -74,7 +74,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -91,7 +91,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -105,22 +105,18 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") - # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -136,34 +132,36 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert response_body == { + "id": 1, + "title": "Updated Goal Title" + } + assert response_body["title"] == "Updated Goal Title" -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- - + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -177,28 +175,21 @@ def test_delete_goal(client, one_goal): response_body = response.get_json() assert "message" in response_body - - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="test to be completed by student") +#@pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"message": "Goal 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 727fce93a..737f3da80 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -3,7 +3,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -25,7 +25,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(db.session.scalar(query).tasks) == 3 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -45,7 +45,7 @@ def test_post_task_ids_to_goal_overwrites_existing_tasks(client, one_task_belong assert len(db.session.scalar(query).tasks) == 2 -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act response = client.get("/goals/1/tasks") @@ -53,14 +53,10 @@ 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") +#@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") @@ -77,7 +73,7 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -102,7 +98,7 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +#@pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json() diff --git a/tests/test_wave_07.py b/tests/test_wave_07.py index 7e7cef55a..663eabd71 100644 --- a/tests/test_wave_07.py +++ b/tests/test_wave_07.py @@ -4,7 +4,7 @@ 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") +#@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) @@ -24,7 +24,7 @@ def test_route_utilities_validate_model_with_task(client, three_tasks): assert task_3.title == "Pay my outstanding tickets 😭" -@pytest.mark.skip(reason="No way to test this feature yet") +#@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 @@ -36,24 +36,20 @@ def test_route_utilities_validate_model_with_task_invalid_id(client, three_tasks response = e.value.get_response() assert response.status_code == 400 - raise Exception("Complete test with an assertion about the response body") - # ***************************************************************************** - # ** Complete test with an assertion about the response body **************** - # ***************************************************************************** + assert response.get_json() == {"message": f"Task id One is invalid"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@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": f"Task 4 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@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) @@ -62,29 +58,27 @@ def test_route_utilities_validate_model_with_goal(client, one_goal): 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") +#@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": f"Goal id One is invalid"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@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": f"Goal 4 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@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 +97,7 @@ 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") +#@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 = { @@ -120,7 +114,7 @@ def test_route_utilities_create_model_with_task_missing_title(client): assert response.get_json() == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") +#@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 +129,7 @@ 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") +#@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 +139,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"}