[LayoutTests] Convert http/tests/blink convert PHP to Python
[WebKit-https.git] / LayoutTests / http / tests / blink / sendbeacon / resources / check-beacon.py
1 #!/usr/bin/env python3
2
3 import os
4 import sys
5 import tempfile
6 import time
7
8 file = __file__.split(':/cygwin')[-1]
9 http_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(file)))))
10 sys.path.insert(0, http_root)
11
12 from resources.portabilityLayer import get_request
13
14
15 def extensive_strip(text):
16     # Sometimes the string ends with \x00
17     # and .strip() does not remove it
18     text = text.strip()
19     while text[-1].encode() == b'\x00':
20         text = text[:-1]
21
22     return text
23
24
25 request = get_request()
26 beacon_filename = os.path.join(tempfile.gettempdir(), 'beacon{}.txt'.format(request.get('name', '')))
27
28 max_attempts = 700
29 retries = int(request.get('retries', max_attempts))
30 while not os.path.isfile(beacon_filename) and retries != 0:
31     time.sleep(0.01)
32     retries -= 1
33
34 sys.stdout.write(
35     'Content-Type: text/plain\r\n'
36     'Access-Control-Allow-Origin: *\r\n\r\n'
37 )
38
39 if os.path.isfile(beacon_filename):
40     with open(beacon_filename, 'r') as beacon_file:
41         sys.stdout.write('Beacon sent successfully\n')
42         for line in beacon_file.readlines():
43             trimmed = extensive_strip(line)
44             if trimmed != '':
45                 sys.stdout.write('{}\n'.format(trimmed))
46
47     os.remove(beacon_filename)
48 else:
49     sys.stdout.write('Beacon not sent\n')