| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- import urllib.request
- import urllib.error
- import json
- def test_calculate_meal():
- url = "http://127.0.0.1:8000/api/meal/calculate"
- login_url = "http://127.0.0.1:8000/api/login"
-
- # Login
- login_data = json.dumps({"username": "testuser", "password": "password"}).encode('utf-8')
- req = urllib.request.Request(login_url, data=login_data, headers={'Content-Type': 'application/json'})
- try:
- with urllib.request.urlopen(req) as response:
- login_resp = json.loads(response.read().decode())
- except urllib.error.URLError as e:
- print(f"Login failed: {e}")
- return
-
- token = login_resp.get("token")
- if not token:
- print("No token received")
- return
-
- headers = {
- "Authorization": f"Bearer {token}",
- "Content-Type": "application/json"
- }
-
- payload = {
- "items": [
- {"food_id": 1, "amount_g": 200.5},
- {"food_id": 2, "amount_g": 50}
- ]
- }
-
- data = json.dumps(payload).encode('utf-8')
- req = urllib.request.Request(url, data=data, headers=headers)
-
- print("Sending payload:")
- print(json.dumps(payload, indent=2))
-
- try:
- with urllib.request.urlopen(req) as response:
- print(f"\nResponse Code: {response.getcode()}")
- resp_data = json.loads(response.read().decode())
- print("Response JSON:")
- print(json.dumps(resp_data, indent=2))
- except urllib.error.HTTPError as e:
- print(f"Response Error: {e.code}")
- print(e.read().decode())
- if __name__ == "__main__":
- test_calculate_meal()
|