diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/ada-project-docs/wave_04.md b/ada-project-docs/wave_04.md index 079ce6485..f06160a76 100644 --- a/ada-project-docs/wave_04.md +++ b/ada-project-docs/wave_04.md @@ -98,9 +98,13 @@ Visit https://api.slack.com/methods/chat.postMessage to read about the Slack API Answer the following questions. These questions will help you become familiar with the API, and make working with it easier. - What is the responsibility of this endpoint? + - post a message on a channel in slack - What is the URL and HTTP method for this endpoint? + - https://slack.com/api/chat.postMessage?channel=&text=& - What are the _two_ _required_ arguments for this endpoint? + - token, channel - How does this endpoint relate to the Slackbot API key (token) we just created? + - I'm assuming we will use this endpoint to send messages about whether or not the tasks have been done Now, visit https://api.slack.com/methods/chat.postMessage/test. @@ -119,8 +123,42 @@ Press the "Test Method" button! Scroll down to see the HTTP response. Answer the following questions: - Did we get a success message? If so, did we see the message in our actual Slack workspace? + - we got ok:True? And yes, we saw a message in our actual slack workspace - Did we get an error emssage? If so, why? + - No... - What is the shape of this JSON? Is it a JSON object or array? What keys and values are there? + - {"ok":, + - "channel":, + - "ts": a string of numbers? Is this an IP?, + - "message"{ + - "bot_id": string, + - "type": "message", + - "text": , + - "user": string, + - "ts": same as before under ts?, + - "app_id": string of caps and nums, + - "team": another string of caps and nums, + - "bot_profile":{ + - "id": same as bot_id, + - "app_id":same as app_id before, + - "name": , + - "icons": { + - "image_36": url, + - "image_48": url, + - "image_72": url + - }, + - "deleted": boolean, + - "updated": a number, + - "team_id": same as team + - }, + - "blocks":[ + - {"type": "rich_text", + - "block_id": "PTh", + - "elements": [ + - {"type":"rich_text_section", + - "elements":[ + - {"type":"text", + - "text": text body}]}]}]}} ### Verify with Postman @@ -139,6 +177,8 @@ Open Postman and make a request that mimics the API call to Slack that we just t - In "Headers," add this new key-value pair: - `Authorization`: `"Bearer xoxb-150..."`, where `xoxb-150...` is your full Slackbot token +--> DO NOT INCLUDE ANY QUOTES <---- + ![](assets/postman_test_headers.png) Press "Send" and see the Slack message come through! diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..691fa6a1a 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,10 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from app.routes.task_routes import task_bp + app.register_blueprint(task_bp) + + from app.routes.goal_routes import goal_bp + app.register_blueprint(goal_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index b0ed11dd8..587c2ad39 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,4 +2,46 @@ class Goal(db.Model): + __tablename__ = 'goals' goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + tasks = db.relationship("Task", backref="goals") + + def to_dict(self): + task_list = [] + for task in self.tasks: + task_list.append(task.id) + if task_list: + return dict( + id=self.goal_id, + task_ids=task_list + ) + return dict( + id=self.goal_id, + title=self.title) + + def get_tasks(self): + from .task import Task + task_list = [] + for task in self.tasks: + readable_task = task.task_to_dict() + task_list.append(readable_task) + return dict( + id=self.goal_id, + title=self.title, + tasks=task_list) + + @classmethod + def from_dict(cls, data_dict): + return cls(title=data_dict["title"]) + + def replace_details(self, data_dict): + if "task_ids" in data_dict: + from .task import Task + for id in data_dict["task_ids"]: + task = Task.query.get(id) + if task not in self.tasks: + self.tasks.append(task) + else: + self.title=data_dict["title"] + return self.to_dict() diff --git a/app/models/task.py b/app/models/task.py index c91ab281f..ee74ffb24 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,64 @@ +import datetime from app import db +from app.models.goal import Goal class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + __tablename__ = 'tasks' + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + is_complete = db.Column(db.Boolean, default=False) + completed_at = db.Column(db.DateTime) + goal_id = db.Column(db.Integer, db.ForeignKey(Goal.goal_id)) + + def task_to_dict(self): + if self.goal_id: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete, + goal_id = self.goal_id + ) + else: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.is_complete) + + @classmethod + def from_dict(cls, data_dict): + if "completed_at" in data_dict: + return cls( + title=data_dict["title"], + description=data_dict["description"], + is_complete=True, + completed_at=data_dict["completed_at"] + ) + else: + return cls( + title=data_dict["title"], + description=data_dict["description"] + ) + + def replace_details(self, data_dict): + self.title=data_dict["title"] + self.description=data_dict["description"] + self.is_complete=False + if "completed_at" in data_dict: + self.completed_at=data_dict["completed_at"] + self.is_complete=True + return self + + def mark_done(self): + self.is_complete = True + current_time = datetime.datetime.now() + self.completed_at = current_time + return self + + def mark_not_done(self): + self.is_complete = False + self.completed_at = None + return self \ No newline at end of file diff --git a/app/routes.py b/app/routes.py deleted file mode 100644 index 3aae38d49..000000000 --- a/app/routes.py +++ /dev/null @@ -1 +0,0 @@ -from flask import Blueprint \ No newline at end of file diff --git a/app/routes/__init__.py b/app/routes/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py new file mode 100644 index 000000000..3e921f0fe --- /dev/null +++ b/app/routes/goal_routes.py @@ -0,0 +1,95 @@ +from flask import Blueprint, jsonify, make_response, request, abort +from app import db +from app.models.goal import Goal +from .task_routes import validate_task_id, Task + +goal_bp = Blueprint("goals", __name__, url_prefix="/goals") + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + +def make_goal_safely(data_dict): + try: + return Goal.from_dict(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def update_goal_safely(goal, data_dict): + try: + return goal.replace_details(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def validate_goal_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + goal = Goal.query.get(id) + if goal: + return goal + error_message(f"No goal with ID {id}. SORRY.", 404) + +@goal_bp.route("", methods=["POST"]) +def add_goal(): + request_body = request.get_json() + new_goal=make_goal_safely(request_body) + + db.session.add(new_goal) + db.session.commit() + + task_response = {"goal":new_goal.to_dict()} + + return jsonify(task_response), 201 + +@goal_bp.route("", methods=["GET"]) +def get_goals(): + goals = Goal.query.all() + + result_list = [goal.to_dict() for goal in goals] + return jsonify(result_list) + +@goal_bp.route("/", methods=["GET"]) +def get_goal_by_id(id): + goal = validate_goal_id(id) + result = {"goal": goal.to_dict()} + return jsonify(result) + +@goal_bp.route("", methods=["PUT"]) +def update_goal(id): + goal = validate_goal_id(id) + request_body = request.get_json() + updated_goal = update_goal_safely(goal, request_body) + + db.session.commit() + + return jsonify({"goal":updated_goal}) + +@goal_bp.route("", methods=["DELETE"]) +def delete_goal(id): + goal = validate_goal_id(id) + db.session.delete(goal) + db.session.commit() + + return jsonify({"details":f'Goal {id} "{goal.title}" successfully deleted'}) + +@goal_bp.route("//tasks", methods=["POST"]) +def add_task_to_goal(id): + goal = validate_goal_id(id) + request_body = request.get_json() + data_dict = {"task_ids": []} + for task in request_body["task_ids"]: + validate_task_id(task) + data_dict["task_ids"].append(task) + # updated_goal = update_goal_safely(goal, request_body) + update_tasks_in_goal = update_goal_safely(goal, data_dict) + db.session.commit() + # task_response = {"goal":update_tasks_in_goal} + + return jsonify(update_tasks_in_goal), 200 + +@goal_bp.route("//tasks", methods=["GET"]) +def get_tasks_from_goal(id): + goal = validate_goal_id(id) + result = goal.get_tasks() + return jsonify(result) \ No newline at end of file diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py new file mode 100644 index 000000000..08e886d0b --- /dev/null +++ b/app/routes/task_routes.py @@ -0,0 +1,106 @@ +from flask import Blueprint, jsonify, make_response, request, abort +from app import db +from app.models.task import Task +from sqlalchemy import desc +import requests +import os + +task_bp = Blueprint("tasks", __name__, url_prefix="/tasks") + +def error_message(message, status_code): + abort(make_response(jsonify(dict(details=message)), status_code)) + +def make_task_safely(data_dict): + try: + return Task.from_dict(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def update_task_safely(task, data_dict): + try: + return task.replace_details(data_dict) + except KeyError as err: + error_message(f"Invalid data", 400) + +def validate_task_id(id): + try: + id = int(id) + except ValueError: + error_message(f"Invalid id {id}", 400) + task = Task.query.get(id) + if task: + return task + error_message(f"No task with ID {id}. SORRY.", 404) + +@task_bp.route("", methods=["POST"]) +def add_task(): + request_body = request.get_json() + new_task=make_task_safely(request_body) + + db.session.add(new_task) + db.session.commit() + + task_response = {"task":new_task.task_to_dict()} + + return jsonify(task_response), 201 + +@task_bp.route("", methods=["GET"]) +def get_tasks(): + sort_param = request.args.get("sort") + if sort_param == "asc": + tasks = Task.query.order_by("title") + elif sort_param == "desc": + tasks = Task.query.order_by(desc(Task.title)) + else: + tasks = Task.query.all() + + result_list = [task.task_to_dict() for task in tasks] + return jsonify(result_list) + +@task_bp.route("/", methods=["GET"]) +def get_task_by_id(id): + task = validate_task_id(id) + result = {"task": task.task_to_dict()} + return jsonify(result) + +@task_bp.route("", methods=["PUT"]) +def update_task(id): + task = validate_task_id(id) + request_body = request.get_json() + updated_task = update_task_safely(task, request_body) + + db.session.commit() + + return jsonify({"task":updated_task.task_to_dict()}) + +@task_bp.route("", methods=["DELETE"]) +def delete_task(id): + task = validate_task_id(id) + db.session.delete(task) + db.session.commit() + + return jsonify({"details":f'Task {id} "{task.title}" successfully deleted'}) + +@task_bp.route("/mark_complete", methods=["PATCH"]) +def mark_complete(id): + task = validate_task_id(id) + updated_task = task.mark_done() + + db.session.commit() + send_slack_message(f"Someone just completed the task {task.title}") + + return jsonify({"task":updated_task.task_to_dict()}) + +@task_bp.route("/mark_incomplete", methods=["PATCH"]) +def mark_incomplete(id): + task = validate_task_id(id) + updated_task = task.mark_not_done() + + db.session.commit() + + return jsonify({"task":updated_task.task_to_dict()}) + +def send_slack_message(message): + Slack_Key = os.environ.get("Slack_API_Token") + requests.post('https://slack.com/api/chat.postMessage', params={'text':message, 'channel':'task-notifications'}, headers={'Authorization':Slack_Key}) + return True \ 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..68feded2a --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,91 @@ +from __future__ import with_statement + +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') + +# 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', + str(current_app.extensions['migrate'].db.get_engine().url).replace( + '%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# 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 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=target_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.') + + connectable = current_app.extensions['migrate'].db.get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_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/601bb9264297_.py b/migrations/versions/601bb9264297_.py new file mode 100644 index 000000000..c5055c930 --- /dev/null +++ b/migrations/versions/601bb9264297_.py @@ -0,0 +1,40 @@ +"""empty message + +Revision ID: 601bb9264297 +Revises: +Create Date: 2022-05-06 17:00:00.294882 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '601bb9264297' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('is_complete', sa.Boolean(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('task_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/bbfd43b6d86a_.py b/migrations/versions/bbfd43b6d86a_.py new file mode 100644 index 000000000..56bedc9a4 --- /dev/null +++ b/migrations/versions/bbfd43b6d86a_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: bbfd43b6d86a +Revises: bc641ad71a61 +Create Date: 2022-05-08 09:02:51.644143 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bbfd43b6d86a' +down_revision = 'bc641ad71a61' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goals', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('goal_id') + ) + op.drop_table('goal') + op.add_column('tasks', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'tasks', 'goals', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'tasks', type_='foreignkey') + op.drop_column('tasks', 'goal_id') + op.create_table('goal', + sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False), + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.PrimaryKeyConstraint('goal_id', name='goal_pkey') + ) + op.drop_table('goals') + # ### end Alembic commands ### diff --git a/migrations/versions/bc641ad71a61_.py b/migrations/versions/bc641ad71a61_.py new file mode 100644 index 000000000..a47a8b14f --- /dev/null +++ b/migrations/versions/bc641ad71a61_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: bc641ad71a61 +Revises: e66361cb0cb1 +Create Date: 2022-05-07 21:02:23.288410 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bc641ad71a61' +down_revision = 'e66361cb0cb1' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('title', sa.String(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('goal', 'title') + # ### end Alembic commands ### diff --git a/migrations/versions/d0dcc64964c0_.py b/migrations/versions/d0dcc64964c0_.py new file mode 100644 index 000000000..bc348aa8c --- /dev/null +++ b/migrations/versions/d0dcc64964c0_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: d0dcc64964c0 +Revises: e6ece79aaff4 +Create Date: 2022-05-07 17:01:14.880507 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'd0dcc64964c0' +down_revision = 'e6ece79aaff4' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('tasks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.drop_table('task') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('task', + sa.Column('title', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('description', sa.VARCHAR(), autoincrement=False, nullable=True), + sa.Column('id', sa.INTEGER(), autoincrement=False, nullable=False) + ) + op.drop_table('tasks') + # ### end Alembic commands ### diff --git a/migrations/versions/e66361cb0cb1_.py b/migrations/versions/e66361cb0cb1_.py new file mode 100644 index 000000000..b37cea978 --- /dev/null +++ b/migrations/versions/e66361cb0cb1_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e66361cb0cb1 +Revises: d0dcc64964c0 +Create Date: 2022-05-07 19:28:12.900453 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e66361cb0cb1' +down_revision = 'd0dcc64964c0' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('tasks', sa.Column('completed_at', sa.DateTime(), nullable=True)) + op.add_column('tasks', sa.Column('is_complete', sa.Boolean(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('tasks', 'is_complete') + op.drop_column('tasks', 'completed_at') + # ### end Alembic commands ### diff --git a/migrations/versions/e68f13a3e02c_.py b/migrations/versions/e68f13a3e02c_.py new file mode 100644 index 000000000..0315f25cf --- /dev/null +++ b/migrations/versions/e68f13a3e02c_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e68f13a3e02c +Revises: 601bb9264297 +Create Date: 2022-05-06 18:34:42.221057 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'e68f13a3e02c' +down_revision = '601bb9264297' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False)) + op.drop_column('task', 'task_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('task', 'id') + # ### end Alembic commands ### diff --git a/migrations/versions/e6ece79aaff4_.py b/migrations/versions/e6ece79aaff4_.py new file mode 100644 index 000000000..197013b21 --- /dev/null +++ b/migrations/versions/e6ece79aaff4_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: e6ece79aaff4 +Revises: e68f13a3e02c +Create Date: 2022-05-07 16:58:41.889535 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'e6ece79aaff4' +down_revision = 'e68f13a3e02c' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('task', 'completed_at') + op.drop_column('task', 'is_complete') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('is_complete', sa.BOOLEAN(), server_default=sa.text('false'), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index 30ff414fe..0c1ecd619 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,12 @@ alembic==1.5.4 attrs==20.3.0 -autopep8==1.5.5 blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +coverage==6.3.2 Flask==1.1.2 -Flask-Migrate==2.6.0 +Flask-Migrate==3.1.0 Flask-SQLAlchemy==2.4.4 gunicorn==20.1.0 idna==2.10 @@ -17,7 +17,7 @@ Mako==1.1.4 MarkupSafe==1.1.1 packaging==20.9 pluggy==0.13.1 -psycopg2-binary==2.8.6 +psycopg2-binary==2.9.3 py==1.10.0 pycodestyle==2.6.0 pyparsing==2.4.7 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..65b1c1448 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): # Act response = client.get("/tasks") @@ -13,7 +13,7 @@ def test_get_tasks_no_saved_tasks(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_one_saved_tasks(client, one_task): # Act response = client.get("/tasks") @@ -32,7 +32,7 @@ def test_get_tasks_one_saved_tasks(client, one_task): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task(client, one_task): # Act response = client.get("/tasks/1") @@ -51,7 +51,7 @@ def test_get_task(client, one_task): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_not_found(client): # Act response = client.get("/tasks/1") @@ -59,14 +59,14 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + assert response_body == {"details":"No task with ID 1. SORRY."} + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -93,7 +93,7 @@ def test_create_task(client): assert new_task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task(client, one_task): # Act response = client.put("/tasks/1", json={ @@ -119,7 +119,7 @@ def test_update_task(client, one_task): assert task.completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_update_task_not_found(client): # Act response = client.put("/tasks/1", json={ @@ -130,14 +130,15 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -152,7 +153,7 @@ def test_delete_task(client, one_task): assert Task.query.get(1) == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task_not_found(client): # Act response = client.delete("/tasks/1") @@ -160,8 +161,9 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -169,7 +171,7 @@ def test_delete_task_not_found(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_title(client): # Act response = client.post("/tasks", json={ @@ -186,7 +188,7 @@ def test_create_task_must_contain_title(client): assert Task.query.all() == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task_must_contain_description(client): # Act response = client.post("/tasks", json={ diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index a087e0909..651e3aebd 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -1,7 +1,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_asc(client, three_tasks): # Act response = client.get("/tasks?sort=asc") @@ -29,7 +29,7 @@ def test_get_tasks_sorted_asc(client, three_tasks): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_sorted_desc(client, three_tasks): # Act response = client.get("/tasks?sort=desc") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 959176ceb..72fc0b4cb 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -5,7 +5,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_incomplete_task(client, one_task): # Arrange """ @@ -42,7 +42,7 @@ def test_mark_complete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_complete_task(client, completed_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -62,7 +62,7 @@ def test_mark_incomplete_on_complete_task(client, completed_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_on_completed_task(client, completed_task): # Arrange """ @@ -99,7 +99,7 @@ def test_mark_complete_on_completed_task(client, completed_task): assert Task.query.get(1).completed_at -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_on_incomplete_task(client, one_task): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -119,7 +119,7 @@ def test_mark_incomplete_on_incomplete_task(client, one_task): assert Task.query.get(1).completed_at == None -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_complete_missing_task(client): # Act response = client.patch("/tasks/1/mark_complete") @@ -127,14 +127,15 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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 pytfeature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +143,9 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"details":"No task with ID 1. SORRY."} - 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*************** # ***************************************************************** @@ -151,7 +153,7 @@ def test_mark_incomplete_missing_task(client): # Let's add this test for creating tasks, now that # the completion functionality has been implemented -@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_with_valid_completed_at(client): # Act response = client.post("/tasks", json={ @@ -181,7 +183,7 @@ def test_create_task_with_valid_completed_at(client): # Let's add this test for updating tasks, now that # the completion functionality has been implemented -@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_with_completed_at_date(client, completed_task): # Act response = client.put("/tasks/1", json={ diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..0ffce56be 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.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_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +12,7 @@ def test_get_goals_no_saved_goals(client): assert response_body == [] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goals_one_saved_goal(client, one_goal): # Act response = client.get("/goals") @@ -29,7 +29,7 @@ def test_get_goals_one_saved_goal(client, one_goal): ] -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -46,22 +46,24 @@ def test_get_goal(client, one_goal): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act response = client.get("/goals/1") response_body = response.get_json() - raise Exception("Complete test") + # raise Exception("Complete test") # Assert # ---- Complete Test ---- # assertion 1 goes here + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details":"No goal with ID 1. SORRY."} # ---- Complete Test ---- -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -80,34 +82,52 @@ def test_create_goal(client): } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - raise Exception("Complete test") + # raise Exception("Complete test") # Act # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert # ---- Complete Assertions Here ---- # assertion 1 goes here + assert response.status_code == 200 # assertion 2 goes here + assert "goal" in response_body # assertion 3 goes here + assert response_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":"No goal with ID 1. SORRY."} # ---- 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") @@ -123,28 +143,33 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 - - raise Exception("Complete test with assertion about response body") + response_body=response.get_json() + assert response_body == {"details":"No goal with ID 1. SORRY."} + # 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 + assert response.status_code == 404 # assertion 2 goes here + assert response_body == {"details":"No goal with ID 1. SORRY."} # ---- 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_create_goal_missing_title(client): # Act response = client.post("/goals", json={}) diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..8a6ba94f5 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -2,7 +2,7 @@ import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -23,7 +23,7 @@ def test_post_task_ids_to_goal(client, one_goal, three_tasks): assert len(Goal.query.get(1).tasks) == 3 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -42,7 +42,7 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on assert len(Goal.query.get(1).tasks) == 2 -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act response = client.get("/goals/1/tasks") @@ -50,14 +50,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":"No goal with ID 1. SORRY."} + # 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") @@ -74,7 +74,7 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -99,7 +99,7 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json()