Quan1811/docstring-api
0
1import requests2import os3 4BASE_URL = "http://127.0.0.1:8000"5 6def test_upload_code():7 print("--- 1. ĐĂNG NHẬP ĐỂ LẤY TOKEN ---")8 # Thay bằng tài khoản thật của bạn9 login_data = {10 "username": "quydzwa", 11 "password": "quydk123" 12 }13 14 login_response = requests.post(f"{BASE_URL}/login", json=login_data)15 16 if login_response.status_code != 200:17 print(f"❌ Đăng nhập thất bại: {login_response.text}")18 return19 20 token = login_response.json().get("access_token")21 print("✅ Đăng nhập thành công!\n")22 23 print("--- 2. TẠO FILE MẪU ĐỂ TEST ---")24 # Tạo nhanh 2 file python mẫu trên máy tính để test upload25 with open("sample1.py", "w", encoding="utf-8") as f:26 f.write("def tinhtong(a, b):\n return a + b\n")27 28 with open("sample2.py", "w", encoding="utf-8") as f:29 f.write("def chao(ten):\n print(f'Xin chào {ten}')\n")30 31 print("✅ Đã tạo file sample1.py và sample2.py\n")32 33 print("--- 3. TEST GỌI API /upload-code ---")34 headers = {35 "Authorization": f"Bearer {token}"36 # Lưu ý: Khi upload file bằng requests, KHÔNG set header Content-Type là application/json37 # requests sẽ tự động set Content-Type là multipart/form-data38 }39 40 # Mở các file để chuẩn bị upload41 # Cấu trúc: ('tên_trường_trong_api', (tên_file, file_object, kiểu_mime))42 # Trong API của bạn, biến nhận vào tên là `files`43 files_to_upload = [44 ('files', ('sample1.py', open('sample1.py', 'rb'), 'text/x-python')),45 ('files', ('sample2.py', open('sample2.py', 'rb'), 'text/x-python'))46 ]47 48 print("Đang gửi file lên server...")49 upload_response = requests.post(f"{BASE_URL}/upload-code", files=files_to_upload, headers=headers)50 51 # Đóng file sau khi gửi xong52 for field_name, file_tuple in files_to_upload:53 file_tuple[1].close()54 55 # Xóa file mẫu (Tùy chọn)56 os.remove("sample1.py")57 os.remove("sample2.py")58 59 print(f"Status Code: {upload_response.status_code}")60 try:61 import json62 print("Response JSON:")63 print(json.dumps(upload_response.json(), indent=2, ensure_ascii=False))64 except Exception:65 print("Response Text:", upload_response.text)66 67if __name__ == "__main__":68 test_upload_code()69 