Skip to content

Commit

Permalink
Treat number string casting like JavaScript
Browse files Browse the repository at this point in the history
Convert floats to ints before casting to string only if they
are equivalent to a whole number
  • Loading branch information
tw4l committed Apr 2, 2024
1 parent 95d26f2 commit 2aed8af
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
9 changes: 9 additions & 0 deletions pywb/warcserver/inputrequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import base64
import cgi
import json
import math
import sys


Expand Down Expand Up @@ -338,6 +339,14 @@ def _parser(json_obj, name=""):
data[get_key(name)] = "false"
elif json_obj is None:
data[get_key(name)] = "null"
elif isinstance(json_obj, float):
# treat floats like JavaScript does - if it is a round number,
# drop the decimals when casting to string
fraction, _ = math.modf(json_obj)
if fraction == 0.0:
data[get_key(name)] = str(int(json_obj))
else:
data[get_key(name)] = str(json_obj)
else:
data[get_key(name)] = str(json_obj)

Expand Down
4 changes: 2 additions & 2 deletions pywb/warcserver/test/test_inputreq.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ def test_post_extract_json(self):

assert mq.append_query('http://example.com/') == 'http://example.com/?__wb_method=POST&a=b&a.2_=2&d=e&f=true&g=false&g.2_=null'

post_data = b'{"type": "event", "id": 44.0, "values": [true, false, null], "source": {"type": "component", "id": "a+b&c= d", "values": [3, 4]}}'
post_data = b'{"type": "event", "id": 44.0, "float": 35.7, "values": [true, false, null], "source": {"type": "component", "id": "a+b&c= d", "values": [3, 4]}}'
mq = MethodQueryCanonicalizer('POST', 'application/json',
len(post_data), BytesIO(post_data))

assert mq.append_query('http://example.com/events') == 'http://example.com/events?__wb_method=POST&type=event&id=44.0&values=true&values.2_=false&values.3_=null&type.2_=component&id.2_=a%2Bb%26c%3D+d&values.4_=3&values.5_=4'
assert mq.append_query('http://example.com/events') == 'http://example.com/events?__wb_method=POST&type=event&id=44&float=35.7&values=true&values.2_=false&values.3_=null&type.2_=component&id.2_=a%2Bb%26c%3D+d&values.4_=3&values.5_=4'

def test_put_extract_method(self):
mq = MethodQueryCanonicalizer('PUT', 'application/x-www-form-urlencoded',
Expand Down

0 comments on commit 2aed8af

Please sign in to comment.