-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathtest_xhr.py
More file actions
97 lines (85 loc) · 2.58 KB
/
test_xhr.py
File metadata and controls
97 lines (85 loc) · 2.58 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from http.server import HTTPServer, BaseHTTPRequestHandler
import pythonmonkey as pm
import threading
import asyncio
import json
def test_xhr():
class TestHTTPRequestHandler(BaseHTTPRequestHandler):
def log_request(self, *args) -> None:
return
def do_GET(self):
self.send_response(200)
self.end_headers()
self.wfile.write(b"get response")
def do_POST(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
length = int(self.headers.get('Content-Length'))
json_string = self.rfile.read(length).decode("utf-8")
parameter_dict = json.loads(json_string)
parameter_dict["User-Agent"] = self.headers['User-Agent']
data = json.dumps(parameter_dict).encode("utf-8")
self.wfile.write(data)
httpd = HTTPServer(('localhost', 4001), TestHTTPRequestHandler)
thread = threading.Thread(target = httpd.serve_forever)
thread.daemon = True
thread.start()
async def async_fn():
assert "get response" == await pm.eval("""
new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:4001');
xhr.onload = function ()
{
if (this.status >= 200 && this.status < 300)
{
resolve(this.response);
}
else
{
reject(new Error(JSON.stringify({
status: this.status,
statusText: this.statusText
})));
}
};
xhr.onerror = function (ev)
{
reject(ev.error);
};
xhr.send();
});
""")
post_result = await pm.eval("""
new Promise(function (resolve, reject)
{
let xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:4001');
xhr.onload = function ()
{
if (this.status >= 200 && this.status < 300)
{
resolve(this.response);
}
else
{
reject(new Error(JSON.stringify({
status: this.status,
statusText: this.statusText
})));
}
};
xhr.onerror = function (ev)
{
console.log(ev)
reject(ev.error);
};
xhr.send(JSON.stringify({fromPM: "snakesandmonkeys"}));
})
""")
result_json = json.loads(post_result)
assert result_json["fromPM"] == "snakesandmonkeys"
assert result_json["User-Agent"].startswith("Python/")
httpd.shutdown()
asyncio.run(async_fn())