'
118 | assert t.render() == escaped_out
119 | assert unicode(t.module) == escaped_out
120 | assert escape(t.module) == escaped_out
121 | assert t.module.say_hello('') == escaped_out
122 | assert escape(t.module.say_hello('')) == escaped_out
123 |
124 |
125 | def test_attr_filter(self):
126 | env = SandboxedEnvironment()
127 | tmpl = env.from_string('{{ 42|attr("__class__")|attr("__subclasses__")() }}')
128 | self.assert_raises(SecurityError, tmpl.render)
129 |
130 |
131 | def suite():
132 | suite = unittest.TestSuite()
133 | suite.addTest(unittest.makeSuite(SandboxTestCase))
134 | return suite
135 |
--------------------------------------------------------------------------------
/lib/jinja2/testsuite/tests.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | jinja2.testsuite.tests
4 | ~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | Who tests the tests?
7 |
8 | :copyright: (c) 2010 by the Jinja Team.
9 | :license: BSD, see LICENSE for more details.
10 | """
11 | import unittest
12 | from jinja2.testsuite import JinjaTestCase
13 |
14 | from jinja2 import Markup, Environment
15 |
16 | env = Environment()
17 |
18 |
19 | class TestsTestCase(JinjaTestCase):
20 |
21 | def test_defined(self):
22 | tmpl = env.from_string('{{ missing is defined }}|{{ true is defined }}')
23 | assert tmpl.render() == 'False|True'
24 |
25 | def test_even(self):
26 | tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')
27 | assert tmpl.render() == 'False|True'
28 |
29 | def test_odd(self):
30 | tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')
31 | assert tmpl.render() == 'True|False'
32 |
33 | def test_lower(self):
34 | tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''')
35 | assert tmpl.render() == 'True|False'
36 |
37 | def test_typechecks(self):
38 | tmpl = env.from_string('''
39 | {{ 42 is undefined }}
40 | {{ 42 is defined }}
41 | {{ 42 is none }}
42 | {{ none is none }}
43 | {{ 42 is number }}
44 | {{ 42 is string }}
45 | {{ "foo" is string }}
46 | {{ "foo" is sequence }}
47 | {{ [1] is sequence }}
48 | {{ range is callable }}
49 | {{ 42 is callable }}
50 | {{ range(5) is iterable }}
51 | ''')
52 | assert tmpl.render().split() == [
53 | 'False', 'True', 'False', 'True', 'True', 'False',
54 | 'True', 'True', 'True', 'True', 'False', 'True'
55 | ]
56 |
57 | def test_sequence(self):
58 | tmpl = env.from_string(
59 | '{{ [1, 2, 3] is sequence }}|'
60 | '{{ "foo" is sequence }}|'
61 | '{{ 42 is sequence }}'
62 | )
63 | assert tmpl.render() == 'True|True|False'
64 |
65 | def test_upper(self):
66 | tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')
67 | assert tmpl.render() == 'True|False'
68 |
69 | def test_sameas(self):
70 | tmpl = env.from_string('{{ foo is sameas false }}|'
71 | '{{ 0 is sameas false }}')
72 | assert tmpl.render(foo=False) == 'True|False'
73 |
74 | def test_no_paren_for_arg1(self):
75 | tmpl = env.from_string('{{ foo is sameas none }}')
76 | assert tmpl.render(foo=None) == 'True'
77 |
78 | def test_escaped(self):
79 | env = Environment(autoescape=True)
80 | tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')
81 | assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'
82 |
83 |
84 | def suite():
85 | suite = unittest.TestSuite()
86 | suite.addTest(unittest.makeSuite(TestsTestCase))
87 | return suite
88 |
--------------------------------------------------------------------------------
/lib/jinja2/testsuite/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | jinja2.testsuite.utils
4 | ~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | Tests utilities jinja uses.
7 |
8 | :copyright: (c) 2010 by the Jinja Team.
9 | :license: BSD, see LICENSE for more details.
10 | """
11 | import os
12 | import gc
13 | import unittest
14 |
15 | import pickle
16 |
17 | from jinja2.testsuite import JinjaTestCase
18 |
19 | from jinja2 import Environment, Undefined, DebugUndefined, \
20 | StrictUndefined, UndefinedError, Template, meta
21 | from jinja2.utils import LRUCache, escape, object_type_repr
22 |
23 |
24 | class LRUCacheTestCase(JinjaTestCase):
25 |
26 | def test_simple(self):
27 | d = LRUCache(3)
28 | d["a"] = 1
29 | d["b"] = 2
30 | d["c"] = 3
31 | d["a"]
32 | d["d"] = 4
33 | assert len(d) == 3
34 | assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
35 |
36 | def test_pickleable(self):
37 | cache = LRUCache(2)
38 | cache["foo"] = 42
39 | cache["bar"] = 23
40 | cache["foo"]
41 |
42 | for protocol in range(3):
43 | copy = pickle.loads(pickle.dumps(cache, protocol))
44 | assert copy.capacity == cache.capacity
45 | assert copy._mapping == cache._mapping
46 | assert copy._queue == cache._queue
47 |
48 |
49 | class HelpersTestCase(JinjaTestCase):
50 |
51 | def test_object_type_repr(self):
52 | class X(object):
53 | pass
54 | self.assert_equal(object_type_repr(42), 'int object')
55 | self.assert_equal(object_type_repr([]), 'list object')
56 | self.assert_equal(object_type_repr(X()),
57 | 'jinja2.testsuite.utils.X object')
58 | self.assert_equal(object_type_repr(None), 'None')
59 | self.assert_equal(object_type_repr(Ellipsis), 'Ellipsis')
60 |
61 |
62 | class MarkupLeakTestCase(JinjaTestCase):
63 |
64 | def test_markup_leaks(self):
65 | counts = set()
66 | for count in xrange(20):
67 | for item in xrange(1000):
68 | escape("foo")
69 | escape("")
70 | escape(u"foo")
71 | escape(u"")
72 | counts.add(len(gc.get_objects()))
73 | assert len(counts) == 1, 'ouch, c extension seems to leak objects'
74 |
75 |
76 | def suite():
77 | suite = unittest.TestSuite()
78 | suite.addTest(unittest.makeSuite(LRUCacheTestCase))
79 | suite.addTest(unittest.makeSuite(HelpersTestCase))
80 |
81 | # this test only tests the c extension
82 | if not hasattr(escape, 'func_code'):
83 | suite.addTest(unittest.makeSuite(MarkupLeakTestCase))
84 |
85 | return suite
86 |
--------------------------------------------------------------------------------
/lib/jinja2/visitor.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | jinja2.visitor
4 | ~~~~~~~~~~~~~~
5 |
6 | This module implements a visitor for the nodes.
7 |
8 | :copyright: (c) 2010 by the Jinja Team.
9 | :license: BSD.
10 | """
11 | from jinja2.nodes import Node
12 |
13 |
14 | class NodeVisitor(object):
15 | """Walks the abstract syntax tree and call visitor functions for every
16 | node found. The visitor functions may return values which will be
17 | forwarded by the `visit` method.
18 |
19 | Per default the visitor functions for the nodes are ``'visit_'`` +
20 | class name of the node. So a `TryFinally` node visit function would
21 | be `visit_TryFinally`. This behavior can be changed by overriding
22 | the `get_visitor` function. If no visitor function exists for a node
23 | (return value `None`) the `generic_visit` visitor is used instead.
24 | """
25 |
26 | def get_visitor(self, node):
27 | """Return the visitor function for this node or `None` if no visitor
28 | exists for this node. In that case the generic visit function is
29 | used instead.
30 | """
31 | method = 'visit_' + node.__class__.__name__
32 | return getattr(self, method, None)
33 |
34 | def visit(self, node, *args, **kwargs):
35 | """Visit a node."""
36 | f = self.get_visitor(node)
37 | if f is not None:
38 | return f(node, *args, **kwargs)
39 | return self.generic_visit(node, *args, **kwargs)
40 |
41 | def generic_visit(self, node, *args, **kwargs):
42 | """Called if no explicit visitor function exists for a node."""
43 | for node in node.iter_child_nodes():
44 | self.visit(node, *args, **kwargs)
45 |
46 |
47 | class NodeTransformer(NodeVisitor):
48 | """Walks the abstract syntax tree and allows modifications of nodes.
49 |
50 | The `NodeTransformer` will walk the AST and use the return value of the
51 | visitor functions to replace or remove the old node. If the return
52 | value of the visitor function is `None` the node will be removed
53 | from the previous location otherwise it's replaced with the return
54 | value. The return value may be the original node in which case no
55 | replacement takes place.
56 | """
57 |
58 | def generic_visit(self, node, *args, **kwargs):
59 | for field, old_value in node.iter_fields():
60 | if isinstance(old_value, list):
61 | new_values = []
62 | for value in old_value:
63 | if isinstance(value, Node):
64 | value = self.visit(value, *args, **kwargs)
65 | if value is None:
66 | continue
67 | elif not isinstance(value, Node):
68 | new_values.extend(value)
69 | continue
70 | new_values.append(value)
71 | old_value[:] = new_values
72 | elif isinstance(old_value, Node):
73 | new_node = self.visit(old_value, *args, **kwargs)
74 | if new_node is None:
75 | delattr(node, field)
76 | else:
77 | setattr(node, field, new_node)
78 | return node
79 |
80 | def visit_list(self, node, *args, **kwargs):
81 | """As transformers may return lists in some places this method
82 | can be used to enforce a list as return value.
83 | """
84 | rv = self.visit(node, *args, **kwargs)
85 | if not isinstance(rv, list):
86 | rv = [rv]
87 | return rv
88 |
--------------------------------------------------------------------------------
/lib/simplejson/ordered_dict.py:
--------------------------------------------------------------------------------
1 | """Drop-in replacement for collections.OrderedDict by Raymond Hettinger
2 |
3 | http://code.activestate.com/recipes/576693/
4 |
5 | """
6 | from UserDict import DictMixin
7 |
8 | # Modified from original to support Python 2.4, see
9 | # http://code.google.com/p/simplejson/issues/detail?id=53
10 | try:
11 | all
12 | except NameError:
13 | def all(seq):
14 | for elem in seq:
15 | if not elem:
16 | return False
17 | return True
18 |
19 | class OrderedDict(dict, DictMixin):
20 |
21 | def __init__(self, *args, **kwds):
22 | if len(args) > 1:
23 | raise TypeError('expected at most 1 arguments, got %d' % len(args))
24 | try:
25 | self.__end
26 | except AttributeError:
27 | self.clear()
28 | self.update(*args, **kwds)
29 |
30 | def clear(self):
31 | self.__end = end = []
32 | end += [None, end, end] # sentinel node for doubly linked list
33 | self.__map = {} # key --> [key, prev, next]
34 | dict.clear(self)
35 |
36 | def __setitem__(self, key, value):
37 | if key not in self:
38 | end = self.__end
39 | curr = end[1]
40 | curr[2] = end[1] = self.__map[key] = [key, curr, end]
41 | dict.__setitem__(self, key, value)
42 |
43 | def __delitem__(self, key):
44 | dict.__delitem__(self, key)
45 | key, prev, next = self.__map.pop(key)
46 | prev[2] = next
47 | next[1] = prev
48 |
49 | def __iter__(self):
50 | end = self.__end
51 | curr = end[2]
52 | while curr is not end:
53 | yield curr[0]
54 | curr = curr[2]
55 |
56 | def __reversed__(self):
57 | end = self.__end
58 | curr = end[1]
59 | while curr is not end:
60 | yield curr[0]
61 | curr = curr[1]
62 |
63 | def popitem(self, last=True):
64 | if not self:
65 | raise KeyError('dictionary is empty')
66 | # Modified from original to support Python 2.4, see
67 | # http://code.google.com/p/simplejson/issues/detail?id=53
68 | if last:
69 | key = reversed(self).next()
70 | else:
71 | key = iter(self).next()
72 | value = self.pop(key)
73 | return key, value
74 |
75 | def __reduce__(self):
76 | items = [[k, self[k]] for k in self]
77 | tmp = self.__map, self.__end
78 | del self.__map, self.__end
79 | inst_dict = vars(self).copy()
80 | self.__map, self.__end = tmp
81 | if inst_dict:
82 | return (self.__class__, (items,), inst_dict)
83 | return self.__class__, (items,)
84 |
85 | def keys(self):
86 | return list(self)
87 |
88 | setdefault = DictMixin.setdefault
89 | update = DictMixin.update
90 | pop = DictMixin.pop
91 | values = DictMixin.values
92 | items = DictMixin.items
93 | iterkeys = DictMixin.iterkeys
94 | itervalues = DictMixin.itervalues
95 | iteritems = DictMixin.iteritems
96 |
97 | def __repr__(self):
98 | if not self:
99 | return '%s()' % (self.__class__.__name__,)
100 | return '%s(%r)' % (self.__class__.__name__, self.items())
101 |
102 | def copy(self):
103 | return self.__class__(self)
104 |
105 | @classmethod
106 | def fromkeys(cls, iterable, value=None):
107 | d = cls()
108 | for key in iterable:
109 | d[key] = value
110 | return d
111 |
112 | def __eq__(self, other):
113 | if isinstance(other, OrderedDict):
114 | return len(self)==len(other) and \
115 | all(p==q for p, q in zip(self.items(), other.items()))
116 | return dict.__eq__(self, other)
117 |
118 | def __ne__(self, other):
119 | return not self == other
120 |
--------------------------------------------------------------------------------
/lib/simplejson/scanner.py:
--------------------------------------------------------------------------------
1 | """JSON token scanner
2 | """
3 | import re
4 | def _import_c_make_scanner():
5 | try:
6 | from simplejson._speedups import make_scanner
7 | return make_scanner
8 | except ImportError:
9 | return None
10 | c_make_scanner = _import_c_make_scanner()
11 |
12 | __all__ = ['make_scanner']
13 |
14 | NUMBER_RE = re.compile(
15 | r'(-?(?:0|[1-9]\d*))(\.\d+)?([eE][-+]?\d+)?',
16 | (re.VERBOSE | re.MULTILINE | re.DOTALL))
17 |
18 | def py_make_scanner(context):
19 | parse_object = context.parse_object
20 | parse_array = context.parse_array
21 | parse_string = context.parse_string
22 | match_number = NUMBER_RE.match
23 | encoding = context.encoding
24 | strict = context.strict
25 | parse_float = context.parse_float
26 | parse_int = context.parse_int
27 | parse_constant = context.parse_constant
28 | object_hook = context.object_hook
29 | object_pairs_hook = context.object_pairs_hook
30 | memo = context.memo
31 |
32 | def _scan_once(string, idx):
33 | try:
34 | nextchar = string[idx]
35 | except IndexError:
36 | raise StopIteration
37 |
38 | if nextchar == '"':
39 | return parse_string(string, idx + 1, encoding, strict)
40 | elif nextchar == '{':
41 | return parse_object((string, idx + 1), encoding, strict,
42 | _scan_once, object_hook, object_pairs_hook, memo)
43 | elif nextchar == '[':
44 | return parse_array((string, idx + 1), _scan_once)
45 | elif nextchar == 'n' and string[idx:idx + 4] == 'null':
46 | return None, idx + 4
47 | elif nextchar == 't' and string[idx:idx + 4] == 'true':
48 | return True, idx + 4
49 | elif nextchar == 'f' and string[idx:idx + 5] == 'false':
50 | return False, idx + 5
51 |
52 | m = match_number(string, idx)
53 | if m is not None:
54 | integer, frac, exp = m.groups()
55 | if frac or exp:
56 | res = parse_float(integer + (frac or '') + (exp or ''))
57 | else:
58 | res = parse_int(integer)
59 | return res, m.end()
60 | elif nextchar == 'N' and string[idx:idx + 3] == 'NaN':
61 | return parse_constant('NaN'), idx + 3
62 | elif nextchar == 'I' and string[idx:idx + 8] == 'Infinity':
63 | return parse_constant('Infinity'), idx + 8
64 | elif nextchar == '-' and string[idx:idx + 9] == '-Infinity':
65 | return parse_constant('-Infinity'), idx + 9
66 | else:
67 | raise StopIteration
68 |
69 | def scan_once(string, idx):
70 | try:
71 | return _scan_once(string, idx)
72 | finally:
73 | memo.clear()
74 |
75 | return scan_once
76 |
77 | make_scanner = c_make_scanner or py_make_scanner
78 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/__init__.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import doctest
3 |
4 |
5 | class OptionalExtensionTestSuite(unittest.TestSuite):
6 | def run(self, result):
7 | import simplejson
8 | run = unittest.TestSuite.run
9 | run(self, result)
10 | simplejson._toggle_speedups(False)
11 | run(self, result)
12 | simplejson._toggle_speedups(True)
13 | return result
14 |
15 |
16 | def additional_tests(suite=None):
17 | import simplejson
18 | import simplejson.encoder
19 | import simplejson.decoder
20 | if suite is None:
21 | suite = unittest.TestSuite()
22 | for mod in (simplejson, simplejson.encoder, simplejson.decoder):
23 | suite.addTest(doctest.DocTestSuite(mod))
24 | suite.addTest(doctest.DocFileSuite('../../index.rst'))
25 | return suite
26 |
27 |
28 | def all_tests_suite():
29 | suite = unittest.TestLoader().loadTestsFromNames([
30 | 'simplejson.tests.test_check_circular',
31 | 'simplejson.tests.test_decode',
32 | 'simplejson.tests.test_default',
33 | 'simplejson.tests.test_dump',
34 | 'simplejson.tests.test_encode_basestring_ascii',
35 | 'simplejson.tests.test_encode_for_html',
36 | 'simplejson.tests.test_fail',
37 | 'simplejson.tests.test_float',
38 | 'simplejson.tests.test_indent',
39 | 'simplejson.tests.test_pass1',
40 | 'simplejson.tests.test_pass2',
41 | 'simplejson.tests.test_pass3',
42 | 'simplejson.tests.test_recursion',
43 | 'simplejson.tests.test_scanstring',
44 | 'simplejson.tests.test_separators',
45 | 'simplejson.tests.test_speedups',
46 | 'simplejson.tests.test_unicode',
47 | 'simplejson.tests.test_decimal',
48 | ])
49 | suite = additional_tests(suite)
50 | return OptionalExtensionTestSuite([suite])
51 |
52 |
53 | def main():
54 | runner = unittest.TextTestRunner()
55 | suite = all_tests_suite()
56 | runner.run(suite)
57 |
58 |
59 | if __name__ == '__main__':
60 | import os
61 | import sys
62 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
63 | main()
64 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_check_circular.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | import simplejson as json
3 |
4 | def default_iterable(obj):
5 | return list(obj)
6 |
7 | class TestCheckCircular(TestCase):
8 | def test_circular_dict(self):
9 | dct = {}
10 | dct['a'] = dct
11 | self.assertRaises(ValueError, json.dumps, dct)
12 |
13 | def test_circular_list(self):
14 | lst = []
15 | lst.append(lst)
16 | self.assertRaises(ValueError, json.dumps, lst)
17 |
18 | def test_circular_composite(self):
19 | dct2 = {}
20 | dct2['a'] = []
21 | dct2['a'].append(dct2)
22 | self.assertRaises(ValueError, json.dumps, dct2)
23 |
24 | def test_circular_default(self):
25 | json.dumps([set()], default=default_iterable)
26 | self.assertRaises(TypeError, json.dumps, [set()])
27 |
28 | def test_circular_off_default(self):
29 | json.dumps([set()], default=default_iterable, check_circular=False)
30 | self.assertRaises(TypeError, json.dumps, [set()], check_circular=False)
31 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_decimal.py:
--------------------------------------------------------------------------------
1 | from decimal import Decimal
2 | from unittest import TestCase
3 |
4 | import simplejson as json
5 |
6 | class TestDecimal(TestCase):
7 | NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500"
8 | def test_decimal_encode(self):
9 | for d in map(Decimal, self.NUMS):
10 | self.assertEquals(json.dumps(d, use_decimal=True), str(d))
11 |
12 | def test_decimal_decode(self):
13 | for s in self.NUMS:
14 | self.assertEquals(json.loads(s, parse_float=Decimal), Decimal(s))
15 |
16 | def test_decimal_roundtrip(self):
17 | for d in map(Decimal, self.NUMS):
18 | # The type might not be the same (int and Decimal) but they
19 | # should still compare equal.
20 | self.assertEquals(
21 | json.loads(
22 | json.dumps(d, use_decimal=True), parse_float=Decimal),
23 | d)
24 | self.assertEquals(
25 | json.loads(
26 | json.dumps([d], use_decimal=True), parse_float=Decimal),
27 | [d])
28 |
29 | def test_decimal_defaults(self):
30 | d = Decimal(1)
31 | # use_decimal=False is the default
32 | self.assertRaises(TypeError, json.dumps, d, use_decimal=False)
33 | self.assertRaises(TypeError, json.dumps, d)
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_decode.py:
--------------------------------------------------------------------------------
1 | import decimal
2 | from unittest import TestCase
3 | from StringIO import StringIO
4 |
5 | import simplejson as json
6 | from simplejson import OrderedDict
7 |
8 | class TestDecode(TestCase):
9 | if not hasattr(TestCase, 'assertIs'):
10 | def assertIs(self, a, b):
11 | self.assertTrue(a is b, '%r is %r' % (a, b))
12 |
13 | def test_decimal(self):
14 | rval = json.loads('1.1', parse_float=decimal.Decimal)
15 | self.assertTrue(isinstance(rval, decimal.Decimal))
16 | self.assertEquals(rval, decimal.Decimal('1.1'))
17 |
18 | def test_float(self):
19 | rval = json.loads('1', parse_int=float)
20 | self.assertTrue(isinstance(rval, float))
21 | self.assertEquals(rval, 1.0)
22 |
23 | def test_decoder_optimizations(self):
24 | # Several optimizations were made that skip over calls to
25 | # the whitespace regex, so this test is designed to try and
26 | # exercise the uncommon cases. The array cases are already covered.
27 | rval = json.loads('{ "key" : "value" , "k":"v" }')
28 | self.assertEquals(rval, {"key":"value", "k":"v"})
29 |
30 | def test_empty_objects(self):
31 | s = '{}'
32 | self.assertEqual(json.loads(s), eval(s))
33 | s = '[]'
34 | self.assertEqual(json.loads(s), eval(s))
35 | s = '""'
36 | self.assertEqual(json.loads(s), eval(s))
37 |
38 | def test_object_pairs_hook(self):
39 | s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
40 | p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4),
41 | ("qrt", 5), ("pad", 6), ("hoy", 7)]
42 | self.assertEqual(json.loads(s), eval(s))
43 | self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
44 | self.assertEqual(json.load(StringIO(s),
45 | object_pairs_hook=lambda x: x), p)
46 | od = json.loads(s, object_pairs_hook=OrderedDict)
47 | self.assertEqual(od, OrderedDict(p))
48 | self.assertEqual(type(od), OrderedDict)
49 | # the object_pairs_hook takes priority over the object_hook
50 | self.assertEqual(json.loads(s,
51 | object_pairs_hook=OrderedDict,
52 | object_hook=lambda x: None),
53 | OrderedDict(p))
54 |
55 | def check_keys_reuse(self, source, loads):
56 | rval = loads(source)
57 | (a, b), (c, d) = sorted(rval[0]), sorted(rval[1])
58 | self.assertIs(a, c)
59 | self.assertIs(b, d)
60 |
61 | def test_keys_reuse_str(self):
62 | s = u'[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]'.encode('utf8')
63 | self.check_keys_reuse(s, json.loads)
64 |
65 | def test_keys_reuse_unicode(self):
66 | s = u'[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]'
67 | self.check_keys_reuse(s, json.loads)
68 |
69 | def test_empty_strings(self):
70 | self.assertEqual(json.loads('""'), "")
71 | self.assertEqual(json.loads(u'""'), u"")
72 | self.assertEqual(json.loads('[""]'), [""])
73 | self.assertEqual(json.loads(u'[""]'), [u""])
74 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_default.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | class TestDefault(TestCase):
6 | def test_default(self):
7 | self.assertEquals(
8 | json.dumps(type, default=repr),
9 | json.dumps(repr(type)))
10 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_dump.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from cStringIO import StringIO
3 |
4 | import simplejson as json
5 |
6 | class TestDump(TestCase):
7 | def test_dump(self):
8 | sio = StringIO()
9 | json.dump({}, sio)
10 | self.assertEquals(sio.getvalue(), '{}')
11 |
12 | def test_dumps(self):
13 | self.assertEquals(json.dumps({}), '{}')
14 |
15 | def test_encode_truefalse(self):
16 | self.assertEquals(json.dumps(
17 | {True: False, False: True}, sort_keys=True),
18 | '{"false": true, "true": false}')
19 | self.assertEquals(json.dumps(
20 | {2: 3.0, 4.0: 5L, False: 1, 6L: True, "7": 0}, sort_keys=True),
21 | '{"false": 1, "2": 3.0, "4.0": 5, "6": true, "7": 0}')
22 |
23 | def test_ordered_dict(self):
24 | # http://bugs.python.org/issue6105
25 | items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
26 | s = json.dumps(json.OrderedDict(items))
27 | self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}')
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_encode_basestring_ascii.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson.encoder
4 |
5 | CASES = [
6 | (u'/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'),
7 | (u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'),
8 | (u'controls', '"controls"'),
9 | (u'\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'),
10 | (u'{"object with 1 member":["array with 1 element"]}', '"{\\"object with 1 member\\":[\\"array with 1 element\\"]}"'),
11 | (u' s p a c e d ', '" s p a c e d "'),
12 | (u'\U0001d120', '"\\ud834\\udd20"'),
13 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'),
14 | ('\xce\xb1\xce\xa9', '"\\u03b1\\u03a9"'),
15 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'),
16 | ('\xce\xb1\xce\xa9', '"\\u03b1\\u03a9"'),
17 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'),
18 | (u'\u03b1\u03a9', '"\\u03b1\\u03a9"'),
19 | (u"`1~!@#$%^&*()_+-={':[,]}|;.>?", '"`1~!@#$%^&*()_+-={\':[,]}|;.>?"'),
20 | (u'\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'),
21 | (u'\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'),
22 | ]
23 |
24 | class TestEncodeBaseStringAscii(TestCase):
25 | def test_py_encode_basestring_ascii(self):
26 | self._test_encode_basestring_ascii(simplejson.encoder.py_encode_basestring_ascii)
27 |
28 | def test_c_encode_basestring_ascii(self):
29 | if not simplejson.encoder.c_encode_basestring_ascii:
30 | return
31 | self._test_encode_basestring_ascii(simplejson.encoder.c_encode_basestring_ascii)
32 |
33 | def _test_encode_basestring_ascii(self, encode_basestring_ascii):
34 | fname = encode_basestring_ascii.__name__
35 | for input_string, expect in CASES:
36 | result = encode_basestring_ascii(input_string)
37 | #self.assertEquals(result, expect,
38 | # '{0!r} != {1!r} for {2}({3!r})'.format(
39 | # result, expect, fname, input_string))
40 | self.assertEquals(result, expect,
41 | '%r != %r for %s(%r)' % (result, expect, fname, input_string))
42 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_encode_for_html.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | import simplejson.decoder
4 | import simplejson.encoder
5 |
6 |
7 | class TestEncodeForHTML(unittest.TestCase):
8 |
9 | def setUp(self):
10 | self.decoder = simplejson.decoder.JSONDecoder()
11 | self.encoder = simplejson.encoder.JSONEncoderForHTML()
12 |
13 | def test_basic_encode(self):
14 | self.assertEqual(r'"\u0026"', self.encoder.encode('&'))
15 | self.assertEqual(r'"\u003c"', self.encoder.encode('<'))
16 | self.assertEqual(r'"\u003e"', self.encoder.encode('>'))
17 |
18 | def test_basic_roundtrip(self):
19 | for char in '&<>':
20 | self.assertEqual(
21 | char, self.decoder.decode(
22 | self.encoder.encode(char)))
23 |
24 | def test_prevent_script_breakout(self):
25 | bad_string = ''
26 | self.assertEqual(
27 | r'"\u003c/script\u003e\u003cscript\u003e'
28 | r'alert(\"gotcha\")\u003c/script\u003e"',
29 | self.encoder.encode(bad_string))
30 | self.assertEqual(
31 | bad_string, self.decoder.decode(
32 | self.encoder.encode(bad_string)))
33 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_fail.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | # Fri Dec 30 18:57:26 2005
6 | JSONDOCS = [
7 | # http://json.org/JSON_checker/test/fail1.json
8 | '"A JSON payload should be an object or array, not a string."',
9 | # http://json.org/JSON_checker/test/fail2.json
10 | '["Unclosed array"',
11 | # http://json.org/JSON_checker/test/fail3.json
12 | '{unquoted_key: "keys must be quoted}',
13 | # http://json.org/JSON_checker/test/fail4.json
14 | '["extra comma",]',
15 | # http://json.org/JSON_checker/test/fail5.json
16 | '["double extra comma",,]',
17 | # http://json.org/JSON_checker/test/fail6.json
18 | '[ , "<-- missing value"]',
19 | # http://json.org/JSON_checker/test/fail7.json
20 | '["Comma after the close"],',
21 | # http://json.org/JSON_checker/test/fail8.json
22 | '["Extra close"]]',
23 | # http://json.org/JSON_checker/test/fail9.json
24 | '{"Extra comma": true,}',
25 | # http://json.org/JSON_checker/test/fail10.json
26 | '{"Extra value after close": true} "misplaced quoted value"',
27 | # http://json.org/JSON_checker/test/fail11.json
28 | '{"Illegal expression": 1 + 2}',
29 | # http://json.org/JSON_checker/test/fail12.json
30 | '{"Illegal invocation": alert()}',
31 | # http://json.org/JSON_checker/test/fail13.json
32 | '{"Numbers cannot have leading zeroes": 013}',
33 | # http://json.org/JSON_checker/test/fail14.json
34 | '{"Numbers cannot be hex": 0x14}',
35 | # http://json.org/JSON_checker/test/fail15.json
36 | '["Illegal backslash escape: \\x15"]',
37 | # http://json.org/JSON_checker/test/fail16.json
38 | '["Illegal backslash escape: \\\'"]',
39 | # http://json.org/JSON_checker/test/fail17.json
40 | '["Illegal backslash escape: \\017"]',
41 | # http://json.org/JSON_checker/test/fail18.json
42 | '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]',
43 | # http://json.org/JSON_checker/test/fail19.json
44 | '{"Missing colon" null}',
45 | # http://json.org/JSON_checker/test/fail20.json
46 | '{"Double colon":: null}',
47 | # http://json.org/JSON_checker/test/fail21.json
48 | '{"Comma instead of colon", null}',
49 | # http://json.org/JSON_checker/test/fail22.json
50 | '["Colon instead of comma": false]',
51 | # http://json.org/JSON_checker/test/fail23.json
52 | '["Bad value", truth]',
53 | # http://json.org/JSON_checker/test/fail24.json
54 | "['single quote']",
55 | # http://code.google.com/p/simplejson/issues/detail?id=3
56 | u'["A\u001FZ control characters in string"]',
57 | ]
58 |
59 | SKIPS = {
60 | 1: "why not have a string payload?",
61 | 18: "spec doesn't specify any nesting limitations",
62 | }
63 |
64 | class TestFail(TestCase):
65 | def test_failures(self):
66 | for idx, doc in enumerate(JSONDOCS):
67 | idx = idx + 1
68 | if idx in SKIPS:
69 | json.loads(doc)
70 | continue
71 | try:
72 | json.loads(doc)
73 | except json.JSONDecodeError:
74 | pass
75 | else:
76 | #self.fail("Expected failure for fail{0}.json: {1!r}".format(idx, doc))
77 | self.fail("Expected failure for fail%d.json: %r" % (idx, doc))
78 |
79 | def test_array_decoder_issue46(self):
80 | # http://code.google.com/p/simplejson/issues/detail?id=46
81 | for doc in [u'[,]', '[,]']:
82 | try:
83 | json.loads(doc)
84 | except json.JSONDecodeError, e:
85 | self.assertEquals(e.pos, 1)
86 | self.assertEquals(e.lineno, 1)
87 | self.assertEquals(e.colno, 1)
88 | except Exception, e:
89 | self.fail("Unexpected exception raised %r %s" % (e, e))
90 | else:
91 | self.fail("Unexpected success parsing '[,]'")
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_float.py:
--------------------------------------------------------------------------------
1 | import math
2 | from unittest import TestCase
3 |
4 | import simplejson as json
5 |
6 | class TestFloat(TestCase):
7 | def test_floats(self):
8 | for num in [1617161771.7650001, math.pi, math.pi**100,
9 | math.pi**-100, 3.1]:
10 | self.assertEquals(float(json.dumps(num)), num)
11 | self.assertEquals(json.loads(json.dumps(num)), num)
12 | self.assertEquals(json.loads(unicode(json.dumps(num))), num)
13 |
14 | def test_ints(self):
15 | for num in [1, 1L, 1<<32, 1<<64]:
16 | self.assertEquals(json.dumps(num), str(num))
17 | self.assertEquals(int(json.dumps(num)), num)
18 | self.assertEquals(json.loads(json.dumps(num)), num)
19 | self.assertEquals(json.loads(unicode(json.dumps(num))), num)
20 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_indent.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 | import textwrap
5 |
6 | class TestIndent(TestCase):
7 | def test_indent(self):
8 | h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh',
9 | 'i-vhbjkhnth',
10 | {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
11 |
12 | expect = textwrap.dedent("""\
13 | [
14 | \t[
15 | \t\t"blorpie"
16 | \t],
17 | \t[
18 | \t\t"whoops"
19 | \t],
20 | \t[],
21 | \t"d-shtaeou",
22 | \t"d-nthiouh",
23 | \t"i-vhbjkhnth",
24 | \t{
25 | \t\t"nifty": 87
26 | \t},
27 | \t{
28 | \t\t"field": "yes",
29 | \t\t"morefield": false
30 | \t}
31 | ]""")
32 |
33 |
34 | d1 = json.dumps(h)
35 | d2 = json.dumps(h, indent='\t', sort_keys=True, separators=(',', ': '))
36 | d3 = json.dumps(h, indent=' ', sort_keys=True, separators=(',', ': '))
37 | d4 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))
38 |
39 | h1 = json.loads(d1)
40 | h2 = json.loads(d2)
41 | h3 = json.loads(d3)
42 | h4 = json.loads(d4)
43 |
44 | self.assertEquals(h1, h)
45 | self.assertEquals(h2, h)
46 | self.assertEquals(h3, h)
47 | self.assertEquals(h4, h)
48 | self.assertEquals(d3, expect.replace('\t', ' '))
49 | self.assertEquals(d4, expect.replace('\t', ' '))
50 | # NOTE: Python 2.4 textwrap.dedent converts tabs to spaces,
51 | # so the following is expected to fail. Python 2.4 is not a
52 | # supported platform in simplejson 2.1.0+.
53 | self.assertEquals(d2, expect)
54 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_pass1.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | # from http://json.org/JSON_checker/test/pass1.json
6 | JSON = r'''
7 | [
8 | "JSON Test Pattern pass1",
9 | {"object with 1 member":["array with 1 element"]},
10 | {},
11 | [],
12 | -42,
13 | true,
14 | false,
15 | null,
16 | {
17 | "integer": 1234567890,
18 | "real": -9876.543210,
19 | "e": 0.123456789e-12,
20 | "E": 1.234567890E+34,
21 | "": 23456789012E666,
22 | "zero": 0,
23 | "one": 1,
24 | "space": " ",
25 | "quote": "\"",
26 | "backslash": "\\",
27 | "controls": "\b\f\n\r\t",
28 | "slash": "/ & \/",
29 | "alpha": "abcdefghijklmnopqrstuvwyz",
30 | "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
31 | "digit": "0123456789",
32 | "special": "`1~!@#$%^&*()_+-={':[,]}|;.>?",
33 | "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
34 | "true": true,
35 | "false": false,
36 | "null": null,
37 | "array":[ ],
38 | "object":{ },
39 | "address": "50 St. James Street",
40 | "url": "http://www.JSON.org/",
41 | "comment": "// /* */": " ",
43 | " s p a c e d " :[1,2 , 3
44 |
45 | ,
46 |
47 | 4 , 5 , 6 ,7 ],
48 | "compact": [1,2,3,4,5,6,7],
49 | "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
50 | "quotes": "" \u0022 %22 0x22 034 "",
51 | "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
52 | : "A key can be any string"
53 | },
54 | 0.5 ,98.6
55 | ,
56 | 99.44
57 | ,
58 |
59 | 1066
60 |
61 |
62 | ,"rosebud"]
63 | '''
64 |
65 | class TestPass1(TestCase):
66 | def test_parse(self):
67 | # test in/out equivalence and parsing
68 | res = json.loads(JSON)
69 | out = json.dumps(res)
70 | self.assertEquals(res, json.loads(out))
71 | try:
72 | json.dumps(res, allow_nan=False)
73 | except ValueError:
74 | pass
75 | else:
76 | self.fail("23456789012E666 should be out of range")
77 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_pass2.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | import simplejson as json
3 |
4 | # from http://json.org/JSON_checker/test/pass2.json
5 | JSON = r'''
6 | [[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]]
7 | '''
8 |
9 | class TestPass2(TestCase):
10 | def test_parse(self):
11 | # test in/out equivalence and parsing
12 | res = json.loads(JSON)
13 | out = json.dumps(res)
14 | self.assertEquals(res, json.loads(out))
15 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_pass3.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | # from http://json.org/JSON_checker/test/pass3.json
6 | JSON = r'''
7 | {
8 | "JSON Test Pattern pass3": {
9 | "The outermost value": "must be an object or array.",
10 | "In this test": "It is an object."
11 | }
12 | }
13 | '''
14 |
15 | class TestPass3(TestCase):
16 | def test_parse(self):
17 | # test in/out equivalence and parsing
18 | res = json.loads(JSON)
19 | out = json.dumps(res)
20 | self.assertEquals(res, json.loads(out))
21 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_recursion.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | class JSONTestObject:
6 | pass
7 |
8 |
9 | class RecursiveJSONEncoder(json.JSONEncoder):
10 | recurse = False
11 | def default(self, o):
12 | if o is JSONTestObject:
13 | if self.recurse:
14 | return [JSONTestObject]
15 | else:
16 | return 'JSONTestObject'
17 | return json.JSONEncoder.default(o)
18 |
19 |
20 | class TestRecursion(TestCase):
21 | def test_listrecursion(self):
22 | x = []
23 | x.append(x)
24 | try:
25 | json.dumps(x)
26 | except ValueError:
27 | pass
28 | else:
29 | self.fail("didn't raise ValueError on list recursion")
30 | x = []
31 | y = [x]
32 | x.append(y)
33 | try:
34 | json.dumps(x)
35 | except ValueError:
36 | pass
37 | else:
38 | self.fail("didn't raise ValueError on alternating list recursion")
39 | y = []
40 | x = [y, y]
41 | # ensure that the marker is cleared
42 | json.dumps(x)
43 |
44 | def test_dictrecursion(self):
45 | x = {}
46 | x["test"] = x
47 | try:
48 | json.dumps(x)
49 | except ValueError:
50 | pass
51 | else:
52 | self.fail("didn't raise ValueError on dict recursion")
53 | x = {}
54 | y = {"a": x, "b": x}
55 | # ensure that the marker is cleared
56 | json.dumps(x)
57 |
58 | def test_defaultrecursion(self):
59 | enc = RecursiveJSONEncoder()
60 | self.assertEquals(enc.encode(JSONTestObject), '"JSONTestObject"')
61 | enc.recurse = True
62 | try:
63 | enc.encode(JSONTestObject)
64 | except ValueError:
65 | pass
66 | else:
67 | self.fail("didn't raise ValueError on default recursion")
68 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_scanstring.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from unittest import TestCase
3 |
4 | import simplejson as json
5 | import simplejson.decoder
6 |
7 | class TestScanString(TestCase):
8 | def test_py_scanstring(self):
9 | self._test_scanstring(simplejson.decoder.py_scanstring)
10 |
11 | def test_c_scanstring(self):
12 | if not simplejson.decoder.c_scanstring:
13 | return
14 | self._test_scanstring(simplejson.decoder.c_scanstring)
15 |
16 | def _test_scanstring(self, scanstring):
17 | self.assertEquals(
18 | scanstring('"z\\ud834\\udd20x"', 1, None, True),
19 | (u'z\U0001d120x', 16))
20 |
21 | if sys.maxunicode == 65535:
22 | self.assertEquals(
23 | scanstring(u'"z\U0001d120x"', 1, None, True),
24 | (u'z\U0001d120x', 6))
25 | else:
26 | self.assertEquals(
27 | scanstring(u'"z\U0001d120x"', 1, None, True),
28 | (u'z\U0001d120x', 5))
29 |
30 | self.assertEquals(
31 | scanstring('"\\u007b"', 1, None, True),
32 | (u'{', 8))
33 |
34 | self.assertEquals(
35 | scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True),
36 | (u'A JSON payload should be an object or array, not a string.', 60))
37 |
38 | self.assertEquals(
39 | scanstring('["Unclosed array"', 2, None, True),
40 | (u'Unclosed array', 17))
41 |
42 | self.assertEquals(
43 | scanstring('["extra comma",]', 2, None, True),
44 | (u'extra comma', 14))
45 |
46 | self.assertEquals(
47 | scanstring('["double extra comma",,]', 2, None, True),
48 | (u'double extra comma', 21))
49 |
50 | self.assertEquals(
51 | scanstring('["Comma after the close"],', 2, None, True),
52 | (u'Comma after the close', 24))
53 |
54 | self.assertEquals(
55 | scanstring('["Extra close"]]', 2, None, True),
56 | (u'Extra close', 14))
57 |
58 | self.assertEquals(
59 | scanstring('{"Extra comma": true,}', 2, None, True),
60 | (u'Extra comma', 14))
61 |
62 | self.assertEquals(
63 | scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True),
64 | (u'Extra value after close', 26))
65 |
66 | self.assertEquals(
67 | scanstring('{"Illegal expression": 1 + 2}', 2, None, True),
68 | (u'Illegal expression', 21))
69 |
70 | self.assertEquals(
71 | scanstring('{"Illegal invocation": alert()}', 2, None, True),
72 | (u'Illegal invocation', 21))
73 |
74 | self.assertEquals(
75 | scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True),
76 | (u'Numbers cannot have leading zeroes', 37))
77 |
78 | self.assertEquals(
79 | scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True),
80 | (u'Numbers cannot be hex', 24))
81 |
82 | self.assertEquals(
83 | scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True),
84 | (u'Too deep', 30))
85 |
86 | self.assertEquals(
87 | scanstring('{"Missing colon" null}', 2, None, True),
88 | (u'Missing colon', 16))
89 |
90 | self.assertEquals(
91 | scanstring('{"Double colon":: null}', 2, None, True),
92 | (u'Double colon', 15))
93 |
94 | self.assertEquals(
95 | scanstring('{"Comma instead of colon", null}', 2, None, True),
96 | (u'Comma instead of colon', 25))
97 |
98 | self.assertEquals(
99 | scanstring('["Colon instead of comma": false]', 2, None, True),
100 | (u'Colon instead of comma', 25))
101 |
102 | self.assertEquals(
103 | scanstring('["Bad value", truth]', 2, None, True),
104 | (u'Bad value', 12))
105 |
106 | def test_issue3623(self):
107 | self.assertRaises(ValueError, json.decoder.scanstring, "xxx", 1,
108 | "xxx")
109 | self.assertRaises(UnicodeDecodeError,
110 | json.encoder.encode_basestring_ascii, "xx\xff")
111 |
112 | def test_overflow(self):
113 | # Python 2.5 does not have maxsize
114 | maxsize = getattr(sys, 'maxsize', sys.maxint)
115 | self.assertRaises(OverflowError, json.decoder.scanstring, "xxx",
116 | maxsize + 1)
117 |
118 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_separators.py:
--------------------------------------------------------------------------------
1 | import textwrap
2 | from unittest import TestCase
3 |
4 | import simplejson as json
5 |
6 |
7 | class TestSeparators(TestCase):
8 | def test_separators(self):
9 | h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
10 | {'nifty': 87}, {'field': 'yes', 'morefield': False} ]
11 |
12 | expect = textwrap.dedent("""\
13 | [
14 | [
15 | "blorpie"
16 | ] ,
17 | [
18 | "whoops"
19 | ] ,
20 | [] ,
21 | "d-shtaeou" ,
22 | "d-nthiouh" ,
23 | "i-vhbjkhnth" ,
24 | {
25 | "nifty" : 87
26 | } ,
27 | {
28 | "field" : "yes" ,
29 | "morefield" : false
30 | }
31 | ]""")
32 |
33 |
34 | d1 = json.dumps(h)
35 | d2 = json.dumps(h, indent=' ', sort_keys=True, separators=(' ,', ' : '))
36 |
37 | h1 = json.loads(d1)
38 | h2 = json.loads(d2)
39 |
40 | self.assertEquals(h1, h)
41 | self.assertEquals(h2, h)
42 | self.assertEquals(d2, expect)
43 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_speedups.py:
--------------------------------------------------------------------------------
1 | import decimal
2 | from unittest import TestCase
3 |
4 | from simplejson import decoder, encoder, scanner
5 |
6 | def has_speedups():
7 | return encoder.c_make_encoder is not None
8 |
9 | class TestDecode(TestCase):
10 | def test_make_scanner(self):
11 | if not has_speedups():
12 | return
13 | self.assertRaises(AttributeError, scanner.c_make_scanner, 1)
14 |
15 | def test_make_encoder(self):
16 | if not has_speedups():
17 | return
18 | self.assertRaises(TypeError, encoder.c_make_encoder,
19 | None,
20 | "\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75",
21 | None)
22 |
--------------------------------------------------------------------------------
/lib/simplejson/tests/test_unicode.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | import simplejson as json
4 |
5 | class TestUnicode(TestCase):
6 | def test_encoding1(self):
7 | encoder = json.JSONEncoder(encoding='utf-8')
8 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
9 | s = u.encode('utf-8')
10 | ju = encoder.encode(u)
11 | js = encoder.encode(s)
12 | self.assertEquals(ju, js)
13 |
14 | def test_encoding2(self):
15 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
16 | s = u.encode('utf-8')
17 | ju = json.dumps(u, encoding='utf-8')
18 | js = json.dumps(s, encoding='utf-8')
19 | self.assertEquals(ju, js)
20 |
21 | def test_encoding3(self):
22 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
23 | j = json.dumps(u)
24 | self.assertEquals(j, '"\\u03b1\\u03a9"')
25 |
26 | def test_encoding4(self):
27 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
28 | j = json.dumps([u])
29 | self.assertEquals(j, '["\\u03b1\\u03a9"]')
30 |
31 | def test_encoding5(self):
32 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
33 | j = json.dumps(u, ensure_ascii=False)
34 | self.assertEquals(j, u'"' + u + u'"')
35 |
36 | def test_encoding6(self):
37 | u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
38 | j = json.dumps([u], ensure_ascii=False)
39 | self.assertEquals(j, u'["' + u + u'"]')
40 |
41 | def test_big_unicode_encode(self):
42 | u = u'\U0001d120'
43 | self.assertEquals(json.dumps(u), '"\\ud834\\udd20"')
44 | self.assertEquals(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')
45 |
46 | def test_big_unicode_decode(self):
47 | u = u'z\U0001d120x'
48 | self.assertEquals(json.loads('"' + u + '"'), u)
49 | self.assertEquals(json.loads('"z\\ud834\\udd20x"'), u)
50 |
51 | def test_unicode_decode(self):
52 | for i in range(0, 0xd7ff):
53 | u = unichr(i)
54 | #s = '"\\u{0:04x}"'.format(i)
55 | s = '"\\u%04x"' % (i,)
56 | self.assertEquals(json.loads(s), u)
57 |
58 | def test_object_pairs_hook_with_unicode(self):
59 | s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
60 | p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4),
61 | (u"qrt", 5), (u"pad", 6), (u"hoy", 7)]
62 | self.assertEqual(json.loads(s), eval(s))
63 | self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
64 | od = json.loads(s, object_pairs_hook=json.OrderedDict)
65 | self.assertEqual(od, json.OrderedDict(p))
66 | self.assertEqual(type(od), json.OrderedDict)
67 | # the object_pairs_hook takes priority over the object_hook
68 | self.assertEqual(json.loads(s,
69 | object_pairs_hook=json.OrderedDict,
70 | object_hook=lambda x: None),
71 | json.OrderedDict(p))
72 |
73 |
74 | def test_default_encoding(self):
75 | self.assertEquals(json.loads(u'{"a": "\xe9"}'.encode('utf-8')),
76 | {'a': u'\xe9'})
77 |
78 | def test_unicode_preservation(self):
79 | self.assertEquals(type(json.loads(u'""')), unicode)
80 | self.assertEquals(type(json.loads(u'"a"')), unicode)
81 | self.assertEquals(type(json.loads(u'["a"]')[0]), unicode)
82 |
83 | def test_ensure_ascii_false_returns_unicode(self):
84 | # http://code.google.com/p/simplejson/issues/detail?id=48
85 | self.assertEquals(type(json.dumps([], ensure_ascii=False)), unicode)
86 | self.assertEquals(type(json.dumps(0, ensure_ascii=False)), unicode)
87 | self.assertEquals(type(json.dumps({}, ensure_ascii=False)), unicode)
88 | self.assertEquals(type(json.dumps("", ensure_ascii=False)), unicode)
89 |
90 | def test_ensure_ascii_false_bytestring_encoding(self):
91 | # http://code.google.com/p/simplejson/issues/detail?id=48
92 | doc1 = {u'quux': 'Arr\xc3\xaat sur images'}
93 | doc2 = {u'quux': u'Arr\xeat sur images'}
94 | doc_ascii = '{"quux": "Arr\\u00eat sur images"}'
95 | doc_unicode = u'{"quux": "Arr\xeat sur images"}'
96 | self.assertEquals(json.dumps(doc1), doc_ascii)
97 | self.assertEquals(json.dumps(doc2), doc_ascii)
98 | self.assertEquals(json.dumps(doc1, ensure_ascii=False), doc_unicode)
99 | self.assertEquals(json.dumps(doc2, ensure_ascii=False), doc_unicode)
100 |
--------------------------------------------------------------------------------
/lib/simplejson/tool.py:
--------------------------------------------------------------------------------
1 | r"""Command-line tool to validate and pretty-print JSON
2 |
3 | Usage::
4 |
5 | $ echo '{"json":"obj"}' | python -m simplejson.tool
6 | {
7 | "json": "obj"
8 | }
9 | $ echo '{ 1.2:3.4}' | python -m simplejson.tool
10 | Expecting property name: line 1 column 2 (char 2)
11 |
12 | """
13 | import sys
14 | import simplejson as json
15 |
16 | def main():
17 | if len(sys.argv) == 1:
18 | infile = sys.stdin
19 | outfile = sys.stdout
20 | elif len(sys.argv) == 2:
21 | infile = open(sys.argv[1], 'rb')
22 | outfile = sys.stdout
23 | elif len(sys.argv) == 3:
24 | infile = open(sys.argv[1], 'rb')
25 | outfile = open(sys.argv[2], 'wb')
26 | else:
27 | raise SystemExit(sys.argv[0] + " [infile [outfile]]")
28 | try:
29 | obj = json.load(infile,
30 | object_pairs_hook=json.OrderedDict,
31 | use_decimal=True)
32 | except ValueError, e:
33 | raise SystemExit(e)
34 | json.dump(obj, outfile, sort_keys=True, indent=' ', use_decimal=True)
35 | outfile.write('\n')
36 |
37 |
38 | if __name__ == '__main__':
39 | main()
40 |
--------------------------------------------------------------------------------
/lib/werkzeug/contrib/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib
4 | ~~~~~~~~~~~~~~~~
5 |
6 | Contains user-submitted code that other users may find useful, but which
7 | is not part of the Werkzeug core. Anyone can write code for inclusion in
8 | the `contrib` package. All modules in this package are distributed as an
9 | add-on library and thus are not part of Werkzeug itself.
10 |
11 | This file itself is mostly for informational purposes and to tell the
12 | Python interpreter that `contrib` is a package.
13 |
14 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
15 | :license: BSD, see LICENSE for more details.
16 | """
17 |
--------------------------------------------------------------------------------
/lib/werkzeug/contrib/limiter.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib.limiter
4 | ~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | A middleware that limits incoming data. This works around problems with
7 | Trac_ or Django_ because those directly stream into the memory.
8 |
9 | .. _Trac: http://trac.edgewall.org/
10 | .. _Django: http://www.djangoproject.com/
11 |
12 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
13 | :license: BSD, see LICENSE for more details.
14 | """
15 | from warnings import warn
16 |
17 | from werkzeug import LimitedStream
18 |
19 |
20 | class StreamLimitMiddleware(object):
21 | """Limits the input stream to a given number of bytes. This is useful if
22 | you have a WSGI application that reads form data into memory (django for
23 | example) and you don't want users to harm the server by uploading tons of
24 | data.
25 |
26 | Default is 10MB
27 | """
28 |
29 | def __init__(self, app, maximum_size=1024 * 1024 * 10):
30 | self.app = app
31 | self.maximum_size = maximum_size
32 |
33 | def __call__(self, environ, start_response):
34 | limit = min(limit, int(environ.get('CONTENT_LENGTH') or 0))
35 | environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit)
36 | return self.app(environ, start_response)
37 |
--------------------------------------------------------------------------------
/lib/werkzeug/contrib/profiler.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib.profiler
4 | ~~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | This module provides a simple WSGI profiler middleware for finding
7 | bottlenecks in web application. It uses the :mod:`profile` or
8 | :mod:`cProfile` module to do the profiling and writes the stats to the
9 | stream provided (defaults to stderr).
10 |
11 | Example usage::
12 |
13 | from werkzeug.contrib.profiler import ProfilerMiddleware
14 | app = ProfilerMiddleware(app)
15 |
16 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
17 | :license: BSD, see LICENSE for more details.
18 | """
19 | import sys
20 | try:
21 | try:
22 | from cProfile import Profile
23 | except ImportError:
24 | from profile import Profile
25 | from pstats import Stats
26 | available = True
27 | except ImportError:
28 | available = False
29 |
30 |
31 | class MergeStream(object):
32 | """An object that redirects `write` calls to multiple streams.
33 | Use this to log to both `sys.stdout` and a file::
34 |
35 | f = open('profiler.log', 'w')
36 | stream = MergeStream(sys.stdout, f)
37 | profiler = ProfilerMiddleware(app, stream)
38 | """
39 |
40 | def __init__(self, *streams):
41 | if not streams:
42 | raise TypeError('at least one stream must be given')
43 | self.streams = streams
44 |
45 | def write(self, data):
46 | for stream in self.streams:
47 | stream.write(data)
48 |
49 |
50 | class ProfilerMiddleware(object):
51 | """Simple profiler middleware. Wraps a WSGI application and profiles
52 | a request. This intentionally buffers the response so that timings are
53 | more exact.
54 |
55 | For the exact meaning of `sort_by` and `restrictions` consult the
56 | :mod:`profile` documentation.
57 |
58 | :param app: the WSGI application to profile.
59 | :param stream: the stream for the profiled stats. defaults to stderr.
60 | :param sort_by: a tuple of columns to sort the result by.
61 | :param restrictions: a tuple of profiling strictions.
62 | """
63 |
64 | def __init__(self, app, stream=None,
65 | sort_by=('time', 'calls'), restrictions=()):
66 | if not available:
67 | raise RuntimeError('the profiler is not available because '
68 | 'profile or pstat is not installed.')
69 | self._app = app
70 | self._stream = stream or sys.stdout
71 | self._sort_by = sort_by
72 | self._restrictions = restrictions
73 |
74 | def __call__(self, environ, start_response):
75 | response_body = []
76 |
77 | def catching_start_response(status, headers, exc_info=None):
78 | start_response(status, headers, exc_info)
79 | return response_body.append
80 |
81 | def runapp():
82 | appiter = self._app(environ, catching_start_response)
83 | response_body.extend(appiter)
84 | if hasattr(appiter, 'close'):
85 | appiter.close()
86 |
87 | p = Profile()
88 | p.runcall(runapp)
89 | body = ''.join(response_body)
90 | stats = Stats(p, stream=self._stream)
91 | stats.sort_stats(*self._sort_by)
92 |
93 | self._stream.write('-' * 80)
94 | self._stream.write('\nPATH: %r\n' % environ.get('PATH_INFO'))
95 | stats.print_stats(*self._restrictions)
96 | self._stream.write('-' * 80 + '\n\n')
97 |
98 | return [body]
99 |
100 |
101 | def make_action(app_factory, hostname='localhost', port=5000,
102 | threaded=False, processes=1, stream=None,
103 | sort_by=('time', 'calls'), restrictions=()):
104 | """Return a new callback for :mod:`werkzeug.script` that starts a local
105 | server with the profiler enabled::
106 |
107 | from werkzeug.contrib import profiler
108 | action_profile = profiler.make_action(make_app)
109 | """
110 | def action(hostname=('h', hostname), port=('p', port),
111 | threaded=threaded, processes=processes):
112 | """Start a new development server."""
113 | from werkzeug.serving import run_simple
114 | app = ProfilerMiddleware(app_factory(), stream, sort_by, restrictions)
115 | run_simple(hostname, port, app, False, None, threaded, processes)
116 | return action
117 |
--------------------------------------------------------------------------------
/lib/werkzeug/contrib/testtools.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.contrib.testtools
4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~
5 |
6 | This module implements extended wrappers for simplified testing.
7 |
8 | `TestResponse`
9 | A response wrapper which adds various cached attributes for
10 | simplified assertions on various content types.
11 |
12 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
13 | :license: BSD, see LICENSE for more details.
14 | """
15 | from werkzeug import Response, cached_property, import_string
16 |
17 |
18 | class ContentAccessors(object):
19 | """
20 | A mixin class for response objects that provides a couple of useful
21 | accessors for unittesting.
22 | """
23 |
24 | def xml(self):
25 | """Get an etree if possible."""
26 | if 'xml' not in self.mimetype:
27 | raise AttributeError(
28 | 'Not a XML response (Content-Type: %s)'
29 | % self.mimetype)
30 | for module in ['xml.etree.ElementTree', 'ElementTree',
31 | 'elementtree.ElementTree']:
32 | etree = import_string(module, silent=True)
33 | if etree is not None:
34 | return etree.XML(self.body)
35 | raise RuntimeError('You must have ElementTree installed '
36 | 'to use TestResponse.xml')
37 | xml = cached_property(xml)
38 |
39 | def lxml(self):
40 | """Get an lxml etree if possible."""
41 | if ('html' not in self.mimetype and 'xml' not in self.mimetype):
42 | raise AttributeError('Not an HTML/XML response')
43 | from lxml import etree
44 | try:
45 | from lxml.html import fromstring
46 | except ImportError:
47 | fromstring = etree.HTML
48 | if self.mimetype=='text/html':
49 | return fromstring(self.data)
50 | return etree.XML(self.data)
51 | lxml = cached_property(lxml)
52 |
53 | def json(self):
54 | """Get the result of simplejson.loads if possible."""
55 | if 'json' not in self.mimetype:
56 | raise AttributeError('Not a JSON response')
57 | try:
58 | from simplejson import loads
59 | except:
60 | from json import loads
61 | return loads(self.data)
62 | json = cached_property(json)
63 |
64 |
65 | class TestResponse(Response, ContentAccessors):
66 | """Pass this to `werkzeug.test.Client` for easier unittesting."""
67 |
--------------------------------------------------------------------------------
/lib/werkzeug/debug/render.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | werkzeug.debug.render
4 | ~~~~~~~~~~~~~~~~~~~~~
5 |
6 | Render the traceback debugging page.
7 |
8 | :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
9 | :license: BSD, see LICENSE for more details.
10 | """
11 | import pprint
12 | from os.path import dirname, join
13 |
14 | from werkzeug.templates import Template
15 |
16 |
17 | def get_template(name):
18 | return Template.from_file(join(dirname(__file__), 'shared', name),
19 | unicode_mode=False, errors='ignore')
20 |
21 |
22 | def load_resource(res):
23 | try:
24 | f = file(join(dirname(__file__), 'shared', res))
25 | except IOError:
26 | return ''
27 | try:
28 | return f.read()
29 | finally:
30 | f.close()
31 |
32 |
33 | t_body = get_template('body.tmpl')
34 | t_codetable = get_template('codetable.tmpl')
35 | t_vartable = get_template('vartable.tmpl')
36 |
37 |
38 | def code_table(frame):
39 | from werkzeug.debug.util import Namespace
40 | lines = []
41 | lineno = frame['context_lineno']
42 | if lineno is not None:
43 | lineno += 1
44 | for l in frame['pre_context']:
45 | lines.append(Namespace(mode='pre', lineno=lineno, code=l))
46 | lineno += 1
47 | lines.append(Namespace(mode='cur', lineno=lineno,
48 | code=frame['context_line']))
49 | lineno += 1
50 | for l in frame['post_context']:
51 | lines.append(Namespace(mode='post', lineno=lineno, code=l))
52 | lineno += 1
53 | else:
54 | lines.append(Namespace(mode='cur', lineno=1,
55 | code='Sourcecode not available'))
56 |
57 | return t_codetable.render(lines=lines)
58 |
59 |
60 | def var_table(var):
61 | def safe_pformat(x):
62 | try:
63 | lines = pprint.pformat(x).splitlines()
64 | except:
65 | return '?'
66 | tmp = []
67 | for line in lines:
68 | if len(line) > 79:
69 | line = line[:79] + '...'
70 | tmp.append(line)
71 | return '\n'.join(tmp)
72 |
73 | # dicts
74 | if isinstance(var, dict) or hasattr(var, 'items'):
75 | value = var.items()
76 | if not value:
77 | typ = 'empty'
78 | else:
79 | typ = 'dict'
80 | value.sort()
81 | value = [(repr(key), safe_pformat(val)) for key, val in value]
82 |
83 | # lists
84 | elif isinstance(var, list):
85 | if not var:
86 | typ = 'empty'
87 | else:
88 | typ = 'list'
89 | value = [safe_pformat(item) for item in var]
90 |
91 | # others
92 | else:
93 | typ = 'simple'
94 | value = repr(var)
95 |
96 | return t_vartable.render(type=typ, value=value)
97 |
98 |
99 | def debug_page(context):
100 | tc = context.to_dict()
101 | tc['var_table'] = var_table
102 | tc['code_table'] = code_table
103 | return t_body.render(tc)
104 |
--------------------------------------------------------------------------------
/lib/werkzeug/debug/shared/body.tmpl:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 | $escape(exception_type) in $escape(last_frame['basename']) (Werkzeug Debugger)
6 |
7 |
8 |
9 |
10 |
11 |
12 |
$escape(exception_type)
13 |
$escape(exception_value)
14 |
15 |
16 | $escape(last_frame['filename']) in
17 | $escape(last_frame['function']),
18 | line $last_frame['lineno']
19 |
20 |
21 |
Traceback (toggle raw view)
22 |
23 |
A problem occurred in your Python WSGI application.
24 | Here is the sequence of function calls leading up to the error, in the order
25 | they occurred. Activate a code line to toggle context lines.
26 |
27 | <% for num, frame in enumerate(frames) %>
28 |
29 |
$escape(frame['function']) in $escape(frame['filename'])
18 | In this console you can execute Python expressions in the context of the
19 | application. The initial namespace was created by the debugger automatically.
20 |
35 | The debugger caught an exception in your WSGI application. You can now
36 | look at the traceback which led to the error.
37 | If you enable JavaScript you can also use additional features such as code
38 | execution (if the evalex feature is enabled), automatic pasting of the
39 | exceptions and much more.
40 |