| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- import urllib.request
- import urllib.error
- import json
- def run_test(name, payload):
- url = "http://127.0.0.1:8000/api/meal/calculate"
- login_url = "http://127.0.0.1:8000/api/login"
- register_url = "http://127.0.0.1:8000/api/register"
-
- print(f"\n--- Testing: {name} ---")
-
- auth_data = json.dumps({"username": "testuser", "password": "password"}).encode('utf-8')
-
- # Try to register first (ignore error if already exists)
- req_reg = urllib.request.Request(register_url, data=auth_data, headers={'Content-Type': 'application/json'})
- try:
- urllib.request.urlopen(req_reg)
- except Exception:
- pass
-
- # Login
- req = urllib.request.Request(login_url, data=auth_data, headers={'Content-Type': 'application/json'})
- try:
- with urllib.request.urlopen(req) as response:
- token = json.loads(response.read().decode()).get("token")
- except Exception as e:
- print(f"Login failed: {e}")
- return
- headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
- data = json.dumps(payload).encode('utf-8')
- req = urllib.request.Request(url, data=data, headers=headers)
-
- try:
- with urllib.request.urlopen(req) as response:
- print(f"Status: {response.getcode()}")
- print(f"Body: {response.read().decode()}")
- except urllib.error.HTTPError as e:
- print(f"Status: {e.code}")
- print(f"Error Body: {e.read().decode()}")
- if __name__ == "__main__":
- # Case 1: amount_g is 0
- run_test("Zero Quantity", {"items": [{"food_id": 1, "amount_g": 0}]})
-
- # Case 2: amount_g is negative
- run_test("Negative Quantity", {"items": [{"food_id": 1, "amount_g": -50}]})
-
- # Case 3: Invalid food_id
- run_test("Invalid Food ID", {"items": [{"food_id": 999999, "amount_g": 100}]})
-
- # Case 4: Mixed valid and invalid IDs
- run_test("Mixed Valid/Invalid IDs", {"items": [
- {"food_id": 1, "amount_g": 100},
- {"food_id": 888888, "amount_g": 200}
- ]})
- # Case 5: Valid request
- run_test("Valid Request", {"items": [{"food_id": 1, "amount_g": 150}]})
|