test_update_product_inventory.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from fastapi.testclient import TestClient
  2. from app.db import update_product_inventory
  3. from app.main import app
  4. from app.parser import read_file
  5. from app.read_settings import read_settings
  6. client = TestClient(app)
  7. def get_inventory_amount(inventories, product_variation_id: str) -> int:
  8. """Helper function to get the inventory amount of the given product
  9. with specified product_id
  10. """
  11. for inventory in inventories:
  12. if inventory.product_variation_id == product_variation_id:
  13. return inventory.amount
  14. def test_update_product_inventory():
  15. """Test the function to update the inventory list of a product. The
  16. function receives a list of strings after the Stripe or
  17. NOWPayments checkout, and update each purchased product's
  18. inventory, by decreasing the inventory amount for each option with
  19. the amount of copies bought of each product.
  20. """
  21. settings = read_settings("settings.toml")
  22. product_list = {
  23. "product_variation_id": "prod_RZBk650b1Tx95N__s",
  24. "product_name": "a-tshirt-01",
  25. "update_amount": 3,
  26. }
  27. tree = "products"
  28. # -- store current inventory amount pre-update
  29. pre_product = read_file(
  30. settings.git_repo,
  31. product_list["product_name"],
  32. settings.document_match,
  33. settings.block_types,
  34. tree,
  35. )
  36. pre_inventory_amount = get_inventory_amount(
  37. pre_product.meta.inventory,
  38. product_list["product_variation_id"],
  39. )
  40. # -- update inventory
  41. update_product_inventory(
  42. product_list["product_name"],
  43. product_list["update_amount"],
  44. product_list["product_variation_id"],
  45. settings,
  46. )
  47. # -- store updated inventory amount post-update
  48. post_product = read_file(
  49. settings.git_repo,
  50. product_list["product_name"],
  51. settings.document_match,
  52. settings.block_types,
  53. tree,
  54. )
  55. post_inventory_amount = get_inventory_amount(
  56. post_product.meta.inventory,
  57. product_list["product_variation_id"]
  58. )
  59. # -- if pre_inventory_amount is already 0 make sure it
  60. # stays like that also after the update else do subtraction
  61. if pre_inventory_amount > 0:
  62. assert (
  63. pre_inventory_amount - product_list["update_amount"]
  64. ) == post_inventory_amount
  65. else:
  66. assert pre_inventory_amount == post_inventory_amount
  67. # Restore the amount to original after the test
  68. update_product_inventory(
  69. product_list["product_name"],
  70. -pre_inventory_amount,
  71. product_list["product_variation_id"],
  72. settings,
  73. )