Bump to 4.8.3
[platform/upstream/ccache.git] / test / http-client
1 #!/usr/bin/env python3
2
3 # This is a simple HTTP client to test readiness of the asynchronously
4 # launched HTTP server.
5
6 import sys
7 import time
8 import urllib.request
9
10
11 def run(url, timeout, basic_auth):
12     deadline = time.time() + timeout
13     req = urllib.request.Request(url, method="HEAD")
14     if basic_auth:
15         import base64
16
17         encoded_credentials = base64.b64encode(
18             basic_auth.encode("ascii")
19         ).decode("ascii")
20         req.add_header("Authorization", f"Basic {encoded_credentials}")
21     while True:
22         try:
23             response = urllib.request.urlopen(req)
24             print(f"Connection successful (code: {response.getcode()})")
25             break
26         except urllib.error.URLError as e:
27             print(e.reason)
28             if time.time() > deadline:
29                 print(
30                     f"All connection attempts failed within {timeout} seconds."
31                 )
32                 sys.exit(1)
33             time.sleep(0.5)
34
35
36 if __name__ == "__main__":
37     import argparse
38
39     parser = argparse.ArgumentParser()
40     parser.add_argument(
41         "--basic-auth", "-B", help="Basic auth tuple like user:pass"
42     )
43     parser.add_argument(
44         "--timeout",
45         "-t",
46         metavar="TIMEOUT",
47         default=10,
48         type=int,
49         help="Maximum seconds to wait for successful connection attempt "
50         "[default: 10 seconds]",
51     )
52     parser.add_argument("url", type=str, help="URL to connect to")
53     args = parser.parse_args()
54
55     run(
56         url=args.url,
57         timeout=args.timeout,
58         basic_auth=args.basic_auth,
59     )