Skip to content

Commit

Permalink
Merge pull request #80 from CSCI-GA-2820-FA23-001/qiyu_fixDB
Browse files Browse the repository at this point in the history
move db action to the model.py
  • Loading branch information
tokotority authored Dec 8, 2023
2 parents 7711642 + 4da3908 commit 263a86a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
8 changes: 8 additions & 0 deletions service/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,14 @@ def deserialize(self, data):
) from error
return self

def change_availability(self):
"""
Changes the availability of the Product
"""
self.available = not self.available
db.session.commit()
logger.info("Availability changed for %s", self.name)

# # flake8: noqa: C901
# def deserialize_update(self, data):
# """
Expand Down
8 changes: 3 additions & 5 deletions service/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from flask import jsonify, request, abort, url_for
from service.common import status # HTTP Status Codes
from service.models import Product, Category, db
from service.models import Product, Category

# Import Flask application
from . import app
Expand Down Expand Up @@ -236,10 +236,8 @@ def change_product_availability(product_id):
f"Product with id '{product_id}' was not found.",
)

new_availability = not product.available
product.available = new_availability
db.session.commit()
message = {"message": f"Product availability changed to {new_availability}"}
product.change_availability()
message = {"message": f"Product availability changed to {product.available}"}
message = {**message, **product.serialize()}

app.logger.info("Product availability changed for ID [%s].", product_id)
Expand Down
17 changes: 17 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,23 @@ def test_delete_a_product(self):
product.delete()
self.assertEqual(len(Product.all()), 0)

def test_change_product_availability(self):
"""It should change the availability of a product"""
# Create a product
product = ProductFactory()
logging.debug(product)
product.id = None
product.create()
self.assertIsNotNone(product.id)
# Check initial availability
initial_availability = product.available
# Change availability
product.change_availability()
self.assertNotEqual(product.available, initial_availability)
# Fetch it back and verify the change
updated_product = Product.find(product.id)
self.assertEqual(updated_product.available, not initial_availability)

def test_list_all_products(self):
"""It should List all products in the database"""
products = Product.all()
Expand Down

0 comments on commit 263a86a

Please sign in to comment.