File size: 2,550 Bytes
136176e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #!/usr/bin/env python3
"""
Test script for badge settings download/upload API endpoints.
"""
import requests
import argparse
import json
from urllib.parse import urljoin
def get_jwt_from_api_key(base_url, api_key):
login_url = urljoin(base_url, "/v1/login")
payload = {"api_token": api_key}
headers = {"Content-Type": "application/json"}
resp = requests.post(login_url, json=payload, headers=headers)
if resp.status_code == 200:
data = resp.json()
return data.get("access_token") or data.get("token")
print(f"Login failed: {resp.status_code} {resp.text}")
return None
def download_badges_json(base_url, jwt_token, output_file):
url = urljoin(base_url, "/badges/settings/download")
headers = {"Authorization": f"Bearer {jwt_token}"}
resp = requests.get(url, headers=headers)
if resp.status_code == 200:
with open(output_file, "wb") as f:
f.write(resp.content)
print(f"Downloaded badge settings to {output_file}")
return True
print(f"Download failed: {resp.status_code} {resp.text}")
return False
def upload_badges_json(base_url, jwt_token, input_file):
url = urljoin(base_url, "/badges/settings/upload")
headers = {"Authorization": f"Bearer {jwt_token}"}
with open(input_file, "rb") as f:
files = {"file": (input_file, f, "application/json")}
resp = requests.post(url, headers=headers, files=files)
if resp.status_code == 200:
data = resp.json()
print("Accepted:", data.get("accepted"))
print("Rejected:", data.get("rejected"))
return True
print(f"Upload failed: {resp.status_code} {resp.text}")
return False
def main():
parser = argparse.ArgumentParser(description="Test badge settings download/upload API.")
parser.add_argument("--url", required=True, help="Base URL of the API server")
parser.add_argument("--token", required=True, help="API key for authentication")
parser.add_argument("--download", metavar="OUTPUT", help="Download badge settings to file")
parser.add_argument("--upload", metavar="INPUT", help="Upload badge settings from file")
args = parser.parse_args()
jwt_token = get_jwt_from_api_key(args.url, args.token)
if not jwt_token:
print("Could not authenticate with provided API key.")
exit(1)
if args.download:
download_badges_json(args.url, jwt_token, args.download)
if args.upload:
upload_badges_json(args.url, jwt_token, args.upload)
if __name__ == "__main__":
main()
|