Skip to content

Commit e72bfd2

Browse files
authored
Merge pull request #437 from Distributive-Network/caleb/fix/xhr-test
Fix XHR Test
2 parents 2ed42d9 + a00347b commit e72bfd2

File tree

2 files changed

+97
-136
lines changed

2 files changed

+97
-136
lines changed

tests/js/xhr.simple

-136
This file was deleted.

tests/python/test_xhr.py

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
from http.server import HTTPServer, BaseHTTPRequestHandler
2+
import pythonmonkey as pm
3+
import threading
4+
import asyncio
5+
import json
6+
7+
def test_xhr():
8+
class TestHTTPRequestHandler(BaseHTTPRequestHandler):
9+
def log_request(self, *args) -> None:
10+
return
11+
12+
def do_GET(self):
13+
self.send_response(200)
14+
self.end_headers()
15+
self.wfile.write(b"get response")
16+
17+
def do_POST(self):
18+
self.send_response(200)
19+
self.send_header('Content-Type', 'application/json')
20+
self.end_headers()
21+
length = int(self.headers.get('Content-Length'))
22+
json_string = self.rfile.read(length).decode("utf-8")
23+
parameter_dict = json.loads(json_string)
24+
parameter_dict["User-Agent"] = self.headers['User-Agent']
25+
data = json.dumps(parameter_dict).encode("utf-8")
26+
self.wfile.write(data)
27+
28+
httpd = HTTPServer(('localhost', 4001), TestHTTPRequestHandler)
29+
thread = threading.Thread(target = httpd.serve_forever)
30+
thread.daemon = True
31+
thread.start()
32+
33+
async def async_fn():
34+
assert "get response" == await pm.eval("""
35+
new Promise(function (resolve, reject) {
36+
let xhr = new XMLHttpRequest();
37+
xhr.open('GET', 'http://localhost:4001');
38+
39+
xhr.onload = function ()
40+
{
41+
if (this.status >= 200 && this.status < 300)
42+
{
43+
resolve(this.response);
44+
}
45+
else
46+
{
47+
reject(new Error(JSON.stringify({
48+
status: this.status,
49+
statusText: this.statusText
50+
})));
51+
}
52+
};
53+
54+
xhr.onerror = function (ev)
55+
{
56+
reject(ev.error);
57+
};
58+
xhr.send();
59+
});
60+
""")
61+
62+
post_result = await pm.eval("""
63+
new Promise(function (resolve, reject)
64+
{
65+
let xhr = new XMLHttpRequest();
66+
xhr.open('POST', 'http://localhost:4001');
67+
68+
xhr.onload = function ()
69+
{
70+
if (this.status >= 200 && this.status < 300)
71+
{
72+
resolve(this.response);
73+
}
74+
else
75+
{
76+
reject(new Error(JSON.stringify({
77+
status: this.status,
78+
statusText: this.statusText
79+
})));
80+
}
81+
};
82+
83+
xhr.onerror = function (ev)
84+
{
85+
console.log(ev)
86+
reject(ev.error);
87+
};
88+
89+
xhr.send(JSON.stringify({fromPM: "snakesandmonkeys"}));
90+
})
91+
""")
92+
93+
result_json = json.loads(post_result)
94+
assert result_json["fromPM"] == "snakesandmonkeys"
95+
assert result_json["User-Agent"].startswith("Python/")
96+
httpd.shutdown()
97+
asyncio.run(async_fn())

0 commit comments

Comments
 (0)