From f71d8f219a88a533826fdd3660349c62b700e504 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 13:30:48 -0800 Subject: [PATCH 01/30] Created migration, registered blueprint, created POST endpoint --- ada-project-docs/setup.md | 2 +- app/__init__.py | 2 + app/models/task.py | 20 +++++ app/routes/task_routes.py | 30 ++++++- migrations/README | 1 + migrations/alembic.ini | 50 ++++++++++++ migrations/env.py | 113 +++++++++++++++++++++++++++ migrations/script.py.mako | 24 ++++++ migrations/versions/71545439cd6f_.py | 39 +++++++++ 9 files changed, 279 insertions(+), 2 deletions(-) create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/71545439cd6f_.py diff --git a/ada-project-docs/setup.md b/ada-project-docs/setup.md index b3ee1840d..dc64381c5 100644 --- a/ada-project-docs/setup.md +++ b/ada-project-docs/setup.md @@ -61,7 +61,7 @@ SQLALCHEMY_TEST_DATABASE_URI=postgresql+psycopg2://postgres:postgres@localhost:5 Run `$ flask db init`. -**_After you make your first model in Wave 1_**, run the other commands `migrate` and `upgrade`. +**_After you make your first model in Wave 1_**, run the other commands `$ flask db migrate` and `$ flask db upgrade`. ## Run `$ flask run` or `$ flask run --debug` diff --git a/app/__init__.py b/app/__init__.py index 3c581ceeb..4d91acfe2 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,7 @@ from flask import Flask from .db import db, migrate from .models import task, goal +from .routes.task_routes import task_bp import os def create_app(config=None): @@ -18,5 +19,6 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here + app.register_blueprint(task_bp) return app diff --git a/app/models/task.py b/app/models/task.py index 5d99666a4..eaae9b9cf 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,5 +1,25 @@ from sqlalchemy.orm import Mapped, mapped_column from ..db import db +from datetime import datetime +from typing import Optional class Task(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + description: Mapped[str] + completed_at: Mapped[Optional[str]] + +def to_dict(self): + return dict( + id=self.id, + title=self.title, + description=self.description, + completed_at=self.completed_at + ) + + + + + + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 3aae38d49..6457a63c0 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1 +1,29 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response, make_response, abort +from app.models.task import Task +from ..db import db + +task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks" ) + +@task_bp.post("") +def create_task(): + request_body = request.get_json() + title = request_body["title"] + description = request_body["description"] + completed_at = request_body["completed_at"] + + new_task = Task(title=title, description=description, completed_at=completed_at) + db.session.add(new_task) + db.session.commit() + + response = { + "id": new_task.id, + "title": new_task.title, + "description": new_task.description, + "completed_at": new_task.completed_at + } + return response, 201 + + + + + diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..0e0484415 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..ec9d45c26 --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..4c9709271 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/71545439cd6f_.py b/migrations/versions/71545439cd6f_.py new file mode 100644 index 000000000..81f7d8b93 --- /dev/null +++ b/migrations/versions/71545439cd6f_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 71545439cd6f +Revises: +Create Date: 2024-10-31 14:01:36.695714 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '71545439cd6f' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=False), + sa.Column('completed_at', sa.String(), 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 6ffaa322b83db3f879afd55491039e8c1764cc4e Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 14:39:53 -0800 Subject: [PATCH 02/30] Fixed POST endpoint logic, enabled test for POST, recreated migration --- app/routes/task_routes.py | 16 +++++++++++----- ...=> 466ce16ba2a2_recreate_model_migrations.py} | 8 ++++---- tests/test_wave_01.py | 2 +- 3 files changed, 16 insertions(+), 10 deletions(-) rename migrations/versions/{71545439cd6f_.py => 466ce16ba2a2_recreate_model_migrations.py} (88%) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 6457a63c0..555fca071 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -9,17 +9,23 @@ def create_task(): request_body = request.get_json() title = request_body["title"] description = request_body["description"] - completed_at = request_body["completed_at"] + try: + completed_at = request_body["completed_at"] + except: + completed_at = None + new_task = Task(title=title, description=description, completed_at=completed_at) db.session.add(new_task) db.session.commit() response = { - "id": new_task.id, - "title": new_task.title, - "description": new_task.description, - "completed_at": new_task.completed_at + "task": { + "id": new_task.id, + "title": new_task.title, + "description": new_task.description, + "is_complete": new_task.completed_at != None + } } return response, 201 diff --git a/migrations/versions/71545439cd6f_.py b/migrations/versions/466ce16ba2a2_recreate_model_migrations.py similarity index 88% rename from migrations/versions/71545439cd6f_.py rename to migrations/versions/466ce16ba2a2_recreate_model_migrations.py index 81f7d8b93..650526161 100644 --- a/migrations/versions/71545439cd6f_.py +++ b/migrations/versions/466ce16ba2a2_recreate_model_migrations.py @@ -1,8 +1,8 @@ -"""empty message +"""Recreate model migrations -Revision ID: 71545439cd6f +Revision ID: 466ce16ba2a2 Revises: -Create Date: 2024-10-31 14:01:36.695714 +Create Date: 2024-11-03 14:27:30.106262 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '71545439cd6f' +revision = '466ce16ba2a2' down_revision = None branch_labels = None depends_on = None diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index dca626d78..292d2a5c4 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -66,7 +66,7 @@ def test_get_task_not_found(client): # ***************************************************************** -@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={ From 5cf4d3c9a0ec7bdc6e931a68892b6faf0a51d726 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 20:52:09 -0800 Subject: [PATCH 03/30] Added endpoints GET(tasks), GET (task), PUT, DELETE. Enabled tests. --- app/routes/task_routes.py | 84 +++++++++++++++++++++++++++++++++++++++ tests/test_wave_01.py | 6 +-- 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 555fca071..5ffb73b27 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -29,6 +29,90 @@ def create_task(): } return response, 201 +@task_bp.get("") +def get_all_task(): + query = db.select(Task) + + title_param = request.args.get("title") + if title_param: + query = query.where(Task.title.ilike(f"%{title_param}%")) + + description_param = request.args.get("description") + if description_param: + query = query.where(Task.description.ilike(f"%{description_param}%")) + + completed_at_param = request.args.get("completed_at") + if completed_at_param: + query = query.where(Task.completed_at.ilike(f"%{completed_at_param}%")) + + query = query.order_by(Task.id) + task = db.session.scalars(query) + # We could also write the line above as: + # books = db.session.execute(query).scalars() + + tasks_response = [] + for task in task: + tasks_response.append( + { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at != None + } + ) + return tasks_response + +@task_bp.get("/") +def get_one_task(task_id): + task = validate_task(task_id) + + return { + "task": { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at != None + } + } + +def validate_task(task_id): + try: + task_id = int(task_id) + except: + response = {"message": f"task {task_id} invalid"} + abort(make_response(response , 400)) + + query = db.select(Task).where(Task.id == task_id) + task = db.session.scalar(query) + + if not task: + response = {"message": f"task {task_id} not found"} + abort(make_response(response, 404)) + + return task + +@task_bp.put("/") +def update_task(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 Response(status=204, mimetype="application/json") + +@task_bp.delete("/") +def delete_task(task_id): + task = validate_task(task_id) + db.session.delete(task) + db.session.commit() + + return Response(status=204, mimetype="application/json") + + + diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 292d2a5c4..5306adadc 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") From d36600eb9ec9a38a50fd49e48769c94413e6a3b6 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 21:13:46 -0800 Subject: [PATCH 04/30] Fixed the issues in PUT endpoint. --- app/routes/task_routes.py | 12 ++++++++++-- tests/test_wave_01.py | 10 +++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 5ffb73b27..55f700a55 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -98,10 +98,18 @@ def update_task(task_id): task.title = request_body["title"] task.description = request_body["description"] - task.completed_at = request_body["completed_at"] db.session.commit() - return Response(status=204, mimetype="application/json") + response = { + "task": { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at != None + } + } + + return response, 200 @task_bp.delete("/") def delete_task(task_id): diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 5306adadc..960a9f73a 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -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,7 +60,11 @@ 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 == { + "message": "task 1 not found" + } + + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -93,7 +97,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={ From c184c1834d3845023363f6fc69f78b2296e3c886 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 21:47:43 -0800 Subject: [PATCH 05/30] Fixed the issues in POST and DELETE implementation. --- app/routes/task_routes.py | 16 ++++++++++++++-- tests/test_wave_01.py | 20 ++++++++++++++------ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 55f700a55..d24b9a809 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -7,6 +7,14 @@ @task_bp.post("") def create_task(): request_body = request.get_json() + try: + title = request_body["title"] + except: + response = { + "details": "Invalid data" + } + return response, 400 + title = request_body["title"] description = request_body["description"] try: @@ -79,7 +87,8 @@ def validate_task(task_id): try: task_id = int(task_id) except: - response = {"message": f"task {task_id} invalid"} + response = {"details": "Invalid data"} + abort(make_response(response , 400)) query = db.select(Task).where(Task.id == task_id) @@ -117,8 +126,11 @@ def delete_task(task_id): db.session.delete(task) db.session.commit() - return Response(status=204, mimetype="application/json") + response = { + "details": f"Task {task_id} \"{task.title}\" successfully deleted" + } + return response, 200 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 960a9f73a..3b39f8c72 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -123,7 +123,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={ @@ -135,13 +135,17 @@ def test_update_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == { + "message": "task 1 not found" + } + + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_task(client, one_task): # Act response = client.delete("/tasks/1") @@ -156,7 +160,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") @@ -165,7 +169,11 @@ def test_delete_task_not_found(client): # Assert assert response.status_code == 404 - raise Exception("Complete test with assertion about response body") + assert response_body == { + "message": "task 1 not found" + } + + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** @@ -173,7 +181,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={ From d3b9a04166839d61c7019a5ac39b1769ecda222d Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 3 Nov 2024 21:55:06 -0800 Subject: [PATCH 06/30] Fixed POST endpoint. --- app/routes/task_routes.py | 12 ++++++++++-- tests/test_wave_01.py | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d24b9a809..6ae821fa1 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -15,8 +15,16 @@ def create_task(): } return response, 400 - title = request_body["title"] - description = request_body["description"] + + try: + description = request_body["description"] + except: + response = { + "details": "Invalid data" + } + return response, 400 + + try: completed_at = request_body["completed_at"] except: diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 3b39f8c72..81b0f170d 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -198,7 +198,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 e1c34d9490da0b9f173b2556d30a978981516501 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 4 Nov 2024 18:48:30 -0800 Subject: [PATCH 07/30] Changed Blueprint @, to_dict function --- app/__init__.py | 2 +- app/models/task.py | 18 ++++++++++-------- app/routes/task_routes.py | 21 +++++++-------------- 3 files changed, 18 insertions(+), 23 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 4d91acfe2..8ba6ea6db 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,7 @@ from flask import Flask from .db import db, migrate from .models import task, goal -from .routes.task_routes import task_bp +from .routes.task_routes import bp as task_bp import os def create_app(config=None): diff --git a/app/models/task.py b/app/models/task.py index eaae9b9cf..a40e0930a 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -9,14 +9,16 @@ class Task(db.Model): description: Mapped[str] completed_at: Mapped[Optional[str]] -def to_dict(self): - return dict( - id=self.id, - title=self.title, - description=self.description, - completed_at=self.completed_at - ) - + def to_dict(self): + return dict( + task=dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.completed_at!=None + ) + ) + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 6ae821fa1..ed73afcfb 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,9 +2,9 @@ from app.models.task import Task from ..db import db -task_bp = Blueprint("task_bp", __name__, url_prefix="/tasks" ) +bp = Blueprint("task_bp", __name__, url_prefix="/tasks" ) -@task_bp.post("") +@bp.post("") def create_task(): request_body = request.get_json() try: @@ -45,7 +45,7 @@ def create_task(): } return response, 201 -@task_bp.get("") +@bp.get("") def get_all_task(): query = db.select(Task) @@ -78,18 +78,11 @@ def get_all_task(): ) return tasks_response -@task_bp.get("/") +@bp.get("/") def get_one_task(task_id): task = validate_task(task_id) - return { - "task": { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at != None - } - } + return task.to_dict() def validate_task(task_id): try: @@ -108,7 +101,7 @@ def validate_task(task_id): return task -@task_bp.put("/") +@bp.put("/") def update_task(task_id): task = validate_task(task_id) request_body = request.get_json() @@ -128,7 +121,7 @@ def update_task(task_id): return response, 200 -@task_bp.delete("/") +@bp.delete("/") def delete_task(task_id): task = validate_task(task_id) db.session.delete(task) From 4a933365b1b19498404514fc9cd84ba9bd81a159 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 4 Nov 2024 19:27:34 -0800 Subject: [PATCH 08/30] Created from_dict function, changed POST endpoint --- app/models/task.py | 9 +++++++ app/routes/task_routes.py | 52 ++++++++++++++++++--------------------- 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index a40e0930a..91cdc4c8d 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -9,6 +9,7 @@ class Task(db.Model): description: Mapped[str] completed_at: Mapped[Optional[str]] + # from model to JSON def to_dict(self): return dict( task=dict( @@ -18,6 +19,14 @@ def to_dict(self): is_complete=self.completed_at!=None ) ) + + # from JSON to model + @classmethod + def from_dict(cls, task_data): + return cls( + title=task_data["title"], + description=task_data["description"] + ) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index ed73afcfb..e1dcc7998 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -7,43 +7,41 @@ @bp.post("") def create_task(): request_body = request.get_json() + try: - title = request_body["title"] - except: + new_task = Task.from_dict(request_body) + + except KeyError as e: response = { "details": "Invalid data" } - return response, 400 + abort(make_response(response, 400)) + + db.session.add(new_task) + db.session.commit() + + return new_task.to_dict(), 201 - try: - description = request_body["description"] - except: - response = { - "details": "Invalid data" - } - return response, 400 + # try: + # description = request_body["description"] + # except: + # response = { + # "details": "Invalid data" + # } + # return response, 400 - try: - completed_at = request_body["completed_at"] - except: - completed_at = None + # try: + # completed_at = request_body["completed_at"] + # except: + # completed_at = None - new_task = Task(title=title, description=description, completed_at=completed_at) - db.session.add(new_task) - db.session.commit() + # new_task = Task(title=title, description=description, completed_at=completed_at) - response = { - "task": { - "id": new_task.id, - "title": new_task.title, - "description": new_task.description, - "is_complete": new_task.completed_at != None - } - } - return response, 201 + + @bp.get("") def get_all_task(): @@ -63,8 +61,6 @@ def get_all_task(): query = query.order_by(Task.id) task = db.session.scalars(query) - # We could also write the line above as: - # books = db.session.execute(query).scalars() tasks_response = [] for task in task: From 413cb82e50f092202b46dba64b7daa210d319f4e Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 4 Nov 2024 19:59:02 -0800 Subject: [PATCH 09/30] Implemented sort by title. --- app/routes/task_routes.py | 7 +++++++ tests/test_wave_02.py | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e1dcc7998..f594d50fb 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -59,6 +59,13 @@ def get_all_task(): if completed_at_param: query = query.where(Task.completed_at.ilike(f"%{completed_at_param}%")) + sort_param = request.args.get("sort") + if sort_param: + if sort_param == "asc": + query = query.order_by(Task.title.asc()) + elif sort_param == "desc": + query = query.order_by(Task.title.desc()) + query = query.order_by(Task.id) task = db.session.scalars(query) 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 41703108383c490ee939d54e07ebf3b575deec3b Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 4 Nov 2024 21:14:34 -0800 Subject: [PATCH 10/30] Implemented wave_03. --- app/routes/task_routes.py | 43 +++++++++++++++++++++++++++++++++++++++ tests/test_wave_03.py | 18 ++++++++-------- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index f594d50fb..baa7c1541 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -1,6 +1,7 @@ from flask import Blueprint, request, Response, make_response, abort from app.models.task import Task from ..db import db +from datetime import datetime bp = Blueprint("task_bp", __name__, url_prefix="/tasks" ) @@ -124,6 +125,48 @@ def update_task(task_id): return response, 200 +@bp.patch("//mark_complete") +def mark_complete(task_id): + task = validate_task(task_id) + + if task.completed_at == None: + task.completed_at = datetime.utcnow() + db.session.commit() + else: + pass + + response = { + "task": { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at != None + } + } + + return response, 200 + +@bp.patch("//mark_incomplete") +def mark_incomplete(task_id): + task = validate_task(task_id) + + if task.completed_at != None: + task.completed_at = None + db.session.commit() + else: + pass + + response = { + "task": { + "id": task.id, + "title": task.title, + "description": task.description, + "is_complete": task.completed_at != None + } + } + + return response, 200 + @bp.delete("/") def delete_task(task_id): task = validate_task(task_id) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 32d379822..07132ecf4 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 == {"message": "task 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_mark_incomplete_missing_task(client): # Act response = client.patch("/tasks/1/mark_incomplete") @@ -142,8 +143,9 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 + assert response_body == {"message": "task 1 not found"} - raise Exception("Complete test with assertion about response body") + # raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** # ***************************************************************** From 357c86baf34533efebb8ce02e35c77806826f6ea Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Tue, 5 Nov 2024 22:54:17 -0800 Subject: [PATCH 11/30] Created goal model, goal_routes, changed task_routes, update migration. --- app/__init__.py | 7 +- app/models/goal.py | 16 +++++ app/routes/goal_routes.py | 104 ++++++++++++++++++++++++++- app/routes/task_routes.py | 27 +------ migrations/versions/47175b038730_.py | 32 +++++++++ 5 files changed, 159 insertions(+), 27 deletions(-) create mode 100644 migrations/versions/47175b038730_.py diff --git a/app/__init__.py b/app/__init__.py index 8ba6ea6db..761aa1149 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,8 @@ from flask import Flask from .db import db, migrate from .models import task, goal -from .routes.task_routes import bp as task_bp +from .routes.task_routes import bp as tasks_bp +from .routes.goal_routes import bp as goals_bp import os def create_app(config=None): @@ -19,6 +20,8 @@ def create_app(config=None): migrate.init_app(app, db) # Register Blueprints here - app.register_blueprint(task_bp) + app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) + return app diff --git a/app/models/goal.py b/app/models/goal.py index 44282656b..de2cec551 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,3 +3,19 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) + title: Mapped[str] + + def to_dict(self): + return dict( + goal=dict( + id=self.id, + title=self.title + ) + ) + + # from JSON to model + @classmethod + def from_dict(cls, goal_data): + return cls( + title=task_data["title"] + ) \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 3aae38d49..9558098c1 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1 +1,103 @@ -from flask import Blueprint \ No newline at end of file +from flask import Blueprint, request, Response, make_response, abort +from app.models.goal import Goal +from ..db import db + +bp = Blueprint("goals_bp", __name__, url_prefix="/goals" ) + +@bp.post("") +def create_goal(): + request_body = request.get_json() + + try: + new_goal = Goal.from_dict(request_body) + + except KeyError as e: + response = { + "details": "Invalid data" + } + abort(make_response(response, 400)) + + db.session.add(new_goal) + db.session.commit() + + return new_goal.to_dict(), 201 + +@bp.get("") +def get_all_goal(): + query = db.select(Goal) + + title_param = request.args.get("title") + if title_param: + query = query.where(Goal.title.ilike(f"%{title_param}%")) + + sort_param = request.args.get("sort") + if sort_param: + if sort_param == "asc": + query = query.order_by(Goal.title.asc()) + elif sort_param == "desc": + query = query.order_by(Goal.title.desc()) + + query = query.order_by(Goal.id) + goals = db.session.scalars(query) + + goals_response = [] + for goal in goals: + goals_response.append( + { + "id": goal.id, + "title": goal.title + } + ) + + return goals_response + +@bp.get("/") +def get_one_goal(goal_id): + goal = validate_goal(goal_id) + + return goal.to_dict() + +def validate_goal(goal_id): + try: + goal_id = int(goal_id) + except: + response = {"details": "Invalid data"} + + abort(make_response(response , 400)) + + query = db.select(Goal).where(Goal.id == goal_id) + goal = db.session.scalar(query) + + if not goal: + response = {"message": f"task {goal_id} not found"} + abort(make_response(response, 404)) + + return goal + +@bp.put("/") +def update_goal(goal_id): + goal = validate_goal(goal_id) + request_body = request.get_json() + + goal.title = request_body["title"] + + db.session.commit() + + response = {} + response.append(goal.to_dict()) + + return response, 200 + +@bp.delete("/") +def delete_goal(goal_id): + goal = validate_goal(goal_id) + db.session.delete(goal) + db.session.commit() + + response = { + "details": f"Goal {goal_id} \"{goal.title}\" successfully deleted" + } + + return response, 200 + + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index baa7c1541..191a815db 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -3,7 +3,7 @@ from ..db import db from datetime import datetime -bp = Blueprint("task_bp", __name__, url_prefix="/tasks" ) +bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks" ) @bp.post("") def create_task(): @@ -23,27 +23,6 @@ def create_task(): return new_task.to_dict(), 201 - - # try: - # description = request_body["description"] - # except: - # response = { - # "details": "Invalid data" - # } - # return response, 400 - - - # try: - # completed_at = request_body["completed_at"] - # except: - # completed_at = None - - - # new_task = Task(title=title, description=description, completed_at=completed_at) - - - - @bp.get("") def get_all_task(): query = db.select(Task) @@ -68,10 +47,10 @@ def get_all_task(): query = query.order_by(Task.title.desc()) query = query.order_by(Task.id) - task = db.session.scalars(query) + tasks = db.session.scalars(query) tasks_response = [] - for task in task: + for task in tasks: tasks_response.append( { "id": task.id, diff --git a/migrations/versions/47175b038730_.py b/migrations/versions/47175b038730_.py new file mode 100644 index 000000000..92a213d51 --- /dev/null +++ b/migrations/versions/47175b038730_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: 47175b038730 +Revises: 466ce16ba2a2 +Create Date: 2024-11-05 22:04:50.222469 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '47175b038730' +down_revision = '466ce16ba2a2' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.add_column(sa.Column('title', sa.String(), nullable=False)) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('goal', schema=None) as batch_op: + batch_op.drop_column('title') + + # ### end Alembic commands ### From 8d495830b62f4b9ec88ed914348558248deee0f3 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 17:09:58 -0800 Subject: [PATCH 12/30] Added slack_bot --- app/routes/task_routes.py | 23 +++++++++++++++++++++++ requirements.txt | 1 + 2 files changed, 24 insertions(+) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 191a815db..4ad69a296 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,6 +2,10 @@ from app.models.task import Task from ..db import db from datetime import datetime +from slack_sdk.errors import SlackApiError +from slack_sdk import WebClient +import os + bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks" ) @@ -106,6 +110,25 @@ def update_task(task_id): @bp.patch("//mark_complete") def mark_complete(task_id): + + # ID of the channel you want to send the message to + channel_id = "api-test-channel" + client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) + + try: + # Call the chat.postMessage method using the WebClient + result = client.chat_postMessage( + channel=channel_id, + text="Hello world" + ) + # logger.info(result) + print(result) + + except SlackApiError as e: + # logger.error(f"Error posting message: {e}") + print(f"Error posting message: {e}") + + task = validate_task(task_id) if task.completed_at == None: diff --git a/requirements.txt b/requirements.txt index af8fc4cf4..c33605f22 100644 --- a/requirements.txt +++ b/requirements.txt @@ -20,6 +20,7 @@ psycopg2-binary==2.9.9 pytest==8.0.0 python-dotenv==1.0.1 requests==2.32.3 +slack_sdk==3.33.3 SQLAlchemy==2.0.25 typing_extensions==4.9.0 urllib3==2.2.3 From 72703ba1bf3f851abec898cab420bb9b374d0d95 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 18:42:59 -0800 Subject: [PATCH 13/30] Fixed goal and goal_routes --- app/models/goal.py | 2 +- app/routes/goal_routes.py | 8 ++++++-- app/routes/task_routes.py | 7 +++---- tests/test_wave_05.py | 2 +- 4 files changed, 11 insertions(+), 8 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index de2cec551..efd1b9d69 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -17,5 +17,5 @@ def to_dict(self): @classmethod def from_dict(cls, goal_data): return cls( - title=task_data["title"] + title=goal_data["title"] ) \ No newline at end of file diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 9558098c1..b77001fbf 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -83,8 +83,12 @@ def update_goal(goal_id): db.session.commit() - response = {} - response.append(goal.to_dict()) + response = { + "goal": { + "id": goal.id, + "title": goal.title + } + } return response, 200 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 4ad69a296..e19748102 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -110,8 +110,9 @@ def update_task(task_id): @bp.patch("//mark_complete") def mark_complete(task_id): + task = validate_task(task_id) - # ID of the channel you want to send the message to + # TODO move to a function channel_id = "api-test-channel" client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) @@ -119,7 +120,7 @@ def mark_complete(task_id): # Call the chat.postMessage method using the WebClient result = client.chat_postMessage( channel=channel_id, - text="Hello world" + text=f"Someone just completed the task \"{task.title}\"" ) # logger.info(result) print(result) @@ -129,8 +130,6 @@ def mark_complete(task_id): print(f"Error posting message: {e}") - task = validate_task(task_id) - if task.completed_at == None: task.completed_at = datetime.utcnow() db.session.commit() diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index aee7c52a1..8e451f908 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") From 12b26712a673534d749b9b6bfb2de5d0ff0e9562 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 19:01:29 -0800 Subject: [PATCH 14/30] Implemented test_wave_5 --- app/routes/goal_routes.py | 32 ++++++++++++++++---------------- app/routes/task_routes.py | 33 +++++++++++++++++---------------- tests/conftest.py | 2 ++ tests/test_wave_05.py | 13 +++++++------ 4 files changed, 42 insertions(+), 38 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index b77001fbf..da38a459d 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -57,22 +57,6 @@ def get_one_goal(goal_id): return goal.to_dict() -def validate_goal(goal_id): - try: - goal_id = int(goal_id) - except: - response = {"details": "Invalid data"} - - abort(make_response(response , 400)) - - query = db.select(Goal).where(Goal.id == goal_id) - goal = db.session.scalar(query) - - if not goal: - response = {"message": f"task {goal_id} not found"} - abort(make_response(response, 404)) - - return goal @bp.put("/") def update_goal(goal_id): @@ -104,4 +88,20 @@ def delete_goal(goal_id): return response, 200 +def validate_goal(goal_id): + try: + goal_id = int(goal_id) + except: + response = {"details": "Invalid data"} + + abort(make_response(response , 400)) + + query = db.select(Goal).where(Goal.id == goal_id) + goal = db.session.scalar(query) + + if not goal: + response = {"message": f"task {goal_id} not found"} + abort(make_response(response, 404)) + + return goal diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index e19748102..1c31a9162 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -71,22 +71,6 @@ def get_one_task(task_id): return task.to_dict() -def validate_task(task_id): - try: - task_id = int(task_id) - except: - response = {"details": "Invalid data"} - - abort(make_response(response , 400)) - - query = db.select(Task).where(Task.id == task_id) - task = db.session.scalar(query) - - if not task: - response = {"message": f"task {task_id} not found"} - abort(make_response(response, 404)) - - return task @bp.put("/") def update_task(task_id): @@ -180,6 +164,23 @@ def delete_task(task_id): return response, 200 +def validate_task(task_id): + try: + task_id = int(task_id) + except: + response = {"details": "Invalid data"} + + abort(make_response(response , 400)) + + query = db.select(Task).where(Task.id == task_id) + task = db.session.scalar(query) + + if not task: + response = {"message": f"task {task_id} not found"} + abort(make_response(response, 404)) + + return task + diff --git a/tests/conftest.py b/tests/conftest.py index e370e597b..5027fcc77 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,5 @@ import pytest +from flask import Flask from app import create_app from app.db import db from flask.signals import request_finished @@ -8,6 +9,7 @@ from app.models.goal import Goal from datetime import datetime + load_dotenv() @pytest.fixture diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 8e451f908..b92e25352 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -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,23 @@ 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 + assert response_body == {"message": f"task 1 not found"} # assertion 2 goes here # ---- 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={ From e2a4241a2a95f4ed049e22c07b487a5bac8def41 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 19:16:40 -0800 Subject: [PATCH 15/30] Completed tests wave_5 --- tests/test_wave_05.py | 45 +++++++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index b92e25352..1bc8dd9b6 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -81,34 +81,40 @@ 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": "Update Goal" + }) + 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": "Update 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_not_found(client): - raise Exception("Complete test") + # raise Exception("Complete test") # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Update Goal" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == {"message": f"task 1 not found"} -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_delete_goal(client, one_goal): # Act response = client.delete("/goals/1") @@ -124,8 +130,9 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 + assert response_body == {"details": 'Goal 1 "Build a habit of going outside daily" successfully deleted'} - 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*************** # ***************************************************************** @@ -145,7 +152,7 @@ def test_delete_goal_not_found(client): # ---- 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={}) From 7fcb7dc663b639ec5ece6d2acf843b0b42149f71 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 20:08:51 -0800 Subject: [PATCH 16/30] Created test wave_05 --- tests/test_wave_05.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 1bc8dd9b6..879154be5 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -57,7 +57,7 @@ def test_get_goal_not_found(client): # Assert # ---- Complete Test ---- assert response.status_code == 404 - assert response_body == {"message": f"task 1 not found"} + assert response_body == {"message": "task 1 not found"} # assertion 2 goes here # ---- Complete Test ---- @@ -138,18 +138,19 @@ def test_delete_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_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 == {"message": "task 1 not found"} + # @pytest.mark.skip(reason="No way to test this feature yet") From c775d41106a253e110974e40096156961e0c294b Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 6 Nov 2024 21:46:56 -0800 Subject: [PATCH 17/30] Created one-to-many relationship goal-task, upgrade migration --- app/__init__.py | 2 +- app/models/goal.py | 3 ++- app/models/task.py | 6 ++++- app/routes/task_routes.py | 32 +++++++++++++------------- migrations/versions/9e67f00c244c_.py | 34 ++++++++++++++++++++++++++++ tests/test_wave_06.py | 2 +- 6 files changed, 59 insertions(+), 20 deletions(-) create mode 100644 migrations/versions/9e67f00c244c_.py diff --git a/app/__init__.py b/app/__init__.py index 761aa1149..62cc533dc 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,6 +1,6 @@ from flask import Flask from .db import db, migrate -from .models import task, goal +from .models import goal, task from .routes.task_routes import bp as tasks_bp from .routes.goal_routes import bp as goals_bp import os diff --git a/app/models/goal.py b/app/models/goal.py index efd1b9d69..b5cf5e2d5 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -1,9 +1,10 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship from ..db import db class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] + task: Mapped[list["Task"]] = relationship(back_populates="goal") def to_dict(self): return dict( diff --git a/app/models/task.py b/app/models/task.py index 91cdc4c8d..273618290 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,4 +1,5 @@ -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy.orm import Mapped, mapped_column, relationship +from sqlalchemy import ForeignKey from ..db import db from datetime import datetime from typing import Optional @@ -8,6 +9,9 @@ class Task(db.Model): title: Mapped[str] description: Mapped[str] completed_at: Mapped[Optional[str]] + goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) + goal: Mapped[Optional["Goal"]] = relationship(back_populates="task") + # from model to JSON def to_dict(self): diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 1c31a9162..6c2859cd7 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -96,22 +96,22 @@ def update_task(task_id): def mark_complete(task_id): task = validate_task(task_id) - # TODO move to a function - channel_id = "api-test-channel" - client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - - try: - # Call the chat.postMessage method using the WebClient - result = client.chat_postMessage( - channel=channel_id, - text=f"Someone just completed the task \"{task.title}\"" - ) - # logger.info(result) - print(result) - - except SlackApiError as e: - # logger.error(f"Error posting message: {e}") - print(f"Error posting message: {e}") + # # TODO move to a function + # channel_id = "api-test-channel" + # client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) + + # try: + # # Call the chat.postMessage method using the WebClient + # result = client.chat_postMessage( + # channel=channel_id, + # text=f"Someone just completed the task \"{task.title}\"" + # ) + # # logger.info(result) + # print(result) + + # except SlackApiError as e: + # # logger.error(f"Error posting message: {e}") + # print(f"Error posting message: {e}") if task.completed_at == None: diff --git a/migrations/versions/9e67f00c244c_.py b/migrations/versions/9e67f00c244c_.py new file mode 100644 index 000000000..90fa0a924 --- /dev/null +++ b/migrations/versions/9e67f00c244c_.py @@ -0,0 +1,34 @@ +"""empty message + +Revision ID: 9e67f00c244c +Revises: 47175b038730 +Create Date: 2024-11-06 20:42:56.969646 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9e67f00c244c' +down_revision = '47175b038730' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) + batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('task', schema=None) as batch_op: + batch_op.drop_constraint(None, type_='foreignkey') + batch_op.drop_column('goal_id') + + # ### end Alembic commands ### diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 8afa4325e..566c52a39 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={ From 84ca5c488d23fe9a38916f19d06bd3416196679d Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Thu, 7 Nov 2024 16:07:44 -0800 Subject: [PATCH 18/30] Added parameter to send or not messages in Slack --- app/routes/task_routes.py | 34 ++++++++++++++++++---------------- tests/test_wave_06.py | 3 +-- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 6c2859cd7..d31cf4dc3 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -96,22 +96,24 @@ def update_task(task_id): def mark_complete(task_id): task = validate_task(task_id) - # # TODO move to a function - # channel_id = "api-test-channel" - # client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - - # try: - # # Call the chat.postMessage method using the WebClient - # result = client.chat_postMessage( - # channel=channel_id, - # text=f"Someone just completed the task \"{task.title}\"" - # ) - # # logger.info(result) - # print(result) - - # except SlackApiError as e: - # # logger.error(f"Error posting message: {e}") - # print(f"Error posting message: {e}") + + if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": + # TODO move to a function + channel_id = "api-test-channel" + client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) + + try: + # Call the chat.postMessage method using the WebClient + result = client.chat_postMessage( + channel=channel_id, + text=f"Someone just completed the task \"{task.title}\"" + ) + # logger.info(result) + print(result) + + except SlackApiError as e: + # logger.error(f"Error posting message: {e}") + print(f"Error posting message: {e}") if task.completed_at == None: diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 566c52a39..607dbedbb 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -1,8 +1,7 @@ from app.models.goal import Goal import pytest - -# @pytest.mark.skip(reason="No way to test this feature yet") +@pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ From d0427083d6960b5ae6c256a2370365ff2aa88a07 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Thu, 7 Nov 2024 17:00:58 -0800 Subject: [PATCH 19/30] Changed models task and goal, goals_routes.pu, task_routes.py --- app/models/goal.py | 3 ++- app/models/task.py | 2 +- app/routes/goal_routes.py | 24 +++++++++++++++++++++++- app/routes/task_routes.py | 3 +-- tests/test_wave_06.py | 4 ++-- 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/app/models/goal.py b/app/models/goal.py index b5cf5e2d5..49d37e535 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,7 +4,8 @@ class Goal(db.Model): id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) title: Mapped[str] - task: Mapped[list["Task"]] = relationship(back_populates="goal") + tasks: Mapped[list["Task"]] = relationship(back_populates="goal") + def to_dict(self): return dict( diff --git a/app/models/task.py b/app/models/task.py index 273618290..8b9d73992 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -10,7 +10,7 @@ class Task(db.Model): description: Mapped[str] completed_at: Mapped[Optional[str]] goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id")) - goal: Mapped[Optional["Goal"]] = relationship(back_populates="task") + goal: Mapped[Optional["Goal"]] = relationship(back_populates="tasks") # from model to JSON diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index da38a459d..5f1e33ec3 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -1,6 +1,8 @@ from flask import Blueprint, request, Response, make_response, abort from app.models.goal import Goal from ..db import db +from ..models.task import Task +from ..routes.task_routes import validate_task bp = Blueprint("goals_bp", __name__, url_prefix="/goals" ) @@ -23,7 +25,7 @@ def create_goal(): return new_goal.to_dict(), 201 @bp.get("") -def get_all_goal(): +def get_all_goals(): query = db.select(Goal) title_param = request.args.get("title") @@ -105,3 +107,23 @@ def validate_goal(goal_id): return goal +@bp.post("//tasks") +def assign_tasks_to_goal(goal_id): + goal = validate_goal(goal_id) + + request_body = request.get_json() + task_ids = request_body["task_ids"] + + for task_id in task_ids: + task = validate_task(task_id) + task.goal_id = goal_id + db.session.add(task) + db.session.commit() + + response = { + "id": int(goal_id), + "task_ids": task_ids + } + + return response, 200 + diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index d31cf4dc3..78b60d812 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -28,7 +28,7 @@ def create_task(): return new_task.to_dict(), 201 @bp.get("") -def get_all_task(): +def get_all_tasks(): query = db.select(Task) title_param = request.args.get("title") @@ -96,7 +96,6 @@ def update_task(task_id): def mark_complete(task_id): task = validate_task(task_id) - if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": # TODO move to a function channel_id = "api-test-channel" diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 607dbedbb..71ac46d57 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -1,7 +1,7 @@ from app.models.goal import Goal import pytest -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_post_task_ids_to_goal(client, one_goal, three_tasks): # Act response = client.post("/goals/1/tasks", json={ @@ -22,7 +22,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={ From 87586e03dcff5a69027e896d841e13273afbfe04 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Thu, 7 Nov 2024 20:18:37 -0800 Subject: [PATCH 20/30] Created test wave_04 --- tests/test_wave_03.py | 4 ++-- tests/test_wave_04.py | 34 ++++++++++++++++++++++++++++++++++ tests/test_wave_06.py | 4 ++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 07132ecf4..b8759bc62 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -80,8 +80,8 @@ def test_mark_complete_on_completed_task(client, completed_task): with patch("requests.post") as mock_get: mock_get.return_value.status_code = 200 - # Act - response = client.patch("/tasks/1/mark_complete") + # Act + response = client.patch("/tasks/1/mark_complete") response_body = response.get_json() # Assert diff --git a/tests/test_wave_04.py b/tests/test_wave_04.py index d0b26b2d1..511d4d9f9 100644 --- a/tests/test_wave_04.py +++ b/tests/test_wave_04.py @@ -1 +1,35 @@ +from app.models.task import Task +import os + # There are no tests for wave 4. + +def test_massage_in_slack_on_completed_task(client, completed_task): +# Act + response = client.patch("/tasks/1/mark_complete") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert "task" in response_body + assert response_body["task"]["is_complete"] == True + assert response_body == { + "task": { + "id": 1, + "title": "Go on my daily walk 🏞", + "description": "Notice something new every day", + "is_complete": True + } + } + assert Task.query.get(1).completed_at + +def test_mark_complete_sends_slack_notification(client, completed_task): + os.environ["SEND_SLACK_NOTIFICATIONS"] = "True" + + + # Act + response = client.patch(f"/tasks/1/mark_complete") + response_body = response.get_json() + + # Assert + assert response.status_code == 200 + assert response_body["task"]["is_complete"] == True \ No newline at end of file diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 71ac46d57..af1dd8002 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -50,6 +50,10 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 + assert response_body == { + + } + raise Exception("Complete test with assertion about response body") # ***************************************************************** # **Complete test with assertion about response body*************** From f6eff4903657191c4788aee81d5e95c7823e1109 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Thu, 7 Nov 2024 21:27:04 -0800 Subject: [PATCH 21/30] Improved test wave_04 --- tests/test_wave_04.py | 20 +++++++------------- tests/test_wave_06.py | 4 ++-- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/tests/test_wave_04.py b/tests/test_wave_04.py index 511d4d9f9..6e39cdf7c 100644 --- a/tests/test_wave_04.py +++ b/tests/test_wave_04.py @@ -4,13 +4,14 @@ # There are no tests for wave 4. def test_massage_in_slack_on_completed_task(client, completed_task): -# Act - response = client.patch("/tasks/1/mark_complete") + os.environ["SEND_SLACK_NOTIFICATIONS"] = "True" + + # Act + response = client.patch(f"/tasks/1/mark_complete") response_body = response.get_json() # Assert assert response.status_code == 200 - assert "task" in response_body assert response_body["task"]["is_complete"] == True assert response_body == { "task": { @@ -22,14 +23,7 @@ def test_massage_in_slack_on_completed_task(client, completed_task): } assert Task.query.get(1).completed_at -def test_mark_complete_sends_slack_notification(client, completed_task): - os.environ["SEND_SLACK_NOTIFICATIONS"] = "True" - - - # Act - response = client.patch(f"/tasks/1/mark_complete") - response_body = response.get_json() + # TODO somehow check that the message was posted in Slack channel. + # I haven't found Slack API method for that - # Assert - assert response.status_code == 200 - assert response_body["task"]["is_complete"] == True \ No newline at end of file + os.environ["SEND_SLACK_NOTIFICATIONS"] = "False" diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index af1dd8002..acd1ffe3f 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -44,7 +44,7 @@ def test_post_task_ids_to_goal_already_with_goals(client, one_task_belongs_to_on @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_goal(client): # Act - response = client.get("/goals/1/tasks") + response = client.get("/goals/100/tasks") response_body = response.get_json() # Assert @@ -54,7 +54,7 @@ def test_get_tasks_for_specific_goal_no_goal(client): } - 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*************** # ***************************************************************** From a61d5c7aa998e0df3b52e768a8a4c067dfe22dda Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Thu, 7 Nov 2024 23:20:28 -0800 Subject: [PATCH 22/30] Added goal_id to task to_dict --- app/models/task.py | 3 ++- app/routes/goal_routes.py | 26 +++++++++++++++++++++++++ tests/test_wave_01.py | 6 ++++-- tests/test_wave_04.py | 40 +++++++++++++++++++-------------------- tests/test_wave_06.py | 2 +- 5 files changed, 53 insertions(+), 24 deletions(-) diff --git a/app/models/task.py b/app/models/task.py index 8b9d73992..e89c14fd8 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -20,7 +20,8 @@ def to_dict(self): id=self.id, title=self.title, description=self.description, - is_complete=self.completed_at!=None + is_complete=self.completed_at!=None, + goal_id=self.goal_id ) ) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 5f1e33ec3..1f021982d 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -127,3 +127,29 @@ def assign_tasks_to_goal(goal_id): return response, 200 +# @bp.get("//tasks") +# def get_goal_with_assigned_tasks(goal_id): +# goal = validate_goal(goal_id) + +# tasks_param = request.args.get("tasks_id") +# if task_param: +# query = db.select(Goal).order_by(Task.id) + +# goals = db.session.scalars(query) + +# goals_response = [] +# for goal in goals: +# goals_response.append( +# response_body == { +# "id": 1, +# "title": "Build a habit of going outside daily", +# "tasks": [{ +# "id": task.id, +# "title": task.title, +# "description": task.description, +# "is_complete": task.completed_at != None +# }] +# } +# ) + +# return goals_response diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 81b0f170d..0d5b96ee6 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -46,7 +46,8 @@ def test_get_task(client, one_task): "id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False + "is_complete": False, + "goal_id": None } } @@ -87,7 +88,8 @@ def test_create_task(client): "id": 1, "title": "A Brand New Task", "description": "Test Description", - "is_complete": False + "is_complete": False, + "goal_id": None } } new_task = Task.query.get(1) diff --git a/tests/test_wave_04.py b/tests/test_wave_04.py index 6e39cdf7c..47e3d6785 100644 --- a/tests/test_wave_04.py +++ b/tests/test_wave_04.py @@ -3,27 +3,27 @@ # There are no tests for wave 4. -def test_massage_in_slack_on_completed_task(client, completed_task): - os.environ["SEND_SLACK_NOTIFICATIONS"] = "True" +# def test_massage_in_slack_on_completed_task(client, completed_task): +# os.environ["SEND_SLACK_NOTIFICATIONS"] = "True" - # Act - response = client.patch(f"/tasks/1/mark_complete") - response_body = response.get_json() +# # Act +# response = client.patch(f"/tasks/1/mark_complete") +# response_body = response.get_json() - # Assert - assert response.status_code == 200 - assert response_body["task"]["is_complete"] == True - assert response_body == { - "task": { - "id": 1, - "title": "Go on my daily walk 🏞", - "description": "Notice something new every day", - "is_complete": True - } - } - assert Task.query.get(1).completed_at +# # Assert +# assert response.status_code == 200 +# assert response_body["task"]["is_complete"] == True +# assert response_body == { +# "task": { +# "id": 1, +# "title": "Go on my daily walk 🏞", +# "description": "Notice something new every day", +# "is_complete": True +# } +# } +# assert Task.query.get(1).completed_at - # TODO somehow check that the message was posted in Slack channel. - # I haven't found Slack API method for that +# # TODO somehow check that the message was posted in Slack channel. +# # I haven't found Slack API method for that - os.environ["SEND_SLACK_NOTIFICATIONS"] = "False" +# os.environ["SEND_SLACK_NOTIFICATIONS"] = "False" diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index acd1ffe3f..49bd770f7 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -102,7 +102,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() From 19de49624a2196b2e33472bf495a719e7f9a112e Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Fri, 8 Nov 2024 00:12:17 -0800 Subject: [PATCH 23/30] Implemented get all task of a goal --- app/routes/goal_routes.py | 52 +++++++++++++++++++-------------------- tests/test_wave_06.py | 12 ++++----- 2 files changed, 31 insertions(+), 33 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 1f021982d..6646b191b 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -127,29 +127,29 @@ def assign_tasks_to_goal(goal_id): return response, 200 -# @bp.get("//tasks") -# def get_goal_with_assigned_tasks(goal_id): -# goal = validate_goal(goal_id) - -# tasks_param = request.args.get("tasks_id") -# if task_param: -# query = db.select(Goal).order_by(Task.id) - -# goals = db.session.scalars(query) - -# goals_response = [] -# for goal in goals: -# goals_response.append( -# response_body == { -# "id": 1, -# "title": "Build a habit of going outside daily", -# "tasks": [{ -# "id": task.id, -# "title": task.title, -# "description": task.description, -# "is_complete": task.completed_at != None -# }] -# } -# ) - -# return goals_response +@bp.get("//tasks") +def get_goal_with_assigned_tasks(goal_id): + goal = validate_goal(goal_id) + + query = db.select(Task).where(Goal.id == goal_id) + + tasks = db.session.scalars(query) + + response = {} + response["id"] = goal.id + response["title"] = goal.title + response["tasks"] = [] + + for task in tasks: + + task_dict = dict( + id=task.id, + title=task.title, + description=task.description, + is_complete=task.completed_at!=None, + goal_id=task.goal_id + ) + + response["tasks"].append(task_dict) + + return response, 200 diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 49bd770f7..82acc27eb 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -41,18 +41,16 @@ 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/100/tasks") + response = client.get("/goals/1/tasks") response_body = response.get_json() # Assert assert response.status_code == 404 - assert response_body == { - - } + assert response_body == {"message": "task 1 not found"} # raise Exception("Complete test with assertion about response body") # ***************************************************************** @@ -60,7 +58,7 @@ def test_get_tasks_for_specific_goal_no_goal(client): # ***************************************************************** -@pytest.mark.skip(reason="No way to test this feature yet") +# @pytest.mark.skip(reason="No way to test this feature yet") def test_get_tasks_for_specific_goal_no_tasks(client, one_goal): # Act response = client.get("/goals/1/tasks") @@ -77,7 +75,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") From c92f8fae37f998a13e37d642d16fae4432af24c6 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Fri, 8 Nov 2024 00:32:25 -0800 Subject: [PATCH 24/30] Fixed some typos --- ada-project-docs/wave_01.md | 4 ++-- ada-project-docs/wave_02.md | 2 +- ada-project-docs/wave_05.md | 2 +- ada-project-docs/wave_06.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ada-project-docs/wave_01.md b/ada-project-docs/wave_01.md index 30be86ad8..98c4e532e 100644 --- a/ada-project-docs/wave_01.md +++ b/ada-project-docs/wave_01.md @@ -40,8 +40,8 @@ Tasks should contain these attributes. **The tests require the following columns ### Tips -- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any mispellings. - - That said, remember that dictionaries do not have an implied order. This is still true in JSON with objects. When you make Postman requests, the order of the key/value pairings within the response JSON object does not need to match the order specified in this document. (The term "object" in JSON is analagous to "dictionary" in Python.) +- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any misspellings. + - That said, remember that dictionaries do not have an implied order. This is still true in JSON with objects. When you make Postman requests, the order of the key/value pairings within the response JSON object does not need to match the order specified in this document. (The term "object" in JSON is analogous to "dictionary" in Python.) - Use the tests in `tests/test_wave_01.py` to guide your implementation. - You may feel that there are missing tests and missing edge cases considered in this wave. This is intentional. - You have fulfilled wave 1 requirements if all of the wave 1 tests pass. diff --git a/ada-project-docs/wave_02.md b/ada-project-docs/wave_02.md index acc1dc0a4..1f3560e3c 100644 --- a/ada-project-docs/wave_02.md +++ b/ada-project-docs/wave_02.md @@ -10,7 +10,7 @@ The following are required routes for wave 2. Feel free to implement the routes ### Tips -- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any mispellings. +- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any misspellings. - Use the tests in `tests/test_wave_02.py` to guide your implementation. - You may feel that there are missing tests and missing edge cases considered in this wave. This is intentional. - You have fulfilled wave 2 requirements if all of the wave 2 tests pass. diff --git a/ada-project-docs/wave_05.md b/ada-project-docs/wave_05.md index bb601b0b5..70272f7ff 100644 --- a/ada-project-docs/wave_05.md +++ b/ada-project-docs/wave_05.md @@ -17,7 +17,7 @@ This wave requires more test writing. - The tests you need to write are scaffolded in the `test_wave_05.py` file. - These tests are currently skipped with `@pytest.mark.skip(reason="test to be completed by student")` and the function body has `pass` in it. Once you implement these tests you should remove the `skip` decorator and the `pass`. - For the tests you write, use the requirements in this document to guide your test writing. - - Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any mispellings. + - Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any misspellings. - You can model your tests off of the Wave 1 tests for Tasks. - Some tests use a [fixture](https://docs.pytest.org/en/6.2.x/fixture.html) named `one_goal` that is defined in `tests/conftest.py`. This fixture saves a specific goal to the test database. diff --git a/ada-project-docs/wave_06.md b/ada-project-docs/wave_06.md index 699738ba8..349805a69 100644 --- a/ada-project-docs/wave_06.md +++ b/ada-project-docs/wave_06.md @@ -18,7 +18,7 @@ Secondly, we should create our new route, `/goals//tasks`, so that our - Use lesson materials and independent research to review how to set up a one-to-many relationship in Flask. - Remember to run `flask db migrate` and `flask db upgrade` whenever there is a change to the model. -- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any mispellings. +- Pay attention to the exact shape of the expected JSON. Double-check nested data structures and the names of the keys for any misspellings. - Use the tests in `tests/test_wave_06.py` to guide your implementation. - Some tests use a fixture named `one_task_belongs_to_one_goal` that is defined in `tests/conftest.py`. This fixture saves a task and a goal to the test database, and uses SQLAlchemy to associate the goal and task together. From de5737597854fc7e549daccd0a7a92e38a6791db Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 17 Nov 2024 16:27:08 -0800 Subject: [PATCH 25/30] changed facts --- app/routes/task_routes.py | 71 ++++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 78b60d812..53a001102 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,9 +2,10 @@ from app.models.task import Task from ..db import db from datetime import datetime -from slack_sdk.errors import SlackApiError -from slack_sdk import WebClient +# from slack_sdk.errors import SlackApiError +# from slack_sdk import WebClient import os +import requests bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks" ) @@ -92,27 +93,64 @@ def update_task(task_id): return response, 200 +# @bp.patch("//mark_complete") +# def mark_complete(task_id): +# task = validate_task(task_id) + +# if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": +# # TODO move to a function +# channel_id = "api-test-channel" +# client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) + +# try: +# # Call the chat.postMessage method using the WebClient +# result = client.chat_postMessage( +# channel=channel_id, +# text=f"Someone just completed the task \"{task.title}\"" +# ) +# # logger.info(result) +# print(result) + +# except SlackApiError as e: +# # logger.error(f"Error posting message: {e}") +# print(f"Error posting message: {e}") + + +# if task.completed_at == None: +# task.completed_at = datetime.utcnow() +# db.session.commit() +# else: +# pass + +# response = { +# "task": { +# "id": task.id, +# "title": task.title, +# "description": task.description, +# "is_complete": task.completed_at != None +# } +# } + +# return response, 200 + @bp.patch("//mark_complete") def mark_complete(task_id): task = validate_task(task_id) if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": - # TODO move to a function - channel_id = "api-test-channel" - client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - try: - # Call the chat.postMessage method using the WebClient - result = client.chat_postMessage( - channel=channel_id, - text=f"Someone just completed the task \"{task.title}\"" - ) - # logger.info(result) - print(result) + url = 'https://slack.com/api/im.open' + # headers = {'content-type': 'x-www-form-urlencoded'} + data = [ + ('token', os.environ.get('SLACK_WEB_CLIENT_TOKEN')), + ('channel', "api-test-channel"), + # ('include_locale', 'true'), + # ('return_im', 'true'), + ('text', f"Someone just completed the task \"{task.title}\"") + ] - except SlackApiError as e: - # logger.error(f"Error posting message: {e}") - print(f"Error posting message: {e}") + r = requests.post(url, data, **headers) + print(r.text) if task.completed_at == None: @@ -132,6 +170,7 @@ def mark_complete(task_id): return response, 200 + @bp.patch("//mark_incomplete") def mark_incomplete(task_id): task = validate_task(task_id) From b815c8ef5df257627c764f2278c01a717fa63a2f Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 18 Nov 2024 12:46:06 -0800 Subject: [PATCH 26/30] Rolled back to slack_sdk usage --- app/routes/task_routes.py | 71 +++++++++------------------------------ 1 file changed, 16 insertions(+), 55 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 53a001102..78b60d812 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,10 +2,9 @@ from app.models.task import Task from ..db import db from datetime import datetime -# from slack_sdk.errors import SlackApiError -# from slack_sdk import WebClient +from slack_sdk.errors import SlackApiError +from slack_sdk import WebClient import os -import requests bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks" ) @@ -93,64 +92,27 @@ def update_task(task_id): return response, 200 -# @bp.patch("//mark_complete") -# def mark_complete(task_id): -# task = validate_task(task_id) - -# if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": -# # TODO move to a function -# channel_id = "api-test-channel" -# client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - -# try: -# # Call the chat.postMessage method using the WebClient -# result = client.chat_postMessage( -# channel=channel_id, -# text=f"Someone just completed the task \"{task.title}\"" -# ) -# # logger.info(result) -# print(result) - -# except SlackApiError as e: -# # logger.error(f"Error posting message: {e}") -# print(f"Error posting message: {e}") - - -# if task.completed_at == None: -# task.completed_at = datetime.utcnow() -# db.session.commit() -# else: -# pass - -# response = { -# "task": { -# "id": task.id, -# "title": task.title, -# "description": task.description, -# "is_complete": task.completed_at != None -# } -# } - -# return response, 200 - @bp.patch("//mark_complete") def mark_complete(task_id): task = validate_task(task_id) if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": + # TODO move to a function + channel_id = "api-test-channel" + client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - url = 'https://slack.com/api/im.open' - # headers = {'content-type': 'x-www-form-urlencoded'} - data = [ - ('token', os.environ.get('SLACK_WEB_CLIENT_TOKEN')), - ('channel', "api-test-channel"), - # ('include_locale', 'true'), - # ('return_im', 'true'), - ('text', f"Someone just completed the task \"{task.title}\"") - ] + try: + # Call the chat.postMessage method using the WebClient + result = client.chat_postMessage( + channel=channel_id, + text=f"Someone just completed the task \"{task.title}\"" + ) + # logger.info(result) + print(result) - r = requests.post(url, data, **headers) - print(r.text) + except SlackApiError as e: + # logger.error(f"Error posting message: {e}") + print(f"Error posting message: {e}") if task.completed_at == None: @@ -170,7 +132,6 @@ def mark_complete(task_id): return response, 200 - @bp.patch("//mark_incomplete") def mark_incomplete(task_id): task = validate_task(task_id) From 7ec9c0f500fc573b9221ca4791a5d8f04cafdb47 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Mon, 18 Nov 2024 18:33:25 -0800 Subject: [PATCH 27/30] Changed send messages in Slack implementation. --- app/routes/task_routes.py | 53 ++++++++++++++++----------------------- 1 file changed, 22 insertions(+), 31 deletions(-) diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 78b60d812..8ed3549d2 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -2,9 +2,9 @@ from app.models.task import Task from ..db import db from datetime import datetime -from slack_sdk.errors import SlackApiError -from slack_sdk import WebClient import os +import requests +from os import environ bp = Blueprint("tasks_bp", __name__, url_prefix="/tasks" ) @@ -96,30 +96,11 @@ def update_task(task_id): def mark_complete(task_id): task = validate_task(task_id) + task.completed_at = datetime.utcnow() + db.session.commit() + if os.environ.get('SEND_SLACK_NOTIFICATIONS') == "True": - # TODO move to a function - channel_id = "api-test-channel" - client = WebClient(token=os.environ.get('SLACK_WEB_CLIENT_TOKEN')) - - try: - # Call the chat.postMessage method using the WebClient - result = client.chat_postMessage( - channel=channel_id, - text=f"Someone just completed the task \"{task.title}\"" - ) - # logger.info(result) - print(result) - - except SlackApiError as e: - # logger.error(f"Error posting message: {e}") - print(f"Error posting message: {e}") - - - if task.completed_at == None: - task.completed_at = datetime.utcnow() - db.session.commit() - else: - pass + send_slack_notification(task.title) response = { "task": { @@ -132,6 +113,22 @@ def mark_complete(task_id): return response, 200 +def send_slack_notification(task_title): + request_data = { + "channel": "#api-test-channel", + "username": "LD bot", + "text": f"Someone just completed the task \"{task_title}\"" + } + + response = requests.post( + url="https://slack.com/api/chat.postMessage", + json=request_data, + headers={"Authorization": f"Bearer {environ.get('SLACK_WEB_CLIENT_TOKEN')}"}, + timeout=5 + ) + response.raise_for_status() + return response.json().get("ok", False) + @bp.patch("//mark_incomplete") def mark_incomplete(task_id): task = validate_task(task_id) @@ -181,9 +178,3 @@ def validate_task(task_id): abort(make_response(response, 404)) return task - - - - - - From 472b7a2cf422516c1f4a94218d22a3280e9ecb54 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Wed, 18 Dec 2024 23:06:22 -0800 Subject: [PATCH 28/30] Restored initial tests, fixed some issues discovered on code review --- app/models/task.py | 24 ++++++----- app/routes/goal_routes.py | 15 ++----- app/routes/task_routes.py | 40 ++++--------------- migrations/versions/47175b038730_.py | 32 --------------- ...69065042fcfc_recreate_model_migrations.py} | 9 +++-- migrations/versions/9e67f00c244c_.py | 34 ---------------- tests/test_wave_01.py | 6 +-- tests/test_wave_03.py | 4 +- 8 files changed, 36 insertions(+), 128 deletions(-) delete mode 100644 migrations/versions/47175b038730_.py rename migrations/versions/{466ce16ba2a2_recreate_model_migrations.py => 69065042fcfc_recreate_model_migrations.py} (78%) delete mode 100644 migrations/versions/9e67f00c244c_.py diff --git a/app/models/task.py b/app/models/task.py index e89c14fd8..3281889a3 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -15,15 +15,21 @@ class Task(db.Model): # from model to JSON def to_dict(self): - return dict( - task=dict( - id=self.id, - title=self.title, - description=self.description, - is_complete=self.completed_at!=None, - goal_id=self.goal_id - ) - ) + if self.goal_id is None: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.completed_at!=None + ) + else: + return dict( + id=self.id, + title=self.title, + description=self.description, + is_complete=self.completed_at!=None, + goal_id=self.goal_id + ) # from JSON to model @classmethod diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index 6646b191b..c276c9448 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -118,7 +118,8 @@ def assign_tasks_to_goal(goal_id): task = validate_task(task_id) task.goal_id = goal_id db.session.add(task) - db.session.commit() + + db.session.commit() response = { "id": int(goal_id), @@ -140,16 +141,6 @@ def get_goal_with_assigned_tasks(goal_id): response["title"] = goal.title response["tasks"] = [] - for task in tasks: - - task_dict = dict( - id=task.id, - title=task.title, - description=task.description, - is_complete=task.completed_at!=None, - goal_id=task.goal_id - ) - - response["tasks"].append(task_dict) + response["tasks"] = [task.to_dict() for task in tasks] return response, 200 diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 8ed3549d2..8f495ae91 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -25,7 +25,7 @@ def create_task(): db.session.add(new_task) db.session.commit() - return new_task.to_dict(), 201 + return {"task": new_task.to_dict()}, 201 @bp.get("") def get_all_tasks(): @@ -52,24 +52,15 @@ def get_all_tasks(): query = query.order_by(Task.id) tasks = db.session.scalars(query) - - tasks_response = [] - for task in tasks: - tasks_response.append( - { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at != None - } - ) - return tasks_response + + response = [task.to_dict() for task in tasks] + return response, 200 @bp.get("/") def get_one_task(task_id): task = validate_task(task_id) - return task.to_dict() + return {"task": task.to_dict()} @bp.put("/") @@ -82,12 +73,7 @@ def update_task(task_id): db.session.commit() response = { - "task": { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at != None - } + "task": task.to_dict() } return response, 200 @@ -103,12 +89,7 @@ def mark_complete(task_id): send_slack_notification(task.title) response = { - "task": { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at != None - } + "task": task.to_dict() } return response, 200 @@ -140,12 +121,7 @@ def mark_incomplete(task_id): pass response = { - "task": { - "id": task.id, - "title": task.title, - "description": task.description, - "is_complete": task.completed_at != None - } + "task": task.to_dict() } return response, 200 diff --git a/migrations/versions/47175b038730_.py b/migrations/versions/47175b038730_.py deleted file mode 100644 index 92a213d51..000000000 --- a/migrations/versions/47175b038730_.py +++ /dev/null @@ -1,32 +0,0 @@ -"""empty message - -Revision ID: 47175b038730 -Revises: 466ce16ba2a2 -Create Date: 2024-11-05 22:04:50.222469 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '47175b038730' -down_revision = '466ce16ba2a2' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('goal', schema=None) as batch_op: - batch_op.add_column(sa.Column('title', sa.String(), nullable=False)) - - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('goal', schema=None) as batch_op: - batch_op.drop_column('title') - - # ### end Alembic commands ### diff --git a/migrations/versions/466ce16ba2a2_recreate_model_migrations.py b/migrations/versions/69065042fcfc_recreate_model_migrations.py similarity index 78% rename from migrations/versions/466ce16ba2a2_recreate_model_migrations.py rename to migrations/versions/69065042fcfc_recreate_model_migrations.py index 650526161..98bb033f0 100644 --- a/migrations/versions/466ce16ba2a2_recreate_model_migrations.py +++ b/migrations/versions/69065042fcfc_recreate_model_migrations.py @@ -1,8 +1,8 @@ """Recreate model migrations -Revision ID: 466ce16ba2a2 +Revision ID: 69065042fcfc Revises: -Create Date: 2024-11-03 14:27:30.106262 +Create Date: 2024-12-16 19:08:24.669263 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '466ce16ba2a2' +revision = '69065042fcfc' down_revision = None branch_labels = None depends_on = None @@ -20,6 +20,7 @@ def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('goal', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_table('task', @@ -27,6 +28,8 @@ def upgrade(): sa.Column('title', sa.String(), nullable=False), sa.Column('description', sa.String(), nullable=False), sa.Column('completed_at', sa.String(), 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/9e67f00c244c_.py b/migrations/versions/9e67f00c244c_.py deleted file mode 100644 index 90fa0a924..000000000 --- a/migrations/versions/9e67f00c244c_.py +++ /dev/null @@ -1,34 +0,0 @@ -"""empty message - -Revision ID: 9e67f00c244c -Revises: 47175b038730 -Create Date: 2024-11-06 20:42:56.969646 - -""" -from alembic import op -import sqlalchemy as sa - - -# revision identifiers, used by Alembic. -revision = '9e67f00c244c' -down_revision = '47175b038730' -branch_labels = None -depends_on = None - - -def upgrade(): - # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('task', schema=None) as batch_op: - batch_op.add_column(sa.Column('goal_id', sa.Integer(), nullable=True)) - batch_op.create_foreign_key(None, 'goal', ['goal_id'], ['id']) - - # ### end Alembic commands ### - - -def downgrade(): - # ### commands auto generated by Alembic - please adjust! ### - with op.batch_alter_table('task', schema=None) as batch_op: - batch_op.drop_constraint(None, type_='foreignkey') - batch_op.drop_column('goal_id') - - # ### end Alembic commands ### diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 0d5b96ee6..81b0f170d 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -46,8 +46,7 @@ def test_get_task(client, one_task): "id": 1, "title": "Go on my daily walk 🏞", "description": "Notice something new every day", - "is_complete": False, - "goal_id": None + "is_complete": False } } @@ -88,8 +87,7 @@ def test_create_task(client): "id": 1, "title": "A Brand New Task", "description": "Test Description", - "is_complete": False, - "goal_id": None + "is_complete": False } } new_task = Task.query.get(1) diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index b8759bc62..07132ecf4 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -80,8 +80,8 @@ def test_mark_complete_on_completed_task(client, completed_task): with patch("requests.post") as mock_get: mock_get.return_value.status_code = 200 - # Act - response = client.patch("/tasks/1/mark_complete") + # Act + response = client.patch("/tasks/1/mark_complete") response_body = response.get_json() # Assert From 92bb214515edf25606df9e7ef30018eda9bb9901 Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Fri, 27 Dec 2024 20:24:44 -0800 Subject: [PATCH 29/30] Changed migration, added Cors --- README.md | 11 +++++++++++ app/__init__.py | 4 ++++ app/routes/task_routes.py | 1 + ...s.py => 91d41aaf0216_recreate_model_migrations.py} | 6 +++--- 4 files changed, 19 insertions(+), 3 deletions(-) rename migrations/versions/{69065042fcfc_recreate_model_migrations.py => 91d41aaf0216_recreate_model_migrations.py} (92%) diff --git a/README.md b/README.md index 85e1c0f69..481217c98 100644 --- a/README.md +++ b/README.md @@ -55,3 +55,14 @@ This project is designed to fulfill the features described in detail in each wav 1. [Wave 6: Establishing a one-to-many relationship between two models](ada-project-docs/wave_06.md) 1. [Wave 7: Deployment](ada-project-docs/wave_07.md) 1. [Optional Enhancements](ada-project-docs/optional-enhancements.md) + +psql -U postgres postgres +drop database task_list_api_development; +create database task_list_api_development; +drop database task_list_api_test; +create database task_list_api_test; +\q +rm -rf migrations +flask db init +flask db migrate -m "Recreate model migrations" +flask db upgrade diff --git a/app/__init__.py b/app/__init__.py index 62cc533dc..f020f1309 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -4,10 +4,14 @@ from .routes.task_routes import bp as tasks_bp from .routes.goal_routes import bp as goals_bp import os +from flask_cors import CORS def create_app(config=None): app = Flask(__name__) + CORS(app) + app.config['CORS_HEADERS'] = 'Content-Type' + app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI') diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 8f495ae91..61ca6cd9b 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -17,6 +17,7 @@ def create_task(): new_task = Task.from_dict(request_body) except KeyError as e: + print(e) response = { "details": "Invalid data" } diff --git a/migrations/versions/69065042fcfc_recreate_model_migrations.py b/migrations/versions/91d41aaf0216_recreate_model_migrations.py similarity index 92% rename from migrations/versions/69065042fcfc_recreate_model_migrations.py rename to migrations/versions/91d41aaf0216_recreate_model_migrations.py index 98bb033f0..23bb27cbd 100644 --- a/migrations/versions/69065042fcfc_recreate_model_migrations.py +++ b/migrations/versions/91d41aaf0216_recreate_model_migrations.py @@ -1,8 +1,8 @@ """Recreate model migrations -Revision ID: 69065042fcfc +Revision ID: 91d41aaf0216 Revises: -Create Date: 2024-12-16 19:08:24.669263 +Create Date: 2024-12-27 20:23:28.094007 """ from alembic import op @@ -10,7 +10,7 @@ # revision identifiers, used by Alembic. -revision = '69065042fcfc' +revision = '91d41aaf0216' down_revision = None branch_labels = None depends_on = None From 33086d8a9bf67504deba4314cf17c9c6f1a1abaf Mon Sep 17 00:00:00 2001 From: Liubov Dav Date: Sun, 5 Jan 2025 00:54:42 -0800 Subject: [PATCH 30/30] Fixed typos --- app/routes/goal_routes.py | 2 +- app/routes/task_routes.py | 2 +- tests/test_wave_01.py | 6 +++--- tests/test_wave_03.py | 4 ++-- tests/test_wave_05.py | 9 +++++---- tests/test_wave_06.py | 2 +- 6 files changed, 13 insertions(+), 12 deletions(-) diff --git a/app/routes/goal_routes.py b/app/routes/goal_routes.py index c276c9448..4a78d5aaa 100644 --- a/app/routes/goal_routes.py +++ b/app/routes/goal_routes.py @@ -102,7 +102,7 @@ def validate_goal(goal_id): goal = db.session.scalar(query) if not goal: - response = {"message": f"task {goal_id} not found"} + response = {"message": f"Goal {goal_id} not found"} abort(make_response(response, 404)) return goal diff --git a/app/routes/task_routes.py b/app/routes/task_routes.py index 61ca6cd9b..d6ace6b50 100644 --- a/app/routes/task_routes.py +++ b/app/routes/task_routes.py @@ -151,7 +151,7 @@ def validate_task(task_id): task = db.session.scalar(query) if not task: - response = {"message": f"task {task_id} not found"} + response = {"message": f"Task {task_id} not found"} abort(make_response(response, 404)) return task diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 81b0f170d..190e0244a 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -61,7 +61,7 @@ def test_get_task_not_found(client): assert response.status_code == 404 assert response_body == { - "message": "task 1 not found" + "message": "Task 1 not found" } # raise Exception("Complete test with assertion about response body") @@ -136,7 +136,7 @@ def test_update_task_not_found(client): assert response.status_code == 404 assert response_body == { - "message": "task 1 not found" + "message": "Task 1 not found" } # raise Exception("Complete test with assertion about response body") @@ -170,7 +170,7 @@ def test_delete_task_not_found(client): assert response.status_code == 404 assert response_body == { - "message": "task 1 not found" + "message": "Task 1 not found" } # raise Exception("Complete test with assertion about response body") diff --git a/tests/test_wave_03.py b/tests/test_wave_03.py index 07132ecf4..e48afcc4b 100644 --- a/tests/test_wave_03.py +++ b/tests/test_wave_03.py @@ -127,7 +127,7 @@ def test_mark_complete_missing_task(client): # Assert assert response.status_code == 404 - assert response_body == {"message": "task 1 not found"} + assert response_body == {"message": "Task 1 not found"} # raise Exception("Complete test with assertion about response body") # ***************************************************************** @@ -143,7 +143,7 @@ def test_mark_incomplete_missing_task(client): # Assert assert response.status_code == 404 - assert response_body == {"message": "task 1 not found"} + assert response_body == {"message": "Task 1 not found"} # raise Exception("Complete test with assertion about response body") # ***************************************************************** diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 879154be5..b17f561d7 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -57,7 +57,7 @@ def test_get_goal_not_found(client): # Assert # ---- Complete Test ---- assert response.status_code == 404 - assert response_body == {"message": "task 1 not found"} + assert response_body == {"message": "Goal 1 not found"} # assertion 2 goes here # ---- Complete Test ---- @@ -111,7 +111,7 @@ def test_update_goal_not_found(client): # Assert assert response.status_code == 404 - assert response_body == {"message": f"task 1 not found"} + assert response_body == {"message": "Goal 1 not found"} # @pytest.mark.skip(reason="No way to test this feature yet") @@ -130,7 +130,8 @@ def test_delete_goal(client, one_goal): # Check that the goal was deleted response = client.get("/goals/1") assert response.status_code == 404 - assert response_body == {"details": 'Goal 1 "Build a habit of going outside daily" successfully deleted'} + response_body = response.get_json() + assert response_body == {"message": "Goal 1 not found"} # raise Exception("Complete test with assertion about response body") # ***************************************************************** @@ -149,7 +150,7 @@ def test_delete_goal_not_found(client): # Assert assert response.status_code == 404 - assert response_body == {"message": "task 1 not found"} + assert response_body == {"message": "Goal 1 not found"} diff --git a/tests/test_wave_06.py b/tests/test_wave_06.py index 82acc27eb..9ecce3954 100644 --- a/tests/test_wave_06.py +++ b/tests/test_wave_06.py @@ -50,7 +50,7 @@ def test_get_tasks_for_specific_goal_no_goal(client): # Assert assert response.status_code == 404 - assert response_body == {"message": "task 1 not found"} + assert response_body == {"message": "Goal 1 not found"} # raise Exception("Complete test with assertion about response body") # *****************************************************************