From 7e91f085cdaf8e3be4d9512aab85140542ab643c Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Tue, 8 Nov 2022 16:06:19 -0800 Subject: [PATCH 01/13] Completes project setup including creation of migrations directory --- migrations/README | 1 + migrations/alembic.ini | 45 ++++++++++++++++++ migrations/env.py | 96 +++++++++++++++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++++++ 4 files changed, 166 insertions(+) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# 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 + +[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 + +[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..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +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.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 = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + 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"} From 2816113d7d6ef670cdc79e4730c513ec5a89b198 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Tue, 8 Nov 2022 23:58:46 -0800 Subject: [PATCH 02/13] Adds attributes to Task model --- app/models/task.py | 5 +++- migrations/versions/0a43a0915e56_.py | 39 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 migrations/versions/0a43a0915e56_.py diff --git a/app/models/task.py b/app/models/task.py index c91ab281f..1e6268095 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -2,4 +2,7 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime, nullable=True) \ No newline at end of file diff --git a/migrations/versions/0a43a0915e56_.py b/migrations/versions/0a43a0915e56_.py new file mode 100644 index 000000000..c3832b7af --- /dev/null +++ b/migrations/versions/0a43a0915e56_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 0a43a0915e56 +Revises: +Create Date: 2022-11-08 23:57:13.680506 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '0a43a0915e56' +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('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### From 704fcc7d316ff2a12dafd55975888e27aa609bde Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 9 Nov 2022 01:07:23 -0800 Subject: [PATCH 03/13] Creates POST endpoint in routes.py, registers task bp in app/__init__.py, adds to_dict method to Task model --- app/__init__.py | 2 ++ app/models/task.py | 12 +++++++++++- app/routes.py | 17 ++++++++++++++++- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..30052751d 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,7 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from .routes import tasks_bp + app.register_blueprint(tasks_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 1e6268095..f1199c5f9 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -5,4 +5,14 @@ class Task(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String) description = db.Column(db.String) - completed_at = db.Column(db.DateTime, nullable=True) \ No newline at end of file + completed_at = db.Column(db.DateTime, nullable=True) + + def to_dict(self): + return dict( + task = dict( + id = self.id, + title = self.title, + description = self.description, + is_complete = False + ) + ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 3aae38d49..ded372fc4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1 +1,16 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, jsonify, abort, make_response, request +from app import db +from app.models.task import Task + +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") + +@tasks_bp.route("", methods=["POST"]) +def create_task(): + request_body = request.get_json() + new_task = Task( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed at"]) + db.session.add(new_task) + db.session.commit() + return make_response(f"Task {new_task.title} has been successfully created", 201) \ No newline at end of file From 26d694bbd06e67d5b0b374b9ed002d0f397d95be Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 9 Nov 2022 01:28:40 -0800 Subject: [PATCH 04/13] Adds GET endpoints for task by ID and all tasks, includes validation by task ID and appropriate HTTP status codes --- app/routes.py | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/app/routes.py b/app/routes.py index ded372fc4..8c1b25f16 100644 --- a/app/routes.py +++ b/app/routes.py @@ -10,7 +10,44 @@ def create_task(): new_task = Task( title=request_body["title"], description=request_body["description"], - completed_at=request_body["completed at"]) + completed_at=request_body["completed at"] + ) db.session.add(new_task) db.session.commit() - return make_response(f"Task {new_task.title} has been successfully created", 201) \ No newline at end of file + return make_response(f"Task '{new_task.title}' has been successfully created", 201) + +@tasks_bp.route("", methods=["GET"]) +def read_all_tasks(): + title_query = request.args.get("title") + completed_at_query = request.args.get("completed at") + task_query = Task.query + if title_query: + task_query = Task.query.filter_by(title=title_query) + if completed_at_query: + task_query = Task.query.filter_by(completed_at=completed_at_query) + + tasks = task_query.all() + + tasks_response = [task.to_dict() for task in tasks] + + return jsonify(tasks_response) + +@tasks_bp.route("/", methods=["GET"]) +def task_endpoint(task_id): + task = validate_task(task_id) + + return jsonify(task.to_dict()) + + +def validate_task(task_id): + try: + task_id = int(task_id) + except: + abort(make_response({"message":f"Task {task_id} invalid"}, 400)) + + task = Task.query.get(task_id) + + if not task: + abort(make_response({"message":f"Task {task_id} not found"}, 404)) + + return task \ No newline at end of file From bb3e22472a072a6c7499d6e6570912cb44132345 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 9 Nov 2022 01:33:11 -0800 Subject: [PATCH 05/13] Adds DELETE endpoint with appropriate HTTP status code to routes.py --- app/routes.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/routes.py b/app/routes.py index 8c1b25f16..7e734ac25 100644 --- a/app/routes.py +++ b/app/routes.py @@ -38,6 +38,15 @@ def task_endpoint(task_id): return jsonify(task.to_dict()) +@tasks_bp.route("/", methods=["DELETE"]) +def task_delete(task_id): + task = validate_task(task_id) + + db.session.delete(task) + db.session.commit() + + return make_response(f"Task '{task.title}' has been successfully deleted", 200) + def validate_task(task_id): try: From 5a7e4180ec3db62c728fc84916c3bd320354a8bb Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 9 Nov 2022 02:02:17 -0800 Subject: [PATCH 06/13] Adds PUT endpoint and appropriate HTTP status code to routes.py, updates to_dict function so it will return properly --- app/models/task.py | 26 ++++++++++++++++++-------- app/routes.py | 11 +++++++++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index f1199c5f9..f2e0f86bd 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -8,11 +8,21 @@ class Task(db.Model): completed_at = db.Column(db.DateTime, nullable=True) def to_dict(self): - return dict( - task = dict( - id = self.id, - title = self.title, - description = self.description, - is_complete = False - ) - ) \ No newline at end of file + task_as_dict = {} + task_as_dict["id"] = self.id + task_as_dict["title"] = self.title + task_as_dict["description"] = self.description + task_as_dict["is complete"] = False + + return task_as_dict + + + + # return dict( + # task = dict( + # id = self.id, + # title = self.title, + # description = self.description, + # is_complete = False + # ) + # ) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 7e734ac25..ce65141eb 100644 --- a/app/routes.py +++ b/app/routes.py @@ -38,6 +38,17 @@ def task_endpoint(task_id): return jsonify(task.to_dict()) +@tasks_bp.route("/", methods=["PUT"]) +def task_update(task_id): + task = validate_task(task_id) + request_body = request.get_json() + task.title = request_body["title"] + task.description = request_body["description"] + task.completed_at = request_body["completed at"] + + db.session.commit() + return make_response(f"Task '{task.title}' has been updated successfully", 200) + @tasks_bp.route("/", methods=["DELETE"]) def task_delete(task_id): task = validate_task(task_id) From 01cf8187d23b9ee7b5d7a306d55152cf72a4820f Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 9 Nov 2022 02:28:59 -0800 Subject: [PATCH 07/13] Adds data validation for POST requests --- app/routes.py | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/app/routes.py b/app/routes.py index ce65141eb..95480fad7 100644 --- a/app/routes.py +++ b/app/routes.py @@ -7,11 +7,8 @@ @tasks_bp.route("", methods=["POST"]) def create_task(): request_body = request.get_json() - new_task = Task( - title=request_body["title"], - description=request_body["description"], - completed_at=request_body["completed at"] - ) + new_task = validate_new_task(request_body) + db.session.add(new_task) db.session.commit() return make_response(f"Task '{new_task.title}' has been successfully created", 201) @@ -56,7 +53,22 @@ def task_delete(task_id): db.session.delete(task) db.session.commit() - return make_response(f"Task '{task.title}' has been successfully deleted", 200) + return make_response({f"details":f"Task {task.id} '{task.title}' successfully deleted"}, 200) + + +def validate_new_task(request_body): + try: + new_task = Task( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed at"] + ) + + except: + abort(make_response({"details":f"Invalid data"}, 400)) + + return new_task + def validate_task(task_id): From 86f7e5e24e964ce2bb20bf2688c0ed8e3b4d5148 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Wed, 4 Jan 2023 02:03:32 -0800 Subject: [PATCH 08/13] Completes Wave 01 --- app/models/task.py | 33 +++++++-------- app/routes.py | 95 ++++++++++++++++++++++++------------------- tests/test_wave_01.py | 42 ++++++++----------- 3 files changed, 86 insertions(+), 84 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index f2e0f86bd..f574464b1 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -2,27 +2,24 @@ class Task(db.Model): - id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String) description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) def to_dict(self): - task_as_dict = {} - task_as_dict["id"] = self.id - task_as_dict["title"] = self.title - task_as_dict["description"] = self.description - task_as_dict["is complete"] = False + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": False + } - return task_as_dict - - - - # return dict( - # task = dict( - # id = self.id, - # title = self.title, - # description = self.description, - # is_complete = False - # ) - # ) \ No newline at end of file + @classmethod + def from_dict(cls, task_data): + new_task = Task( + title=task_data["title"], + description=task_data["description"] + # completed_at=task_data["completed_at"] + ) + return new_task \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 95480fad7..352c14e19 100644 --- a/app/routes.py +++ b/app/routes.py @@ -4,22 +4,54 @@ tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +def validate_complete_request(request_body): + try: + if request_body["title"] and request_body["description"]: + return request_body + + except: + abort(make_response({"details": "Invalid data"}, 400)) + + +def validate_task_id(task_id): + try: + task_id = int(task_id) + except: + abort(make_response({"details": "Invalid data"}, 404)) + + task = Task.query.get(task_id) + + if not task: + abort(make_response({"details": "Invalid data"}, 404)) + + return task + + @tasks_bp.route("", methods=["POST"]) def create_task(): request_body = request.get_json() - new_task = validate_new_task(request_body) - + valid_data = validate_complete_request(request_body) + new_task = Task.from_dict(valid_data) + db.session.add(new_task) db.session.commit() - return make_response(f"Task '{new_task.title}' has been successfully created", 201) + + task_response = { + "task": new_task.to_dict() + } + return make_response(jsonify(task_response), 201) + @tasks_bp.route("", methods=["GET"]) -def read_all_tasks(): +def get_all_tasks(): title_query = request.args.get("title") + description_query = request.args.get("description") completed_at_query = request.args.get("completed at") task_query = Task.query if title_query: task_query = Task.query.filter_by(title=title_query) + if description_query: + task_query = Task.query.filter_by(description=description_query) if completed_at_query: task_query = Task.query.filter_by(completed_at=completed_at_query) @@ -27,59 +59,38 @@ def read_all_tasks(): tasks_response = [task.to_dict() for task in tasks] - return jsonify(tasks_response) + return make_response(jsonify(tasks_response), 200) @tasks_bp.route("/", methods=["GET"]) -def task_endpoint(task_id): - task = validate_task(task_id) +def get_one_task(task_id): + task = validate_task_id(task_id) - return jsonify(task.to_dict()) + task_response = { + "task": task.to_dict() + } + + return make_response(jsonify(task_response), 200) @tasks_bp.route("/", methods=["PUT"]) def task_update(task_id): - task = validate_task(task_id) + task = validate_task_id(task_id) request_body = request.get_json() task.title = request_body["title"] task.description = request_body["description"] - task.completed_at = request_body["completed at"] + # task.completed_at = request_body["completed at"] + + task_response = { + "task": task.to_dict() + } db.session.commit() - return make_response(f"Task '{task.title}' has been updated successfully", 200) + return make_response((task_response), 200) @tasks_bp.route("/", methods=["DELETE"]) def task_delete(task_id): - task = validate_task(task_id) + task = validate_task_id(task_id) db.session.delete(task) db.session.commit() - return make_response({f"details":f"Task {task.id} '{task.title}' successfully deleted"}, 200) - - -def validate_new_task(request_body): - try: - new_task = Task( - title=request_body["title"], - description=request_body["description"], - completed_at=request_body["completed at"] - ) - - except: - abort(make_response({"details":f"Invalid data"}, 400)) - - return new_task - - - -def validate_task(task_id): - try: - task_id = int(task_id) - except: - abort(make_response({"message":f"Task {task_id} invalid"}, 400)) - - task = Task.query.get(task_id) - - if not task: - abort(make_response({"message":f"Task {task_id} not found"}, 404)) - - return task \ No newline at end of file + return make_response({'details': f'Task {task.id} "{task.title}" successfully deleted'}, 200) \ No newline at end of file diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..824ca49e3 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") @@ -60,13 +60,11 @@ def test_get_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_task(client): # Act response = client.post("/tasks", json={ @@ -93,7 +91,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 +117,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={ @@ -131,13 +129,12 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") + +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -152,7 +149,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") @@ -161,15 +158,12 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** - + # raise Exception("Complete test with assertion about response body") + assert response_body == {"details":"Invalid data"} 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 +180,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={ From ae22656339b3e055bbfd2415e792f6a291f6012e Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Sat, 21 Jan 2023 19:55:49 -0800 Subject: [PATCH 09/13] Completed Wave02 --- app/routes.py | 10 ++++++++-- tests/test_wave_02.py | 4 ++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/app/routes.py b/app/routes.py index 352c14e19..384a73409 100644 --- a/app/routes.py +++ b/app/routes.py @@ -47,20 +47,26 @@ def get_all_tasks(): title_query = request.args.get("title") description_query = request.args.get("description") completed_at_query = request.args.get("completed at") - task_query = Task.query + sort_query = request.args.get("sort") + task_query = Task.query.all() if title_query: task_query = Task.query.filter_by(title=title_query) if description_query: task_query = Task.query.filter_by(description=description_query) if completed_at_query: task_query = Task.query.filter_by(completed_at=completed_at_query) + if sort_query == "asc": + task_query = Task.query.order_by(Task.title.asc()) + if sort_query == "desc": + task_query = Task.query.order_by(Task.title.desc()) - tasks = task_query.all() + tasks = task_query tasks_response = [task.to_dict() for task in tasks] return make_response(jsonify(tasks_response), 200) + @tasks_bp.route("/", methods=["GET"]) def get_one_task(task_id): task = validate_task_id(task_id) 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") From a5b5e18da2770dbe275fbc1413b217e3c69dc2fb Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Sat, 21 Jan 2023 23:05:08 -0800 Subject: [PATCH 10/13] Set up new migrations because of issues with the previous ones --- app/models/task.py | 22 +++++++-- app/routes.py | 46 ++++++++++++++++--- ..._setting_up_new_migrations_because_of_.py} | 10 ++-- tests/test_wave_03.py | 8 ++-- 4 files changed, 67 insertions(+), 19 deletions(-) rename migrations/versions/{0a43a0915e56_.py => ec9ba7413409_setting_up_new_migrations_because_of_.py} (77%) diff --git a/app/models/task.py b/app/models/task.py index f574464b1..e93cb5c2b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -7,19 +7,35 @@ class Task(db.Model): description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) - def to_dict(self): + def to_dict_post_put(self): return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": False + } + + def to_dict_get_patch(self): + if not self.completed_at: + return { "id": self.id, "title": self.title, "description": self.description, "is_complete": False } + else: + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": True + } @classmethod def from_dict(cls, task_data): new_task = Task( title=task_data["title"], - description=task_data["description"] - # completed_at=task_data["completed_at"] + description=task_data["description"], + completed_at=None ) return new_task \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 384a73409..a652cb6fe 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,4 +1,5 @@ from flask import Blueprint, jsonify, abort, make_response, request +from datetime import datetime from app import db from app.models.task import Task @@ -37,13 +38,13 @@ def create_task(): db.session.commit() task_response = { - "task": new_task.to_dict() + "task": new_task.to_dict_post_put() } return make_response(jsonify(task_response), 201) @tasks_bp.route("", methods=["GET"]) -def get_all_tasks(): +def get_all_tasks_sort_asc(): title_query = request.args.get("title") description_query = request.args.get("description") completed_at_query = request.args.get("completed at") @@ -62,7 +63,7 @@ def get_all_tasks(): tasks = task_query - tasks_response = [task.to_dict() for task in tasks] + tasks_response = [task.to_dict_get_patch() for task in tasks] return make_response(jsonify(tasks_response), 200) @@ -72,26 +73,57 @@ def get_one_task(task_id): task = validate_task_id(task_id) task_response = { - "task": task.to_dict() + "task": task.to_dict_get_patch() } return make_response(jsonify(task_response), 200) @tasks_bp.route("/", methods=["PUT"]) -def task_update(task_id): +def task_update_entire_entry(task_id): task = validate_task_id(task_id) request_body = request.get_json() task.title = request_body["title"] task.description = request_body["description"] - # task.completed_at = request_body["completed at"] + + db.session.commit() task_response = { - "task": task.to_dict() + "task": task.to_dict_post_put() } + return make_response((task_response), 200) + +@tasks_bp.route("/", methods=["PATCH"]) +def task_mark_complete(task_id): + task = validate_task_id(task_id) + request_body = request.get_json() + if not request_body["completed_at"]: + task.completed_at = None + else: + task.completed_at = datetime.now() + db.session.commit() + + task_response = { + "task": task.to_dict_get_patch() + } + return make_response((task_response), 200) +# @tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +# def task_mark_incomplete(task_id): +# task = validate_task_id(task_id) +# task.completed_at = None + +# db.session.commit() + +# task_response = { +# "task": task.to_dict_get_patch() +# } + +# return make_response((task_response), 200) + + @tasks_bp.route("/", methods=["DELETE"]) def task_delete(task_id): task = validate_task_id(task_id) diff --git a/migrations/versions/0a43a0915e56_.py b/migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py similarity index 77% rename from migrations/versions/0a43a0915e56_.py rename to migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py index c3832b7af..6e7b419e9 100644 --- a/migrations/versions/0a43a0915e56_.py +++ b/migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py @@ -1,8 +1,8 @@ -"""empty message +"""Setting up new migrations because of errors with the previous setup -Revision ID: 0a43a0915e56 +Revision ID: ec9ba7413409 Revises: -Create Date: 2022-11-08 23:57:13.680506 +Create Date: 2023-01-21 23:01:06.963776 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '0a43a0915e56' +revision = 'ec9ba7413409' down_revision = None branch_labels = None depends_on = None @@ -23,7 +23,7 @@ def upgrade(): sa.PrimaryKeyConstraint('goal_id') ) op.create_table('task', - sa.Column('id', sa.Integer(), nullable=False), + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('title', sa.String(), nullable=True), sa.Column('description', sa.String(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True), diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..da8e6ba1e 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") From 023bbfee6d3b48dcfe4bed9a0b7bb58b7e321043 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Sat, 21 Jan 2023 23:21:23 -0800 Subject: [PATCH 11/13] Completes Wave03 --- app/routes.py | 28 ++++++++++++---------------- tests/test_wave_03.py | 22 ++++++++++++---------- 2 files changed, 24 insertions(+), 26 deletions(-) diff --git a/app/routes.py b/app/routes.py index a652cb6fe..c1b79de5c 100644 --- a/app/routes.py +++ b/app/routes.py @@ -93,15 +93,10 @@ def task_update_entire_entry(task_id): return make_response((task_response), 200) -@tasks_bp.route("/", methods=["PATCH"]) +@tasks_bp.route("//mark_complete", methods=["PATCH"]) def task_mark_complete(task_id): task = validate_task_id(task_id) - request_body = request.get_json() - if not request_body["completed_at"]: - task.completed_at = None - else: - task.completed_at = datetime.now() - + task.completed_at = datetime.now() db.session.commit() task_response = { @@ -109,19 +104,20 @@ def task_mark_complete(task_id): } return make_response((task_response), 200) + -# @tasks_bp.route("//mark_incomplete", methods=["PATCH"]) -# def task_mark_incomplete(task_id): -# task = validate_task_id(task_id) -# task.completed_at = None +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def task_mark_incomplete(task_id): + task = validate_task_id(task_id) + task.completed_at = None -# db.session.commit() + db.session.commit() -# task_response = { -# "task": task.to_dict_get_patch() -# } + task_response = { + "task": task.to_dict_get_patch() + } -# return make_response((task_response), 200) + return make_response((task_response), 200) @tasks_bp.route("/", methods=["DELETE"]) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index da8e6ba1e..ec092f41a 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -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") @@ -128,13 +128,14 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert response_body == { + "details": "Invalid data" + } + 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_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -143,7 +144,8 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert response_body == { + "details": "Invalid data" + } + assert Task.query.all() == [] From 47a30d94873c0c16b7ce921b98ce011a0cb72141 Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Sun, 22 Jan 2023 00:15:48 -0800 Subject: [PATCH 12/13] Completes Wave05 --- app/__init__.py | 5 +- app/goal_routes.py | 92 +++++++++++++++++++ app/models/goal.py | 17 +++- app/{routes.py => task_routes.py} | 2 +- ...7a2_started_building_out_the_goal_model.py | 32 +++++++ tests/test_wave_01.py | 2 - tests/test_wave_05.py | 92 +++++++++++-------- 7 files changed, 197 insertions(+), 45 deletions(-) create mode 100644 app/goal_routes.py rename app/{routes.py => task_routes.py} (100%) create mode 100644 migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py diff --git a/app/__init__.py b/app/__init__.py index 30052751d..4d510c552 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,7 +30,10 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here - from .routes import tasks_bp + from .task_routes import tasks_bp app.register_blueprint(tasks_bp) + from .goal_routes import goals_bp + app.register_blueprint(goals_bp) + return app diff --git a/app/goal_routes.py b/app/goal_routes.py new file mode 100644 index 000000000..3a9d0f798 --- /dev/null +++ b/app/goal_routes.py @@ -0,0 +1,92 @@ +from flask import Blueprint, jsonify, abort, make_response, request +from datetime import datetime +from app import db +from app.models.goal import Goal + +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + +def validate_complete_request(request_body): + try: + if request_body["title"]: + return request_body + + except: + abort(make_response({"details": "Invalid data"}, 400)) + + +def validate_goal_id(goal_id): + try: + goal_id = int(goal_id) + except: + abort(make_response({"details": "Invalid data"}, 404)) + + goal = Goal.query.get(goal_id) + + if not goal: + abort(make_response({"details": "Invalid data"}, 404)) + + return goal + + +@goals_bp.route("", methods=["POST"]) +def create_goal(): + request_body = request.get_json() + valid_data = validate_complete_request(request_body) + new_goal = Goal.from_dict(valid_data) + + db.session.add(new_goal) + db.session.commit() + + goal_response = { + "goal": new_goal.to_dict() + } + return make_response(jsonify(goal_response), 201) + + +@goals_bp.route("", methods=["GET"]) +def get_all_goals_sort_asc(): + goal_query = Goal.query.all() + title_query = request.args.get("title") + if title_query: + goal_query = Goal.query.filter_by(title=title_query) + + goals = goal_query + + goals_response = [goal.to_dict() for goal in goals] + + return make_response(jsonify(goals_response), 200) + + +@goals_bp.route("/", methods=["GET"]) +def get_one_goal(goal_id): + goal = validate_goal_id(goal_id) + + goal_response = { + "goal": goal.to_dict() + } + + return make_response(jsonify(goal_response), 200) + +@goals_bp.route("/", methods=["PUT"]) +def goal_update_entire_entry(goal_id): + goal = validate_goal_id(goal_id) + request_body = request.get_json() + goal.title = request_body["title"] + + db.session.commit() + + goal_response = { + "goal": goal.to_dict() + } + + return make_response((goal_response), 200) + + +@goals_bp.route("/", methods=["DELETE"]) +def goal_delete(goal_id): + goal = validate_goal_id(goal_id) + + db.session.delete(goal) + db.session.commit() + + return make_response({'details': f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200) \ No newline at end of file diff --git a/app/models/goal.py b/app/models/goal.py index b0ed11dd8..4ee88ad33 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,4 +2,19 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + } + + @classmethod + def from_dict(cls, goal_data): + new_goal = Goal( + title=goal_data["title"], + ) + return new_goal + diff --git a/app/routes.py b/app/task_routes.py similarity index 100% rename from app/routes.py rename to app/task_routes.py index c1b79de5c..f02d294ee 100644 --- a/app/routes.py +++ b/app/task_routes.py @@ -45,11 +45,11 @@ def create_task(): @tasks_bp.route("", methods=["GET"]) def get_all_tasks_sort_asc(): + task_query = Task.query.all() title_query = request.args.get("title") description_query = request.args.get("description") completed_at_query = request.args.get("completed at") sort_query = request.args.get("sort") - task_query = Task.query.all() if title_query: task_query = Task.query.filter_by(title=title_query) if description_query: diff --git a/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py b/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py new file mode 100644 index 000000000..e32d7c025 --- /dev/null +++ b/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py @@ -0,0 +1,32 @@ +"""Started building out the Goal model + +Revision ID: 9303eafed7a2 +Revises: ec9ba7413409 +Create Date: 2023-01-21 23:29:10.301349 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9303eafed7a2' +down_revision = 'ec9ba7413409' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('id', sa.Integer(), nullable=False)) + op.add_column('goal', sa.Column('title', sa.String(), nullable=True)) + op.drop_column('goal', 'goal_id') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False)) + op.drop_column('goal', 'title') + op.drop_column('goal', 'id') + # ### end Alembic commands ### diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 824ca49e3..81204bbc3 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -1,6 +1,4 @@ from app.models.task import Task -import pytest - # @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_no_saved_tasks(client): diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..70d4a69df 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,7 +1,6 @@ -import pytest +from app.models.goal import 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_goals_no_saved_goals(client): # Act response = client.get("/goals") @@ -12,7 +11,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 +28,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 +45,20 @@ 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 - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_create_goal(client): # Act response = client.post("/goals", json={ @@ -78,36 +75,48 @@ def test_create_goal(client): "title": "My New Goal" } } + new_goal = Goal.query.get(1) + assert new_goal + assert new_goal.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" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title" + } + } + goal = Goal.query.get(1) + assert goal.title == "Updated Goal Title" -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title", + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -124,27 +133,30 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert "details" in response_body + assert response_body == { + "details": 'Goal 1 "Build a habit of going outside daily" successfully deleted' + } + assert Goal.query.get(1) == None -@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":"Invalid data"} + assert Goal.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_goal_missing_title(client): # Act response = client.post("/goals", json={}) From 72fde3c8d27bf06161fd8c5810193442a6e86e4f Mon Sep 17 00:00:00 2001 From: Anika Stephen Wilbur Date: Sun, 22 Jan 2023 16:44:54 -0800 Subject: [PATCH 13/13] Completed Wave06 --- app/goal_routes.py | 84 ++++++++++++++++--- app/models/goal.py | 7 +- app/models/task.py | 43 +++++++--- app/task_routes.py | 20 ++--- ...05340_trying_to_get_everything_to_work.py} | 15 ++-- ...7a2_started_building_out_the_goal_model.py | 32 ------- tests/test_wave_06.py | 19 ++--- 7 files changed, 138 insertions(+), 82 deletions(-) rename migrations/versions/{ec9ba7413409_setting_up_new_migrations_because_of_.py => 4149cc305340_trying_to_get_everything_to_work.py} (66%) delete mode 100644 migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py diff --git a/app/goal_routes.py b/app/goal_routes.py index 3a9d0f798..2d2bdd450 100644 --- a/app/goal_routes.py +++ b/app/goal_routes.py @@ -1,7 +1,7 @@ from flask import Blueprint, jsonify, abort, make_response, request -from datetime import datetime from app import db from app.models.goal import Goal +from app.models.task import Task goals_bp = Blueprint("goals", __name__, url_prefix="/goals") @@ -14,18 +14,18 @@ def validate_complete_request(request_body): abort(make_response({"details": "Invalid data"}, 400)) -def validate_goal_id(goal_id): +def validate_model_id(cls, model_id): try: - goal_id = int(goal_id) + model_id = int(model_id) except: abort(make_response({"details": "Invalid data"}, 404)) - goal = Goal.query.get(goal_id) + model = cls.query.get(model_id) - if not goal: + if not model: abort(make_response({"details": "Invalid data"}, 404)) - return goal + return model @goals_bp.route("", methods=["POST"]) @@ -59,7 +59,7 @@ def get_all_goals_sort_asc(): @goals_bp.route("/", methods=["GET"]) def get_one_goal(goal_id): - goal = validate_goal_id(goal_id) + goal = validate_model_id(Goal, goal_id) goal_response = { "goal": goal.to_dict() @@ -69,7 +69,7 @@ def get_one_goal(goal_id): @goals_bp.route("/", methods=["PUT"]) def goal_update_entire_entry(goal_id): - goal = validate_goal_id(goal_id) + goal = validate_model_id(Goal, goal_id) request_body = request.get_json() goal.title = request_body["title"] @@ -84,9 +84,73 @@ def goal_update_entire_entry(goal_id): @goals_bp.route("/", methods=["DELETE"]) def goal_delete(goal_id): - goal = validate_goal_id(goal_id) + goal = validate_model_id(Goal, goal_id) db.session.delete(goal) db.session.commit() - return make_response({'details': f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200) \ No newline at end of file + return make_response({'details': f'Goal {goal.id} "{goal.title}" successfully deleted'}, 200) + +@goals_bp.route("//tasks", methods=["POST"]) +def add_tasks_to_goal(goal_id): + goal = validate_model_id(Goal, goal_id) + request_body = request.get_json() + + for task_id in request_body["task_ids"]: + task = validate_model_id(Task, task_id) + goal.tasks.append(task) + db.session.commit() + + goal_response = { + "id": goal.id, + "task_ids": request_body["task_ids"] + } + + + return make_response(jsonify(goal_response), 200) + + +@goals_bp.route("//tasks", methods=["GET"]) +def get_goal_with_tasks(goal_id): + goal = validate_model_id(Goal, goal_id) + + tasks = [] + for task in goal.tasks: + tasks.append( + { + "id": task.id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": False + } + ) + + goal_response = { + "id": goal.id, + "title": goal.title, + "tasks": tasks + } + + return make_response(jsonify(goal_response), 200) + +@goals_bp.route("/tasks/", methods=["GET"]) +def get_one_task(goal_id, task_id): + goal = validate_model_id(Goal, goal_id) + task = validate_model_id(Task, task_id) + + task_response = [] + for task in goal.tasks: + task_response.append( + { + "task": { + "id": task.id, + "goal_id": task.goal_id, + "title": task.title, + "description": task.description, + "is_complete": False + } + } + ) + + return make_response(jsonify(task_response), 200) diff --git a/app/models/goal.py b/app/models/goal.py index 4ee88ad33..4826c40de 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -2,8 +2,10 @@ class Goal(db.Model): - id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String) + tasks = db.relationship("Task", back_populates="goal", lazy=True) + def to_dict(self): return { @@ -16,5 +18,4 @@ def from_dict(cls, goal_data): new_goal = Goal( title=goal_data["title"], ) - return new_goal - + return new_goal \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index e93cb5c2b..198bf5d9f 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -6,6 +6,9 @@ class Task(db.Model): title = db.Column(db.String) description = db.Column(db.String) completed_at = db.Column(db.DateTime, nullable=True) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.id'), nullable=True) + goal = db.relationship("Goal", back_populates="tasks") + def to_dict_post_put(self): return { @@ -17,19 +20,37 @@ def to_dict_post_put(self): def to_dict_get_patch(self): if not self.completed_at: - return { - "id": self.id, - "title": self.title, - "description": self.description, - "is_complete": False - } + if self.goal_id: + return { + "id": self.id, + "goal_id": self.goal_id, + "title": self.title, + "description": self.description, + "is_complete": False + } + else: + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": False + } else: - return { - "id": self.id, - "title": self.title, - "description": self.description, - "is_complete": True + if self.goal_id: + return { + "id": self.id, + "goal_id": self.goal_id, + "title": self.title, + "description": self.description, + "is_complete": False } + else: + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": True + } @classmethod def from_dict(cls, task_data): diff --git a/app/task_routes.py b/app/task_routes.py index f02d294ee..e37f037d2 100644 --- a/app/task_routes.py +++ b/app/task_routes.py @@ -14,18 +14,18 @@ def validate_complete_request(request_body): abort(make_response({"details": "Invalid data"}, 400)) -def validate_task_id(task_id): +def validate_model_id(cls, model_id): try: - task_id = int(task_id) + model_id = int(model_id) except: abort(make_response({"details": "Invalid data"}, 404)) - task = Task.query.get(task_id) + model = cls.query.get(model_id) - if not task: + if not model: abort(make_response({"details": "Invalid data"}, 404)) - return task + return model @tasks_bp.route("", methods=["POST"]) @@ -70,7 +70,7 @@ def get_all_tasks_sort_asc(): @tasks_bp.route("/", methods=["GET"]) def get_one_task(task_id): - task = validate_task_id(task_id) + task = validate_model_id(Task, task_id) task_response = { "task": task.to_dict_get_patch() @@ -80,7 +80,7 @@ def get_one_task(task_id): @tasks_bp.route("/", methods=["PUT"]) def task_update_entire_entry(task_id): - task = validate_task_id(task_id) + task = validate_model_id(Task, task_id) request_body = request.get_json() task.title = request_body["title"] task.description = request_body["description"] @@ -95,7 +95,7 @@ def task_update_entire_entry(task_id): @tasks_bp.route("//mark_complete", methods=["PATCH"]) def task_mark_complete(task_id): - task = validate_task_id(task_id) + task = validate_model_id(Task, task_id) task.completed_at = datetime.now() db.session.commit() @@ -108,7 +108,7 @@ def task_mark_complete(task_id): @tasks_bp.route("//mark_incomplete", methods=["PATCH"]) def task_mark_incomplete(task_id): - task = validate_task_id(task_id) + task = validate_model_id(Task, task_id) task.completed_at = None db.session.commit() @@ -122,7 +122,7 @@ def task_mark_incomplete(task_id): @tasks_bp.route("/", methods=["DELETE"]) def task_delete(task_id): - task = validate_task_id(task_id) + task = validate_model_id(Task, task_id) db.session.delete(task) db.session.commit() diff --git a/migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py b/migrations/versions/4149cc305340_trying_to_get_everything_to_work.py similarity index 66% rename from migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py rename to migrations/versions/4149cc305340_trying_to_get_everything_to_work.py index 6e7b419e9..7feab09c4 100644 --- a/migrations/versions/ec9ba7413409_setting_up_new_migrations_because_of_.py +++ b/migrations/versions/4149cc305340_trying_to_get_everything_to_work.py @@ -1,8 +1,8 @@ -"""Setting up new migrations because of errors with the previous setup +"""Trying to get everything to work -Revision ID: ec9ba7413409 +Revision ID: 4149cc305340 Revises: -Create Date: 2023-01-21 23:01:06.963776 +Create Date: 2023-01-22 15:15:55.065075 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = 'ec9ba7413409' +revision = '4149cc305340' down_revision = None branch_labels = None depends_on = None @@ -19,14 +19,17 @@ 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') + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') ) op.create_table('task', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('title', sa.String(), nullable=True), sa.Column('description', sa.String(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### diff --git a/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py b/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py deleted file mode 100644 index e32d7c025..000000000 --- a/migrations/versions/9303eafed7a2_started_building_out_the_goal_model.py +++ /dev/null @@ -1,32 +0,0 @@ -"""Started building out the Goal model - -Revision ID: 9303eafed7a2 -Revises: ec9ba7413409 -Create Date: 2023-01-21 23:29:10.301349 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '9303eafed7a2' -down_revision = 'ec9ba7413409' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('goal', sa.Column('id', sa.Integer(), nullable=False)) - op.add_column('goal', sa.Column('title', sa.String(), nullable=True)) - op.drop_column('goal', 'goal_id') - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - op.add_column('goal', sa.Column('goal_id', sa.INTEGER(), autoincrement=True, nullable=False)) - op.drop_column('goal', 'title') - op.drop_column('goal', 'id') - # ### end Alembic commands ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..2efcf77ab 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") @@ -51,13 +51,12 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") - # ***************************************************************** - # **Complete test with assertion about response body*************** - # ***************************************************************** + # raise Exception("Complete test with assertion about response body") + assert response_body == {"details": "Invalid data"} -@pytest.mark.skip(reason="No way to test this feature yet") + +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -74,7 +73,7 @@ def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): # Act response = client.get("/goals/1/tasks") @@ -99,7 +98,7 @@ def test_get_tasks_for_specific_goal(client, one_task_belongs_to_one_goal): } -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_task_includes_goal_id(client, one_task_belongs_to_one_goal): response = client.get("/tasks/1") response_body = response.get_json()