Quan1811/docstring-api
0
1import requests2import random3 4BASE_URL = "http://127.0.0.1:8000"5 6def test_full_flow():7 # 1. Thông tin user ngẫu nhiên8 rand_id = random.randint(1000, 9999)9 user_data = {10 "username": f"user_{rand_id}", 11 "password": "password123", 12 "email": f"email_{rand_id}@example.com"13 }14 15 print(f"\n--- 1. ĐĂNG KÝ: {user_data['username']} ---")16 reg_resp = requests.post(f"{BASE_URL}/register", json=user_data)17 print(f"Status: {reg_resp.status_code}, Res: {reg_resp.json()}")18 19 print("\n--- 2. ĐĂNG NHẬP ---")20 login_resp = requests.post(f"{BASE_URL}/login", json={21 "username": user_data["username"],22 "password": user_data["password"]23 })24 25 if login_resp.status_code != 200:26 print("Đăng nhập thất bại!")27 return28 29 login_data = login_resp.json()30 token = login_data["access_token"]31 print(f"Login thành công! Token: {token[:20]}...")32 33 # Headers kèm Token để gọi các API bảo mật34 headers = {"Authorization": f"Bearer {token}"}35 36 print("\n--- 3. THÊM CODE (Cần Token) ---")37 code_payload = {38 "content": "def hello_world():\n print('Hello')", 39 "docstring": "" 40 }41 add_resp = requests.post(f"{BASE_URL}/add-code", json=code_payload, headers=headers)42 43 if add_resp.status_code == 200:44 res = add_resp.json()45 print(f"Thành công! Docstring: {res['final_docstring']}")46 else:47 print(f"Lỗi add-code: {add_resp.status_code} - {add_resp.text}")48 49 print("\n--- 4. XEM LỊCH SỬ (Chỉ thấy của mình) ---")50 his_resp = requests.get(f"{BASE_URL}/history", headers=headers)51 if his_resp.status_code == 200:52 history = his_resp.json()53 print(f"Số lượng bản ghi: {len(history)}")54 for item in history:55 print(f"- [{item['timestamp']}] Code: {item['code'][:20]}...")56 else:57 print(f"Lỗi lấy lịch sử: {his_resp.text}")58 59if __name__ == "__main__":60 try:61 test_full_flow()62 except requests.exceptions.ConnectionError:63 print("Lỗi: Server chưa chạy. Hãy chạy 'python main.py' trước.")