diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..16731e550 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,13 +1,18 @@ +import os + from flask import Flask + from .db import db, migrate from .models import task, goal -import os +from .routes.task_routes import bp as tasks_bp +from .routes.goal_routes import bp as goals_bp + def create_app(config=None): app = Flask(__name__) - app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False - app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") if config: # Merge `config` into the app's configuration @@ -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/db.py b/app/db.py index 3ada8d10c..bf98adaa2 100644 --- a/app/db.py +++ b/app/db.py @@ -1,6 +1,8 @@ from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate + from .models.base import Base + db = SQLAlchemy(model_class=Base) -migrate = Migrate() \ No newline at end of file +migrate = Migrate() diff --git a/app/models/base.py b/app/models/base.py index 227841686..fa2b68a5d 100644 --- a/app/models/base.py +++ b/app/models/base.py @@ -1,4 +1,5 @@ from sqlalchemy.orm import DeclarativeBase + class Base(DeclarativeBase): - pass \ No newline at end of file + pass diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..4461d5692 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,5 +1,18 @@ -from sqlalchemy.orm import Mapped, mapped_column +from typing import List + +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") + + def to_dict(self): + return {"id": self.id, "title": self.title} + + @classmethod + def from_dict(cls, data): + return cls(title=data["title"]) diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..a3e09f1eb 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,36 @@ -from sqlalchemy.orm import Mapped, mapped_column +from datetime import datetime +from typing import Optional + +from sqlalchemy.orm import Mapped, mapped_column, relationship + from ..db import db + 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]] + goal_id: Mapped[Optional[int]] = mapped_column(db.ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") + + def to_dict(self): + task_dict = { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": self.completed_at is not None, + } + + if self.goal_id: + task_dict["goal_id"] = self.goal_id + + return task_dict + + @classmethod + def from_dict(cls, task_data): + return cls( + title=task_data["title"], + description=task_data["description"], + completed_at=task_data.get("completed_at"), + ) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..ca1314b87 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,68 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response + +from app.models.goal import Goal +from app.models.task import Task +from .. 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(): + request_body = request.get_json() + return create_model(Goal, request_body) + + +@bp.post("//tasks") +def add_tasks_to_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + task_ids = request_body.get("task_ids", []) + goal.tasks = [] + + for task_id in task_ids: + task = validate_model(Task, task_id) + goal.tasks.append(task) + + db.session.commit() + return {"id": goal.id, "task_ids": task_ids} + + +@bp.get("//tasks") +def get_tasks_of_goal(goal_id): + goal = validate_model(Goal, goal_id) + tasks = [task.to_dict() for task in goal.tasks] + return {"id": goal.id, "title": goal.title, "tasks": tasks} + + +@bp.get("") +def get_all_goals(): + return get_models_with_filters(Goal, request.args) + + +@bp.get("/") +def get_one_goal(goal_id): + goal = validate_model(Goal, goal_id) + return {"goal": goal.to_dict()} + + +@bp.put("/") +def update_goal(goal_id): + goal = validate_model(Goal, goal_id) + request_body = request.get_json() + + if "title" not in request_body: + return {"details": "Invalid data. 'title' is required."}, 400 + + 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") diff --git a/app/routes/route_utilities.py b/app/routes/route_utilities.py new file mode 100644 index 000000000..aa8e64bf5 --- /dev/null +++ b/app/routes/route_utilities.py @@ -0,0 +1,75 @@ +import os, requests +from flask import abort, make_response + +from ..db import db + + +def validate_model(cls, model_id): + try: + model_id = int(model_id) + except: + response = {"details": f"{cls.__name__} id {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 = {"details": f"{cls.__name__} id {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 as error: + response = {"details": "Invalid data"} + abort(make_response(response, 400)) + + db.session.add(new_model) + db.session.commit() + return ({cls.__name__.lower(): new_model.to_dict()}), 201 + + +def get_models_with_filters(cls, filters=None): + query = db.select(cls) + sort_param = None + + if filters: + filters_dict = dict(filters) + sort_param = filters_dict.pop("sort", None) + + for attribute, value in filters_dict.items(): + if hasattr(cls, attribute): + query = query.where(getattr(cls, attribute).ilike(f"%{value}%")) + + if sort_param == "asc": + query = query.order_by(cls.title.asc()) + elif sort_param == "desc": + query = query.order_by(cls.title.desc()) + else: + query = query.order_by(cls.id) + + models = db.session.scalars(query) + return [model.to_dict() for model in models] + + +def call_slack_api(task): + slack_url = "https://slack.com/api/chat.postMessage" + slack_token = os.environ.get("SLACKBOT_TOKEN") + + headers = { + "Authorization": f"Bearer {slack_token}", + "Content-Type": "application/json", + } + + data = { + "channel": "test-slack-api", + "text": f"Someone just completed the task {task.title}", + } + + responce = requests.post(slack_url, headers=headers, json=data) + return responce diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..3f4bafd28 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,73 @@ -from flask import Blueprint \ No newline at end of file +from datetime import datetime + +from flask import Blueprint, request, Response, make_response + +from app.models.task import Task +from .route_utilities import ( + validate_model, + create_model, + get_models_with_filters, + call_slack_api, +) +from ..db import db + + +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks") + + +@bp.post("") +def create_task(): + request_body = request.get_json() + + return create_model(Task, request_body) + + +@bp.get("") +def get_all_tasks(): + return get_models_with_filters(Task, request.args) + + +@bp.patch("//mark_complete") +def mark_complete(task_id): + task = validate_model(Task, task_id) + task.completed_at = datetime.today() + db.session.commit() + + call_slack_api(task) + return make_response(task.to_dict(), 204) + + +@bp.patch("//mark_incomplete") +def mark_incomplete(task_id): + task = validate_model(Task, task_id) + task.completed_at = None + db.session.commit() + return Response(status=204, mimetype="application/json") + + +@bp.get("/") +def get_one_task(task_id): + task = validate_model(Task, task_id) + return {"task": task.to_dict()} + + +@bp.put("/") +def update_task(task_id): + task = validate_model(Task, task_id) + request_body = request.get_json() + + if "title" not in request_body or "description" not in request_body: + return make_response({"details": "Invalid data"}, 400) + + 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") diff --git a/cli/main.py b/cli/main.py index 04d8e0f5d..bfc76b785 100644 --- a/cli/main.py +++ b/cli/main.py @@ -1,17 +1,18 @@ import task_list OPTIONS = { - "1": "List all tasks", - "2": "Create a task", - "3": "View one task", - "4": "Update task", - "5": "Delete task", - "6": "Mark complete", - "7": "Mark incomplete", - "8": "Delete all tasks", - "9": "List all options", - "10": "Quit" - } + "1": "List all tasks", + "2": "Create a task", + "3": "View one task", + "4": "Update task", + "5": "Delete task", + "6": "Mark complete", + "7": "Mark incomplete", + "8": "Delete all tasks", + "9": "List all options", + "10": "Quit", +} + def list_options(): @@ -25,18 +26,21 @@ def make_choice(): while choice not in valid_choices: print("\n What would you like to do? ") - choice = input("Make your selection using the option number. Select 9 to list all options: ") + choice = input( + "Make your selection using the option number. Select 9 to list all options: " + ) return choice -def get_task_from_user(msg = "Input the id of the task you would like to work with: "): + +def get_task_from_user(msg="Input the id of the task you would like to work with: "): task = None tasks = task_list.list_tasks() if not tasks: task_list.print_stars("This option is not possible because there are no tasks.") return task count = 0 - help_count = 3 #number of tries before offering assistance + help_count = 3 # number of tries before offering assistance while not task: id = input(msg) task = task_list.get_task(id) @@ -44,11 +48,14 @@ def get_task_from_user(msg = "Input the id of the task you would like to work wi print_surround_stars("I cannot find that task. Please try again.") count += 1 if count >= help_count: - print("You seem to be having trouble selecting a task. Please choose from the following list of tasks.") + print( + "You seem to be having trouble selecting a task. Please choose from the following list of tasks." + ) print_all_tasks() - + return task + def print_task(task): print_single_row_of_stars() print("title: ", task["title"]) @@ -57,6 +64,7 @@ def print_task(task): print("id: ", task["id"]) print_single_row_of_stars() + def print_all_tasks(): tasks = task_list.list_tasks() print("\nTasks:") @@ -67,36 +75,42 @@ def print_all_tasks(): print_task(task) print_single_row_of_stars() + def print_surround_stars(sentence): print_single_row_of_stars() print(sentence) print_single_row_of_stars() + def print_single_row_of_stars(): print("\n**************************\n") + def create_task(): print("Great! Let's create a new task.") - title=input("What is the title of your task? ") - description=input("What is the description of your task? ") + title = input("What is the title of your task? ") + description = input("What is the description of your task? ") response = task_list.create_task(title, description) print_task(response) + def view_task(): task = get_task_from_user("Input the id of the task you would like to select ") - if task: + if task: print("\nSelected Task:") print_task(task) + def edit_task(): task = get_task_from_user() if task: - title=input("What is the new title of your task? ") - description=input("What is the new description of your task? ") + title = input("What is the new title of your task? ") + description = input("What is the new description of your task? ") response = task_list.update_task(task["id"], title, description) print("\nUpdated Task:") print_task(response) + def delete_task_ui(): task = get_task_from_user("Input the id of the task you would like to delete: ") if task: @@ -104,11 +118,14 @@ def delete_task_ui(): print("\nTask has been deleted.") print_all_tasks() + def change_task_complete_status(status): status_text = "complete" if not status: status_text = "incomplete" - task = get_task_from_user(f"Input the id of the task you would like to mark {status_text}: ") + task = get_task_from_user( + f"Input the id of the task you would like to mark {status_text}: " + ) if task: if status: response = task_list.mark_complete(task["id"]) @@ -117,43 +134,45 @@ def change_task_complete_status(status): print(f"\nTask marked {status_text}:") print_task(response) + def delete_all_tasks(): for task in task_list.list_tasks(): task_list.delete_task(task["id"]) print_surround_stars("Deleted all tasks.") + def run_cli(): - + play = True while play: # get input and validate choice = make_choice() - if choice=='1': + if choice == "1": print_all_tasks() - elif choice=='2': + elif choice == "2": create_task() - elif choice=='3': + elif choice == "3": view_task() - elif choice=='4': + elif choice == "4": edit_task() - elif choice=='5': + elif choice == "5": delete_task_ui() - elif choice=='6': + elif choice == "6": change_task_complete_status(True) - elif choice=='7': + elif choice == "7": change_task_complete_status(False) - elif choice=='8': + elif choice == "8": delete_all_tasks() - elif choice=='9': + elif choice == "9": list_options() - elif choice=='10': - play=False + elif choice == "10": + play = False print("Welcome to Task List CLI") print("These are the actions you can take:") print_single_row_of_stars() list_options() -run_cli() \ No newline at end of file +run_cli() diff --git a/cli/task_list.py b/cli/task_list.py index 137f3fa06..ebdae2f73 100644 --- a/cli/task_list.py +++ b/cli/task_list.py @@ -2,58 +2,56 @@ url = "http://localhost:5000" + def parse_response(response): if response.status_code >= 400: return None - + return response.json()["task"] + def create_task(title, description, completed_at=None): query_params = { "title": title, "description": description, - "completed_at": completed_at + "completed_at": completed_at, } - response = requests.post(url+"/tasks",json=query_params) + response = requests.post(url + "/tasks", json=query_params) return parse_response(response) + def list_tasks(): - response = requests.get(url+"/tasks") + response = requests.get(url + "/tasks") return response.json() + def get_task(id): - response = requests.get(url+f"/tasks/{id}") + response = requests.get(url + f"/tasks/{id}") if response.status_code != 200: return None - + return parse_response(response) -def update_task(id,title,description): - query_params = { - "title": title, - "description": description - } +def update_task(id, title, description): + + query_params = {"title": title, "description": description} - response = requests.put( - url+f"/tasks/{id}", - json=query_params - ) + response = requests.put(url + f"/tasks/{id}", json=query_params) return parse_response(response) + def delete_task(id): - response = requests.delete(url+f"/tasks/{id}") + response = requests.delete(url + f"/tasks/{id}") return response.json() + def mark_complete(id): - response = requests.patch(url+f"/tasks/{id}/mark_complete") + response = requests.patch(url + f"/tasks/{id}/mark_complete") return parse_response(response) + def mark_incomplete(id): - response = requests.patch(url+f"/tasks/{id}/mark_incomplete") + response = requests.patch(url + f"/tasks/{id}/mark_incomplete") return parse_response(response) - - - - 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..d004741b2 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,108 @@ +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/61d7672dd37e_added_model_goal.py b/migrations/versions/61d7672dd37e_added_model_goal.py new file mode 100644 index 000000000..b39554161 --- /dev/null +++ b/migrations/versions/61d7672dd37e_added_model_goal.py @@ -0,0 +1,33 @@ +"""Added Model Goal. + +Revision ID: 61d7672dd37e +Revises: e4ad941cbf09 +Create Date: 2025-05-10 21:32:03.541894 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "61d7672dd37e" +down_revision = "e4ad941cbf09" +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/8cf3c04ce4b6_migration_added_one_to_many_.py b/migrations/versions/8cf3c04ce4b6_migration_added_one_to_many_.py new file mode 100644 index 000000000..e4ce12fdc --- /dev/null +++ b/migrations/versions/8cf3c04ce4b6_migration_added_one_to_many_.py @@ -0,0 +1,37 @@ +"""Migration: added one-to-many relationship between goals and tasks. +q + + +Revision ID: 8cf3c04ce4b6 +Revises: 61d7672dd37e +Create Date: 2025-05-11 01:44:57.765674 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "8cf3c04ce4b6" +down_revision = "61d7672dd37e" +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("task", schema=None) as batch_op: + batch_op.add_column(sa.Column("goal_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, "goal", ["goal_id"], ["id"]) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table("task", schema=None) as batch_op: + batch_op.drop_constraint(None, type_="foreignkey") + batch_op.drop_column("goal_id") + + # ### end Alembic commands ### diff --git a/migrations/versions/e4ad941cbf09_.py b/migrations/versions/e4ad941cbf09_.py new file mode 100644 index 000000000..be79fc534 --- /dev/null +++ b/migrations/versions/e4ad941cbf09_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: e4ad941cbf09 +Revises: +Create Date: 2025-05-09 15:45:48.985330 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "e4ad941cbf09" +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/tests/conftest.py b/tests/conftest.py index a01499583..bd579a594 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -10,12 +10,13 @@ load_dotenv() + @pytest.fixture def app(): # create the app with a test configuration test_config = { "TESTING": True, - "SQLALCHEMY_DATABASE_URI": os.environ.get('SQLALCHEMY_TEST_DATABASE_URI') + "SQLALCHEMY_DATABASE_URI": os.environ.get("SQLALCHEMY_TEST_DATABASE_URI"), } app = create_app(test_config) @@ -42,9 +43,11 @@ def client(app): # This fixture creates a task and saves it in the database @pytest.fixture def one_task(app): - new_task = Task(title="Go on my daily walk 🏞", - description="Notice something new every day", - completed_at=None) + new_task = Task( + title="Go on my daily walk 🏞", + description="Notice something new every day", + completed_at=None, + ) db.session.add(new_task) db.session.commit() @@ -55,17 +58,15 @@ def one_task(app): # them in the database @pytest.fixture def three_tasks(app): - db.session.add_all([ - Task(title="Water the garden 🌷", - description="", - completed_at=None), - Task(title="Answer forgotten email 📧", - description="", - completed_at=None), - Task(title="Pay my outstanding tickets 😭", - description="", - completed_at=None) - ]) + db.session.add_all( + [ + Task(title="Water the garden 🌷", description="", completed_at=None), + Task(title="Answer forgotten email 📧", description="", completed_at=None), + Task( + title="Pay my outstanding tickets 😭", description="", completed_at=None + ), + ] + ) db.session.commit() @@ -75,9 +76,11 @@ def three_tasks(app): # valid completed_at date @pytest.fixture def completed_task(app): - new_task = Task(title="Go on my daily walk 🏞", - description="Notice something new every day", - completed_at=datetime.now()) + new_task = Task( + title="Go on my daily walk 🏞", + description="Notice something new every day", + completed_at=datetime.now(), + ) db.session.add(new_task) db.session.commit() @@ -104,4 +107,4 @@ 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() \ No newline at end of file + db.session.commit() diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 55475db79..36c21d92c 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.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_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -14,7 +14,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") @@ -28,12 +28,12 @@ def test_get_tasks_one_saved_tasks(client, one_task): "id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False + "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_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -47,12 +47,12 @@ def test_get_task(client, one_task): "id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False + "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_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -60,20 +60,24 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details": "Task id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act - response = client.post("/tasks", json={ - "title": "A Brand New Task", - "description": "Test Description", - }) + response = client.post( + "/tasks", + json={ + "title": "A Brand New Task", + "description": "Test Description", + }, + ) response_body = response.get_json() # Assert @@ -84,10 +88,10 @@ def test_create_task(client): "id": 1, "title": "A Brand New Task", "description": "Test Description", - "is_complete": False + "is_complete": False, } } - + query = db.select(Task).where(Task.id == 1) new_task = db.session.scalar(query) @@ -97,13 +101,16 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act - response = client.put("/tasks/1", json={ - "title": "Updated Task Title", - "description": "Updated Test Description", - }) + response = client.put( + "/tasks/1", + json={ + "title": "Updated Task Title", + "description": "Updated Test Description", + }, + ) # Assert assert response.status_code == 204 @@ -116,26 +123,29 @@ def test_update_task(client, one_task): assert task.completed_at == None - -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act - response = client.put("/tasks/1", json={ - "title": "Updated Task Title", - "description": "Updated Test Description", - }) + 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 == {"details": "Task id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -146,7 +156,8 @@ 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") @@ -154,8 +165,9 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details": "Task id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -163,35 +175,27 @@ def test_delete_task_not_found(client): assert db.session.scalars(db.select(Task)).all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @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 = 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 == { - "details": "Invalid data" - } + assert response_body == {"details": "Invalid data"} 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={ - "title": "A Brand New Task" - }) + 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 == { - "details": "Invalid data" - } - assert db.session.scalars(db.select(Task)).all() == [] \ No newline at end of file + assert response_body == {"details": "Invalid data"} + assert db.session.scalars(db.select(Task)).all() == [] diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..e8ad1599c 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") @@ -15,21 +15,24 @@ def test_get_tasks_sorted_asc(client, three_tasks): "id": 2, "title": "Answer forgotten email 📧", "description": "", - "is_complete": False}, + "is_complete": False, + }, { "id": 3, "title": "Pay my outstanding tickets 😭", "description": "", - "is_complete": False}, + "is_complete": False, + }, { "id": 1, "title": "Water the garden 🌷", "description": "", - "is_complete": False} + "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_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") @@ -43,15 +46,18 @@ def test_get_tasks_sorted_desc(client, three_tasks): "description": "", "id": 1, "is_complete": False, - "title": "Water the garden 🌷"}, + "title": "Water the garden 🌷", + }, { "description": "", "id": 3, "is_complete": False, - "title": "Pay my outstanding tickets 😭"}, + "title": "Pay my outstanding tickets 😭", + }, { "description": "", "id": 2, "is_complete": False, - "title": "Answer forgotten email 📧"}, + "title": "Answer forgotten email 📧", + }, ] diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index d7d441695..64539672f 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 """ @@ -29,16 +29,15 @@ def test_mark_complete_on_incomplete_task(client, one_task): # 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") +# @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 @@ -46,7 +45,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 """ @@ -66,7 +65,6 @@ def test_mark_complete_on_completed_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_complete") - # Assert assert response.status_code == 204 @@ -74,7 +72,8 @@ 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 +85,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 +93,15 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details": "Task id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -109,8 +109,9 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details": "Task id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 222d10cf0..9d3fa2fe5 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,9 @@ import pytest +from app.models.goal import Goal +from app.db import db -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +14,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -21,15 +23,10 @@ def test_get_goals_one_saved_goal(client, one_goal): # Assert assert response.status_code == 200 assert len(response_body) == 1 - assert response_body == [ - { - "id": 1, - "title": "Build a habit of going outside daily" - } - ] + assert response_body == [{"id": 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_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -39,75 +36,83 @@ def test_get_goal(client, one_goal): assert response.status_code == 200 assert "goal" in response_body assert response_body == { - "goal": { - "id": 1, - "title": "Build a habit of going outside daily" - } + "goal": {"id": 1, "title": "Build a habit of going outside daily"} } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): - pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + # raise Exception("Complete test") # Assert # ---- Complete Test ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details": "Goal id 1 not found"} # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act - response = client.post("/goals", json={ - "title": "My New Goal" - }) + response = client.post("/goals", json={"title": "My New Goal"}) response_body = response.get_json() # Assert assert response.status_code == 201 assert "goal" in response_body - assert response_body == { - "goal": { - "id": 1, - "title": "My New Goal" - } - } + assert response_body == {"goal": {"id": 1, "title": "My New Goal"}} -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- - + response = client.put("/goals/1", json={"title": "Updated Goal Title"}) # Assert + query = db.select(Goal).where(Goal.id == 1) + goal = db.session.scalar(query) # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 204 # assertion 2 goes here + assert goal.title == "Updated Goal Title" # assertion 3 goes here + assert goal.id == 1 + + get_response = client.get("/goals/1") + get_body = get_response.get_json() + assert get_body == {"goal": {"id": 1, "title": "Updated Goal Title"}} # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- - + response = client.put( + "/goals/1", + json={ + "title": "Updated Goal Title", + }, + ) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details": "Goal id 1 not found"} # ---- Complete Assertions Here ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -120,29 +125,33 @@ def test_delete_goal(client, one_goal): assert response.status_code == 404 response_body = response.get_json() - assert "message" in response_body + assert response_body == {"details": "Goal id 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- + response = client.delete("/goals/1") + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here # assertion 2 goes here # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"details": "Goal id 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={}) @@ -150,6 +159,4 @@ def test_create_goal_missing_title(client): # Assert assert response.status_code == 400 - assert response_body == { - "details": "Invalid data" - } + assert response_body == {"details": "Invalid data"} diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 0317f835a..0241e7fa2 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -3,49 +3,41 @@ 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={ - "task_ids": [1, 2, 3] - }) + 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 - assert response_body == { - "id": 1, - "task_ids": [1, 2, 3] - } + assert response_body == {"id": 1, "task_ids": [1, 2, 3]} # Check that Goal was updated in the db 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_already_with_goals(client, one_task_belongs_to_one_goal, three_tasks): +# @pytest.mark.skip(reason="No way to test this feature yet") +def test_post_task_ids_to_goal_already_with_goals( + client, one_task_belongs_to_one_goal, three_tasks +): # Act - response = client.post("/goals/1/tasks", json={ - "task_ids": [2, 4] - }) + 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 - assert response_body == { - "id": 1, - "task_ids": [2, 4] - } + assert response_body == {"id": 1, "task_ids": [2, 4]} 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") +# @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 +45,14 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "Goal id 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") @@ -73,11 +65,11 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): assert response_body == { "id": 1, "title": "Build a habit of going outside daily", - "tasks": [] + "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_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -96,13 +88,13 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): "goal_id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False + "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_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json() @@ -116,6 +108,6 @@ def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): "goal_id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False + "is_complete": False, } }