Quellcode durchsuchen

Remove obsolete test_ files

FerRo988 vor 2 Wochen
Ursprung
Commit
e32db0170f
8 geänderte Dateien mit 0 neuen und 377 gelöschten Zeilen
  1. 0 16
      scratch/test_perf.py
  2. 0 13
      scratch/test_search.py
  3. 0 54
      test_api_task62.py
  4. 0 24
      test_debug.py
  5. 0 114
      test_math_logic.py
  6. 0 105
      test_meal_math.py
  7. 0 39
      test_qwen_perf.py
  8. 0 12
      test_rag.py

+ 0 - 16
scratch/test_perf.py

@@ -1,16 +0,0 @@
-import paramiko
-import sys
-
-host = '192.168.130.171'
-user = 'roni'
-pw = 'BTSai123'
-client = paramiko.SSHClient()
-client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
-try:
-    client.connect(host, username=user, password=pw)
-    cmd = """time curl -s -X POST http://127.0.0.1:11434/api/chat -d '{"model": "qwen3.5:4b", "messages": [{"role": "user", "content": "hello"}], "stream": false}'"""
-    stdin, stdout, stderr = client.exec_command(cmd)
-    print('STDOUT:', stdout.read().decode())
-    print('STDERR:', stderr.read().decode())
-finally:
-    client.close()

+ 0 - 13
scratch/test_search.py

@@ -1,13 +0,0 @@
-import sys
-import os
-sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
-from database import search_foods_by_name
-
-if __name__ == "__main__":
-    for query in ["egg", "bacon", "salmon", "beef"]:
-        results = search_foods_by_name(query)
-        print(f"Results for '{query}':")
-        for r in results:
-            print(f" - {r['name']} (Category: {r['category']})")
-        if not results:
-            print(" - NO RESULTS")

+ 0 - 54
test_api_task62.py

@@ -1,54 +0,0 @@
-from fastapi.testclient import TestClient
-from main import app
-from database import get_db_connection
-import uuid
-
-client = TestClient(app)
-
-def run_tests():
-    u1 = f"testu1_{uuid.uuid4().hex[:6]}"
-    u2 = f"testu2_{uuid.uuid4().hex[:6]}"
-    
-    res1 = client.post("/api/register", json={"username": u1, "password": "password123"})
-    t1 = res1.json().get("token")
-    
-    res2 = client.post("/api/register", json={"username": u2, "password": "password123"})
-    t2 = res2.json().get("token")
-    
-    h1 = {"Authorization": f"Bearer {t1}"}
-    h2 = {"Authorization": f"Bearer {t2}"}
-    
-    res = client.post("/api/meals", headers=h1, json={
-        "name": "Test Meal",
-        "items": [{"food_id": 1, "amount_g": 100}]
-    })
-    
-    meal_id = res.json()["meal_id"]
-    print(f"Created meal {meal_id}")
-    
-    # User 2 tries to rename
-    res = client.put(f"/api/meals/{meal_id}", headers=h2, json={"name": "Hacked"})
-    print(f"User 2 rename status: {res.status_code} (Expected 404)")
-    
-    # User 1 renames
-    res = client.put(f"/api/meals/{meal_id}", headers=h1, json={"name": "Renamed"})
-    print(f"User 1 rename status: {res.status_code} (Expected 200)")
-    
-    # User 2 tries to delete
-    res = client.delete(f"/api/meals/{meal_id}", headers=h2)
-    print(f"User 2 delete status: {res.status_code} (Expected 404)")
-    
-    # Delete
-    res = client.delete(f"/api/meals/{meal_id}", headers=h1)
-    print(f"User 1 delete status: {res.status_code} (Expected 200)")
-    
-    # Check DB
-    conn = get_db_connection()
-    c = conn.cursor()
-    c.execute("SELECT COUNT(*) FROM meal_items WHERE meal_id = ?", (meal_id,))
-    count = c.fetchone()[0]
-    print(f"Remaining items in DB: {count} (Expected 0)")
-    conn.close()
-
-if __name__ == "__main__":
-    run_tests()

+ 0 - 24
test_debug.py

@@ -1,24 +0,0 @@
-import httpx
-import json
-
-def debug_chat():
-    url = "http://localhost:11434/api/chat"
-    messages = [
-        {"role": "system", "content": "[SYSTEM: NUTRITIONAL ANALYST MODE]\nYou are the LocalFoodAI Analyst. Use ONLY verified local data for values.\nCRITICAL: Provide direct, concise answers. Skip all internal monologues, <thought> tags, or reasoning steps.\nFor each food discussed, you MUST follow this structure:\n1. Header: ### 🥗 [Name] (per 100g)\n2. Macros: A markdown table for Cal, P, F, C, Fib, Sug, Chol.\n3. Micros: A bulleted list for Na, Ca, Fe, K, VitA, VitC.\n4. Insight: A 1-sentence analysis of the food's nutritional profile.\nAlways prioritize local data over training memory. If a nutrient is missing, say 'Data not available'."},
-        {"role": "user", "content": "How much protein in 100g of salmon?"}
-    ]
-    payload = {
-        "model": "qwen3.5:9b",
-        "messages": messages,
-        "stream": False
-    }
-    
-    print("Sending debug request...")
-    with httpx.Client(timeout=300.0) as client:
-        response = client.post(url, json=payload)
-        print(f"Status: {response.status_code}")
-        print("Response Body:")
-        print(response.text)
-
-if __name__ == "__main__":
-    debug_chat()

+ 0 - 114
test_math_logic.py

@@ -1,114 +0,0 @@
-import unittest
-from unittest.mock import patch, MagicMock
-from fastapi.testclient import TestClient
-from main import app
-
-class TestMealMathLogic(unittest.TestCase):
-    def setUp(self):
-        self.client = TestClient(app)
-        # Mock user authentication for the calculation endpoint
-        self.headers = {"Authorization": "Bearer mock-token"}
-
-    @patch("main.get_user_from_token")
-    @patch("main.get_foods_by_ids")
-    def test_math_scaling_and_aggregation(self, mock_get_foods, mock_auth):
-        # 1. Setup mocks
-        mock_auth.return_value = {"id": 1, "username": "testuser"}
-        
-        # Mock database return for two foods
-        mock_get_foods.return_value = [
-            {
-                "id": 1, "name": "Food A", 
-                "calories": 100.0, "protein_g": 10.0, "fat_g": 5.0, "carbs_g": 2.0,
-                "fiber_g": 1.0, "sugar_g": 0.5, "cholesterol_mg": 0.0,
-                "vitamin_a_iu": 0.0, "vitamin_c_mg": 0.0,
-                "calcium_mg": 0.0, "iron_mg": 0.0, "potassium_mg": 0.0, "sodium_mg": 0.0
-            },
-            {
-                "id": 2, "name": "Food B", 
-                "calories": 200.0, "protein_g": 20.0, "fat_g": 10.0, "carbs_g": 4.0,
-                "fiber_g": 2.0, "sugar_g": 1.0, "cholesterol_mg": 5.0,
-                "vitamin_a_iu": 100.0, "vitamin_c_mg": 10.0,
-                "calcium_mg": 50.0, "iron_mg": 2.0, "potassium_mg": 300.0, "sodium_mg": 100.0
-            }
-        ]
-
-        # 2. Test Case: 50g of Food A and 150g of Food B
-        # Expected Food A (50g): Cal=50, Pro=5
-        # Expected Food B (150g): Cal=300, Pro=30
-        # Totals: Cal=350, Pro=35, Weight=200
-        
-        payload = {
-            "items": [
-                {"food_id": 1, "amount_g": 50},
-                {"food_id": 2, "amount_g": 150}
-            ]
-        }
-        
-        response = self.client.post("/api/meal/calculate", json=payload, headers=self.headers)
-        
-        self.assertEqual(response.status_code, 200)
-        data = response.json()
-        
-        self.assertEqual(data["total_weight_g"], 200.0)
-        self.assertEqual(data["macros"]["calories"], 350.0)
-        self.assertEqual(data["macros"]["protein_g"], 35.0)
-        self.assertEqual(data["macros"]["fat_g"], 17.5) # (5 * 0.5) + (10 * 1.5) = 2.5 + 15 = 17.5
-        self.assertEqual(data["macros"]["carbs_g"], 7.0) # (2 * 0.5) + (4 * 1.5) = 1.0 + 6.0 = 7.0
-
-    @patch("main.get_user_from_token")
-    @patch("main.get_foods_by_ids")
-    def test_precision_rounding(self, mock_get_foods, mock_auth):
-        mock_auth.return_value = {"id": 1, "username": "testuser"}
-        
-        # Mock food with irregular values to trigger rounding
-        mock_get_foods.return_value = [
-            {
-                "id": 1, "name": "Irregular Food", 
-                "calories": 123.456, "protein_g": 10.123, "fat_g": 5.555, "carbs_g": 0.0,
-                "fiber_g": 0.0, "sugar_g": 0.0, "cholesterol_mg": 0.0,
-                "vitamin_a_iu": 0.0, "vitamin_c_mg": 0.0,
-                "calcium_mg": 0.0, "iron_mg": 0.0, "potassium_mg": 0.0, "sodium_mg": 0.0
-            }
-        ]
-
-        # 123g of Food A -> Ratio 1.23
-        # Calories: 123.456 * 1.23 = 151.85088 -> Rounded to 151.85
-        # Protein: 10.123 * 1.23 = 12.45129 -> Rounded to 12.45
-        # Fat: 5.555 * 1.23 = 6.83265 -> Rounded to 6.83
-        
-        payload = {"items": [{"food_id": 1, "amount_g": 123}]}
-        response = self.client.post("/api/meal/calculate", json=payload, headers=self.headers)
-        
-        data = response.json()
-        self.assertEqual(data["macros"]["calories"], 151.85)
-        self.assertEqual(data["macros"]["protein_g"], 12.45)
-        self.assertEqual(data["macros"]["fat_g"], 6.83)
-
-    @patch("main.get_user_from_token")
-    @patch("main.get_foods_by_ids")
-    def test_null_value_handling(self, mock_get_foods, mock_auth):
-        mock_auth.return_value = {"id": 1, "username": "testuser"}
-        
-        # Mock food with NULLs
-        mock_get_foods.return_value = [
-            {
-                "id": 1, "name": "Null Food", 
-                "calories": None, "protein_g": 10.0, "fat_g": None, "carbs_g": 2.0,
-                "fiber_g": None, "sugar_g": None, "cholesterol_mg": None,
-                "vitamin_a_iu": None, "vitamin_c_mg": None,
-                "calcium_mg": None, "iron_mg": None, "potassium_mg": None, "sodium_mg": None
-            }
-        ]
-        
-        payload = {"items": [{"food_id": 1, "amount_g": 100}]}
-        response = self.client.post("/api/meal/calculate", json=payload, headers=self.headers)
-        
-        self.assertEqual(response.status_code, 200)
-        data = response.json()
-        self.assertEqual(data["macros"]["calories"], 0.0)
-        self.assertEqual(data["macros"]["fat_g"], 0.0)
-        self.assertEqual(data["extended"]["fiber_g"], 0.0)
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 105
test_meal_math.py

@@ -1,105 +0,0 @@
-import unittest
-import httpx
-import json
-
-class TestMealMath(unittest.TestCase):
-    BASE_URL = "http://192.168.130.171:8000/api"
-    TOKEN = None
-    FOOD_ID_1 = None # Will be populated
-    FOOD_1_DATA = None
-
-    @classmethod
-    def setUpClass(cls):
-        with httpx.Client(timeout=30.0) as client:
-            # 1. Login to get token
-            login_res = client.post(f"{cls.BASE_URL}/login", json={
-                "username": "ferro988",
-                "password": "password"
-            })
-            if login_res.status_code == 200:
-                cls.TOKEN = login_res.json()["token"]
-            
-            # 2. Search for a baseline food (e.g., Chicken)
-            search_res = client.get(f"{cls.BASE_URL}/food/search?q=Chicken", headers={
-                "Authorization": f"Bearer {cls.TOKEN}"
-            })
-            if search_res.status_code == 200:
-                foods = search_res.json()
-                if foods:
-                    cls.FOOD_ID_1 = foods[0]["id"]
-                    cls.FOOD_1_DATA = foods[0]
-
-    def test_baseline_100g(self):
-        """Verify that 100g returns the exact database values."""
-        payload = {"items": [{"food_id": self.FOOD_ID_1, "amount_g": 100}]}
-        with httpx.Client(timeout=30.0) as client:
-            res = client.post(f"{self.BASE_URL}/meal/calculate", json=payload, headers={
-                "Authorization": f"Bearer {self.TOKEN}"
-            })
-            self.assertEqual(res.status_code, 200)
-            data = res.json()
-            
-            # Check macros
-            self.assertEqual(data["macros"]["calories"], self.FOOD_1_DATA["calories"])
-            self.assertEqual(data["macros"]["protein_g"], self.FOOD_1_DATA["protein_g"])
-
-    def test_half_portion_50g(self):
-        """Verify that 50g returns exactly 50% of the database values."""
-        payload = {"items": [{"food_id": self.FOOD_ID_1, "amount_g": 50}]}
-        with httpx.Client(timeout=30.0) as client:
-            res = client.post(f"{self.BASE_URL}/meal/calculate", json=payload, headers={
-                "Authorization": f"Bearer {self.TOKEN}"
-            })
-            self.assertEqual(res.status_code, 200)
-            data = res.json()
-            
-            expected_cal = round(self.FOOD_1_DATA["calories"] * 0.5, 2)
-            expected_pro = round(self.FOOD_1_DATA["protein_g"] * 0.5, 2)
-            
-            self.assertEqual(data["macros"]["calories"], expected_cal)
-            self.assertEqual(data["macros"]["protein_g"], expected_pro)
-
-    def test_irregular_portion_237g(self):
-        """Verify that 237g correctly applies the ratio (2.37x)."""
-        payload = {"items": [{"food_id": self.FOOD_ID_1, "amount_g": 237}]}
-        with httpx.Client(timeout=30.0) as client:
-            res = client.post(f"{self.BASE_URL}/meal/calculate", json=payload, headers={
-                "Authorization": f"Bearer {self.TOKEN}"
-            })
-            self.assertEqual(res.status_code, 200)
-            data = res.json()
-            
-            ratio = 2.37
-            expected_cal = round(self.FOOD_1_DATA["calories"] * ratio, 2)
-            
-            self.assertEqual(data["macros"]["calories"], expected_cal)
-
-    def test_multi_item_aggregation(self):
-        """Verify that two items sum up correctly."""
-        with httpx.Client(timeout=30.0) as client:
-            # Get a second food
-            search_res = client.get(f"{self.BASE_URL}/food/search?q=Rice", headers={
-                "Authorization": f"Bearer {self.TOKEN}"
-            })
-            food2 = search_res.json()[0]
-            
-            payload = {
-                "items": [
-                    {"food_id": self.FOOD_ID_1, "amount_g": 100},
-                    {"food_id": food2["id"], "amount_g": 200}
-                ]
-            }
-            res = client.post(f"{self.BASE_URL}/meal/calculate", json=payload, headers={
-                "Authorization": f"Bearer {self.TOKEN}"
-            })
-            self.assertEqual(res.status_code, 200)
-            data = res.json()
-            
-            expected_cal = round(self.FOOD_1_DATA["calories"] + (food2["calories"] * 2.0), 2)
-            expected_weight = 100 + 200
-            
-            self.assertEqual(data["macros"]["calories"], expected_cal)
-            self.assertEqual(data["total_weight_g"], expected_weight)
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 39
test_qwen_perf.py

@@ -1,39 +0,0 @@
-import httpx
-import time
-import json
-
-def test_performance():
-    url = "http://localhost:11434/api/chat"
-    payload = {
-        "model": "qwen3.5:9b",
-        "messages": [{"role": "user", "content": "Hi."}],
-        "stream": True
-    }
-    
-    print(f"Starting streaming test for qwen3.5:9b...")
-    start_time = time.time()
-    
-    try:
-        with httpx.Client(timeout=300.0) as client:
-            with client.stream("POST", url, json=payload) as response:
-                response.raise_for_status()
-                print("\n--- Response ---")
-                for line in response.iter_lines():
-                    if line:
-                        chunk = json.loads(line)
-                        content = chunk.get("message", {}).get("content", "")
-                        print(content, end="", flush=True)
-                        if chunk.get("done"):
-                            break
-                print("\n----------------")
-            
-            end_time = time.time()
-            duration = end_time - start_time
-            print(f"Duration: {duration:.2f} seconds")
-
-            
-    except Exception as e:
-        print(f"Error during test: {e}")
-
-if __name__ == "__main__":
-    test_performance()

+ 0 - 12
test_rag.py

@@ -1,12 +0,0 @@
-import sys
-import os
-sys.path.insert(0, '/home/roni/LocalFoodAI')
-from main import extract_food_context
-
-messages = [{"role": "user", "content": "how many calories in tuna?"}]
-context = extract_food_context(messages)
-if context:
-    print("SUCCESS: Context extracted")
-    print(context)
-else:
-    print("FAILURE: No context extracted")