verify_validation.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import urllib.request
  2. import urllib.error
  3. import json
  4. def run_test(name, payload):
  5. url = "http://127.0.0.1:8000/api/meal/calculate"
  6. login_url = "http://127.0.0.1:8000/api/login"
  7. register_url = "http://127.0.0.1:8000/api/register"
  8. print(f"\n--- Testing: {name} ---")
  9. auth_data = json.dumps({"username": "testuser", "password": "password"}).encode('utf-8')
  10. # Try to register first (ignore error if already exists)
  11. req_reg = urllib.request.Request(register_url, data=auth_data, headers={'Content-Type': 'application/json'})
  12. try:
  13. urllib.request.urlopen(req_reg)
  14. except Exception:
  15. pass
  16. # Login
  17. req = urllib.request.Request(login_url, data=auth_data, headers={'Content-Type': 'application/json'})
  18. try:
  19. with urllib.request.urlopen(req) as response:
  20. token = json.loads(response.read().decode()).get("token")
  21. except Exception as e:
  22. print(f"Login failed: {e}")
  23. return
  24. headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
  25. data = json.dumps(payload).encode('utf-8')
  26. req = urllib.request.Request(url, data=data, headers=headers)
  27. try:
  28. with urllib.request.urlopen(req) as response:
  29. print(f"Status: {response.getcode()}")
  30. print(f"Body: {response.read().decode()}")
  31. except urllib.error.HTTPError as e:
  32. print(f"Status: {e.code}")
  33. print(f"Error Body: {e.read().decode()}")
  34. if __name__ == "__main__":
  35. # Case 1: amount_g is 0
  36. run_test("Zero Quantity", {"items": [{"food_id": 1, "amount_g": 0}]})
  37. # Case 2: amount_g is negative
  38. run_test("Negative Quantity", {"items": [{"food_id": 1, "amount_g": -50}]})
  39. # Case 3: Invalid food_id
  40. run_test("Invalid Food ID", {"items": [{"food_id": 999999, "amount_g": 100}]})
  41. # Case 4: Mixed valid and invalid IDs
  42. run_test("Mixed Valid/Invalid IDs", {"items": [
  43. {"food_id": 1, "amount_g": 100},
  44. {"food_id": 888888, "amount_g": 200}
  45. ]})
  46. # Case 5: Valid request
  47. run_test("Valid Request", {"items": [{"food_id": 1, "amount_g": 150}]})