diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..28bf3c67c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,8 @@ from flask import Flask 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): @@ -10,13 +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 diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..492fe0a6a 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,18 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db 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 = cls(title=goal_data['title']) + return new_goal + + def to_dict(self): + 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 5d99666a4..7c4cdc0a8 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,44 @@ -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 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) + 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): + if 'is_complete' not in task_data.keys() or task_data['is_complete'] is False: + task_data['is_complete'] = None + + new_task = Task( + title=task_data['title'], + description=task_data['description'], + completed_at=task_data['is_complete'], + goal_id=task_data.get('goal_id', None) + ) + + return new_task + + def to_dict(self): + task_dict = {} + + 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 + + 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/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..f31801d08 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,65 @@ -from flask import Blueprint \ No newline at end of file +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, get_models_with_filters + +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(): + return get_models_with_filters(Goal, request.args) + +@bp.get('/') +def get_goal_by_id(goal_id): + goal = validate_model(Goal, goal_id) + return goal.to_dict() + +@bp.put('/') +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): + goal = validate_model(Goal, goal_id) + db.session.delete(goal) + db.session.commit() + 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 + +@bp.get('//tasks') +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 diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..649294d3d --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,75 @@ +from flask import abort, make_response, Response +from ..db import db +import os +import requests + +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 + +def create_model(cls, model_data): + try: + new_model = cls.from_dict(model_data) + + except KeyError: + response = {'details': f'Invalid data'} + abort(make_response(response, 400)) + + db.session.add(new_model) + db.session.commit() + + return new_model.to_dict(), 201 + +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) + + 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) + + else: + query = query.order_by(cls.title) + + models = db.session.scalars(query) + models_response = [model.to_dict() for model in models] + return models_response + +def send_slack_message(task): + slack_token = os.environ.get("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}' + } + 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 3aae38d49..db702d3c6 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,59 @@ -from flask import Blueprint \ No newline at end of file +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, send_slack_message +from datetime import datetime + +bp = Blueprint('tasks_bp', __name__, url_prefix='/tasks') + +@bp.get('') +def get_all_tasks(): + return get_models_with_filters(Task, request.args), 200 + +@bp.get('/') +def get_one_task_by_id(task_id): + task = validate_model(Task, task_id) + return task.to_dict() + +@bp.post('') +def create_task(): + request_body = request.get_json() + return create_model(Task, request_body) + +@bp.put('/') +def update_task(task_id): + 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): + task = validate_model(Task, task_id) + + db.session.delete(task) + 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') + +@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 send_slack_message(task) \ 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/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 ### 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/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 ### 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 diff --git a/tests/test_query_params_refactor.py b/tests/test_query_params_refactor.py new file mode 100644 index 000000000..bb40cce6b --- /dev/null +++ b/tests/test_query_params_refactor.py @@ -0,0 +1,114 @@ +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_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_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() + + 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_sort_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__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_sort_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_sort_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 + +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 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index fac95a0a3..bfe48cc4f 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,116 +2,87 @@ 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", 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" 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", 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" 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, 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 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 = { "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 -@pytest.mark.skip(reason="No way to test this feature yet") 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) -@pytest.mark.skip(reason="No way to test this feature yet") 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) -@pytest.mark.skip(reason="No way to test this feature yet") 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 == [] - -@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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 1 assert response_body == [ @@ -123,14 +94,10 @@ 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == { "id": 1, @@ -139,32 +106,20 @@ 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") response_body = response.get_json() - # 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") 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, @@ -181,15 +136,12 @@ 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={ "title": "Updated Task Title", "description": "Updated Test Description", }) - # Assert assert response.status_code == 204 query = db.select(Task).where(Task.id == 1) @@ -199,63 +151,38 @@ 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={ "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'} - 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_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 -@pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): - # Act response = client.delete("/tasks/1") response_body = response.get_json() - # 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() == [] - -@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={ "description": "Test Description" }) response_body = response.get_json() - # Assert assert response.status_code == 400 assert "details" in response_body assert response_body == { @@ -263,16 +190,12 @@ 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={ "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 a087e0909..b6b545748 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,13 +1,9 @@ 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 3 assert response_body == [ @@ -28,14 +24,10 @@ 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") 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 d7d441695..26e813317 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,10 +5,7 @@ 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 """ The future Wave 4 adds special functionality to this route, so for this test, we need to set-up "mocking." @@ -24,31 +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 - -@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") - - # Assert assert response.status_code == 204 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 """ The future Wave 4 adds special functionality to this route, so for this test, we need to set-up "mocking." @@ -64,53 +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 -@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") - # Assert assert response.status_code == 204 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") response_body = response.get_json() - # 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") 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 - - 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 diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b7cc330ae..94ab844ad 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,19 +1,14 @@ 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!") - #Act goal_dict = new_goal.to_dict() - #Assert 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 +20,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,50 +31,32 @@ 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 = { "title": "Seize the Day!", } - #Act goal_obj = Goal.from_dict(goal_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 = { } - - #Act & Assert 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") response_body = response.get_json() - # Assert 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert len(response_body) == 1 assert response_body == [ @@ -90,85 +66,60 @@ 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert response_body == { "id": 1, "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={ "title": "My New Goal" }) response_body = response.get_json() - # Assert assert response.status_code == 201 assert response_body == { "id": 1, "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.put("/goals/1", json={ + "title": "My New Title" + }) - # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + 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' -@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") - - # Assert assert response.status_code == 204 # Check that the goal was deleted @@ -177,34 +128,20 @@ 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={}) 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 727fce93a..010148080 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,16 +2,12 @@ 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={ "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 @@ -24,16 +20,12 @@ 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={ "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 @@ -44,29 +36,17 @@ 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") response_body = response.get_json() - # 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert "tasks" in response_body assert len(response_body["tasks"]) == 0 @@ -76,14 +56,10 @@ 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") response_body = response.get_json() - # Assert assert response.status_code == 200 assert "tasks" in response_body assert len(response_body["tasks"]) == 1 @@ -101,8 +77,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() diff --git a/tests/test_wave_07.py b/tests/test_wave_07.py index 7e7cef55a..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,95 +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'} -@pytest.mark.skip(reason="No way to test this feature yet") 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 -@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 = { "description": "", "completed_at": None } - #Act with pytest.raises(HTTPException) as e: create_model(Task, request_body) @@ -119,33 +86,24 @@ 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 = { "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 -@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 = { } - #Act 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"}