test_update_product_inventory.py 2.8 KB

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