def test_repeated_key(self): import _pypyjson a = '{"abc": "4", "k": 1, "k": 2}' d = _pypyjson.loads(a) assert d == {u"abc": u"4", u"k": 2} a = '{"abc": "4", "k": 1, "k": 1.5, "c": null, "k": 2}' d = _pypyjson.loads(a) assert d == {u"abc": u"4", u"c": None, u"k": 2}
def test_check_strategy(self): import __pypy__ import _pypyjson d = _pypyjson.loads('{"a": 1}') assert __pypy__.strategy(d) == "JsonDictStrategy" d = _pypyjson.loads('{}') assert __pypy__.strategy(d) == "EmptyDictStrategy"
def test_decode_array(self): import _pypyjson assert _pypyjson.loads('[]') == [] assert _pypyjson.loads('[ ]') == [] assert _pypyjson.loads('[1]') == [1] assert _pypyjson.loads('[1, 2]') == [1, 2] raises(ValueError, "_pypyjson.loads('[1: 2]')") raises(ValueError, "_pypyjson.loads('[1, 2')") raises(ValueError, """_pypyjson.loads('["extra comma",]')""")
def test_decode_object(self): import _pypyjson assert _pypyjson.loads('{}') == {} assert _pypyjson.loads('{ }') == {} # s = '{"hello": "world", "aaa": "bbb"}' assert _pypyjson.loads(s) == {'hello': 'world', 'aaa': 'bbb'} raises(ValueError, _pypyjson.loads, '{"key"') raises(ValueError, _pypyjson.loads, '{"key": 42')
def test_unicode_not_a_surrogate_pair(self): import _pypyjson res = _pypyjson.loads('"z\\ud800\\ud800x"') assert list(res) == [u'z', u'\ud800', u'\ud800', u'x'] res = _pypyjson.loads('"z\\udbff\\uffffx"') assert list(res) == [u'z', u'\udbff', u'\uffff', u'x'] res = _pypyjson.loads('"z\\ud800\\ud834\\udd20x"') assert res == u'z\ud800\U0001d120x' res = _pypyjson.loads('"z\\udc00\\udc00x"') assert list(res) == [u'z', u'\udc00', u'\udc00', u'x']
def test_decode_object(self): import _pypyjson assert _pypyjson.loads("{}") == {} assert _pypyjson.loads("{ }") == {} # s = '{"hello": "world", "aaa": "bbb"}' assert _pypyjson.loads(s) == {"hello": "world", "aaa": "bbb"} raises(ValueError, _pypyjson.loads, '{"key"') raises(ValueError, _pypyjson.loads, '{"key": 42')
def test_keys_reuse(self): import _pypyjson s = '[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]' rval = _pypyjson.loads(s) (a, b), (c, d) = sorted(rval[0]), sorted(rval[1]) assert a is c assert b is d
def active(): rawData = _pypyjson.loads(request.data) my_id = rawData["name"] if my_id in session: response.add(my_id + " is an active player") else: response.add(my_id + " is dead")
def test_iter_keys_value_items(self): import _pypyjson d = _pypyjson.loads('{"a": 1, "b": "x"}') assert list(d.iterkeys()) == [u"a", u"b"] assert list(d.itervalues()) == [1, u"x"] assert list(d.iteritems()) == [(u"a", 1), (u"b", u"x")]
def join(): rawData = _pypyjson.loads(request.data) my_id = rawData["name"] session[my_id] = -1 session["end_game"] = False response.add(my_id + " joined the game") return
def test_huge_map(self): import _pypyjson import __pypy__ s = '{' + ",".join('"%s": %s' % (i, i) for i in range(200)) + '}' res = _pypyjson.loads(s) assert len(res) == 200 assert __pypy__.strategy(res) == "UnicodeDictStrategy"
def test_skip_whitespace(self): import _pypyjson s = ' "hello" ' assert _pypyjson.loads(s) == "hello" s = ' "hello" extra' raises(ValueError, "_pypyjson.loads(s)")
def test_escape_sequence(self): import _pypyjson assert _pypyjson.loads(r'"\\"') == u'\\' assert _pypyjson.loads(r'"\""') == u'"' assert _pypyjson.loads(r'"\/"') == u'/' assert _pypyjson.loads(r'"\b"') == u'\b' assert _pypyjson.loads(r'"\f"') == u'\f' assert _pypyjson.loads(r'"\n"') == u'\n' assert _pypyjson.loads(r'"\r"') == u'\r' assert _pypyjson.loads(r'"\t"') == u'\t'
def commit(): rawData = _pypyjson.loads(request.data) my_id = rawData["name"] my_value = rawData["value"] if my_id in session: session[my_id] = my_value session["end_game"] = False response.add(my_id + " commited to " + my_value) return
def test_dict_order_retained_when_switching_strategies(self): import _pypyjson import __pypy__ d = _pypyjson.loads('{"a": 1, "b": "x"}') assert list(d) == [u"a", u"b"] # devolve assert not 1 in d assert __pypy__.strategy(d) == "UnicodeDictStrategy" assert list(d) == [u"a", u"b"]
def test_delitem(self): import __pypy__ import _pypyjson d = _pypyjson.loads('{"a": 1, "b": "x"}') del d[u"a"] assert __pypy__.strategy(d) == "UnicodeDictStrategy" assert len(d) == 1 assert d == {u"b": "x"}
def test_objdict_bug(self): import _pypyjson a = """{"foo": "bar"}""" d = _pypyjson.loads(a) d['foo'] = 'x' class Obj(object): pass x = Obj() x.__dict__ = d x.foo = 'baz' # used to segfault on pypy3 d = _pypyjson.loads(a) x = Obj() x.__dict__ = d x.foo # used to segfault on pypy3
def test_escape_sequence(self): import _pypyjson assert _pypyjson.loads(r'"\\"') == "\\" assert _pypyjson.loads(r'"\""') == '"' assert _pypyjson.loads(r'"\/"') == "/" assert _pypyjson.loads(r'"\b"') == "\b" assert _pypyjson.loads(r'"\f"') == "\f" assert _pypyjson.loads(r'"\n"') == "\n" assert _pypyjson.loads(r'"\r"') == "\r" assert _pypyjson.loads(r'"\t"') == "\t"
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``s`` (a ``str`` instance containing a JSON document) to a Python object. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN, null, true, false. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. The ``encoding`` argument is ignored and deprecated. """ if (cls is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not kw): return _pypyjson.loads(s) if _pypyjson else _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(**kw).decode(s)
def test_setdefault(self): import __pypy__ import _pypyjson d = _pypyjson.loads('{"a": 1, "b": "x"}') assert d.setdefault(u"a", "blub") == 1 d.setdefault(u"x", 23) assert __pypy__.strategy(d) == "UnicodeDictStrategy" assert len(d) == 3 assert d == {u"a": 1, u"b": "x", u"x": 23}
def test_decode_constants(self): import _pypyjson assert _pypyjson.loads('null') is None raises(ValueError, _pypyjson.loads, 'nul') raises(ValueError, _pypyjson.loads, 'nu') raises(ValueError, _pypyjson.loads, 'n') raises(ValueError, _pypyjson.loads, 'nuXX') # assert _pypyjson.loads('true') is True raises(ValueError, _pypyjson.loads, 'tru') raises(ValueError, _pypyjson.loads, 'tr') raises(ValueError, _pypyjson.loads, 't') raises(ValueError, _pypyjson.loads, 'trXX') # assert _pypyjson.loads('false') is False raises(ValueError, _pypyjson.loads, 'fals') raises(ValueError, _pypyjson.loads, 'fal') raises(ValueError, _pypyjson.loads, 'fa') raises(ValueError, _pypyjson.loads, 'f') raises(ValueError, _pypyjson.loads, 'falXX')
def test_decode_constants(self): import _pypyjson assert _pypyjson.loads("null") is None raises(ValueError, _pypyjson.loads, "nul") raises(ValueError, _pypyjson.loads, "nu") raises(ValueError, _pypyjson.loads, "n") raises(ValueError, _pypyjson.loads, "nuXX") # assert _pypyjson.loads("true") is True raises(ValueError, _pypyjson.loads, "tru") raises(ValueError, _pypyjson.loads, "tr") raises(ValueError, _pypyjson.loads, "t") raises(ValueError, _pypyjson.loads, "trXX") # assert _pypyjson.loads("false") is False raises(ValueError, _pypyjson.loads, "fals") raises(ValueError, _pypyjson.loads, "fal") raises(ValueError, _pypyjson.loads, "fa") raises(ValueError, _pypyjson.loads, "f") raises(ValueError, _pypyjson.loads, "falXX")
def test_bug(self): import _pypyjson a = """ { "top": { "k": "8", "k": "8", "boom": 1 } } """ d = _pypyjson.loads(a) str(d) repr(d)
def reveal(): rawData = _pypyjson.loads(request.data) my_id = rawData["name"] my_opponent = rawData["opponent"] if my_opponent not in session: response.add("Opponent doesnt exist") return if session[my_id] >= session[my_opponent]: response.add("Your value is no less than your opponent") else: response.add("Your value is less than your opponent") return
def test_popitem(self): import __pypy__ import _pypyjson d = _pypyjson.loads('{"a": 1, "b": "x"}') k, v = d.popitem() assert __pypy__.strategy(d) == "UnicodeDictStrategy" if k == u"a": assert v == 1 assert len(d) == 1 assert d == {u"b": "x"} else: assert v == u"x" assert len(d) == 1 assert d == {u"a": 1}
def myMethodB(): global RECENT_KEY print "[i] list handled!" rawData = _pypyjson.loads(request.data) if 'email' in rawData: email = rawData['email'] # queried email if email in session: data = session[email] # return transactions associated with email else: data = [] # not found else: # if no email provided in query, return recent transactions data = session[RECENT_KEY] msg = str(data) print('msg', msg) response.add(msg) # return list return
def test_simple(self): import __pypy__ import _pypyjson d = _pypyjson.loads('{"a": 1, "b": "x"}') assert len(d) == 2 assert d[u"a"] == 1 assert d[u"b"] == u"x" assert u"c" not in d d[u"a"] = 5 assert d[u"a"] == 5 assert __pypy__.strategy(d) == "JsonDictStrategy" # devolve it assert not 1 in d assert __pypy__.strategy(d) == "UnicodeDictStrategy" assert len(d) == 2 assert d[u"a"] == 5 assert d[u"b"] == u"x" assert u"c" not in d
def myMethodA(): global RECENT_KEY global MAX_RECENT print "[i] create handled!" rawData = _pypyjson.loads(request.data) sender = rawData["sender"] if sender not in session: session[sender] = [] session[sender] = [rawData] + session[sender] if RECENT_KEY not in session: session[RECENT_KEY] = [] session[RECENT_KEY] = [rawData] + session[RECENT_KEY] max_len = min(MAX_RECENT, len(session[RECENT_KEY])) session[RECENT_KEY] = session[RECENT_KEY][ 0:max_len] # store up to max_len items # return the added item msg = str(rawData) print('msg', msg) response.add(msg) return
def test_skip_whitespace(self): import _pypyjson s = ' "hello" ' assert _pypyjson.loads(s) == u'hello' s = ' "hello" extra' raises(ValueError, "_pypyjson.loads(s)")
def test_invalid_utf_8(self): import _pypyjson s = '"\xe0"' # this is an invalid UTF8 sequence inside a string assert _pypyjson.loads(s) == "à"
def test_escape_sequence_in_the_middle(self): import _pypyjson s = r'"hello\nworld"' assert _pypyjson.loads(s) == "hello\nworld"
def test_escape_sequence_unicode(self): import _pypyjson s = r'"\u1234"' assert _pypyjson.loads(s) == u'\u1234'
def submit(): rawData = _pypyjson.loads(request.data) my_id = rawData["name"] my_value = rawData["value"] session[my_id] = my_value return
def test_decode_string_utf8(self): import _pypyjson s = u'àèìòù' res = _pypyjson.loads('"%s"' % s.encode('utf-8')) assert res == s
def test_decode_string(self): import _pypyjson res = _pypyjson.loads('"hello"') assert res == u'hello' assert type(res) is unicode
def test_unicode_surrogate_pair(self): import _pypyjson expected = u'z\U0001d120x' res = _pypyjson.loads('"z\\ud834\\udd20x"') assert res == expected
def test_nan(self): import math import _pypyjson res = _pypyjson.loads('NaN') assert math.isnan(res)
def test_surrogate_pair(self): import _pypyjson json = '{"a":"\\uD83D"}' res = _pypyjson.loads(json) assert res == {u'a': u'\ud83d'}
def check(s, val): res = _pypyjson.loads(s) assert type(res) is type(val) assert res == val
def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name must be specified. Encodings that are not ASCII based (such as UCS-2) are not allowed and should be decoded to ``unicode`` first. ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting). ``object_pairs_hook`` is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of ``object_pairs_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, collections.OrderedDict will remember the order of insertion). If ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority. ``parse_float``, if specified, will be called with the string of every JSON float to be decoded. By default this is equivalent to float(num_str). This can be used to use another datatype or parser for JSON floats (e.g. decimal.Decimal). ``parse_int``, if specified, will be called with the string of every JSON int to be decoded. By default this is equivalent to int(num_str). This can be used to use another datatype or parser for JSON integers (e.g. float). ``parse_constant``, if specified, will be called with one of the following strings: -Infinity, Infinity, NaN. This can be used to raise an exception if invalid JSON numbers are encountered. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg; otherwise ``JSONDecoder`` is used. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not kw): if _pypyjson and not isinstance(s, unicode): return _pypyjson.loads(s) else: return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant return cls(encoding=encoding, **kw).decode(s)