verify_meal_math.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import urllib.request
  2. import urllib.error
  3. import json
  4. def test_calculate_meal():
  5. url = "http://127.0.0.1:8000/api/meal/calculate"
  6. login_url = "http://127.0.0.1:8000/api/login"
  7. # Login
  8. login_data = json.dumps({"username": "testuser", "password": "password"}).encode('utf-8')
  9. req = urllib.request.Request(login_url, data=login_data, headers={'Content-Type': 'application/json'})
  10. try:
  11. with urllib.request.urlopen(req) as response:
  12. login_resp = json.loads(response.read().decode())
  13. except urllib.error.URLError as e:
  14. print(f"Login failed: {e}")
  15. return
  16. token = login_resp.get("token")
  17. if not token:
  18. print("No token received")
  19. return
  20. headers = {
  21. "Authorization": f"Bearer {token}",
  22. "Content-Type": "application/json"
  23. }
  24. payload = {
  25. "items": [
  26. {"food_id": 1, "amount_g": 200.5},
  27. {"food_id": 2, "amount_g": 50}
  28. ]
  29. }
  30. data = json.dumps(payload).encode('utf-8')
  31. req = urllib.request.Request(url, data=data, headers=headers)
  32. print("Sending payload:")
  33. print(json.dumps(payload, indent=2))
  34. try:
  35. with urllib.request.urlopen(req) as response:
  36. print(f"\nResponse Code: {response.getcode()}")
  37. resp_data = json.loads(response.read().decode())
  38. print("Response JSON:")
  39. print(json.dumps(resp_data, indent=2))
  40. except urllib.error.HTTPError as e:
  41. print(f"Response Error: {e.code}")
  42. print(e.read().decode())
  43. if __name__ == "__main__":
  44. test_calculate_meal()