Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix XHR Test #437

Merged
merged 6 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 0 additions & 136 deletions tests/js/xhr.simple

This file was deleted.

97 changes: 97 additions & 0 deletions tests/python/test_xhr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,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

Xmader marked this conversation as resolved.
Show resolved Hide resolved
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())
Loading