From e25bdba3a3a53b09be5269d8b065c13b73ab55c3 Mon Sep 17 00:00:00 2001 From: yum Date: Sun, 1 Jan 2023 21:05:27 -0800 Subject: Embed git in package package.ps1 fetches PortableGit and embeds it in the package. This eliminates all but one runtime dependency (MSVC++ Redistributable). * Move Python into a new FOSS folder. --- .../future-0.18.2/tests/test_future/__init__.py | 0 .../tests/test_future/test_backports.py | 665 +++ .../future-0.18.2/tests/test_future/test_buffer.py | 251 ++ .../tests/test_future/test_builtins.py | 1876 +++++++++ .../test_future/test_builtins_explicit_import.py | 18 + .../future-0.18.2/tests/test_future/test_bytes.py | 786 ++++ .../tests/test_future/test_chainmap.py | 160 + .../tests/test_future/test_common_iterators.py | 39 + .../tests/test_future/test_decorators.py | 57 + .../future-0.18.2/tests/test_future/test_dict.py | 142 + .../tests/test_future/test_email_multipart.py | 31 + .../tests/test_future/test_explicit_imports.py | 49 + .../tests/test_future/test_futurize.py | 1432 +++++++ .../future-0.18.2/tests/test_future/test_html.py | 27 + .../tests/test_future/test_htmlparser.py | 764 ++++ .../tests/test_future/test_http_cookiejar.py | 1755 ++++++++ .../tests/test_future/test_httplib.py | 568 +++ .../tests/test_future/test_import_star.py | 61 + .../tests/test_future/test_imports_httplib.py | 25 + .../tests/test_future/test_imports_urllib.py | 44 + .../future-0.18.2/tests/test_future/test_int.py | 1096 +++++ .../tests/test_future/test_int_old_division.py | 101 + .../tests/test_future/test_isinstance.py | 287 ++ .../tests/test_future/test_libfuturize_fixers.py | 4413 ++++++++++++++++++++ .../future-0.18.2/tests/test_future/test_list.py | 192 + .../tests/test_future/test_magicsuper.py | 135 + .../future-0.18.2/tests/test_future/test_object.py | 289 ++ .../tests/test_future/test_pasteurize.py | 256 ++ .../test_future/test_py2_str_literals_to_bytes.py | 1 + .../future-0.18.2/tests/test_future/test_range.py | 216 + .../tests/test_future/test_requests.py | 107 + .../tests/test_future/test_standard_library.py | 624 +++ .../future-0.18.2/tests/test_future/test_str.py | 591 +++ .../future-0.18.2/tests/test_future/test_super.py | 347 ++ .../tests/test_future/test_surrogateescape.py | 142 + .../future-0.18.2/tests/test_future/test_urllib.py | 1386 ++++++ .../tests/test_future/test_urllib2.py | 1569 +++++++ .../tests/test_future/test_urllib_response.py | 45 + .../tests/test_future/test_urllib_toplevel.py | 1401 +++++++ .../tests/test_future/test_urllibnet.py | 231 + .../tests/test_future/test_urlparse.py | 860 ++++ .../future-0.18.2/tests/test_future/test_utils.py | 406 ++ 42 files changed, 23445 insertions(+) create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/__init__.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_backports.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_buffer.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins_explicit_import.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_bytes.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_chainmap.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_common_iterators.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_decorators.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_dict.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_email_multipart.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_explicit_imports.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_futurize.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_html.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_htmlparser.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_http_cookiejar.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_httplib.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_import_star.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_imports_httplib.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_imports_urllib.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_int.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_int_old_division.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_isinstance.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_libfuturize_fixers.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_list.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_magicsuper.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_object.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_pasteurize.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_py2_str_literals_to_bytes.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_range.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_requests.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_standard_library.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_str.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_super.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_surrogateescape.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urllib.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urllib2.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urllib_response.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urllib_toplevel.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urllibnet.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_urlparse.py create mode 100644 FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_utils.py (limited to 'FOSS/Python/Dependencies/future-0.18.2/tests/test_future') diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/__init__.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_backports.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_backports.py new file mode 100644 index 0000000..9eeb741 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_backports.py @@ -0,0 +1,665 @@ +# -*- coding: utf-8 -*- +""" +Tests for various backported functions and classes in ``future.backports`` +""" + +from __future__ import absolute_import, print_function + +import sys +import copy +import inspect +import pickle +from random import randrange, shuffle + +from future.backports.misc import (count, + _count, + OrderedDict, + Counter, + ChainMap, + _count_elements) +from future.utils import PY2, PY26 +from future.tests.base import unittest, skip26, expectedFailurePY27 + +if PY2: + from collections import Mapping, MutableMapping +else: + from collections.abc import Mapping, MutableMapping + + +class CountTest(unittest.TestCase): + """Test the count function.""" + + def _test_count_func(self, func): + self.assertEqual(next(func(1)), 1) + self.assertEqual(next(func(start=1)), 1) + + c = func() + self.assertEqual(next(c), 0) + self.assertEqual(next(c), 1) + self.assertEqual(next(c), 2) + c = func(1, 1) + self.assertEqual(next(c), 1) + self.assertEqual(next(c), 2) + c = func(step=1) + self.assertEqual(next(c), 0) + self.assertEqual(next(c), 1) + c = func(start=1, step=1) + self.assertEqual(next(c), 1) + self.assertEqual(next(c), 2) + + c = func(-1) + self.assertEqual(next(c), -1) + self.assertEqual(next(c), 0) + self.assertEqual(next(c), 1) + c = func(1, -1) + self.assertEqual(next(c), 1) + self.assertEqual(next(c), 0) + self.assertEqual(next(c), -1) + c = func(-1, -1) + self.assertEqual(next(c), -1) + self.assertEqual(next(c), -2) + self.assertEqual(next(c), -3) + + def test_count(self): + """Test the count function.""" + self._test_count_func(count) + + def test_own_count(self): + """Test own count implementation.""" + if PY26: + self.assertIs(count, _count) + else: + self.assertNotEqual(count, _count) + self._test_count_func(_count) + + +################################################################################ +### ChainMap (helper class for configparser and the string module) +################################################################################ + +class TestChainMap(unittest.TestCase): + + def test_basics(self): + c = ChainMap() + c['a'] = 1 + c['b'] = 2 + d = c.new_child() + d['b'] = 20 + d['c'] = 30 + self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}]) # check internal state + self.assertEqual(d.items(), dict(a=1, b=20, c=30).items()) # check items/iter/getitem + self.assertEqual(len(d), 3) # check len + for key in 'abc': # check contains + self.assertIn(key, d) + for k, v in dict(a=1, b=20, c=30, z=100).items(): # check get + self.assertEqual(d.get(k, 100), v) + + del d['b'] # unmask a value + self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}]) # check internal state + self.assertEqual(d.items(), dict(a=1, b=2, c=30).items()) # check items/iter/getitem + self.assertEqual(len(d), 3) # check len + for key in 'abc': # check contains + self.assertIn(key, d) + for k, v in dict(a=1, b=2, c=30, z=100).items(): # check get + self.assertEqual(d.get(k, 100), v) + self.assertIn(repr(d), [ # check repr + type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})", + type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})" + ]) + + for e in d.copy(), copy.copy(d): # check shallow copies + self.assertEqual(d, e) + self.assertEqual(d.maps, e.maps) + self.assertIsNot(d, e) + self.assertIsNot(d.maps[0], e.maps[0]) + for m1, m2 in zip(d.maps[1:], e.maps[1:]): + self.assertIs(m1, m2) + + _ChainMap = ChainMap + + for e in [pickle.loads(pickle.dumps(d)), + copy.deepcopy(d), + eval(repr(d)) + ]: # check deep copies + self.assertEqual(d, e) + self.assertEqual(d.maps, e.maps) + self.assertIsNot(d, e) + for m1, m2 in zip(d.maps, e.maps): + self.assertIsNot(m1, m2, e) + + f = d.new_child() + f['b'] = 5 + self.assertEqual(f.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}]) + self.assertEqual(f.parents.maps, [{'c':30}, {'a':1, 'b':2}]) # check parents + self.assertEqual(f['b'], 5) # find first in chain + self.assertEqual(f.parents['b'], 2) # look beyond maps[0] + + def test_contructor(self): + self.assertEqual(ChainMap().maps, [{}]) # no-args --> one new dict + self.assertEqual(ChainMap({1:2}).maps, [{1:2}]) # 1 arg --> list + + def test_bool(self): + self.assertFalse(ChainMap()) + self.assertFalse(ChainMap({}, {})) + self.assertTrue(ChainMap({1:2}, {})) + self.assertTrue(ChainMap({}, {1:2})) + + def test_missing(self): + class DefaultChainMap(ChainMap): + def __missing__(self, key): + return 999 + d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30)) + for k, v in dict(a=1, b=2, c=30, d=999).items(): + self.assertEqual(d[k], v) # check __getitem__ w/missing + for k, v in dict(a=1, b=2, c=30, d=77).items(): + self.assertEqual(d.get(k, 77), v) # check get() w/ missing + for k, v in dict(a=True, b=True, c=True, d=False).items(): + self.assertEqual(k in d, v) # check __contains__ w/missing + self.assertEqual(d.pop('a', 1001), 1, d) + self.assertEqual(d.pop('a', 1002), 1002) # check pop() w/missing + self.assertEqual(d.popitem(), ('b', 2)) # check popitem() w/missing + with self.assertRaises(KeyError): + d.popitem() + + def test_dict_coercion(self): + d = ChainMap(dict(a=1, b=2), dict(b=20, c=30)) + self.assertEqual(dict(d), dict(a=1, b=2, c=30)) + self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30)) + + +################################################################################ +### Counter +################################################################################ + +class CounterSubclassWithSetItem(Counter): + # Test a counter subclass that overrides __setitem__ + def __init__(self, *args, **kwds): + self.called = False + Counter.__init__(self, *args, **kwds) + def __setitem__(self, key, value): + self.called = True + Counter.__setitem__(self, key, value) + +class CounterSubclassWithGet(Counter): + # Test a counter subclass that overrides get() + def __init__(self, *args, **kwds): + self.called = False + Counter.__init__(self, *args, **kwds) + def get(self, key, default): + self.called = True + return Counter.get(self, key, default) + +class TestCounter(unittest.TestCase): + + def test_basics(self): + c = Counter('abcaba') + self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1})) + self.assertEqual(c, Counter(a=3, b=2, c=1)) + self.assertIsInstance(c, dict) + self.assertIsInstance(c, Mapping) + self.assertTrue(issubclass(Counter, dict)) + self.assertTrue(issubclass(Counter, Mapping)) + self.assertEqual(len(c), 3) + self.assertEqual(sum(c.values()), 6) + self.assertEqual(sorted(c.values()), [1, 2, 3]) + self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) + self.assertEqual(sorted(c), ['a', 'b', 'c']) + self.assertEqual(sorted(c.items()), + [('a', 3), ('b', 2), ('c', 1)]) + self.assertEqual(c['b'], 2) + self.assertEqual(c['z'], 0) + self.assertEqual(c.__contains__('c'), True) + self.assertEqual(c.__contains__('z'), False) + self.assertEqual(c.get('b', 10), 2) + self.assertEqual(c.get('z', 10), 10) + self.assertEqual(c, dict(a=3, b=2, c=1)) + self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") + self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) + for i in range(5): + self.assertEqual(c.most_common(i), + [('a', 3), ('b', 2), ('c', 1)][:i]) + self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') + c['a'] += 1 # increment an existing value + c['b'] -= 2 # sub existing value to zero + del c['c'] # remove an entry + del c['c'] # make sure that del doesn't raise KeyError + c['d'] -= 2 # sub from a missing value + c['e'] = -5 # directly assign a missing value + c['f'] += 4 # add to a missing value + self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) + self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') + self.assertEqual(c.pop('f'), 4) + self.assertNotIn('f', c) + for i in range(3): + elem, cnt = c.popitem() + self.assertNotIn(elem, c) + c.clear() + self.assertEqual(c, {}) + self.assertEqual(repr(c), 'Counter()') + self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') + self.assertRaises(TypeError, hash, c) + c.update(dict(a=5, b=3)) + c.update(c=1) + c.update(Counter('a' * 50 + 'b' * 30)) + c.update() # test case with no args + c.__init__('a' * 500 + 'b' * 300) + c.__init__('cdc') + c.__init__() + self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) + self.assertEqual(c.setdefault('d', 5), 1) + self.assertEqual(c['d'], 1) + self.assertEqual(c.setdefault('e', 5), 5) + self.assertEqual(c['e'], 5) + + def test_copying(self): + # Check that counters are copyable, deepcopyable, picklable, and + #have a repr/eval round-trip + words = Counter('which witch had which witches wrist watch'.split()) + update_test = Counter() + update_test.update(words) + for i, dup in enumerate([ + words.copy(), + copy.copy(words), + copy.deepcopy(words), + pickle.loads(pickle.dumps(words, 0)), + pickle.loads(pickle.dumps(words, 1)), + pickle.loads(pickle.dumps(words, 2)), + pickle.loads(pickle.dumps(words, -1)), + eval(repr(words)), + update_test, + Counter(words), + ]): + msg = (i, dup, words) + self.assertTrue(dup is not words) + self.assertEqual(dup, words) + self.assertEqual(len(dup), len(words)) + self.assertEqual(type(dup), type(words)) + + def test_copy_subclass(self): + class MyCounter(Counter): + pass + c = MyCounter('slartibartfast') + d = c.copy() + self.assertEqual(d, c) + self.assertEqual(len(d), len(c)) + self.assertEqual(type(d), type(c)) + + def test_conversions(self): + # Convert to: set, list, dict + s = 'she sells sea shells by the sea shore' + self.assertEqual(sorted(Counter(s).elements()), sorted(s)) + self.assertEqual(sorted(Counter(s)), sorted(set(s))) + self.assertEqual(dict(Counter(s)), dict(Counter(s).items())) + self.assertEqual(set(Counter(s)), set(s)) + + def test_invariant_for_the_in_operator(self): + c = Counter(a=10, b=-2, c=0) + for elem in c: + self.assertTrue(elem in c) + self.assertIn(elem, c) + + def test_multiset_operations(self): + # Verify that adding a zero counter will strip zeros and negatives + c = Counter(a=10, b=-2, c=0) + Counter() + self.assertEqual(dict(c), dict(a=10)) + + elements = 'abcd' + for i in range(1000): + # test random pairs of multisets + p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + p.update(e=1, f=-1, g=0) + q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + q.update(h=1, i=-1, j=0) + for counterop, numberop in [ + (Counter.__add__, lambda x, y: max(0, x+y)), + (Counter.__sub__, lambda x, y: max(0, x-y)), + (Counter.__or__, lambda x, y: max(0,x,y)), + (Counter.__and__, lambda x, y: max(0, min(x,y))), + ]: + result = counterop(p, q) + for x in elements: + self.assertEqual(numberop(p[x], q[x]), result[x], + (counterop, x, p, q)) + # verify that results exclude non-positive counts + self.assertTrue(x>0 for x in result.values()) + + elements = 'abcdef' + for i in range(100): + # verify that random multisets with no repeats are exactly like sets + p = Counter(dict((elem, randrange(0, 2)) for elem in elements)) + q = Counter(dict((elem, randrange(0, 2)) for elem in elements)) + for counterop, setop in [ + (Counter.__sub__, set.__sub__), + (Counter.__or__, set.__or__), + (Counter.__and__, set.__and__), + ]: + counter_result = counterop(p, q) + set_result = setop(set(p.elements()), set(q.elements())) + self.assertEqual(counter_result, dict.fromkeys(set_result, 1)) + + @expectedFailurePY27 + def test_inplace_operations(self): + elements = 'abcd' + for i in range(1000): + # test random pairs of multisets + p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + p.update(e=1, f=-1, g=0) + q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + q.update(h=1, i=-1, j=0) + for inplace_op, regular_op in [ + (Counter.__iadd__, Counter.__add__), + (Counter.__isub__, Counter.__sub__), + (Counter.__ior__, Counter.__or__), + (Counter.__iand__, Counter.__and__), + ]: + c = p.copy() + c_id = id(c) + regular_result = regular_op(c, q) + inplace_result = inplace_op(c, q) + self.assertEqual(inplace_result, regular_result) + self.assertEqual(id(inplace_result), c_id) + + def test_subtract(self): + c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) + c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50) + self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) + c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) + c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)) + self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50)) + c = Counter('aaabbcd') + c.subtract('aaaabbcce') + self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1)) + + @expectedFailurePY27 + def test_unary(self): + c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40) + self.assertEqual(dict(+c), dict(c=5, d=10, e=15, g=40)) + self.assertEqual(dict(-c), dict(a=5)) + + def test_repr_nonsortable(self): + c = Counter(a=2, b=None) + r = repr(c) + self.assertIn("'a': 2", r) + self.assertIn("'b': None", r) + + def test_helper_function(self): + # two paths, one for real dicts and one for other mappings + elems = list('abracadabra') + + d = dict() + _count_elements(d, elems) + self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}) + + m = OrderedDict() + _count_elements(m, elems) + self.assertEqual(m, + OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])) + + # test fidelity to the pure python version + c = CounterSubclassWithSetItem('abracadabra') + self.assertTrue(c.called) + c = CounterSubclassWithGet('abracadabra') + self.assertTrue(c.called) + + +################################################################################ +### OrderedDict +################################################################################ + +class TestOrderedDict(unittest.TestCase): + + def test_init(self): + with self.assertRaises(TypeError): + OrderedDict([('a', 1), ('b', 2)], None) # too many args + pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] + self.assertEqual(sorted(OrderedDict(dict(pairs)).items()), pairs) # dict input + self.assertEqual(sorted(OrderedDict(**dict(pairs)).items()), pairs) # kwds input + self.assertEqual(list(OrderedDict(pairs).items()), pairs) # pairs input + self.assertEqual(list(OrderedDict([('a', 1), ('b', 2), ('c', 9), ('d', 4)], + c=3, e=5).items()), pairs) # mixed input + + # Make sure that direct calls to __init__ do not clear previous contents + d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) + d.__init__([('e', 5), ('f', 6)], g=7, d=4) + self.assertEqual(list(d.items()), + [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) + + def test_update(self): + with self.assertRaises(TypeError): + OrderedDict().update([('a', 1), ('b', 2)], None) # too many args + pairs = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)] + od = OrderedDict() + od.update(dict(pairs)) + self.assertEqual(sorted(od.items()), pairs) # dict input + od = OrderedDict() + od.update(**dict(pairs)) + self.assertEqual(sorted(od.items()), pairs) # kwds input + od = OrderedDict() + od.update(pairs) + self.assertEqual(list(od.items()), pairs) # pairs input + od = OrderedDict() + od.update([('a', 1), ('b', 2), ('c', 9), ('d', 4)], c=3, e=5) + self.assertEqual(list(od.items()), pairs) # mixed input + + ### The tests below fail on Py2.6 + if PY26: + return + # Issue 9137: Named argument called 'other' or 'self' + # shouldn't be treated specially. + od = OrderedDict() + od.update(self=23) + self.assertEqual(list(od.items()), [('self', 23)]) + od = OrderedDict() + od.update(other={}) + self.assertEqual(list(od.items()), [('other', {})]) + od = OrderedDict() + od.update(red=5, blue=6, other=7, self=8) + self.assertEqual(sorted(list(od.items())), + [('blue', 6), ('other', 7), ('red', 5), ('self', 8)]) + + # Make sure that direct calls to update do not clear previous contents + # add that updates items are not moved to the end + d = OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 44), ('e', 55)]) + d.update([('e', 5), ('f', 6)], g=7, d=4) + self.assertEqual(list(d.items()), + [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]) + + def test_abc(self): + self.assertIsInstance(OrderedDict(), MutableMapping) + self.assertTrue(issubclass(OrderedDict, MutableMapping)) + + def test_clear(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od = OrderedDict(pairs) + self.assertEqual(len(od), len(pairs)) + od.clear() + self.assertEqual(len(od), 0) + + def test_delitem(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + od = OrderedDict(pairs) + del od['a'] + self.assertNotIn('a', od) + with self.assertRaises(KeyError): + del od['a'] + self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) + + def test_setitem(self): + od = OrderedDict([('d', 1), ('b', 2), ('c', 3), ('a', 4), ('e', 5)]) + od['c'] = 10 # existing element + od['f'] = 20 # new element + self.assertEqual(list(od.items()), + [('d', 1), ('b', 2), ('c', 10), ('a', 4), ('e', 5), ('f', 20)]) + + def test_iterators(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od = OrderedDict(pairs) + self.assertEqual(list(od), [t[0] for t in pairs]) + self.assertEqual(list(od.keys()), [t[0] for t in pairs]) + self.assertEqual(list(od.values()), [t[1] for t in pairs]) + self.assertEqual(list(od.items()), pairs) + self.assertEqual(list(reversed(od)), + [t[0] for t in reversed(pairs)]) + + def test_popitem(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od = OrderedDict(pairs) + while pairs: + self.assertEqual(od.popitem(), pairs.pop()) + with self.assertRaises(KeyError): + od.popitem() + self.assertEqual(len(od), 0) + + def test_pop(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od = OrderedDict(pairs) + shuffle(pairs) + while pairs: + k, v = pairs.pop() + self.assertEqual(od.pop(k), v) + with self.assertRaises(KeyError): + od.pop('xyz') + self.assertEqual(len(od), 0) + self.assertEqual(od.pop(k, 12345), 12345) + + # make sure pop still works when __missing__ is defined + class Missing(OrderedDict): + def __missing__(self, key): + return 0 + m = Missing(a=1) + self.assertEqual(m.pop('b', 5), 5) + self.assertEqual(m.pop('a', 6), 1) + self.assertEqual(m.pop('a', 6), 6) + with self.assertRaises(KeyError): + m.pop('a') + + def test_equality(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od1 = OrderedDict(pairs) + od2 = OrderedDict(pairs) + self.assertEqual(od1, od2) # same order implies equality + pairs = pairs[2:] + pairs[:2] + od2 = OrderedDict(pairs) + self.assertNotEqual(od1, od2) # different order implies inequality + # comparison to regular dict is not order sensitive + self.assertEqual(od1, dict(od2)) + self.assertEqual(dict(od2), od1) + # different length implied inequality + self.assertNotEqual(od1, OrderedDict(pairs[:-1])) + + def test_copying(self): + # Check that ordered dicts are copyable, deepcopyable, picklable, + # and have a repr/eval round-trip + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + od = OrderedDict(pairs) + update_test = OrderedDict() + update_test.update(od) + for i, dup in enumerate([ + od.copy(), + copy.copy(od), + copy.deepcopy(od), + pickle.loads(pickle.dumps(od, 0)), + pickle.loads(pickle.dumps(od, 1)), + pickle.loads(pickle.dumps(od, 2)), + # pickle.loads(pickle.dumps(od, 3)), + pickle.loads(pickle.dumps(od, -1)), + eval(repr(od)), + update_test, + OrderedDict(od), + ]): + self.assertTrue(dup is not od) + self.assertEqual(dup, od) + self.assertEqual(list(dup.items()), list(od.items())) + self.assertEqual(len(dup), len(od)) + self.assertEqual(type(dup), type(od)) + + def test_yaml_linkage(self): + # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. + # In yaml, lists are native but tuples are not. + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + od = OrderedDict(pairs) + # yaml.dump(od) --> + # '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n' + self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1])) + + # def test_reduce_not_too_fat(self): + # # do not save instance dictionary if not needed + # pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + # od = OrderedDict(pairs) + # self.assertEqual(len(od.__reduce__()), 2) + # od.x = 10 + # self.assertEqual(len(od.__reduce__()), 3) + + def test_repr(self): + od = OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]) + self.assertEqual(repr(od), + "OrderedDict([('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)])") + self.assertEqual(eval(repr(od)), od) + self.assertEqual(repr(OrderedDict()), "OrderedDict()") + + def test_repr_recursive(self): + # See issue #9826 + od = OrderedDict.fromkeys('abc') + od['x'] = od + self.assertEqual(repr(od), + "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") + + def test_setdefault(self): + pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] + shuffle(pairs) + od = OrderedDict(pairs) + pair_order = list(od.items()) + self.assertEqual(od.setdefault('a', 10), 3) + # make sure order didn't change + self.assertEqual(list(od.items()), pair_order) + self.assertEqual(od.setdefault('x', 10), 10) + # make sure 'x' is added to the end + self.assertEqual(list(od.items())[-1], ('x', 10)) + + # make sure setdefault still works when __missing__ is defined + class Missing(OrderedDict): + def __missing__(self, key): + return 0 + self.assertEqual(Missing().setdefault(5, 9), 9) + + def test_reinsert(self): + # Given insert a, insert b, delete a, re-insert a, + # verify that a is now later than b. + od = OrderedDict() + od['a'] = 1 + od['b'] = 2 + del od['a'] + od['a'] = 1 + self.assertEqual(list(od.items()), [('b', 2), ('a', 1)]) + + @expectedFailurePY27 + def test_move_to_end(self): + od = OrderedDict.fromkeys('abcde') + self.assertEqual(list(od), list('abcde')) + od.move_to_end('c') + self.assertEqual(list(od), list('abdec')) + od.move_to_end('c', 0) + self.assertEqual(list(od), list('cabde')) + od.move_to_end('c', 0) + self.assertEqual(list(od), list('cabde')) + od.move_to_end('e') + self.assertEqual(list(od), list('cabde')) + with self.assertRaises(KeyError): + od.move_to_end('x') + + def test_override_update(self): + # Verify that subclasses can override update() without breaking __init__() + class MyOD(OrderedDict): + def update(self, *args, **kwds): + raise Exception() + items = [('a', 1), ('c', 3), ('b', 2)] + self.assertEqual(list(MyOD(items).items()), items) + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_buffer.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_buffer.py new file mode 100644 index 0000000..74cfb74 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_buffer.py @@ -0,0 +1,251 @@ +# Tests that work for both bytes and buffer objects. +# See PEP 3137. + +from __future__ import (absolute_import, division, + print_function, unicode_literals) +from future.builtins import * +from future.tests.base import unittest, expectedFailurePY26 + +import struct +import sys + + +class MixinBytesBufferCommonTests(object): + """Tests that work for both bytes and buffer objects. + See PEP 3137. + """ + + def marshal(self, x): + """Convert x into the appropriate type for these tests.""" + raise RuntimeError('test class must provide a marshal method') + + def test_islower(self): + self.assertFalse(self.marshal(b'').islower()) + self.assertTrue(self.marshal(b'a').islower()) + self.assertFalse(self.marshal(b'A').islower()) + self.assertFalse(self.marshal(b'\n').islower()) + self.assertTrue(self.marshal(b'abc').islower()) + self.assertFalse(self.marshal(b'aBc').islower()) + self.assertTrue(self.marshal(b'abc\n').islower()) + self.assertRaises(TypeError, self.marshal(b'abc').islower, 42) + + def test_isupper(self): + self.assertFalse(self.marshal(b'').isupper()) + self.assertFalse(self.marshal(b'a').isupper()) + self.assertTrue(self.marshal(b'A').isupper()) + self.assertFalse(self.marshal(b'\n').isupper()) + self.assertTrue(self.marshal(b'ABC').isupper()) + self.assertFalse(self.marshal(b'AbC').isupper()) + self.assertTrue(self.marshal(b'ABC\n').isupper()) + self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42) + + def test_istitle(self): + self.assertFalse(self.marshal(b'').istitle()) + self.assertFalse(self.marshal(b'a').istitle()) + self.assertTrue(self.marshal(b'A').istitle()) + self.assertFalse(self.marshal(b'\n').istitle()) + self.assertTrue(self.marshal(b'A Titlecased Line').istitle()) + self.assertTrue(self.marshal(b'A\nTitlecased Line').istitle()) + self.assertTrue(self.marshal(b'A Titlecased, Line').istitle()) + self.assertFalse(self.marshal(b'Not a capitalized String').istitle()) + self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle()) + self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle()) + self.assertFalse(self.marshal(b'NOT').istitle()) + self.assertRaises(TypeError, self.marshal(b'abc').istitle, 42) + + def test_isspace(self): + self.assertFalse(self.marshal(b'').isspace()) + self.assertFalse(self.marshal(b'a').isspace()) + self.assertTrue(self.marshal(b' ').isspace()) + self.assertTrue(self.marshal(b'\t').isspace()) + self.assertTrue(self.marshal(b'\r').isspace()) + self.assertTrue(self.marshal(b'\n').isspace()) + self.assertTrue(self.marshal(b' \t\r\n').isspace()) + self.assertFalse(self.marshal(b' \t\r\na').isspace()) + self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42) + + def test_isalpha(self): + self.assertFalse(self.marshal(b'').isalpha()) + self.assertTrue(self.marshal(b'a').isalpha()) + self.assertTrue(self.marshal(b'A').isalpha()) + self.assertFalse(self.marshal(b'\n').isalpha()) + self.assertTrue(self.marshal(b'abc').isalpha()) + self.assertFalse(self.marshal(b'aBc123').isalpha()) + self.assertFalse(self.marshal(b'abc\n').isalpha()) + self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42) + + def test_isalnum(self): + self.assertFalse(self.marshal(b'').isalnum()) + self.assertTrue(self.marshal(b'a').isalnum()) + self.assertTrue(self.marshal(b'A').isalnum()) + self.assertFalse(self.marshal(b'\n').isalnum()) + self.assertTrue(self.marshal(b'123abc456').isalnum()) + self.assertTrue(self.marshal(b'a1b3c').isalnum()) + self.assertFalse(self.marshal(b'aBc000 ').isalnum()) + self.assertFalse(self.marshal(b'abc\n').isalnum()) + self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42) + + def test_isdigit(self): + self.assertFalse(self.marshal(b'').isdigit()) + self.assertFalse(self.marshal(b'a').isdigit()) + self.assertTrue(self.marshal(b'0').isdigit()) + self.assertTrue(self.marshal(b'0123456789').isdigit()) + self.assertFalse(self.marshal(b'0123456789a').isdigit()) + + self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42) + + def test_lower(self): + self.assertEqual(bytes(b'hello'), self.marshal(b'HeLLo').lower()) + self.assertEqual(bytes(b'hello'), self.marshal(b'hello').lower()) + self.assertRaises(TypeError, self.marshal(b'hello').lower, 42) + + def test_upper(self): + self.assertEqual(bytes(b'HELLO'), self.marshal(b'HeLLo').upper()) + self.assertEqual(bytes(b'HELLO'), self.marshal(b'HELLO').upper()) + self.assertRaises(TypeError, self.marshal(b'hello').upper, 42) + + def test_capitalize(self): + self.assertEqual(bytes(b' hello '), self.marshal(b' hello ').capitalize()) + self.assertEqual(bytes(b'Hello '), self.marshal(b'Hello ').capitalize()) + self.assertEqual(bytes(b'Hello '), self.marshal(b'hello ').capitalize()) + self.assertEqual(bytes(b'Aaaa'), self.marshal(b'aaaa').capitalize()) + self.assertEqual(bytes(b'Aaaa'), self.marshal(b'AaAa').capitalize()) + + self.assertRaises(TypeError, self.marshal(b'hello').capitalize, 42) + + def test_ljust(self): + self.assertEqual(bytes(b'abc '), self.marshal(b'abc').ljust(10)) + self.assertEqual(bytes(b'abc '), self.marshal(b'abc').ljust(6)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').ljust(3)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').ljust(2)) + self.assertEqual(bytes(b'abc*******'), self.marshal(b'abc').ljust(10, b'*')) + self.assertRaises(TypeError, self.marshal(b'abc').ljust) + + def test_rjust(self): + self.assertEqual(bytes(b' abc'), self.marshal(b'abc').rjust(10)) + self.assertEqual(bytes(b' abc'), self.marshal(b'abc').rjust(6)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').rjust(3)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').rjust(2)) + self.assertEqual(bytes(b'*******abc'), self.marshal(b'abc').rjust(10, b'*')) + self.assertRaises(TypeError, self.marshal(b'abc').rjust) + + def test_center(self): + self.assertEqual(bytes(b' abc '), self.marshal(b'abc').center(10)) + self.assertEqual(bytes(b' abc '), self.marshal(b'abc').center(6)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').center(3)) + self.assertEqual(bytes(b'abc'), self.marshal(b'abc').center(2)) + self.assertEqual(bytes(b'***abc****'), self.marshal(b'abc').center(10, b'*')) + self.assertRaises(TypeError, self.marshal(b'abc').center) + + def test_swapcase(self): + self.assertEqual(bytes(b'hEllO CoMPuTErS'), + self.marshal(bytes(b'HeLLo cOmpUteRs')).swapcase()) + + self.assertRaises(TypeError, self.marshal(b'hello').swapcase, 42) + + def test_zfill(self): + self.assertEqual(bytes(b'123'), self.marshal(b'123').zfill(2)) + self.assertEqual(bytes(b'123'), self.marshal(b'123').zfill(3)) + self.assertEqual(bytes(b'0123'), self.marshal(b'123').zfill(4)) + self.assertEqual(bytes(b'+123'), self.marshal(b'+123').zfill(3)) + self.assertEqual(bytes(b'+123'), self.marshal(b'+123').zfill(4)) + self.assertEqual(bytes(b'+0123'), self.marshal(b'+123').zfill(5)) + self.assertEqual(bytes(b'-123'), self.marshal(b'-123').zfill(3)) + self.assertEqual(bytes(b'-123'), self.marshal(b'-123').zfill(4)) + self.assertEqual(bytes(b'-0123'), self.marshal(b'-123').zfill(5)) + self.assertEqual(bytes(b'000'), self.marshal(b'').zfill(3)) + self.assertEqual(bytes(b'34'), self.marshal(b'34').zfill(1)) + self.assertEqual(bytes(b'0034'), self.marshal(b'34').zfill(4)) + + self.assertRaises(TypeError, self.marshal(b'123').zfill) + + def test_expandtabs(self): + self.assertEqual(bytes(b'abc\rab def\ng hi'), + self.marshal(b'abc\rab\tdef\ng\thi').expandtabs()) + self.assertEqual(bytes(b'abc\rab def\ng hi'), + self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8)) + self.assertEqual(bytes(b'abc\rab def\ng hi'), + self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(4)) + self.assertEqual(bytes(b'abc\r\nab def\ng hi'), + self.marshal(b'abc\r\nab\tdef\ng\thi').expandtabs(4)) + self.assertEqual(bytes(b'abc\rab def\ng hi'), + self.marshal(b'abc\rab\tdef\ng\thi').expandtabs()) + self.assertEqual(bytes(b'abc\rab def\ng hi'), + self.marshal(b'abc\rab\tdef\ng\thi').expandtabs(8)) + self.assertEqual(bytes(b'abc\r\nab\r\ndef\ng\r\nhi'), + self.marshal(b'abc\r\nab\r\ndef\ng\r\nhi').expandtabs(4)) + self.assertEqual(bytes(b' a\n b'), self.marshal(b' \ta\n\tb').expandtabs(1)) + + self.assertRaises(TypeError, self.marshal(b'hello').expandtabs, 42, 42) + # This test is only valid when sizeof(int) == sizeof(void*) == 4. + if sys.maxsize < (1 << 32) and struct.calcsize('P') == 4: + self.assertRaises(OverflowError, + self.marshal(b'\ta\n\tb').expandtabs, sys.maxsize) + + def test_title(self): + self.assertEqual(bytes(b' Hello '), self.marshal(b' hello ').title()) + self.assertEqual(bytes(b'Hello '), self.marshal(b'hello ').title()) + self.assertEqual(bytes(b'Hello '), self.marshal(b'Hello ').title()) + self.assertEqual(bytes(b'Format This As Title String'), + self.marshal(b'fOrMaT thIs aS titLe String').title()) + self.assertEqual(bytes(b'Format,This-As*Title;String'), + self.marshal(b'fOrMaT,thIs-aS*titLe;String').title()) + self.assertEqual(bytes(b'Getint'), self.marshal(b'getInt').title()) + self.assertRaises(TypeError, self.marshal(b'hello').title, 42) + + def test_splitlines(self): + self.assertEqual([bytes(b'abc'), bytes(b'def'), bytes(b''), bytes(b'ghi')], + self.marshal(b'abc\ndef\n\rghi').splitlines()) + self.assertEqual([bytes(b'abc'), bytes(b'def'), bytes(b''), bytes(b'ghi')], + self.marshal(b'abc\ndef\n\r\nghi').splitlines()) + self.assertEqual([bytes(b'abc'), bytes(b'def'), bytes(b'ghi')], + self.marshal(b'abc\ndef\r\nghi').splitlines()) + # TODO: add bytes calls around these too ... + self.assertEqual([b'abc', b'def', b'ghi'], + self.marshal(b'abc\ndef\r\nghi\n').splitlines()) + self.assertEqual([b'abc', b'def', b'ghi', b''], + self.marshal(b'abc\ndef\r\nghi\n\r').splitlines()) + self.assertEqual([b'', b'abc', b'def', b'ghi', b''], + self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines()) + self.assertEqual([b'', b'abc', b'def', b'ghi', b''], + self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(False)) + self.assertEqual([b'\n', b'abc\n', b'def\r\n', b'ghi\n', b'\r'], + self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(True)) + self.assertEqual([b'', b'abc', b'def', b'ghi', b''], + self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(False)) + self.assertEqual([b'\n', b'abc\n', b'def\r\n', b'ghi\n', b'\r'], + self.marshal(b'\nabc\ndef\r\nghi\n\r').splitlines(True)) + + self.assertRaises(TypeError, self.marshal(b'abc').splitlines, 42, 42) + + +# From Python-3.3.5/Lib/test/test_bytes.py: + +class BytearrayPEP3137Test(unittest.TestCase, + MixinBytesBufferCommonTests): + def marshal(self, x): + return bytearray(bytes(x)) + + @expectedFailurePY26 + def test_returns_new_copy(self): + val = self.marshal(b'1234') + # On immutable types these MAY return a reference to themselves + # but on mutable types like bytearray they MUST return a new copy. + for methname in ('zfill', 'rjust', 'ljust', 'center'): + method = getattr(val, methname) + newval = method(3) + self.assertEqual(val, newval) + self.assertTrue(val is not newval, + methname+' returned self on a mutable object') + for expr in ('val.split()[0]', 'val.rsplit()[0]', + 'val.partition(b".")[0]', 'val.rpartition(b".")[2]', + 'val.splitlines()[0]', 'val.replace(b"", b"")'): + newval = eval(expr) + self.assertEqual(val, newval) + self.assertTrue(val is not newval, + expr+' returned val on a mutable object') + + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins.py new file mode 100644 index 0000000..ca07b9e --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins.py @@ -0,0 +1,1876 @@ +# -*- coding: utf-8 -*- +""" +Tests to make sure the behaviour of the builtins is sensible and correct. +""" + +from __future__ import absolute_import, division, print_function, unicode_literals +from future.builtins import (bytes, dict, int, range, round, str, super, + ascii, chr, hex, input, next, oct, open, pow, + filter, map, zip, min, max) + +from future.utils import PY3, exec_, native_str, implements_iterator +from future.tests.base import (unittest, skip26, expectedFailurePY2, + expectedFailurePY26) + +import sys +import textwrap +import tempfile +import os +from subprocess import Popen, PIPE +from numbers import Integral +from decimal import Decimal + + +class TestBuiltins(unittest.TestCase): + def setUp(self): + self.tempdir = tempfile.mkdtemp() + os.path.sep + + def test_super(self): + class verbose_list(list): + ''' + A class that uses the new simpler super() function + ''' + def append(self, item): + print('Adding an item') + super().append(item) + + l = verbose_list() + l.append('blah') + self.assertEqual(l[0], 'blah') + self.assertEqual(len(l), 1) + self.assertTrue(isinstance(l, list)) + + def test_super_2(self): + """ + This occurs in the backported email/_header_value_parser.py + module and seems to fail. + """ + class Terminal(str): + def __new__(cls, value, token_type): + self = super().__new__(cls, value) + self.token_type = token_type + self.defects = [] + return self + + DOT = Terminal('.', 'dot') + + self.assertTrue(True) + + def test_isinstance_int(self): + """ + Redefining ``int`` to a ``long`` subclass on Py2 makes this + test fail unless __instancecheck__() is defined appropriately (or + isinstance is redefined, as we used to do ...) + """ + self.assertTrue(isinstance(0, int)) + self.assertTrue(isinstance(int(1), int)) + self.assertFalse(isinstance(1.0, int)) + + def test_isinstance_Integral(self): + """ + Tests the preferred alternative to the above + """ + self.assertTrue(isinstance(0, Integral)) + + def test_isinstance_long(self): + """ + Py2's long doesn't inherit from int! + """ + self.assertTrue(isinstance(10**100, int)) + self.assertTrue(isinstance(int(2**64), int)) + if not PY3: + self.assertTrue(isinstance(long(1), int)) + # Note: the following is a SyntaxError on Py3: + # self.assertTrue(isinstance(1L, int)) + + def test_isinstance_bytes(self): + self.assertTrue(isinstance(b'byte-string', bytes)) + self.assertFalse(isinstance(b'byte-string', str)) + + def test_isinstance_str(self): + self.assertTrue(isinstance('string', str)) + self.assertTrue(isinstance(u'string', str)) + self.assertFalse(isinstance(u'string', bytes)) + + @expectedFailurePY2 + def test_type(self): + """ + The following fails when passed a unicode string on Python + (including when unicode_literals is in effect) and fails when + passed a byte-string on Python 3. So type() always wants a native + string as the first argument. + + TODO: maybe provide a replacement that works identically on Py2/3? + """ + mytype = type('blah', (dict,), {"old": 1, "new": 2}) + d = mytype() + self.assertTrue(isinstance(d, mytype)) + self.assertTrue(isinstance(d, dict)) + + def test_isinstance_tuple_of_types(self): + # These two should be equivalent, even if ``int`` is a special + # backported type. + label = 1 + self.assertTrue(isinstance(label, (float, Decimal)) or + isinstance(label, int)) + self.assertTrue(isinstance(label, (float, Decimal, int))) + self.assertTrue(isinstance(10**100, (float, Decimal, int))) + + self.assertTrue(isinstance(b'blah', (str, bytes))) + self.assertTrue(isinstance(b'blah', (bytes, float, int))) + + self.assertFalse(isinstance(b'blah', (str, Decimal, float, int))) + + self.assertTrue(isinstance('blah', (str, Decimal, float, int))) + self.assertTrue(isinstance(u'blah', (Decimal, float, int, str))) + + self.assertFalse(isinstance('blah', (bytes, Decimal, float, int))) + + def test_round(self): + """ + Note that the Python 2.x round() function fails these tests. The + Python 3.x round() function passes them, as should our custom + round() function. + """ + self.assertEqual(round(0.1250, 2), 0.12) + self.assertEqual(round(0.1350, 2), 0.14) + self.assertEqual(round(0.1251, 2), 0.13) + self.assertEqual(round(0.125000001, 2), 0.13) + self.assertEqual(round(123.5, 0), 124.0) + self.assertEqual(round(123.5), 124) + self.assertEqual(round(12.35, 2), 12.35) + self.assertEqual(round(12.35, 1), 12.3) + self.assertEqual(round(12.35, 0), 12.0) + self.assertEqual(round(123.5, 1), 123.5) + + self.assertTrue(isinstance(round(123.5, 0), float)) + self.assertTrue(isinstance(round(123.5), Integral)) + + @unittest.skip('negative ndigits not implemented yet') + def test_round_negative_ndigits(self): + self.assertEqual(round(10.1350, 0), 10.0) + self.assertEqual(round(10.1350, -1), 10.0) + self.assertEqual(round(10.1350, -2), 0.0) + self.assertEqual(round(10.1350, -3), 0.0) + + self.assertEqual(round(12.35, -1), 10.0) + self.assertEqual(round(12.35, -2), 0.0) + self.assertEqual(round(123.5, -1), 120.0) + self.assertEqual(round(123.5, -2), 100.0) + self.assertEqual(round(123.551, -2), 100.0) + self.assertEqual(round(123.551, -3), 0.0) + + def test_newnext_doc_example(self): + # Python 3-style iterator: + class Upper(object): + def __init__(self, iterable): + self._iter = iter(iterable) + def __next__(self): # note the Py3 interface + return next(self._iter).upper() + def __iter__(self): + return self + + # from future.builtins import next + itr = Upper('hello') + self.assertEqual(next(itr), 'H') + self.assertEqual(next(itr), 'E') + # This doesn't work on Py2 because next() isn't defined: + # self.assertEqual(list(itr), 'LLO') + + # Check that regular Py2 iterators with just a .next method also work: + itr2 = iter(['one', 'three', 'five']) + self.assertEqual(next(itr2), 'one') + + +############################################################## +# Below here are the tests from Py3.3'2 test_builtin.py module +############################################################## + +from future.backports.test.support import TESTFN, unlink, run_unittest, check_warnings +import ast +import collections + +import io +import locale +import os +import pickle +import platform +import random +import sys +import traceback +import types +# Imported above more portably (using unittest2 on Py2.6): +import warnings +from operator import neg +try: + import pty, signal +except ImportError: + pty = signal = None + + +class Squares: + + def __init__(self, max): + self.max = max + self.sofar = [] + + def __len__(self): return len(self.sofar) + + def __getitem__(self, i): + if not 0 <= i < self.max: raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(n*n) + n += 1 + return self.sofar[i] + +class StrSquares: + + def __init__(self, max): + self.max = max + self.sofar = [] + + def __len__(self): + return len(self.sofar) + + def __getitem__(self, i): + if not 0 <= i < self.max: + raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(str(n*n)) + n += 1 + return self.sofar[i] + +class BitBucket: + def write(self, line): + pass + +test_conv_no_sign = [ + ('0', 0), + ('1', 1), + ('9', 9), + ('10', 10), + ('99', 99), + ('100', 100), + ('314', 314), + (' 314', 314), + ('314 ', 314), + (' \t\t 314 \t\t ', 314), + (repr(sys.maxsize), sys.maxsize), + (' 1x', ValueError), + (' 1 ', 1), + (' 1\02 ', ValueError), + ('', ValueError), + (' ', ValueError), + (' \t\t ', ValueError), + (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), + (chr(0x200), ValueError), +] + +test_conv_sign = [ + ('0', 0), + ('1', 1), + ('9', 9), + ('10', 10), + ('99', 99), + ('100', 100), + ('314', 314), + (' 314', ValueError), + ('314 ', 314), + (' \t\t 314 \t\t ', ValueError), + (repr(sys.maxsize), sys.maxsize), + (' 1x', ValueError), + (' 1 ', ValueError), + (' 1\02 ', ValueError), + ('', ValueError), + (' ', ValueError), + (' \t\t ', ValueError), + (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), + (chr(0x200), ValueError), +] + +class TestFailingBool: + def __bool__(self): + raise RuntimeError + # On Py2: + def __nonzero__(self): + raise RuntimeError + +class TestFailingIter: + def __iter__(self): + raise RuntimeError + +def filter_char(arg): + return ord(arg) > ord("d") + +def map_char(arg): + return chr(ord(arg)+1) + +class BuiltinTest(unittest.TestCase): + # Helper to check picklability + def check_iter_pickle(self, it, seq): + itorg = it + d = pickle.dumps(it) + it = pickle.loads(d) + self.assertEqual(type(itorg), type(it)) + self.assertEqual(list(it), seq) + + #test the iterator after dropping one from it + it = pickle.loads(d) + try: + next(it) + except StopIteration: + return + d = pickle.dumps(it) + it = pickle.loads(d) + self.assertEqual(list(it), seq[1:]) + + def test_import(self): + __import__('sys') + __import__('time') + __import__('string') + __import__(name='sys') + __import__(name='time', level=0) + self.assertRaises(ImportError, __import__, 'spamspam') + self.assertRaises(TypeError, __import__, 1, 2, 3, 4) + self.assertRaises(ValueError, __import__, '') + self.assertRaises(TypeError, __import__, 'sys', name='sys') + + def test_abs(self): + # int + self.assertEqual(abs(0), 0) + self.assertEqual(abs(1234), 1234) + self.assertEqual(abs(-1234), 1234) + self.assertTrue(abs(-sys.maxsize-1) > 0) + # float + self.assertEqual(abs(0.0), 0.0) + self.assertEqual(abs(3.14), 3.14) + self.assertEqual(abs(-3.14), 3.14) + # str + self.assertRaises(TypeError, abs, 'a') + # bool + self.assertEqual(abs(True), 1) + self.assertEqual(abs(False), 0) + # other + self.assertRaises(TypeError, abs) + self.assertRaises(TypeError, abs, None) + class AbsClass(object): + def __abs__(self): + return -5 + self.assertEqual(abs(AbsClass()), -5) + + def test_all(self): + self.assertEqual(all([2, 4, 6]), True) + self.assertEqual(all([2, None, 6]), False) + self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) + self.assertRaises(RuntimeError, all, TestFailingIter()) + self.assertRaises(TypeError, all, 10) # Non-iterable + self.assertRaises(TypeError, all) # No args + self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args + self.assertEqual(all([]), True) # Empty iterator + self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit + S = [50, 60] + self.assertEqual(all(x > 42 for x in S), True) + S = [50, 40, 60] + self.assertEqual(all(x > 42 for x in S), False) + + def test_any(self): + self.assertEqual(any([None, None, None]), False) + self.assertEqual(any([None, 4, None]), True) + self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) + self.assertRaises(RuntimeError, any, TestFailingIter()) + self.assertRaises(TypeError, any, 10) # Non-iterable + self.assertRaises(TypeError, any) # No args + self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args + self.assertEqual(any([]), False) # Empty iterator + self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit + S = [40, 60, 30] + self.assertEqual(any(x > 42 for x in S), True) + S = [10, 20, 30] + self.assertEqual(any(x > 42 for x in S), False) + + def test_ascii(self): + # Was: self.assertEqual(ascii(''), "''") # '\'\'') + # Heisenbug on Py2.7?! + self.assertEqual(ascii(0), '0') + self.assertEqual(ascii(()), '()') + self.assertEqual(ascii([]), '[]') + self.assertEqual(ascii({}), '{}') + a = [] + a.append(a) + self.assertEqual(ascii(a), '[[...]]') + a = {} + a[0] = a + self.assertEqual(ascii(a), '{0: {...}}') + # Advanced checks for unicode strings + def _check_uni(s): + self.assertEqual(ascii(s), repr(s)) + _check_uni("'") + _check_uni('"') + _check_uni('"\'') + _check_uni('\0') + _check_uni('\r\n\t .') + # Unprintable non-ASCII characters + _check_uni('\x85') + _check_uni('\u1fff') + _check_uni('\U00012fff') + # Lone surrogates + _check_uni('\ud800') + _check_uni('\udfff') + + # Issue #9804: surrogates should be joined even for printable + # wide characters (UCS-2 builds). + + # Fails on Py2.7. Was: + # self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'") + # # All together + # s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx." + # self.assertEqual(ascii(s), + # r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""") + + def test_neg(self): + x = -sys.maxsize-1 + self.assertTrue(isinstance(x, int)) + self.assertEqual(-x, sys.maxsize+1) + + def test_callable(self): + self.assertTrue(callable(len)) + self.assertFalse(callable("a")) + self.assertTrue(callable(callable)) + self.assertTrue(callable(lambda x, y: x + y)) + self.assertFalse(callable(__builtins__)) + def f(): pass + self.assertTrue(callable(f)) + + class C1(object): # Was: class C1: (old-style class on Py2) + def meth(self): pass + self.assertTrue(callable(C1)) + c = C1() + self.assertTrue(callable(c.meth)) + self.assertFalse(callable(c)) + + # __call__ is looked up on the class, not the instance + c.__call__ = None + self.assertFalse(callable(c)) + c.__call__ = lambda self: 0 + self.assertFalse(callable(c)) + del c.__call__ + self.assertFalse(callable(c)) + + class C2(object): + def __call__(self): pass + c2 = C2() + self.assertTrue(callable(c2)) + c2.__call__ = None + self.assertTrue(callable(c2)) + class C3(C2): pass + c3 = C3() + self.assertTrue(callable(c3)) + + def test_chr(self): + self.assertEqual(chr(32), ' ') + self.assertEqual(chr(65), 'A') + self.assertEqual(chr(97), 'a') + self.assertEqual(chr(0xff), '\xff') + self.assertRaises(ValueError, chr, 1<<24) + self.assertRaises(TypeError, chr) + self.assertEqual(chr(0x0000FFFF), "\U0000FFFF") + self.assertRaises(ValueError, chr, -1) + self.assertRaises(ValueError, chr, 0x00110000) + self.assertRaises((OverflowError, ValueError), chr, 2**32) + + @unittest.skip('FIXME: skip on narrow builds?') + def test_ord_big(self): + """ + These tests seem to fail on OS X (narrow Python build?) + """ + self.assertEqual(chr(sys.maxunicode), + str('\\U0010ffff'.encode("ascii"), 'unicode-escape')) + self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF) + self.assertEqual(ord("\U00010000"), 0x00010000) + self.assertEqual(ord("\U00010001"), 0x00010001) + self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE) + self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF) + self.assertEqual(ord("\U00100000"), 0x00100000) + self.assertEqual(ord("\U00100001"), 0x00100001) + self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE) + self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF) + + @unittest.skip('FIXME: skip on narrow builds?') + def test_chr_big(self): + """ + These tests seem to fail on OS X (narrow Python build?) + """ + self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF) + self.assertEqual(chr(0x00010000), "\U00010000") + self.assertEqual(chr(0x00010001), "\U00010001") + self.assertEqual(chr(0x000FFFFE), "\U000FFFFE") + self.assertEqual(chr(0x000FFFFF), "\U000FFFFF") + self.assertEqual(chr(0x00100000), "\U00100000") + self.assertEqual(chr(0x00100001), "\U00100001") + self.assertEqual(chr(0x0010FFFE), "\U0010FFFE") + self.assertEqual(chr(0x0010FFFF), "\U0010FFFF") + + def test_compile(self): + compile('print(1)\n', '', 'exec') + bom = b'\xef\xbb\xbf' + compile(bom + b'print(1)\n', '', 'exec') + compile(source='pass', filename='?', mode='exec') + compile(dont_inherit=0, filename='tmp', source='0', mode='eval') + compile('pass', '?', dont_inherit=1, mode='exec') + # Fails on Py2.7: + # Was: compile(memoryview(b"text"), "name", "exec") + self.assertRaises(TypeError, compile) + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'badmode') + self.assertRaises(ValueError, compile, 'print(42)\n', '', 'single', 0xff) + # Raises TypeError in Python < v3.5, ValueError in v3.5: + self.assertRaises((TypeError, ValueError), compile, chr(0), 'f', 'exec') + self.assertRaises(TypeError, compile, 'pass', '?', 'exec', + mode='eval', source='0', filename='tmp') + compile('print("\xe5")\n', '', 'exec') + self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad') + + # test the optimize argument + # These tests fail on Py2.7 ... + + # codestr = '''def f(): + # """doc""" + # try: + # assert False + # except AssertionError: + # return (True, f.__doc__) + # else: + # return (False, f.__doc__) + # ''' + # def f(): """doc""" + # values = [(-1, __debug__, f.__doc__), + # (0, True, 'doc'), + # (1, False, 'doc'), + # (2, False, None)] + # for optval, debugval, docstring in values: + # # test both direct compilation and compilation via AST + # codeobjs = [] + # codeobjs.append(compile(codestr, "", "exec", optimize=optval)) + # tree = ast.parse(codestr) + # codeobjs.append(compile(tree, "", "exec", optimize=optval)) + # for code in codeobjs: + # ns = {} + # exec_(code, ns) + # rv = ns['f']() + # self.assertEqual(rv, (debugval, docstring)) + + def test_delattr(self): + sys.spam = 1 + delattr(sys, 'spam') + self.assertRaises(TypeError, delattr) + + def test_dir(self): + # dir(wrong number of arguments) + self.assertRaises(TypeError, dir, 42, 42) + + # dir() - local scope + local_var = 1 + self.assertIn('local_var', dir()) + + # dir(module) + self.assertIn('exit', dir(sys)) + + # dir(module_with_invalid__dict__) + class Foo(types.ModuleType): + __dict__ = 8 + f = Foo(native_str("foo")) + self.assertRaises(TypeError, dir, f) + + # dir(type) + self.assertIn("strip", dir(str)) + self.assertNotIn("__mro__", dir(str)) + + # dir(obj) + class Foo(object): + def __init__(self): + self.x = 7 + self.y = 8 + self.z = 9 + f = Foo() + self.assertIn("y", dir(f)) + + # dir(obj_no__dict__) + class Foo(object): + __slots__ = [] + f = Foo() + self.assertIn("__repr__", dir(f)) + + # dir(obj_no__class__with__dict__) + # (an ugly trick to cause getattr(f, "__class__") to fail) + class Foo(object): + __slots__ = ["__class__", "__dict__"] + def __init__(self): + self.bar = "wow" + f = Foo() + self.assertNotIn("__repr__", dir(f)) + self.assertIn("bar", dir(f)) + + # dir(obj_using __dir__) + class Foo(object): + def __dir__(self): + return ["kan", "ga", "roo"] + f = Foo() + self.assertTrue(dir(f) == ["ga", "kan", "roo"]) + + # dir(obj__dir__tuple) + # Was: + # class Foo(object): + # def __dir__(self): + # return ("b", "c", "a") + # res = dir(Foo()) + # self.assertIsInstance(res, list) + # self.assertTrue(res == ["a", "b", "c"]) + + # dir(obj__dir__not_sequence) + class Foo(object): + def __dir__(self): + return 7 + f = Foo() + self.assertRaises(TypeError, dir, f) + + # These tests fail on Py2: + # # dir(traceback) + # try: + # raise IndexError + # except: + # self.assertEqual(len(dir(sys.exc_info()[2])), 4) + # + # # test that object has a __dir__() + # self.assertEqual(sorted([].__dir__()), dir([])) + + def test_divmod(self): + self.assertEqual(divmod(12, 7), (1, 5)) + self.assertEqual(divmod(-12, 7), (-2, 2)) + self.assertEqual(divmod(12, -7), (-2, -2)) + self.assertEqual(divmod(-12, -7), (1, -5)) + + self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0)) + + for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)), + (-3.25, 1.0, (-4.0, 0.75)), + (3.25, -1.0, (-4.0, -0.75)), + (-3.25, -1.0, (3.0, -0.25))]: + result = divmod(num, denom) + self.assertAlmostEqual(result[0], exp_result[0]) + self.assertAlmostEqual(result[1], exp_result[1]) + + self.assertRaises(TypeError, divmod) + + def test_eval(self): + self.assertEqual(eval('1+1'), 2) + self.assertEqual(eval(' 1+1\n'), 2) + globals = {'a': 1, 'b': 2} + locals = {'b': 200, 'c': 300} + self.assertEqual(eval('a', globals) , 1) + self.assertEqual(eval('a', globals, locals), 1) + self.assertEqual(eval('b', globals, locals), 200) + self.assertEqual(eval('c', globals, locals), 300) + globals = {'a': 1, 'b': 2} + locals = {'b': 200, 'c': 300} + bom = b'\xef\xbb\xbf' + self.assertEqual(eval(bom + b'a', globals, locals), 1) + self.assertEqual(eval('"\xe5"', globals), "\xe5") + self.assertRaises(TypeError, eval) + self.assertRaises(TypeError, eval, ()) + self.assertRaises(SyntaxError, eval, bom[:2] + b'a') + + def test_general_eval(self): + # Tests that general mappings can be used for the locals argument + + class M: + "Test mapping interface versus possible calls from eval()." + def __getitem__(self, key): + if key == 'a': + return 12 + raise KeyError + def keys(self): + return list('xyz') + + m = M() + g = globals() + self.assertEqual(eval('a', g, m), 12) + self.assertRaises(NameError, eval, 'b', g, m) + self.assertEqual(eval('dir()', g, m), list('xyz')) + self.assertEqual(eval('globals()', g, m), g) + self.assertEqual(eval('locals()', g, m), m) + self.assertRaises(TypeError, eval, 'a', m) + class A: + "Non-mapping" + pass + m = A() + self.assertRaises(TypeError, eval, 'a', g, m) + + # Verify that dict subclasses work as well + class D(dict): + def __getitem__(self, key): + if key == 'a': + return 12 + return dict.__getitem__(self, key) + def keys(self): + return list('xyz') + + d = D() + self.assertEqual(eval('a', g, d), 12) + self.assertRaises(NameError, eval, 'b', g, d) + self.assertEqual(eval('dir()', g, d), list('xyz')) + self.assertEqual(eval('globals()', g, d), g) + self.assertEqual(eval('locals()', g, d), d) + + # Verify locals stores (used by list comps) + eval('[locals() for i in (2,3)]', g, d) + if PY3: + from collections import UserDict + else: + from UserDict import UserDict + eval('[locals() for i in (2,3)]', g, UserDict()) + + class SpreadSheet: + "Sample application showing nested, calculated lookups." + _cells = {} + def __setitem__(self, key, formula): + self._cells[key] = formula + def __getitem__(self, key): + return eval(self._cells[key], globals(), self) + + ss = SpreadSheet() + ss['a1'] = '5' + ss['a2'] = 'a1*6' + ss['a3'] = 'a2*7' + self.assertEqual(ss['a3'], 210) + + # Verify that dir() catches a non-list returned by eval + # SF bug #1004669 + class C: + def __getitem__(self, item): + raise KeyError(item) + def keys(self): + return 1 # used to be 'a' but that's no longer an error + self.assertRaises(TypeError, eval, 'dir()', globals(), C()) + + def test_exec_(self): + g = {} + exec_('z = 1', g) + if '__builtins__' in g: + del g['__builtins__'] + self.assertEqual(g, {'z': 1}) + + exec_('z = 1+1', g) + if '__builtins__' in g: + del g['__builtins__'] + self.assertEqual(g, {'z': 2}) + g = {} + l = {} + + with check_warnings(): + warnings.filterwarnings("ignore", "global statement", + module="") + exec_('global a; a = 1; b = 2', g, l) + if '__builtins__' in g: + del g['__builtins__'] + if '__builtins__' in l: + del l['__builtins__'] + self.assertEqual((g, l), ({'a': 1}, {'b': 2})) + + def test_exec_globals(self): + code = compile("print('Hello World!')", "", "exec") + # no builtin function + # Was: + # self.assertRaisesRegex(NameError, "name 'print' is not defined", + # exec_, code, {'__builtins__': {}}) + # Now: + self.assertRaises(NameError, + exec_, code, {'__builtins__': {}}) + # __builtins__ must be a mapping type + # Was: + # self.assertRaises(TypeError, + # exec_, code, {'__builtins__': 123}) + # Raises a NameError again on Py2 + + # no __build_class__ function + code = compile("class A: pass", "", "exec") + # Was: + # self.assertRaisesRegex(NameError, "__build_class__ not found", + # exec_, code, {'__builtins__': {}}) + self.assertRaises(NameError, + exec_, code, {'__builtins__': {}}) + + class frozendict_error(Exception): + pass + + class frozendict(dict): + def __setitem__(self, key, value): + raise frozendict_error("frozendict is readonly") + + # This test seems to fail with "TypeError: 'module' object is not iterable": + # # read-only builtins + # frozen_builtins = frozendict(__builtins__) + # code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec") + # self.assertRaises(frozendict_error, + # exec_, code, {'__builtins__': frozen_builtins}) + + # read-only globals + namespace = frozendict({}) + code = compile("x=1", "test", "exec") + self.assertRaises(frozendict_error, + exec_, code, namespace) + + def test_exec_redirected(self): + savestdout = sys.stdout + sys.stdout = None # Whatever that cannot flush() + try: + # Used to raise SystemError('error return without exception set') + exec_('a') + except NameError: + pass + finally: + sys.stdout = savestdout + + def test_filter(self): + self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) + self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) + self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) + self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81]) + self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81]) + def identity(item): + return 1 + filter(identity, Squares(5)) + self.assertRaises(TypeError, filter) + class BadSeq(object): + def __getitem__(self, index): + if index<4: + return 42 + raise ValueError + self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq())) + def badfunc(): + pass + self.assertRaises(TypeError, list, filter(badfunc, range(5))) + + # test bltinmodule.c::filtertuple() + self.assertEqual(list(filter(None, (1, 2))), [1, 2]) + self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) + self.assertRaises(TypeError, list, filter(42, (1, 2))) + + @expectedFailurePY2 + def test_filter_pickle(self): + f1 = filter(filter_char, "abcdeabcde") + f2 = filter(filter_char, "abcdeabcde") + self.check_iter_pickle(f1, list(f2)) + + def test_getattr(self): + self.assertTrue(getattr(sys, 'stdout') is sys.stdout) + self.assertRaises(TypeError, getattr, sys, 1) + self.assertRaises(TypeError, getattr, sys, 1, "foo") + self.assertRaises(TypeError, getattr) + # These tests fail on Py2: + # self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode)) + # unicode surrogates are not encodable to the default encoding (utf8) + # self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E") + # This test fails on Py2 + + def test_hasattr(self): + self.assertTrue(hasattr(sys, 'stdout')) + self.assertRaises(TypeError, hasattr, sys, 1) + self.assertRaises(TypeError, hasattr) + # Fails on Py2: + # self.assertEqual(False, hasattr(sys, chr(sys.maxunicode))) + + # Check that hasattr propagates all exceptions outside of + # AttributeError. + class A(object): + def __getattr__(self, what): + raise SystemExit + self.assertRaises(SystemExit, hasattr, A(), "b") + class B(object): + def __getattr__(self, what): + raise ValueError + # Was: self.assertRaises(ValueError, hasattr, B(), "b") + # Fails on Py2 + + def test_hash(self): + hash(None) + self.assertEqual(hash(1), hash(1)) + self.assertEqual(hash(1), hash(1.0)) + hash('spam') + self.assertEqual(hash('spam'), hash(b'spam')) + hash((0,1,2,3)) + def f(): pass + self.assertRaises(TypeError, hash, []) + self.assertRaises(TypeError, hash, {}) + # Bug 1536021: Allow hash to return long objects + class X: + def __hash__(self): + return 2**100 + self.assertTrue(isinstance(hash(X()), int)) + class Z(int): + def __hash__(self): + return self + self.assertEqual(hash(Z(42)), hash(42)) + + def test_hex(self): + self.assertEqual(hex(16), '0x10') + self.assertEqual(hex(-16), '-0x10') + self.assertRaises(TypeError, hex, {}) + + def test_id(self): + id(None) + id(1) + id(1.0) + id('spam') + id((0,1,2,3)) + id([0,1,2,3]) + id({'spam': 1, 'eggs': 2, 'ham': 3}) + + # Test input() later, alphabetized as if it were raw_input + + def test_iter(self): + self.assertRaises(TypeError, iter) + self.assertRaises(TypeError, iter, 42, 42) + lists = [("1", "2"), ["1", "2"], "12"] + for l in lists: + i = iter(l) + self.assertEqual(next(i), '1') + self.assertEqual(next(i), '2') + self.assertRaises(StopIteration, next, i) + + def test_isinstance(self): + class C: + pass + class D(C): + pass + class E: + pass + c = C() + d = D() + e = E() + self.assertTrue(isinstance(c, C)) + self.assertTrue(isinstance(d, C)) + self.assertTrue(not isinstance(e, C)) + self.assertTrue(not isinstance(c, D)) + self.assertTrue(not isinstance('foo', E)) + self.assertRaises(TypeError, isinstance, E, 'foo') + self.assertRaises(TypeError, isinstance) + + def test_issubclass(self): + class C: + pass + class D(C): + pass + class E: + pass + c = C() + d = D() + e = E() + self.assertTrue(issubclass(D, C)) + self.assertTrue(issubclass(C, C)) + self.assertTrue(not issubclass(C, D)) + self.assertRaises(TypeError, issubclass, 'foo', E) + self.assertRaises(TypeError, issubclass, E, 'foo') + self.assertRaises(TypeError, issubclass) + + def test_len(self): + self.assertEqual(len('123'), 3) + self.assertEqual(len(()), 0) + self.assertEqual(len((1, 2, 3, 4)), 4) + self.assertEqual(len([1, 2, 3, 4]), 4) + self.assertEqual(len({}), 0) + self.assertEqual(len({'a':1, 'b': 2}), 2) + class BadSeq: + def __len__(self): + raise ValueError + self.assertRaises(ValueError, len, BadSeq()) + class InvalidLen: + def __len__(self): + return None + self.assertRaises(TypeError, len, InvalidLen()) + class FloatLen: + def __len__(self): + return 4.5 + self.assertRaises(TypeError, len, FloatLen()) + class HugeLen: + def __len__(self): + return sys.maxsize + 1 + # Was: self.assertRaises(OverflowError, len, HugeLen()) + class NoLenMethod(object): pass + self.assertRaises(TypeError, len, NoLenMethod()) + + def test_map(self): + self.assertEqual( + list(map(lambda x: x*x, range(1,4))), + [1, 4, 9] + ) + try: + from math import sqrt + except ImportError: + def sqrt(x): + return pow(x, 0.5) + self.assertEqual( + list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])), + [[4.0, 2.0], [9.0, 3.0]] + ) + self.assertEqual( + list(map(lambda x, y: x+y, [1,3,2], [9,1,4])), + [10, 4, 6] + ) + + def plus(*v): + accu = 0 + for i in v: accu = accu + i + return accu + self.assertEqual( + list(map(plus, [1, 3, 7])), + [1, 3, 7] + ) + self.assertEqual( + list(map(plus, [1, 3, 7], [4, 9, 2])), + [1+4, 3+9, 7+2] + ) + self.assertEqual( + list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])), + [1+4+1, 3+9+1, 7+2+0] + ) + self.assertEqual( + list(map(int, Squares(10))), + [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] + ) + def Max(a, b): + if a is None: + return b + if b is None: + return a + return max(a, b) + self.assertEqual( + list(map(Max, Squares(3), Squares(2))), + [0, 1] + ) + self.assertRaises(TypeError, map) + self.assertRaises(TypeError, map, lambda x: x, 42) + class BadSeq: + def __iter__(self): + raise ValueError + yield None + self.assertRaises(ValueError, list, map(lambda x: x, BadSeq())) + def badfunc(x): + raise RuntimeError + self.assertRaises(RuntimeError, list, map(badfunc, range(5))) + + @expectedFailurePY2 + def test_map_pickle(self): + m1 = map(map_char, "Is this the real life?") + m2 = map(map_char, "Is this the real life?") + self.check_iter_pickle(m1, list(m2)) + + def test_max(self): + self.assertEqual(max('123123'), '3') + self.assertEqual(max(1, 2, 3), 3) + self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) + self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) + + self.assertEqual(max(1, 2, 3.0), 3.0) + self.assertEqual(max(1, 2.0, 3), 3) + self.assertEqual(max(1.0, 2, 3), 3) + + for stmt in ( + "max(key=int)", # no args + "max(1, key=int)", # single arg not iterable + "max(1, 2, keystone=int)", # wrong keyword + "max(1, 2, key=int, abc=int)", # two many keywords + "max(1, 2, key=1)", # keyfunc is not callable + ): + try: + exec_(stmt, globals()) + except TypeError: + pass + else: + self.fail(stmt) + + self.assertEqual(max((1,), key=neg), 1) # one elem iterable + self.assertEqual(max((1,2), key=neg), 1) # two elem iterable + self.assertEqual(max(1, 2, key=neg), 1) # two elems + + data = [random.randrange(200) for i in range(100)] + keys = dict((elem, random.randrange(50)) for elem in data) + f = keys.__getitem__ + self.assertEqual(max(data, key=f), + sorted(reversed(data), key=f)[-1]) + + self.assertEqual(max([], default=5), 5) + with self.assertRaises(TypeError): + max(None, default=5) + with self.assertRaises(TypeError): + max(1, 2, default=0) + self.assertEqual(max([], default=0), 0) + self.assertIs(max([], default=None), None) + + def test_min(self): + self.assertEqual(min('123123'), '1') + self.assertEqual(min(1, 2, 3), 1) + self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) + self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) + + self.assertEqual(min(1, 2, 3.0), 1) + self.assertEqual(min(1, 2.0, 3), 1) + self.assertEqual(min(1.0, 2, 3), 1.0) + + self.assertRaises(TypeError, min) + self.assertRaises(TypeError, min, 42) + self.assertRaises(ValueError, min, ()) + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, min, BadSeq()) + self.assertEqual(max(x for x in [5, 4, 3]), 5) + + for stmt in ( + "min(key=int)", # no args + "min(1, key=int)", # single arg not iterable + "min(1, 2, keystone=int)", # wrong keyword + "min(1, 2, key=int, abc=int)", # two many keywords + "min(1, 2, key=1)", # keyfunc is not callable + ): + try: + exec_(stmt, globals()) + except TypeError: + pass + else: + self.fail(stmt) + + self.assertEqual(min((1,), key=neg), 1) # one elem iterable + self.assertEqual(min((1,2), key=neg), 2) # two elem iterable + self.assertEqual(min(1, 2, key=neg), 2) # two elems + + data = [random.randrange(200) for i in range(100)] + keys = dict((elem, random.randrange(50)) for elem in data) + f = keys.__getitem__ + self.assertEqual(min(data, key=f), + sorted(data, key=f)[0]) + self.assertEqual(min([], default=5), 5) + self.assertEqual(min([], default=0), 0) + self.assertIs(min([], default=None), None) + with self.assertRaises(TypeError): + max(None, default=5) + with self.assertRaises(TypeError): + max(1, 2, default=0) + + # Test iterables that can only be looped once #510 + self.assertEqual(min(x for x in [5]), 5) + + def test_next(self): + it = iter(range(2)) + self.assertEqual(next(it), 0) + self.assertEqual(next(it), 1) + self.assertRaises(StopIteration, next, it) + self.assertRaises(StopIteration, next, it) + self.assertEqual(next(it, 42), 42) + + class Iter(object): + def __iter__(self): + return self + def __next__(self): + raise StopIteration + + # Was: it = iter(Iter()) + # Needs this on Py2: + Iter = implements_iterator(Iter) + it = iter(Iter()) + self.assertEqual(next(it, 42), 42) + self.assertRaises(StopIteration, next, it) + + def gen(): + yield 1 + return + + it = gen() + self.assertEqual(next(it), 1) + self.assertRaises(StopIteration, next, it) + self.assertEqual(next(it, 42), 42) + + def test_oct(self): + self.assertEqual(oct(100), '0o144') + self.assertEqual(oct(-100), '-0o144') + self.assertRaises(TypeError, oct, ()) + + def write_testfile(self): + # NB the first 4 lines are also used to test input, below + fp = open(TESTFN, 'w') + try: + fp.write('1+1\n') + fp.write('The quick brown fox jumps over the lazy dog') + fp.write('.\n') + fp.write('Dear John\n') + fp.write('XXX'*100) + fp.write('YYY'*100) + finally: + fp.close() + + def test_open(self): + self.write_testfile() + fp = open(TESTFN, 'r') + try: + self.assertEqual(fp.readline(4), '1+1\n') + self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') + self.assertEqual(fp.readline(4), 'Dear') + self.assertEqual(fp.readline(100), ' John\n') + self.assertEqual(fp.read(300), 'XXX'*100) + self.assertEqual(fp.read(1000), 'YYY'*100) + finally: + fp.close() + unlink(TESTFN) + + def test_open_default_encoding(self): + old_environ = dict(os.environ) + try: + # try to get a user preferred encoding different than the current + # locale encoding to check that open() uses the current locale + # encoding and not the user preferred encoding + for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): + if key in os.environ: + del os.environ[key] + + self.write_testfile() + current_locale_encoding = locale.getpreferredencoding(False) + fp = open(TESTFN, 'w') + try: + self.assertEqual(fp.encoding, current_locale_encoding) + finally: + fp.close() + unlink(TESTFN) + finally: + os.environ.clear() + os.environ.update(old_environ) + + def test_ord(self): + self.assertEqual(ord(' '), 32) + self.assertEqual(ord('A'), 65) + self.assertEqual(ord('a'), 97) + self.assertEqual(ord('\x80'), 128) + self.assertEqual(ord('\xff'), 255) + + self.assertEqual(ord(b' '), 32) + self.assertEqual(ord(b'A'), 65) + self.assertEqual(ord(b'a'), 97) + self.assertEqual(ord(b'\x80'), 128) + self.assertEqual(ord(b'\xff'), 255) + + self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode) + self.assertRaises(TypeError, ord, 42) + + def test_pow(self): + self.assertEqual(pow(0,0), 1) + self.assertEqual(pow(0,1), 0) + self.assertEqual(pow(1,0), 1) + self.assertEqual(pow(1,1), 1) + + self.assertEqual(pow(2,0), 1) + self.assertEqual(pow(2,10), 1024) + self.assertEqual(pow(2,20), 1024*1024) + self.assertEqual(pow(2,30), 1024*1024*1024) + + self.assertEqual(pow(-2,0), 1) + self.assertEqual(pow(-2,1), -2) + self.assertEqual(pow(-2,2), 4) + self.assertEqual(pow(-2,3), -8) + + self.assertAlmostEqual(pow(0.,0), 1.) + self.assertAlmostEqual(pow(0.,1), 0.) + self.assertAlmostEqual(pow(1.,0), 1.) + self.assertAlmostEqual(pow(1.,1), 1.) + + self.assertAlmostEqual(pow(2.,0), 1.) + self.assertAlmostEqual(pow(2.,10), 1024.) + self.assertAlmostEqual(pow(2.,20), 1024.*1024.) + self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) + + self.assertAlmostEqual(pow(-2.,0), 1.) + self.assertAlmostEqual(pow(-2.,1), -2.) + self.assertAlmostEqual(pow(-2.,2), 4.) + self.assertAlmostEqual(pow(-2.,3), -8.) + + for x in 2, int(2), 2.0: + for y in 10, int(10), 10.0: + for z in 1000, int(1000), 1000.0: + if isinstance(x, float) or \ + isinstance(y, float) or \ + isinstance(z, float): + self.assertRaises(TypeError, pow, x, y, z) + else: + self.assertAlmostEqual(pow(x, y, z), 24.0) + + self.assertAlmostEqual(pow(-1, 0.5), 1j) + self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) + + # Raises TypeError in Python < v3.5, ValueError in v3.5: + self.assertRaises((TypeError, ValueError), pow, -1, -2, 3) + self.assertRaises(ValueError, pow, 1, 2, 0) + + self.assertRaises(TypeError, pow) + + def test_input(self): + self.write_testfile() + fp = open(TESTFN, 'r') + savestdin = sys.stdin + savestdout = sys.stdout # Eats the echo + try: + sys.stdin = fp + sys.stdout = BitBucket() + self.assertEqual(input(), "1+1") + self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') + self.assertEqual(input('testing\n'), 'Dear John') + + # SF 1535165: don't segfault on closed stdin + # sys.stdout must be a regular file for triggering + sys.stdout = savestdout + sys.stdin.close() + self.assertRaises(ValueError, input) + + sys.stdout = BitBucket() + sys.stdin = io.StringIO("NULL\0") + self.assertRaises(TypeError, input, 42, 42) + sys.stdin = io.StringIO(" 'whitespace'") + self.assertEqual(input(), " 'whitespace'") + sys.stdin = io.StringIO() + self.assertRaises(EOFError, input) + + del sys.stdout + self.assertRaises(RuntimeError, input, 'prompt') + del sys.stdin + self.assertRaises(RuntimeError, input, 'prompt') + finally: + sys.stdin = savestdin + sys.stdout = savestdout + fp.close() + unlink(TESTFN) + + @expectedFailurePY2 + @unittest.skipUnless(pty, "the pty and signal modules must be available") + def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): + if not sys.stdin.isatty() or not sys.stdout.isatty(): + self.skipTest("stdin and stdout must be ttys") + r, w = os.pipe() + try: + pid, fd = pty.fork() + except (OSError, AttributeError) as e: + os.close(r) + os.close(w) + self.skipTest("pty.fork() raised {0}".format(e)) + if pid == 0: + # Child + try: + # Make sure we don't get stuck if there's a problem + signal.alarm(2) + os.close(r) + # Check the error handlers are accounted for + if stdio_encoding: + sys.stdin = io.TextIOWrapper(sys.stdin.detach(), + encoding=stdio_encoding, + errors='surrogateescape') + sys.stdout = io.TextIOWrapper(sys.stdout.detach(), + encoding=stdio_encoding, + errors='replace') + with open(w, "w") as wpipe: + print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe) + print(ascii(input(prompt)), file=wpipe) + except: + traceback.print_exc() + finally: + # We don't want to return to unittest... + os._exit(0) + # Parent + os.close(w) + os.write(fd, terminal_input + b"\r\n") + # Get results from the pipe + with open(r, "r") as rpipe: + lines = [] + while True: + line = rpipe.readline().strip() + if line == "": + # The other end was closed => the child exited + break + lines.append(line) + # Check the result was got and corresponds to the user's terminal input + if len(lines) != 2: + # Something went wrong, try to get at stderr + with open(fd, "r", encoding="ascii", errors="ignore") as child_output: + self.fail("got %d lines in pipe but expected 2, child output was:\n%s" + % (len(lines), child_output.read())) + os.close(fd) + # Check we did exercise the GNU readline path + self.assertIn(lines[0], set(['tty = True', 'tty = False'])) + if lines[0] != 'tty = True': + self.skipTest("standard IO in should have been a tty") + input_result = eval(lines[1]) # ascii() -> eval() roundtrip + if stdio_encoding: + expected = terminal_input.decode(stdio_encoding, 'surrogateescape') + else: + expected = terminal_input.decode(sys.stdin.encoding) # what else? + self.assertEqual(input_result, expected) + + @expectedFailurePY26 + def test_input_tty(self): + # Test input() functionality when wired to a tty (the code path + # is different and invokes GNU readline if available). + self.check_input_tty("prompt", b"quux") + + @expectedFailurePY26 + def test_input_tty_non_ascii(self): + # Check stdin/stdout encoding is used when invoking GNU readline + self.check_input_tty("prompté", b"quux\xe9", "utf-8") + + @expectedFailurePY26 + def test_input_tty_non_ascii_unicode_errors(self): + # Check stdin/stdout error handler is used when invoking GNU readline + self.check_input_tty("prompté", b"quux\xe9", "ascii") + + # test_int(): see test_int.py for tests of built-in function int(). + + def test_repr(self): + # Was: self.assertEqual(repr(''), "\'\'") + # Why is this failing on Py2.7? A Heisenbug ... + self.assertEqual(repr(0), '0') + self.assertEqual(repr(()), '()') + self.assertEqual(repr([]), '[]') + self.assertEqual(repr({}), '{}') + + # Future versions of the above: + self.assertEqual(repr(str('')), '\'\'') + self.assertEqual(repr(int(0)), '0') + self.assertEqual(repr(dict({})), '{}') + self.assertEqual(repr(dict()), '{}') + + a = [] + a.append(a) + self.assertEqual(repr(a), '[[...]]') + a = {} + a[0] = a + self.assertEqual(repr(a), '{0: {...}}') + + @expectedFailurePY2 + def test_round(self): + self.assertEqual(round(0.0), 0.0) + # Was: self.assertEqual(type(round(0.0)), int) + # Now: + self.assertTrue(isinstance(round(0.0), int)) + self.assertEqual(round(1.0), 1.0) + self.assertEqual(round(10.0), 10.0) + self.assertEqual(round(1000000000.0), 1000000000.0) + self.assertEqual(round(1e20), 1e20) + + self.assertEqual(round(-1.0), -1.0) + self.assertEqual(round(-10.0), -10.0) + self.assertEqual(round(-1000000000.0), -1000000000.0) + self.assertEqual(round(-1e20), -1e20) + + self.assertEqual(round(0.1), 0.0) + self.assertEqual(round(1.1), 1.0) + self.assertEqual(round(10.1), 10.0) + self.assertEqual(round(1000000000.1), 1000000000.0) + + self.assertEqual(round(-1.1), -1.0) + self.assertEqual(round(-10.1), -10.0) + self.assertEqual(round(-1000000000.1), -1000000000.0) + + self.assertEqual(round(0.9), 1.0) + self.assertEqual(round(9.9), 10.0) + self.assertEqual(round(999999999.9), 1000000000.0) + + self.assertEqual(round(-0.9), -1.0) + self.assertEqual(round(-9.9), -10.0) + self.assertEqual(round(-999999999.9), -1000000000.0) + + self.assertEqual(round(-8.0, -1), -10.0) + self.assertEqual(type(round(-8.0, -1)), float) + + self.assertEqual(type(round(-8.0, 0)), float) + self.assertEqual(type(round(-8.0, 1)), float) + + # Check even / odd rounding behaviour + self.assertEqual(round(5.5), 6) + self.assertEqual(round(6.5), 6) + self.assertEqual(round(-5.5), -6) + self.assertEqual(round(-6.5), -6) + + # Check behavior on ints + self.assertEqual(round(0), 0) + self.assertEqual(round(8), 8) + self.assertEqual(round(-8), -8) + # Was: + # self.assertEqual(type(round(0)), int) + # self.assertEqual(type(round(-8, -1)), int) + # self.assertEqual(type(round(-8, 0)), int) + # self.assertEqual(type(round(-8, 1)), int) + # Now: + self.assertTrue(isinstance(round(0), int)) + self.assertTrue(isinstance(round(-8, -1), int)) + self.assertTrue(isinstance(round(-8, 0), int)) + self.assertTrue(isinstance(round(-8, 1), int)) + + # test new kwargs + self.assertEqual(round(number=-8.0, ndigits=-1), -10.0) + + self.assertRaises(TypeError, round) + + # test generic rounding delegation for reals + class TestRound: + def __round__(self): + return 23 + + class TestNoRound: + pass + + self.assertEqual(round(TestRound()), 23) + + self.assertRaises(TypeError, round, 1, 2, 3) + self.assertRaises(TypeError, round, TestNoRound()) + + t = TestNoRound() + t.__round__ = lambda *args: args + self.assertRaises(TypeError, round, t) + self.assertRaises(TypeError, round, t, 0) + + # # Some versions of glibc for alpha have a bug that affects + # # float -> integer rounding (floor, ceil, rint, round) for + # # values in the range [2**52, 2**53). See: + # # + # # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350 + # # + # # We skip this test on Linux/alpha if it would fail. + # linux_alpha = (platform.system().startswith('Linux') and + # platform.machine().startswith('alpha')) + # system_round_bug = round(5e15+1) != 5e15+1 + # @unittest.skipIf(PY26)linux_alpha and system_round_bug, + # "test will fail; failure is probably due to a " + # "buggy system round function") + @skip26 + def test_round_large(self): + # Issue #1869: integral floats should remain unchanged + self.assertEqual(round(5e15-1), 5e15-1) + self.assertEqual(round(5e15), 5e15) + self.assertEqual(round(5e15+1), 5e15+1) + self.assertEqual(round(5e15+2), 5e15+2) + self.assertEqual(round(5e15+3), 5e15+3) + + def test_setattr(self): + setattr(sys, 'spam', 1) + self.assertEqual(sys.spam, 1) + self.assertRaises(TypeError, setattr, sys, 1, 'spam') + self.assertRaises(TypeError, setattr) + + # test_str(): see test_unicode.py and test_bytes.py for str() tests. + + def test_sum(self): + self.assertEqual(sum([]), 0) + self.assertEqual(sum(list(range(2,8))), 27) + self.assertEqual(sum(iter(list(range(2,8)))), 27) + self.assertEqual(sum(Squares(10)), 285) + self.assertEqual(sum(iter(Squares(10))), 285) + self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) + + self.assertRaises(TypeError, sum) + self.assertRaises(TypeError, sum, 42) + self.assertRaises(TypeError, sum, ['a', 'b', 'c']) + self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') + self.assertRaises(TypeError, sum, [b'a', b'c'], b'') + # Was: + # values = [bytearray(b'a'), bytearray(b'b')] + # self.assertRaises(TypeError, sum, values, bytearray(b'')) + # Currently fails on Py2 -- i.e. sum(values, bytearray(b'')) is allowed + self.assertRaises(TypeError, sum, [[1], [2], [3]]) + self.assertRaises(TypeError, sum, [{2:3}]) + self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) + + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, sum, BadSeq()) + + empty = [] + sum(([x] for x in range(10)), empty) + self.assertEqual(empty, []) + + def test_type(self): + self.assertEqual(type(''), type('123')) + self.assertNotEqual(type(''), type(())) + + # We don't want self in vars(), so these are static methods + + @staticmethod + def get_vars_f0(): + return vars() + + @staticmethod + def get_vars_f2(): + BuiltinTest.get_vars_f0() + a = 1 + b = 2 + return vars() + + class C_get_vars(object): + def getDict(self): + return {'a':2} + __dict__ = property(fget=getDict) + + def test_vars(self): + self.assertEqual(set(vars()), set(dir())) + self.assertEqual(set(vars(sys)), set(dir(sys))) + self.assertEqual(self.get_vars_f0(), {}) + self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) + self.assertRaises(TypeError, vars, 42, 42) + self.assertRaises(TypeError, vars, 42) + self.assertEqual(vars(self.C_get_vars()), {'a':2}) + + def test_zip(self): + a = (1, 2, 3) + b = (4, 5, 6) + t = [(1, 4), (2, 5), (3, 6)] + self.assertEqual(list(zip(a, b)), t) + b = [4, 5, 6] + self.assertEqual(list(zip(a, b)), t) + b = (4, 5, 6, 7) + self.assertEqual(list(zip(a, b)), t) + class I: + def __getitem__(self, i): + if i < 0 or i > 2: raise IndexError + return i + 4 + self.assertEqual(list(zip(a, I())), t) + self.assertEqual(list(zip()), []) + self.assertEqual(list(zip(*[])), []) + self.assertRaises(TypeError, zip, None) + class G: + pass + self.assertRaises(TypeError, zip, a, G()) + self.assertRaises(RuntimeError, zip, a, TestFailingIter()) + + # Make sure zip doesn't try to allocate a billion elements for the + # result list when one of its arguments doesn't say how long it is. + # A MemoryError is the most likely failure mode. + class SequenceWithoutALength: + def __getitem__(self, i): + if i == 5: + raise IndexError + else: + return i + self.assertEqual( + list(zip(SequenceWithoutALength(), range(2**30))), + list(enumerate(range(5))) + ) + + class BadSeq: + def __getitem__(self, i): + if i == 5: + raise ValueError + else: + return i + self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq())) + + @expectedFailurePY2 + def test_zip_pickle(self): + a = (1, 2, 3) + b = (4, 5, 6) + t = [(1, 4), (2, 5), (3, 6)] + z1 = zip(a, b) + self.check_iter_pickle(z1, t) + + def test_format(self): + # Test the basic machinery of the format() builtin. Don't test + # the specifics of the various formatters + self.assertEqual(format(3, ''), '3') + + # Returns some classes to use for various tests. There's + # an old-style version, and a new-style version + def classes_new(): + class A(object): + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromA(A): + pass + + class Simple(object): pass + class DerivedFromSimple(Simple): + def __init__(self, x): + self.x = x + def __format__(self, format_spec): + return str(self.x) + format_spec + class DerivedFromSimple2(DerivedFromSimple): pass + return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 + + def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2): + self.assertEqual(format(A(3), 'spec'), '3spec') + self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec') + self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc') + self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'), + '10abcdef') + + class_test(*classes_new()) + + def empty_format_spec(value): + # test that: + # format(x, '') == str(x) + # format(x) == str(x) + self.assertEqual(format(value, ""), str(value)) + self.assertEqual(format(value), str(value)) + + # for builtin types, format(x, "") == str(x) + empty_format_spec(17**13) + empty_format_spec(1.0) + empty_format_spec(3.1415e104) + empty_format_spec(-3.1415e104) + empty_format_spec(3.1415e-104) + empty_format_spec(-3.1415e-104) + empty_format_spec(object) + empty_format_spec(None) + + # TypeError because self.__format__ returns the wrong type + class BadFormatResult: + def __format__(self, format_spec): + return 1.0 + self.assertRaises(TypeError, format, BadFormatResult(), "") + + # TypeError because format_spec is not unicode or str + self.assertRaises(TypeError, format, object(), 4) + self.assertRaises(TypeError, format, object(), object()) + + # tests for object.__format__ really belong elsewhere, but + # there's no good place to put them + x = object().__format__('') + self.assertTrue(x.startswith('= 4: + if should_raise_warning: + self.assertRaises(TypeError, format, obj, fmt_str) + else: + try: + format(obj, fmt_str) + except TypeError: + self.fail('object.__format__ raised TypeError unexpectedly') + else: + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always", DeprecationWarning) + format(obj, fmt_str) + # Was: + # if should_raise_warning: + # self.assertEqual(len(w), 1) + # self.assertIsInstance(w[0].message, DeprecationWarning) + # self.assertIn('object.__format__ with a non-empty format ' + # 'string', str(w[0].message)) + # else: + # self.assertEqual(len(w), 0) + # Py2.7 fails these tests + + fmt_strs = ['', 's'] + + class A: + def __format__(self, fmt_str): + return format('', fmt_str) + + for fmt_str in fmt_strs: + test_deprecated_format_string(A(), fmt_str, False) + + class B: + pass + + class C(object): + pass + + for cls in [object, B, C]: + for fmt_str in fmt_strs: + test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0) + # -------------------------------------------------------------------- + + # make sure we can take a subclass of str as a format spec + class DerivedFromStr(str): pass + self.assertEqual(format(0, DerivedFromStr('10')), ' 0') + + def test_bin(self): + self.assertEqual(bin(0), '0b0') + self.assertEqual(bin(1), '0b1') + self.assertEqual(bin(-1), '-0b1') + self.assertEqual(bin(2**65), '0b1' + '0' * 65) + self.assertEqual(bin(2**65-1), '0b' + '1' * 65) + self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65) + self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65) + + def test_bytearray_translate(self): + x = bytearray(b"abc") + self.assertRaises(ValueError, x.translate, b"1", 1) + self.assertRaises(TypeError, x.translate, b"1"*256, 1) + + def test_construct_singletons(self): + for const in None, Ellipsis, NotImplemented: + tp = type(const) + # Was: self.assertIs(tp(), const) + # Fails for Py2 + self.assertRaises(TypeError, tp, 1, 2) + self.assertRaises(TypeError, tp, a=1, b=2) + +class TestSorted(unittest.TestCase): + + def test_basic(self): + data = list(range(100)) + copy = data[:] + random.shuffle(copy) + self.assertEqual(data, sorted(copy)) + self.assertNotEqual(data, copy) + + data.reverse() + random.shuffle(copy) + self.assertEqual(data, sorted(copy, key=lambda x: -x)) + self.assertNotEqual(data, copy) + random.shuffle(copy) + self.assertEqual(data, sorted(copy, reverse=1)) + self.assertNotEqual(data, copy) + + def test_inputtypes(self): + s = 'abracadabra' + types = [list, tuple, str] + for T in types: + self.assertEqual(sorted(s), sorted(T(s))) + + s = ''.join(set(s)) # unique letters only + types = [str, set, frozenset, list, tuple, dict.fromkeys] + for T in types: + self.assertEqual(sorted(s), sorted(T(s))) + + def test_baddecorator(self): + data = 'The quick Brown fox Jumped over The lazy Dog'.split() + self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) + + + # def test_input(self, interpreter='python2'): + # """ + # Passes in a string to the waiting input() + # """ + # code = ''' + # from future.builtins import input + # def greet(name): + # print "Hello, {0}!".format(name) + # print "What's your name?" + # name = input() + # greet(name) + # ''' + # with open(self.tempdir + 'input_test_script.py', 'w') as f: + # f.write(textwrap.dedent(code)) + # p1 = Popen([interpreter, 'input_test_script.py'], stdout=PIPE, stdin=PIPE, stderr=None) + # (stdout, stderr) = p1.communicate(b'Ed') + # # print(stdout) + # # print(stderr) + # self.assertEqual(stdout, b"What's your name?\nHello, Ed!\n") + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins_explicit_import.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins_explicit_import.py new file mode 100644 index 0000000..24800c4 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_builtins_explicit_import.py @@ -0,0 +1,18 @@ +""" +Tests to make sure that all builtins can be imported explicitly from the +future.builtins namespace. +""" + +from __future__ import absolute_import, division, unicode_literals +from future.builtins import (filter, map, zip) +from future.builtins import (ascii, chr, hex, input, isinstance, next, oct, open) +from future.builtins import (bytes, dict, int, range, round, str, super) +from future.tests.base import unittest + + +class TestBuiltinsExplicitImport(unittest.TestCase): + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_bytes.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_bytes.py new file mode 100644 index 0000000..b9b157d --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_bytes.py @@ -0,0 +1,786 @@ +# -*- coding: utf-8 -*- +""" +Tests for the backported bytes object +""" + +from __future__ import absolute_import, unicode_literals, print_function +from future.builtins import * +from future import utils + +from numbers import Integral +from future.tests.base import unittest, expectedFailurePY2 + + +TEST_UNICODE_STR = u'ℝεα∂@ßʟ℮ ☂ℯṧт υηḯ¢☺ḓ℮' +# Tk icon as a .gif: +TEST_BYTE_STR = b'GIF89a\x0e\x00\x0b\x00\x80\xff\x00\xff\x00\x00\xc0\xc0\xc0!\xf9\x04\x01\x00\x00\x01\x00,\x00\x00\x00\x00\x0e\x00\x0b\x00@\x02\x1f\x0c\x8e\x10\xbb\xcan\x90\x99\xaf&\xd8\x1a\xce\x9ar\x06F\xd7\xf1\x90\xa1c\x9e\xe8\x84\x99\x89\x97\xa2J\x01\x00;\x1a\x14\x00;;\xba\nD\x14\x00\x00;;' + + +class TestBytes(unittest.TestCase): + def test_bytes_encoding_arg(self): + """ + The bytes class has changed in Python 3 to accept an + additional argument in the constructor: encoding. + + It would be nice to support this without breaking the + isinstance(..., bytes) test below. + """ + u = u'Unicode string: \u5b54\u5b50' + b = bytes(u, encoding='utf-8') + self.assertEqual(b, u.encode('utf-8')) + + nu = str(u) + b = bytes(nu, encoding='utf-8') + self.assertEqual(b, u.encode('utf-8')) + + def test_bytes_encoding_arg_issue_193(self): + """ + This used to be True: bytes(str(u'abc'), 'utf8') == b"b'abc'" + """ + u = u'abc' + b = bytes(str(u), 'utf8') + self.assertNotEqual(b, b"b'abc'") + self.assertEqual(b, b'abc') + self.assertEqual(b, bytes(b'abc')) + + def test_bytes_encoding_arg_non_kwarg(self): + """ + As above, but with a positional argument + """ + u = u'Unicode string: \u5b54\u5b50' + b = bytes(u, 'utf-8') + self.assertEqual(b, u.encode('utf-8')) + + nu = str(u) + b = bytes(nu, 'utf-8') + self.assertEqual(b, u.encode('utf-8')) + + def test_bytes_string_no_encoding(self): + with self.assertRaises(TypeError): + bytes(u'ABC') + + def test_bytes_int(self): + """ + In Py3, bytes(int) -> bytes object of size given by the parameter initialized with null + """ + self.assertEqual(bytes(5), b'\x00\x00\x00\x00\x00') + # Test using newint: + self.assertEqual(bytes(int(5)), b'\x00\x00\x00\x00\x00') + self.assertTrue(isinstance(bytes(int(5)), bytes)) + + # Negative counts are not allowed in Py3: + with self.assertRaises(ValueError): + bytes(-1) + with self.assertRaises(ValueError): + bytes(int(-1)) + + @unittest.skipIf(utils.PY3, 'test not needed on Py3: all ints are long') + def test_bytes_long(self): + """ + As above, but explicitly feeding in a long on Py2. Note that + checks like: + isinstance(n, int) + are fragile on Py2, because isinstance(10L, int) is False. + """ + m = long(5) + n = long(-1) + self.assertEqual(bytes(m), b'\x00\x00\x00\x00\x00') + # Negative counts are not allowed in Py3: + with self.assertRaises(ValueError): + bytes(n) + + def test_bytes_empty(self): + """ + bytes() -> b'' + """ + self.assertEqual(bytes(), b'') + + def test_bytes_iterable_of_ints(self): + self.assertEqual(bytes([65, 66, 67]), b'ABC') + self.assertEqual(bytes([int(120), int(121), int(122)]), b'xyz') + + def test_bytes_bytes(self): + self.assertEqual(bytes(b'ABC'), b'ABC') + + def test_bytes_is_bytes(self): + b = bytes(b'ABC') + self.assertTrue(bytes(b) is b) + self.assertEqual(repr(bytes(b)), "b'ABC'") + + def test_bytes_fromhex(self): + self.assertEqual(bytes.fromhex('bb 0f'), b'\xbb\x0f') + self.assertEqual(bytes.fromhex('1234'), b'\x124') + self.assertEqual(bytes.fromhex('12ffa0'), b'\x12\xff\xa0') + b = b'My bytestring' + self.assertEqual(bytes(b).fromhex('bb 0f'), b'\xbb\x0f') + + def test_isinstance_bytes(self): + self.assertTrue(isinstance(bytes(b'blah'), bytes)) + + def test_isinstance_bytes_subclass(self): + """ + Issue #89 + """ + value = bytes(b'abc') + class Magic(bytes): + pass + self.assertTrue(isinstance(value, bytes)) + self.assertFalse(isinstance(value, Magic)) + + def test_isinstance_oldbytestrings_bytes(self): + """ + Watch out for this. Byte-strings produced in various places in Py2 + are of type 'str'. With 'from future.builtins import bytes', 'bytes' + is redefined to be a subclass of 'str', not just an alias for 'str'. + """ + self.assertTrue(isinstance(b'blah', bytes)) # not with the redefined bytes obj + self.assertTrue(isinstance(u'blah'.encode('utf-8'), bytes)) # not with the redefined bytes obj + + def test_bytes_getitem(self): + b = bytes(b'ABCD') + self.assertEqual(b[0], 65) + self.assertEqual(b[-1], 68) + self.assertEqual(b[0:1], b'A') + self.assertEqual(b[:], b'ABCD') + + @expectedFailurePY2 + def test_b_literal_creates_newbytes_object(self): + """ + It would nice if the b'' literal syntax could be coaxed into producing + bytes objects somehow ... ;) + """ + b = b'ABCD' + self.assertTrue(isinstance(b, bytes)) + self.assertEqual(b[0], 65) + self.assertTrue(repr(b).startswith('b')) + + def test_repr(self): + b = bytes(b'ABCD') + self.assertTrue(repr(b).startswith('b')) + + def test_str(self): + b = bytes(b'ABCD') + self.assertEqual(str(b), "b'ABCD'") + + def test_bytes_setitem(self): + b = b'ABCD' + with self.assertRaises(TypeError): + b[0] = b'B' + + def test_bytes_iteration(self): + b = bytes(b'ABCD') + for item in b: + self.assertTrue(isinstance(item, Integral)) + self.assertEqual(list(b), [65, 66, 67, 68]) + + def test_bytes_plus_unicode_string(self): + b = bytes(b'ABCD') + u = u'EFGH' + with self.assertRaises(TypeError): + b + u + + with self.assertRaises(TypeError): + u + b + + def test_bytes_plus_bytes(self): + b1 = bytes(b'ABCD') + b2 = b1 + b1 + self.assertEqual(b2, b'ABCDABCD') + self.assertTrue(isinstance(b2, bytes)) + + b3 = b1 + b'ZYXW' + self.assertEqual(b3, b'ABCDZYXW') + self.assertTrue(isinstance(b3, bytes)) + + b4 = b'ZYXW' + b1 + self.assertEqual(b4, b'ZYXWABCD') + self.assertTrue(isinstance(b4, bytes)) + + def test_find_not_found(self): + self.assertEqual(-1, bytes(b'ABCDE').find(b':')) + + def test_find_found(self): + self.assertEqual(2, bytes(b'AB:CD:E').find(b':')) + + def test_rfind_not_found(self): + self.assertEqual(-1, bytes(b'ABCDE').rfind(b':')) + + def test_rfind_found(self): + self.assertEqual(5, bytes(b'AB:CD:E').rfind(b':')) + + def test_bytes_join_bytes(self): + b = bytes(b' * ') + strings = [b'AB', b'EFGH', b'IJKL'] + result = b.join(strings) + self.assertEqual(result, b'AB * EFGH * IJKL') + self.assertTrue(isinstance(result, bytes)) + + def test_bytes_join_others(self): + b = bytes(b' ') + with self.assertRaises(TypeError): + b.join([42]) + with self.assertRaises(TypeError): + b.join(b'blah') + with self.assertRaises(TypeError): + b.join(bytes(b'blah')) + + def test_bytes_join_unicode_strings(self): + b = bytes(b'ABCD') + strings = [u'EFGH', u'IJKL'] + with self.assertRaises(TypeError): + b.join(strings) + + def test_bytes_replace(self): + b = bytes(b'ABCD') + c = b.replace(b'A', b'F') + self.assertEqual(c, b'FBCD') + self.assertTrue(isinstance(c, bytes)) + + with self.assertRaises(TypeError): + b.replace(b'A', u'F') + with self.assertRaises(TypeError): + b.replace(u'A', b'F') + + def test_bytes_partition(self): + b1 = bytes(b'ABCD') + parts = b1.partition(b'B') + self.assertEqual(parts, (b'A', b'B', b'CD')) + self.assertTrue(all([isinstance(p, bytes) for p in parts])) + + b2 = bytes(b'ABCDABCD') + parts = b2.partition(b'B') + self.assertEqual(parts, (b'A', b'B', b'CDABCD')) + + def test_bytes_rpartition(self): + b2 = bytes(b'ABCDABCD') + parts = b2.rpartition(b'B') + self.assertEqual(parts, (b'ABCDA', b'B', b'CD')) + self.assertTrue(all([isinstance(p, bytes) for p in parts])) + + def test_bytes_contains_something(self): + b = bytes(b'ABCD') + self.assertTrue(b'A' in b) + self.assertTrue(65 in b) + + self.assertTrue(b'AB' in b) + self.assertTrue(bytes([65, 66]) in b) + + self.assertFalse(b'AC' in b) + self.assertFalse(bytes([65, 67]) in b) + + self.assertFalse(b'Z' in b) + self.assertFalse(99 in b) + + with self.assertRaises(TypeError): + u'A' in b + + def test_bytes_index(self): + b = bytes(b'ABCD') + self.assertEqual(b.index(b'B'), 1) + self.assertEqual(b.index(67), 2) + + def test_startswith(self): + b = bytes(b'abcd') + self.assertTrue(b.startswith(b'a')) + self.assertTrue(b.startswith((b'a', b'b'))) + self.assertTrue(b.startswith(bytes(b'ab'))) + self.assertFalse(b.startswith((b'A', b'B'))) + + with self.assertRaises(TypeError) as cm: + b.startswith(65) + with self.assertRaises(TypeError) as cm: + b.startswith([b'A']) + exc = str(cm.exception) + # self.assertIn('bytes', exc) + # self.assertIn('tuple', exc) + + def test_endswith(self): + b = bytes(b'abcd') + self.assertTrue(b.endswith(b'd')) + self.assertTrue(b.endswith((b'c', b'd'))) + self.assertTrue(b.endswith(bytes(b'cd'))) + self.assertFalse(b.endswith((b'A', b'B'))) + + with self.assertRaises(TypeError) as cm: + b.endswith(65) + with self.assertRaises(TypeError) as cm: + b.endswith([b'D']) + exc = str(cm.exception) + # self.assertIn('bytes', exc) + # self.assertIn('tuple', exc) + + def test_decode(self): + b = bytes(b'abcd') + s = b.decode('utf-8') + self.assertEqual(s, 'abcd') + self.assertTrue(isinstance(s, str)) + + def test_encode(self): + b = bytes(b'abcd') + with self.assertRaises(AttributeError) as cm: + b.encode('utf-8') + + def test_eq(self): + """ + Equals: == + """ + b = bytes(b'ABCD') + self.assertEqual(b, b'ABCD') + self.assertTrue(b == b'ABCD') + self.assertEqual(b'ABCD', b) + self.assertEqual(b, b) + self.assertFalse(b == b'ABC') + self.assertFalse(b == bytes(b'ABC')) + self.assertFalse(b == u'ABCD') + self.assertFalse(b == str('ABCD')) + # Fails: + # self.assertFalse(u'ABCD' == b) + self.assertFalse(str('ABCD') == b) + + self.assertFalse(b == list(b)) + self.assertFalse(b == str(b)) + self.assertFalse(b == u'ABC') + self.assertFalse(bytes(b'Z') == 90) + + def test_ne(self): + b = bytes(b'ABCD') + self.assertFalse(b != b) + self.assertFalse(b != b'ABCD') + self.assertTrue(b != b'ABCDEFG') + self.assertTrue(b != bytes(b'ABCDEFG')) + self.assertTrue(b'ABCDEFG' != b) + + # self.assertTrue(b'ABCD' != u'ABCD') + self.assertTrue(b != u'ABCD') + self.assertTrue(b != u'ABCDE') + self.assertTrue(bytes(b'') != str(u'')) + self.assertTrue(str(u'') != bytes(b'')) + + self.assertTrue(b != list(b)) + self.assertTrue(b != str(b)) + + def test_hash(self): + d = {} + b = bytes(b'ABCD') + native_b = b'ABCD' + s = str('ABCD') + native_s = u'ABCD' + d[b] = b + d[s] = s + self.assertEqual(len(d), 2) + # This should overwrite d[s] but not d[b]: + d[native_s] = native_s + self.assertEqual(len(d), 2) + # This should overwrite d[native_s] again: + d[s] = s + self.assertEqual(len(d), 2) + self.assertEqual(set(d.keys()), set([s, b])) + + @unittest.expectedFailure + def test_hash_with_native_types(self): + # Warning: initializing the dict with native Py2 types throws the + # hashing out: + d = {u'ABCD': u'ABCD', b'ABCD': b'ABCD'} + # On Py2: len(d) == 1 + b = bytes(b'ABCD') + s = str('ABCD') + d[s] = s + d[b] = b + # Fails: + self.assertEqual(len(d) > 1) + + def test_add(self): + b = bytes(b'ABC') + c = bytes(b'XYZ') + d = b + c + self.assertTrue(isinstance(d, bytes)) + self.assertEqual(d, b'ABCXYZ') + f = b + b'abc' + self.assertTrue(isinstance(f, bytes)) + self.assertEqual(f, b'ABCabc') + g = b'abc' + b + self.assertTrue(isinstance(g, bytes)) + self.assertEqual(g, b'abcABC') + + def test_cmp(self): + b = bytes(b'ABC') + with self.assertRaises(TypeError): + b > 3 + with self.assertRaises(TypeError): + b > u'XYZ' + with self.assertRaises(TypeError): + b <= 3 + with self.assertRaises(TypeError): + b >= int(3) + with self.assertRaises(TypeError): + b < 3.3 + with self.assertRaises(TypeError): + b > (3.3 + 3j) + with self.assertRaises(TypeError): + b >= (1, 2) + with self.assertRaises(TypeError): + b <= [1, 2] + + def test_mul(self): + b = bytes(b'ABC') + c = b * 4 + self.assertTrue(isinstance(c, bytes)) + self.assertEqual(c, b'ABCABCABCABC') + d = b * int(4) + self.assertTrue(isinstance(d, bytes)) + self.assertEqual(d, b'ABCABCABCABC') + if utils.PY2: + e = b * long(4) + self.assertTrue(isinstance(e, bytes)) + self.assertEqual(e, b'ABCABCABCABC') + + def test_rmul(self): + b = bytes(b'XYZ') + c = 3 * b + self.assertTrue(isinstance(c, bytes)) + self.assertEqual(c, b'XYZXYZXYZ') + d = b * int(3) + self.assertTrue(isinstance(d, bytes)) + self.assertEqual(d, b'XYZXYZXYZ') + if utils.PY2: + e = long(3) * b + self.assertTrue(isinstance(e, bytes)) + self.assertEqual(e, b'XYZXYZXYZ') + + def test_slice(self): + b = bytes(b'ABCD') + c1 = b[:] + self.assertTrue(isinstance(c1, bytes)) + self.assertTrue(c1 == b) + # The following is not true, whereas it is true normally on Py2 and + # Py3. Does this matter?: + # self.assertTrue(c1 is b) + + c2 = b[10:] + self.assertTrue(isinstance(c2, bytes)) + self.assertTrue(c2 == bytes(b'')) + self.assertTrue(c2 == b'') + + c3 = b[:0] + self.assertTrue(isinstance(c3, bytes)) + self.assertTrue(c3 == bytes(b'')) + self.assertTrue(c3 == b'') + + c4 = b[:1] + self.assertTrue(isinstance(c4, bytes)) + self.assertTrue(c4 == bytes(b'A')) + self.assertTrue(c4 == b'A') + + c5 = b[:-1] + self.assertTrue(isinstance(c5, bytes)) + self.assertTrue(c5 == bytes(b'ABC')) + self.assertTrue(c5 == b'ABC') + + def test_bytes_frozenset(self): + _ALWAYS_SAFE = bytes(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'abcdefghijklmnopqrstuvwxyz' + b'0123456789' + b'_.-') # from Py3.3's urllib.parse + s = frozenset(_ALWAYS_SAFE) + self.assertTrue(65 in s) + self.assertFalse(64 in s) + # Convert back to bytes + b1 = bytes(s) + self.assertTrue(65 in b1) + self.assertEqual(set(b1), set(_ALWAYS_SAFE)) + + def test_bytes_within_range(self): + """ + Python 3 does this: + >>> bytes([255, 254, 256]) + ValueError + ... + ValueError: bytes must be in range(0, 256) + + Ensure our bytes() constructor has the same behaviour + """ + b1 = bytes([254, 255]) + self.assertEqual(b1, b'\xfe\xff') + with self.assertRaises(ValueError): + b2 = bytes([254, 255, 256]) + + def test_bytes_hasattr_encode(self): + """ + This test tests whether hasattr(b, 'encode') is False, like it is on Py3. + """ + b = bytes(b'abcd') + self.assertFalse(hasattr(b, 'encode')) + self.assertTrue(hasattr(b, 'decode')) + + def test_quote_from_bytes(self): + """ + This test was failing in the backported urllib.parse module in quote_from_bytes + """ + empty = bytes([]) + self.assertEqual(empty, b'') + self.assertTrue(type(empty), bytes) + + empty2 = bytes(()) + self.assertEqual(empty2, b'') + self.assertTrue(type(empty2), bytes) + + safe = bytes(u'Philosopher guy: 孔子. More text here.'.encode('utf-8')) + safe = bytes([c for c in safe if c < 128]) + self.assertEqual(safe, b'Philosopher guy: . More text here.') + self.assertTrue(type(safe), bytes) + + def test_rstrip(self): + b = bytes(b'abcd') + c = b.rstrip(b'd') + self.assertEqual(c, b'abc') + self.assertEqual(type(c), type(b)) + + def test_maketrans(self): + """ + Issue #51. + + Test is from Py3.3.5. + """ + transtable = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' + self.assertEqual(bytes.maketrans(b'', b''), transtable) + + transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377' + self.assertEqual(bytes.maketrans(b'abc', b'xyz'), transtable) + + transtable = b'\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374xyz' + self.assertEqual(bytes.maketrans(b'\375\376\377', b'xyz'), transtable) + self.assertRaises(ValueError, bytes.maketrans, b'abc', b'xyzq') + self.assertRaises(TypeError, bytes.maketrans, 'abc', 'def') + + @unittest.skipUnless(utils.PY2, 'test requires Python 2') + def test_mod_custom_dict(self): + import UserDict + + class MyDict(UserDict.UserDict): + pass + + d = MyDict() + d['foo'] = bytes(b'bar') + self.assertFalse(isinstance(d, dict)) + self.assertTrue(isinstance(d, UserDict.UserDict)) + + self.assertEqual(bytes(b'%(foo)s') % d, b'bar') + + @unittest.skipUnless(utils.PY35_PLUS or utils.PY2, + 'test requires Python 2 or 3.5+') + def test_mod_more(self): + self.assertEqual(b'%s' % b'aaa', b'aaa') + self.assertEqual(bytes(b'%s') % b'aaa', b'aaa') + self.assertEqual(bytes(b'%s') % bytes(b'aaa'), b'aaa') + + self.assertEqual(b'%s' % (b'aaa',), b'aaa') + self.assertEqual(bytes(b'%s') % (b'aaa',), b'aaa') + self.assertEqual(bytes(b'%s') % (bytes(b'aaa'),), b'aaa') + + self.assertEqual(bytes(b'%(x)s') % {b'x': b'aaa'}, b'aaa') + self.assertEqual(bytes(b'%(x)s') % {b'x': bytes(b'aaa')}, b'aaa') + + @unittest.skipUnless(utils.PY35_PLUS or utils.PY2, + 'test requires Python 2 or 3.5+') + def test_mod(self): + """ + From Py3.5 test suite (post-PEP 461). + + The bytes mod code is in _PyBytes_Format() in bytesobject.c in Py3.5. + """ + + # XXX Add support for %b! + # + # b = bytes(b'hello, %b!') + # orig = b + # b = b % b'world' + # self.assertEqual(b, b'hello, world!') + # self.assertEqual(orig, b'hello, %b!') + # self.assertFalse(b is orig) + + b = bytes(b'%s / 100 = %d%%') + a = b % (b'seventy-nine', 79) + self.assertEqual(a, b'seventy-nine / 100 = 79%') + + b = bytes(b'%s / 100 = %d%%') + a = b % (bytes(b'seventy-nine'), 79) + self.assertEqual(a, b'seventy-nine / 100 = 79%') + + @unittest.skipUnless(utils.PY35_PLUS or utils.PY2, + 'test requires Python 2 or 3.5+') + def test_imod(self): + """ + From Py3.5 test suite (post-PEP 461) + """ + # if (3, 0) <= sys.version_info[:2] < (3, 5): + # raise unittest.SkipTest('bytes % not yet implemented on Py3.0-3.4') + + # b = bytes(b'hello, %b!') + # orig = b + # b %= b'world' + # self.assertEqual(b, b'hello, world!') + # self.assertEqual(orig, b'hello, %b!') + # self.assertFalse(b is orig) + + b = bytes(b'%s / 100 = %d%%') + b %= (b'seventy-nine', 79) + self.assertEqual(b, b'seventy-nine / 100 = 79%') + + b = bytes(b'%s / 100 = %d%%') + b %= (bytes(b'seventy-nine'), 79) + self.assertEqual(b, b'seventy-nine / 100 = 79%') + + # def test_mod_pep_461(self): + # """ + # Test for the PEP 461 functionality (resurrection of %s formatting for + # bytes). + # """ + # b1 = bytes(b'abc%b') + # b2 = b1 % b'def' + # self.assertEqual(b2, b'abcdef') + # self.assertTrue(isinstance(b2, bytes)) + # self.assertEqual(type(b2), bytes) + # b3 = b1 % bytes(b'def') + # self.assertEqual(b3, b'abcdef') + # self.assertTrue(isinstance(b3, bytes)) + # self.assertEqual(type(b3), bytes) + # + # # %s is supported for backwards compatibility with Py2's str + # b4 = bytes(b'abc%s') + # b5 = b4 % b'def' + # self.assertEqual(b5, b'abcdef') + # self.assertTrue(isinstance(b5, bytes)) + # self.assertEqual(type(b5), bytes) + # b6 = b4 % bytes(b'def') + # self.assertEqual(b6, b'abcdef') + # self.assertTrue(isinstance(b6, bytes)) + # self.assertEqual(type(b6), bytes) + # + # self.assertEqual(bytes(b'%c') % 48, b'0') + # self.assertEqual(bytes(b'%c') % b'a', b'a') + # + # # For any numeric code %x, formatting of + # # b"%x" % val + # # is supposed to be equivalent to + # # ("%x" % val).encode("ascii") + # for code in b'xdiouxXeEfFgG': + # bytechar = bytes([code]) + # pct_str = u"%" + bytechar.decode('ascii') + # for val in range(300): + # self.assertEqual(bytes(b"%" + bytechar) % val, + # (pct_str % val).encode("ascii")) + # + # with self.assertRaises(TypeError): + # bytes(b'%b') % 3.14 + # # Traceback (most recent call last): + # # ... + # # TypeError: b'%b' does not accept 'float' + # + # with self.assertRaises(TypeError): + # bytes(b'%b') % 'hello world!' + # # Traceback (most recent call last): + # # ... + # # TypeError: b'%b' does not accept 'str' + # + # self.assertEqual(bytes(b'%a') % 3.14, b'3.14') + # + # self.assertEqual(bytes(b'%a') % b'abc', b"b'abc'") + # self.assertEqual(bytes(b'%a') % bytes(b'abc'), b"b'abc'") + # + # self.assertEqual(bytes(b'%a') % 'def', b"'def'") + # + # # PEP 461 was updated after an Py3.5 alpha release to specify that %r is now supported + # # for compatibility: http://legacy.python.org/dev/peps/pep-0461/#id16 + # assert bytes(b'%r' % b'abc') == bytes(b'%a' % b'abc') + # + # # with self.assertRaises(TypeError): + # # bytes(b'%r' % 'abc') + + @expectedFailurePY2 + def test_multiple_inheritance(self): + """ + Issue #96 (for newbytes instead of newobject) + """ + if utils.PY2: + from collections import Container + else: + from collections.abc import Container + + class Base(bytes): + pass + + class Foo(Base, Container): + def __contains__(self, item): + return False + + @expectedFailurePY2 + def test_with_metaclass_and_bytes(self): + """ + Issue #91 (for newdict instead of newobject) + """ + from future.utils import with_metaclass + + class MetaClass(type): + pass + + class TestClass(with_metaclass(MetaClass, bytes)): + pass + + def test_surrogateescape_decoding(self): + """ + Tests whether surrogateescape decoding works correctly. + """ + pairs = [(u'\udcc3', b'\xc3'), + (u'\udcff', b'\xff')] + + for (s, b) in pairs: + decoded = bytes(b).decode('utf-8', 'surrogateescape') + self.assertEqual(s, decoded) + self.assertTrue(isinstance(decoded, str)) + self.assertEqual(b, decoded.encode('utf-8', 'surrogateescape')) + + def test_issue_171_part_a(self): + b1 = str(u'abc \u0123 do re mi').encode(u'utf_8') + b2 = bytes(u'abc \u0123 do re mi', u'utf_8') + b3 = bytes(str(u'abc \u0123 do re mi'), u'utf_8') + + @expectedFailurePY2 + def test_issue_171_part_b(self): + """ + Tests whether: + >>> nativebytes = bytes ; nativestr = str ; from builtins import * + >>> nativebytes(bytes(b'asdf'))[0] == b'a' == b'asdf' + """ + nativebytes = type(b'') + nativestr = type('') + b = nativebytes(bytes(b'asdf')) + self.assertEqual(b, b'asdf') + + def test_cast_to_bytes(self): + """ + Tests whether __bytes__ method is called + """ + + class TestObject: + def __bytes__(self): + return b'asdf' + + self.assertEqual(bytes(TestObject()), b'asdf') + + def test_cast_to_bytes_iter_precedence(self): + """ + Tests that call to __bytes__ is preferred to iteration + """ + + class TestObject: + def __bytes__(self): + return b'asdf' + + def __iter__(self): + return iter(b'hjkl') + + self.assertEqual(bytes(TestObject()), b'asdf') + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_chainmap.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_chainmap.py new file mode 100644 index 0000000..2440401 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_chainmap.py @@ -0,0 +1,160 @@ +""" +Tests for the future.standard_library module +""" + +from __future__ import absolute_import, print_function +from future import standard_library +from future import utils +from future.tests.base import unittest, CodeHandler, expectedFailurePY2 + +import sys +import tempfile +import os +import copy +import textwrap +from subprocess import CalledProcessError + + +class TestChainMap(CodeHandler): + + def setUp(self): + self.interpreter = sys.executable + standard_library.install_aliases() + super(TestChainMap, self).setUp() + + def tearDown(self): + # standard_library.remove_hooks() + pass + + @staticmethod + def simple_cm(): + from collections import ChainMap + c = ChainMap() + c['one'] = 1 + c['two'] = 2 + + cc = c.new_child() + cc['one'] = 'one' + + return c, cc + + + def test_repr(self): + c, cc = TestChainMap.simple_cm() + + order1 = "ChainMap({'one': 'one'}, {'one': 1, 'two': 2})" + order2 = "ChainMap({'one': 'one'}, {'two': 2, 'one': 1})" + assert repr(cc) in [order1, order2] + + + def test_recursive_repr(self): + """ + Test for degnerative recursive cases. Very unlikely in + ChainMaps. But all must bow before the god of testing coverage. + """ + from collections import ChainMap + c = ChainMap() + c['one'] = c + assert repr(c) == "ChainMap({'one': ...})" + + + def test_get(self): + c, cc = TestChainMap.simple_cm() + + assert cc.get('two') == 2 + assert cc.get('three') == None + assert cc.get('three', 'notthree') == 'notthree' + + + def test_bool(self): + from collections import ChainMap + c = ChainMap() + assert not(bool(c)) + + c['one'] = 1 + c['two'] = 2 + assert bool(c) + + cc = c.new_child() + cc['one'] = 'one' + assert cc + + + def test_fromkeys(self): + from collections import ChainMap + keys = 'a b c'.split() + c = ChainMap.fromkeys(keys) + assert len(c) == 3 + assert c['a'] == None + assert c['b'] == None + assert c['c'] == None + + + def test_copy(self): + c, cc = TestChainMap.simple_cm() + new_cc = cc.copy() + assert new_cc is not cc + assert sorted(new_cc.items()) == sorted(cc.items()) + + + def test_parents(self): + c, cc = TestChainMap.simple_cm() + + new_c = cc.parents + assert c is not new_c + assert len(new_c) == 2 + assert new_c['one'] == c['one'] + assert new_c['two'] == c['two'] + + + def test_delitem(self): + c, cc = TestChainMap.simple_cm() + + with self.assertRaises(KeyError): + del cc['two'] + + del cc['one'] + assert len(cc) == 2 + assert cc['one'] == 1 + assert cc['two'] == 2 + + + def test_popitem(self): + c, cc = TestChainMap.simple_cm() + + assert cc.popitem() == ('one', 'one') + + with self.assertRaises(KeyError): + cc.popitem() + + + def test_pop(self): + c, cc = TestChainMap.simple_cm() + + assert cc.pop('one') == 'one' + + with self.assertRaises(KeyError): + cc.pop('two') + + assert len(cc) == 2 + + + def test_clear(self): + c, cc = TestChainMap.simple_cm() + + cc.clear() + assert len(cc) == 2 + assert cc['one'] == 1 + assert cc['two'] == 2 + + + def test_missing(self): + + c, cc = TestChainMap.simple_cm() + + with self.assertRaises(KeyError): + cc['clown'] + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_common_iterators.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_common_iterators.py new file mode 100644 index 0000000..d274c23 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_common_iterators.py @@ -0,0 +1,39 @@ +from __future__ import absolute_import + +from future.builtins.iterators import * +from future.tests.base import unittest + + +class TestIterators(unittest.TestCase): + def test_range(self): + self.assertNotEqual(type(range(10)), list) + self.assertEqual(sum(range(10)), 45) + self.assertTrue(9 in range(10)) + self.assertEqual(list(range(5)), [0, 1, 2, 3, 4]) + self.assertEqual(repr(range(10)), 'range(0, 10)') + self.assertEqual(repr(range(1, 10)), 'range(1, 10)') + self.assertEqual(repr(range(1, 1)), 'range(1, 1)') + self.assertEqual(repr(range(-10, 10, 2)), 'range(-10, 10, 2)') + + def test_map(self): + def square(x): + return x**2 + self.assertNotEqual(type(map(square, range(10))), list) + self.assertEqual(sum(map(square, range(10))), 285) + self.assertEqual(list(map(square, range(3))), [0, 1, 4]) + + def test_zip(self): + a = range(10) + b = ['a', 'b', 'c'] + self.assertNotEqual(type(zip(a, b)), list) + self.assertEqual(list(zip(a, b)), [(0, 'a'), (1, 'b'), (2, 'c')]) + + def test_filter(self): + a = range(10) + def is_odd(x): + return x % 2 == 1 + self.assertNotEqual(type(filter(is_odd, a)), list) + self.assertEqual(list(filter(is_odd, a)), [1, 3, 5, 7, 9]) + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_decorators.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_decorators.py new file mode 100644 index 0000000..9ec2bb3 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_decorators.py @@ -0,0 +1,57 @@ +""" +Tests to make sure the decorators (implements_iterator and +python2_unicode_compatible) are working. +""" + +from __future__ import absolute_import, division +from future import utils +from future.builtins import * +from future.utils import implements_iterator, python_2_unicode_compatible +from future.tests.base import unittest + + +class TestDecorators(unittest.TestCase): + def test_python_2_unicode_compatible_decorator(self): + my_unicode_str = u'Unicode string: \u5b54\u5b50' + # With the decorator: + @python_2_unicode_compatible + class A(object): + def __str__(self): + return my_unicode_str + a = A() + assert len(str(a)) == 18 + if not utils.PY3: + assert hasattr(a, '__unicode__') + self.assertEqual(str(a), my_unicode_str) + self.assertTrue(isinstance(str(a).encode('utf-8'), bytes)) + + # Manual equivalent on Py2 without the decorator: + if not utils.PY3: + class B(object): + def __unicode__(self): + return u'Unicode string: \u5b54\u5b50' + def __str__(self): + return unicode(self).encode('utf-8') + b = B() + assert str(a) == str(b) + + def test_implements_iterator(self): + + @implements_iterator + class MyIter(object): + def __next__(self): + return 'Next!' + def __iter__(self): + return self + + itr = MyIter() + self.assertEqual(next(itr), 'Next!') + + itr2 = MyIter() + for i, item in enumerate(itr2): + if i >= 3: + break + self.assertEqual(item, 'Next!') + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_dict.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_dict.py new file mode 100644 index 0000000..ff9dd4a --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_dict.py @@ -0,0 +1,142 @@ +# -*- coding: utf-8 -*- +""" +Tests for the backported class:`dict` class. +""" + +from __future__ import absolute_import, unicode_literals, print_function +from future.builtins import * +from future import utils +from future.tests.base import unittest, expectedFailurePY2 + +import os +import sys + +class TestDict(unittest.TestCase): + def setUp(self): + self.d1 = {'C': 1, 'B': 2, 'A': 3} + self.d2 = dict(key1='value1', key2='value2') + + def test_dict_empty(self): + """ + dict() -> {} + """ + self.assertEqual(dict(), {}) + + def test_dict_dict(self): + """ + Exrapolated from issue #50 -- newlist(newlist([...])) + """ + d = dict({1: 2, 2: 4, 3: 9}) + d2 = dict(d) + self.assertEqual(len(d2), 3) + self.assertEqual(d2, d) + self.assertTrue(isinstance(d2, dict)) + self.assertTrue(type(d2) == dict) + + def test_dict_eq(self): + d = self.d1 + self.assertEqual(dict(d), d) + + def test_dict_keys(self): + """ + The keys, values and items methods should now return iterators on + Python 2.x (with set-like behaviour on Python 2.7). + """ + d = self.d1 + self.assertEqual(set(dict(d)), set(d)) + self.assertEqual(set(dict(d).keys()), set(d.keys())) + with self.assertRaises(TypeError): + dict(d).keys()[0] + + def test_dict_values(self): + d = self.d1 + self.assertEqual(set(dict(d).values()), set(d.values())) + with self.assertRaises(TypeError): + dict(d).values()[0] + + def test_dict_items(self): + d = self.d1 + self.assertEqual(set(dict(d).items()), set(d.items())) + with self.assertRaises(TypeError): + dict(d).items()[0] + + def test_isinstance_dict(self): + d = self.d1 + self.assertTrue(isinstance(d, dict)) + + def test_isinstance_dict_subclass(self): + """ + Issue #89 + """ + value = dict() + class Magic(dict): + pass + self.assertTrue(isinstance(value, dict)) + self.assertFalse(isinstance(value, Magic)) + + def test_dict_getitem(self): + d = dict({'C': 1, 'B': 2, 'A': 3}) + self.assertEqual(d['C'], 1) + self.assertEqual(d['B'], 2) + self.assertEqual(d['A'], 3) + with self.assertRaises(KeyError): + self.assertEqual(d['D']) + + def test_methods_do_not_produce_lists(self): + for d in (dict(self.d1), self.d2): + assert not isinstance(d.keys(), list) + assert not isinstance(d.values(), list) + assert not isinstance(d.items(), list) + + @unittest.skipIf(sys.version_info[:2] == (2, 6), + 'set-like behaviour of dict methods is only available in Py2.7+') + def test_set_like_behaviour(self): + d1, d2 = self.d1, self.d2 + assert d1.keys() & d2.keys() == set() + assert isinstance(d1.keys() & d2.keys(), set) + assert isinstance(d1.values() | d2.keys(), set) + assert isinstance(d1.items() | d2.items(), set) + + @expectedFailurePY2 + def test_braces_create_newdict_object(self): + """ + It would nice if the {} dict syntax could be coaxed + into producing our new dict objects somehow ... + """ + d = self.d1 + self.assertTrue(type(d) == dict) + + @expectedFailurePY2 + def test_multiple_inheritance(self): + """ + Issue #96 (for newdict instead of newobject) + """ + if utils.PY2: + from collections import Container + else: + from collections.abc import Container + + class Base(dict): + pass + + class Foo(Base, Container): + def __contains__(self, item): + return False + + @expectedFailurePY2 + def test_with_metaclass_and_dict(self): + """ + Issue #91 (for newdict instead of newobject) + """ + from future.utils import with_metaclass + + class MetaClass(type): + pass + + class TestClass(with_metaclass(MetaClass, dict)): + pass + + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_email_multipart.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_email_multipart.py new file mode 100644 index 0000000..cbd93b8 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_email_multipart.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +"""Tests for multipart emails.""" + +from future.tests.base import unittest +import future.backports.email as email +import future.backports.email.mime.multipart +from future.builtins import list + +class EmailMultiPartTests(unittest.TestCase): + """Tests for handling multipart email Messages.""" + + def test_multipart_serialize_without_boundary(self): + """Tests that serializing an empty multipart email does not fail.""" + multipart_message = email.mime.multipart.MIMEMultipart() + self.assertIsNot(multipart_message.as_string(), None) + + def test_multipart_set_boundary_does_not_change_header_type(self): + """ + Tests that Message.set_boundary() does not cause Python2 errors. + + In particular, tests that set_boundary does not cause the type of the + message headers list to be changed from the future built-in list. + """ + multipart_message = email.mime.multipart.MIMEMultipart() + headers_type = type(multipart_message._headers) + self.assertEqual(headers_type, type(list())) + + boundary = '===============6387699881409002085==' + multipart_message.set_boundary(boundary) + headers_type = type(multipart_message._headers) + self.assertEqual(headers_type, type(list())) diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_explicit_imports.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_explicit_imports.py new file mode 100644 index 0000000..7a23c3e --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_explicit_imports.py @@ -0,0 +1,49 @@ +""" +This tests whether explicit imports like + + from future.builtins import str, range + +etc. all work as expected on both Python 2 and Python 3. + +""" + +from __future__ import absolute_import, print_function, unicode_literals + +import copy + +from future import utils +from future.tests.base import unittest + + +class TestExplicitImports(unittest.TestCase): + def test_py3_builtin_imports(self): + from future.builtins import (input, + filter, + map, + range, + round, + super, + str, + zip) + + def test_py2k_disabled_builtins(self): + """ + On Py2 these should import. + """ + if not utils.PY3: + from future.builtins.disabled import (apply, + cmp, + coerce, + execfile, + file, + long, + raw_input, + reduce, + reload, + unicode, + xrange, + StandardError) + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_futurize.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_futurize.py new file mode 100644 index 0000000..0d7c42d --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_futurize.py @@ -0,0 +1,1432 @@ +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function + +import pprint +import tempfile +from subprocess import Popen, PIPE +import os + +from libfuturize.fixer_util import is_shebang_comment, is_encoding_comment +from lib2to3.fixer_util import FromImport +from lib2to3.pytree import Leaf, Node +from lib2to3.pygram import token + +from future.tests.base import (CodeHandler, unittest, skip26, reformat_code, + order_future_lines, expectedFailurePY26) +from future.utils import PY2 + + +class TestLibFuturize(unittest.TestCase): + + def setUp(self): + # For tests that need a text file: + _, self.textfilename = tempfile.mkstemp(text=True) + super(TestLibFuturize, self).setUp() + + def tearDown(self): + os.unlink(self.textfilename) + + def test_correct_exit_status(self): + """ + Issue #119: futurize and pasteurize were not exiting with the correct + status code. This is because the status code returned from + libfuturize.main.main() etc. was a ``newint``, which sys.exit() always + translates into 1! + """ + from libfuturize.main import main + retcode = main([self.textfilename]) + self.assertTrue(isinstance(retcode, int)) # i.e. Py2 builtin int + + def test_is_shebang_comment(self): + """ + Tests whether the fixer_util.is_encoding_comment() function is working. + """ + shebang_comments = [u'#!/usr/bin/env python\n' + u"#!/usr/bin/python2\n", + u"#! /usr/bin/python3\n", + ] + not_shebang_comments = [u"# I saw a giant python\n", + u"# I have never seen a python2\n", + ] + for comment in shebang_comments: + node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")]) + node.prefix = comment + self.assertTrue(is_shebang_comment(node)) + + for comment in not_shebang_comments: + node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")]) + node.prefix = comment + self.assertFalse(is_shebang_comment(node)) + + + def test_is_encoding_comment(self): + """ + Tests whether the fixer_util.is_encoding_comment() function is working. + """ + encoding_comments = [u"# coding: utf-8", + u"# encoding: utf-8", + u"# -*- coding: latin-1 -*-", + u"# vim: set fileencoding=iso-8859-15 :", + ] + not_encoding_comments = [u"# We use the file encoding utf-8", + u"coding = 'utf-8'", + u"encoding = 'utf-8'", + ] + for comment in encoding_comments: + node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")]) + node.prefix = comment + self.assertTrue(is_encoding_comment(node)) + + for comment in not_encoding_comments: + node = FromImport(u'math', [Leaf(token.NAME, u'cos', prefix=" ")]) + node.prefix = comment + self.assertFalse(is_encoding_comment(node)) + + +class TestFuturizeSimple(CodeHandler): + """ + This class contains snippets of Python 2 code (invalid Python 3) and + tests for whether they can be passed to ``futurize`` and immediately + run under both Python 2 again and Python 3. + """ + + def test_encoding_comments_kept_at_top(self): + """ + Issues #10 and #97: If there is a source encoding comment line + (PEP 263), is it kept at the top of a module by ``futurize``? + """ + before = """ + # coding=utf-8 + + print 'Hello' + """ + after = """ + # coding=utf-8 + + from __future__ import print_function + print('Hello') + """ + self.convert_check(before, after) + + before = """ + #!/usr/bin/env python + # -*- coding: latin-1 -*-" + + print 'Hello' + """ + after = """ + #!/usr/bin/env python + # -*- coding: latin-1 -*-" + + from __future__ import print_function + print('Hello') + """ + self.convert_check(before, after) + + def test_multiline_future_import(self): + """ + Issue #113: don't crash if a future import has multiple lines + """ + text = """ + from __future__ import ( + division + ) + """ + self.convert(text) + + def test_shebang_blank_with_future_division_import(self): + """ + Issue #43: Is shebang line preserved as the first + line by futurize when followed by a blank line? + """ + before = """ + #!/usr/bin/env python + + import math + 1 / 5 + """ + after = """ + #!/usr/bin/env python + + from __future__ import division + from past.utils import old_div + import math + old_div(1, 5) + """ + self.convert_check(before, after) + + def test_shebang_blank_with_print_import(self): + before = """ + #!/usr/bin/env python + + import math + print 'Hello' + """ + after = """ + #!/usr/bin/env python + from __future__ import print_function + + import math + print('Hello') + """ + self.convert_check(before, after) + + def test_shebang_comment(self): + """ + Issue #43: Is shebang line preserved as the first + line by futurize when followed by a comment? + """ + before = """ + #!/usr/bin/env python + # some comments + # and more comments + + import math + print 'Hello!' + """ + after = """ + #!/usr/bin/env python + # some comments + # and more comments + from __future__ import print_function + + import math + print('Hello!') + """ + self.convert_check(before, after) + + def test_shebang_docstring(self): + """ + Issue #43: Is shebang line preserved as the first + line by futurize when followed by a docstring? + """ + before = ''' + #!/usr/bin/env python + """ + a doc string + """ + import math + print 'Hello!' + ''' + after = ''' + #!/usr/bin/env python + """ + a doc string + """ + from __future__ import print_function + import math + print('Hello!') + ''' + self.convert_check(before, after) + + def test_oldstyle_classes(self): + """ + Stage 2 should convert old-style to new-style classes. This makes + the new-style class explicit and reduces the gap between the + behaviour (e.g. method resolution order) on Py2 and Py3. It also + allows us to provide ``newobject`` (see + test_oldstyle_classes_iterator). + """ + before = """ + class Blah: + pass + """ + after = """ + from builtins import object + class Blah(object): + pass + """ + self.convert_check(before, after, ignore_imports=False) + + def test_oldstyle_classes_iterator(self): + """ + An old-style class used as an iterator should be converted + properly. This requires ``futurize`` to do both steps (adding + inheritance from object and adding the newobject import) in the + right order. Any next() method should also be renamed to __next__. + """ + before = """ + class Upper: + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): + return next(self._iter).upper() + def __iter__(self): + return self + + assert list(Upper('hello')) == list('HELLO') + """ + after = """ + from builtins import next + from builtins import object + class Upper(object): + def __init__(self, iterable): + self._iter = iter(iterable) + def __next__(self): + return next(self._iter).upper() + def __iter__(self): + return self + + assert list(Upper('hello')) == list('HELLO') + """ + self.convert_check(before, after, ignore_imports=False) + + # Try it again with this convention: class Upper(): + before2 = """ + class Upper(): + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): + return next(self._iter).upper() + def __iter__(self): + return self + + assert list(Upper('hello')) == list('HELLO') + """ + self.convert_check(before2, after) + + @unittest.expectedFailure + def test_problematic_string(self): + """ This string generates a SyntaxError on Python 3 unless it has + an r prefix. + """ + before = r""" + s = 'The folder is "C:\Users"'. + """ + after = r""" + s = r'The folder is "C:\Users"'. + """ + self.convert_check(before, after) + + @unittest.skip('--tobytes feature removed for now ...') + def test_tobytes(self): + """ + The --tobytes option converts all UNADORNED string literals 'abcd' to b'abcd'. + It does apply to multi-line strings but doesn't apply if it's a raw + string, because ur'abcd' is a SyntaxError on Python 2 and br'abcd' is a + SyntaxError on Python 3. + """ + before = r""" + s0 = '1234' + s1 = '''5678 + ''' + s2 = "9abc" + # Unchanged: + s3 = r'1234' + s4 = R"defg" + s5 = u'hijk' + s6 = u"lmno" + s7 = b'lmno' + s8 = b"pqrs" + """ + after = r""" + s0 = b'1234' + s1 = b'''5678 + ''' + s2 = b"9abc" + # Unchanged: + s3 = r'1234' + s4 = R"defg" + s5 = u'hijk' + s6 = u"lmno" + s7 = b'lmno' + s8 = b"pqrs" + """ + self.convert_check(before, after, tobytes=True) + + def test_cmp(self): + before = """ + assert cmp(1, 2) == -1 + assert cmp(2, 1) == 1 + """ + after = """ + from past.builtins import cmp + assert cmp(1, 2) == -1 + assert cmp(2, 1) == 1 + """ + self.convert_check(before, after, stages=(1, 2), ignore_imports=False) + + def test_execfile(self): + before = """ + with open('mytempfile.py', 'w') as f: + f.write('x = 1') + execfile('mytempfile.py') + x += 1 + assert x == 2 + """ + after = """ + from past.builtins import execfile + with open('mytempfile.py', 'w') as f: + f.write('x = 1') + execfile('mytempfile.py') + x += 1 + assert x == 2 + """ + self.convert_check(before, after, stages=(1, 2), ignore_imports=False) + + @unittest.expectedFailure + def test_izip(self): + before = """ + from itertools import izip + for (a, b) in izip([1, 3, 5], [2, 4, 6]): + pass + """ + after = """ + from builtins import zip + for (a, b) in zip([1, 3, 5], [2, 4, 6]): + pass + """ + self.convert_check(before, after, stages=(1, 2), ignore_imports=False) + + def test_UserList(self): + before = """ + from UserList import UserList + a = UserList([1, 3, 5]) + assert len(a) == 3 + """ + after = """ + from collections import UserList + a = UserList([1, 3, 5]) + assert len(a) == 3 + """ + self.convert_check(before, after, stages=(1, 2), ignore_imports=True) + + @unittest.expectedFailure + def test_no_unneeded_list_calls(self): + """ + TODO: get this working + """ + code = """ + for (a, b) in zip(range(3), range(3, 6)): + pass + """ + self.unchanged(code) + + @expectedFailurePY26 + def test_import_builtins(self): + before = """ + a = raw_input() + b = open(a, b, c) + c = filter(a, b) + d = map(a, b) + e = isinstance(a, str) + f = bytes(a, encoding='utf-8') + for g in xrange(10**10): + pass + h = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) + super(MyClass, self) + """ + after = """ + from builtins import bytes + from builtins import filter + from builtins import input + from builtins import map + from builtins import range + from functools import reduce + a = input() + b = open(a, b, c) + c = list(filter(a, b)) + d = list(map(a, b)) + e = isinstance(a, str) + f = bytes(a, encoding='utf-8') + for g in range(10**10): + pass + h = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) + super(MyClass, self) + """ + self.convert_check(before, after, ignore_imports=False, run=False) + + def test_input_without_import(self): + before = """ + a = input() + """ + after = """ + from builtins import input + a = eval(input()) + """ + self.convert_check(before, after, ignore_imports=False, run=False) + + def test_input_with_import(self): + before = """ + from builtins import input + a = input() + """ + after = """ + from builtins import input + a = input() + """ + self.convert_check(before, after, ignore_imports=False, run=False) + + def test_xrange(self): + """ + The ``from builtins import range`` line was being added to the + bottom of the file as of v0.11.4, but only using Py2.7's lib2to3. + (Py3.3's lib2to3 seems to work.) + """ + before = """ + for i in xrange(10): + pass + """ + after = """ + from builtins import range + for i in range(10): + pass + """ + self.convert_check(before, after, ignore_imports=False) + + def test_source_coding_utf8(self): + """ + Tests to ensure that the source coding line is not corrupted or + removed. It must be left as the first line in the file (including + before any __future__ imports). Also tests whether the unicode + characters in this encoding are parsed correctly and left alone. + """ + code = """ + # -*- coding: utf-8 -*- + icons = [u"◐", u"◓", u"◑", u"◒"] + """ + + def test_exception_syntax(self): + """ + Test of whether futurize handles the old-style exception syntax + """ + before = """ + try: + pass + except IOError, e: + val = e.errno + """ + after = """ + try: + pass + except IOError as e: + val = e.errno + """ + self.convert_check(before, after) + + def test_super(self): + """ + This tests whether futurize keeps the old two-argument super() calls the + same as before. It should, because this still works in Py3. + """ + code = ''' + class VerboseList(list): + def append(self, item): + print('Adding an item') + super(VerboseList, self).append(item) + ''' + self.unchanged(code) + + @unittest.expectedFailure + def test_file(self): + """ + file() as a synonym for open() is obsolete and invalid on Python 3. + """ + before = ''' + f = file(self.textfilename) + data = f.read() + f.close() + ''' + after = ''' + f = open(__file__) + data = f.read() + f.close() + ''' + self.convert_check(before, after) + + def test_apply(self): + before = ''' + def addup(*x): + return sum(x) + + assert apply(addup, (10,20)) == 30 + ''' + after = """ + def addup(*x): + return sum(x) + + assert addup(*(10,20)) == 30 + """ + self.convert_check(before, after) + + @unittest.skip('not implemented yet') + def test_download_pypi_package_and_test(self): + URL = 'http://pypi.python.org/pypi/{0}/json' + + import requests + package = 'future' + r = requests.get(URL.format(package)) + pprint.pprint(r.json()) + + download_url = r.json()['urls'][0]['url'] + filename = r.json()['urls'][0]['filename'] + # r2 = requests.get(download_url) + # with open('/tmp/' + filename, 'w') as tarball: + # tarball.write(r2.content) + + @expectedFailurePY26 + def test_raw_input(self): + """ + Passes in a string to the waiting input() after futurize + conversion. + + The code is the first snippet from these docs: + http://docs.python.org/2/library/2to3.html + """ + before = """ + from io import BytesIO + def greet(name): + print "Hello, {0}!".format(name) + print "What's your name?" + import sys + oldstdin = sys.stdin + + sys.stdin = BytesIO(b'Ed\\n') + name = raw_input() + greet(name.decode()) + + sys.stdin = oldstdin + assert name == b'Ed' + """ + desired = """ + from io import BytesIO + def greet(name): + print("Hello, {0}!".format(name)) + print("What's your name?") + import sys + oldstdin = sys.stdin + + sys.stdin = BytesIO(b'Ed\\n') + name = input() + greet(name.decode()) + + sys.stdin = oldstdin + assert name == b'Ed' + """ + self.convert_check(before, desired, run=False) + + for interpreter in self.interpreters: + p1 = Popen([interpreter, self.tempdir + 'mytestscript.py'], + stdout=PIPE, stdin=PIPE, stderr=PIPE) + (stdout, stderr) = p1.communicate(b'Ed') + self.assertEqual(stderr, b'') + self.assertEqual(stdout, b"What's your name?\nHello, Ed!\n") + + def test_literal_prefixes_are_not_stripped(self): + """ + Tests to ensure that the u'' and b'' prefixes on unicode strings and + byte strings are not removed by the futurize script. Removing the + prefixes on Py3.3+ is unnecessary and loses some information -- namely, + that the strings have explicitly been marked as unicode or bytes, + rather than just e.g. a guess by some automated tool about what they + are. + """ + code = ''' + s = u'unicode string' + b = b'byte string' + ''' + self.unchanged(code) + + def test_division(self): + before = """ + x = 1 / 2 + """ + after = """ + from past.utils import old_div + x = old_div(1, 2) + """ + self.convert_check(before, after, stages=[1, 2]) + + def test_already_future_division(self): + code = """ + from __future__ import division + x = 1 / 2 + assert x == 0.5 + y = 3. / 2. + assert y == 1.5 + """ + self.unchanged(code) + + +class TestFuturizeRenamedStdlib(CodeHandler): + @unittest.skip('Infinite loop?') + def test_renamed_modules(self): + before = """ + import ConfigParser + import copy_reg + import cPickle + import cStringIO + """ + after = """ + import configparser + import copyreg + import pickle + import io + """ + # We can't run the converted code because configparser may + # not be there. + self.convert_check(before, after, run=False) + + @unittest.skip('Not working yet ...') + def test_urllib_refactor(self): + # Code like this using urllib is refactored by futurize --stage2 to use + # the new Py3 module names, but ``future`` doesn't support urllib yet. + before = """ + import urllib + + URL = 'http://pypi.python.org/pypi/future/json' + package = 'future' + r = urllib.urlopen(URL.format(package)) + data = r.read() + """ + after = """ + from future import standard_library + standard_library.install_aliases() + import urllib.request + + URL = 'http://pypi.python.org/pypi/future/json' + package = 'future' + r = urllib.request.urlopen(URL.format(package)) + data = r.read() + """ + self.convert_check(before, after) + + @unittest.skip('Infinite loop?') + def test_renamed_copy_reg_and_cPickle_modules(self): + """ + Example from docs.python.org/2/library/copy_reg.html + """ + before = """ + import copy_reg + import copy + import cPickle + class C(object): + def __init__(self, a): + self.a = a + + def pickle_c(c): + print('pickling a C instance...') + return C, (c.a,) + + copy_reg.pickle(C, pickle_c) + c = C(1) + d = copy.copy(c) + p = cPickle.dumps(c) + """ + after = """ + import copyreg + import copy + import pickle + class C(object): + def __init__(self, a): + self.a = a + + def pickle_c(c): + print('pickling a C instance...') + return C, (c.a,) + + copyreg.pickle(C, pickle_c) + c = C(1) + d = copy.copy(c) + p = pickle.dumps(c) + """ + self.convert_check(before, after) + + @unittest.expectedFailure + def test_Py2_StringIO_module(self): + """ + This requires that the argument to io.StringIO be made a + unicode string explicitly if we're not using unicode_literals: + + Ideally, there would be a fixer for this. For now: + + TODO: add the Py3 equivalent for this to the docs. Also add back + a test for the unicode_literals case. + """ + before = """ + import cStringIO + import StringIO + s1 = cStringIO.StringIO('my string') + s2 = StringIO.StringIO('my other string') + assert isinstance(s1, cStringIO.InputType) + """ + + # There is no io.InputType in Python 3. futurize should change this to + # something like this. But note that the input to io.StringIO + # must be a unicode string on both Py2 and Py3. + after = """ + import io + import io + s1 = io.StringIO(u'my string') + s2 = io.StringIO(u'my other string') + assert isinstance(s1, io.StringIO) + """ + self.convert_check(before, after) + + +class TestFuturizeStage1(CodeHandler): + """ + Tests "stage 1": safe optimizations: modernizing Python 2 code so that it + uses print functions, new-style exception syntax, etc. + + The behaviour should not change and this should introduce no dependency on + the ``future`` package. It produces more modern Python 2-only code. The + goal is to reduce the size of the real porting patch-set by performing + the uncontroversial patches first. + """ + + def test_apply(self): + """ + apply() should be changed by futurize --stage1 + """ + before = ''' + def f(a, b): + return a + b + + args = (1, 2) + assert apply(f, args) == 3 + assert apply(f, ('a', 'b')) == 'ab' + ''' + after = ''' + def f(a, b): + return a + b + + args = (1, 2) + assert f(*args) == 3 + assert f(*('a', 'b')) == 'ab' + ''' + self.convert_check(before, after, stages=[1]) + + def test_next_1(self): + """ + Custom next methods should not be converted to __next__ in stage1, but + any obj.next() calls should be converted to next(obj). + """ + before = """ + class Upper: + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): # note the Py2 interface + return next(self._iter).upper() + def __iter__(self): + return self + + itr = Upper('hello') + assert itr.next() == 'H' + assert next(itr) == 'E' + assert list(itr) == list('LLO') + """ + + after = """ + class Upper: + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): # note the Py2 interface + return next(self._iter).upper() + def __iter__(self): + return self + + itr = Upper('hello') + assert next(itr) == 'H' + assert next(itr) == 'E' + assert list(itr) == list('LLO') + """ + self.convert_check(before, after, stages=[1], run=PY2) + + @unittest.expectedFailure + def test_next_2(self): + """ + This version of the above doesn't currently work: the self._iter.next() call in + line 5 isn't converted to next(self._iter). + """ + before = """ + class Upper: + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): # note the Py2 interface + return self._iter.next().upper() + def __iter__(self): + return self + + itr = Upper('hello') + assert itr.next() == 'H' + assert next(itr) == 'E' + assert list(itr) == list('LLO') + """ + + after = """ + class Upper(object): + def __init__(self, iterable): + self._iter = iter(iterable) + def next(self): # note the Py2 interface + return next(self._iter).upper() + def __iter__(self): + return self + + itr = Upper('hello') + assert next(itr) == 'H' + assert next(itr) == 'E' + assert list(itr) == list('LLO') + """ + self.convert_check(before, after, stages=[1], run=PY2) + + def test_xrange(self): + """ + xrange should not be changed by futurize --stage1 + """ + code = ''' + for i in xrange(10): + pass + ''' + self.unchanged(code, stages=[1], run=PY2) + + @unittest.expectedFailure + def test_absolute_import_changes(self): + """ + Implicit relative imports should be converted to absolute or explicit + relative imports correctly. + + Issue #16 (with porting bokeh/bbmodel.py) + """ + with open(self.tempdir + 'specialmodels.py', 'w') as f: + f.write('pass') + + before = """ + import specialmodels.pandasmodel + specialmodels.pandasmodel.blah() + """ + after = """ + from __future__ import absolute_import + from .specialmodels import pandasmodel + pandasmodel.blah() + """ + self.convert_check(before, after, stages=[1]) + + def test_safe_futurize_imports(self): + """ + The standard library module names should not be changed until stage 2 + """ + before = """ + import ConfigParser + import HTMLParser + from itertools import ifilterfalse + + ConfigParser.ConfigParser + HTMLParser.HTMLParser + assert list(ifilterfalse(lambda x: x % 2, [2, 4])) == [2, 4] + """ + self.unchanged(before, stages=[1], run=PY2) + + def test_print(self): + before = """ + print 'Hello' + """ + after = """ + print('Hello') + """ + self.convert_check(before, after, stages=[1]) + + before = """ + import sys + print >> sys.stderr, 'Hello', 'world' + """ + after = """ + import sys + print('Hello', 'world', file=sys.stderr) + """ + self.convert_check(before, after, stages=[1]) + + def test_print_already_function(self): + """ + Running futurize --stage1 should not add a second set of parentheses + """ + before = """ + print('Hello') + """ + self.unchanged(before, stages=[1]) + + @unittest.expectedFailure + def test_print_already_function_complex(self): + """ + Running futurize --stage1 does add a second second set of parentheses + in this case. This is because the underlying lib2to3 has two distinct + grammars -- with a print statement and with a print function -- and, + when going forwards (2 to both), futurize assumes print is a statement, + which raises a ParseError. + """ + before = """ + import sys + print('Hello', 'world', file=sys.stderr) + """ + self.unchanged(before, stages=[1]) + + def test_exceptions(self): + before = """ + try: + raise AttributeError('blah') + except AttributeError, e: + pass + """ + after = """ + try: + raise AttributeError('blah') + except AttributeError as e: + pass + """ + self.convert_check(before, after, stages=[1]) + + @unittest.expectedFailure + def test_string_exceptions(self): + """ + 2to3 does not convert string exceptions: see + http://python3porting.com/differences.html. + """ + before = """ + try: + raise "old string exception" + except Exception, e: + pass + """ + after = """ + try: + raise Exception("old string exception") + except Exception as e: + pass + """ + self.convert_check(before, after, stages=[1]) + + def test_oldstyle_classes(self): + """ + We don't convert old-style classes to new-style automatically in + stage 1 (but we should in stage 2). So Blah should not inherit + explicitly from object yet. + """ + before = """ + class Blah: + pass + """ + self.unchanged(before, stages=[1]) + + def test_stdlib_modules_not_changed(self): + """ + Standard library module names should not be changed in stage 1 + """ + before = """ + import ConfigParser + import HTMLParser + import collections + + print 'Hello' + try: + raise AttributeError('blah') + except AttributeError, e: + pass + """ + after = """ + import ConfigParser + import HTMLParser + import collections + + print('Hello') + try: + raise AttributeError('blah') + except AttributeError as e: + pass + """ + self.convert_check(before, after, stages=[1], run=PY2) + + def test_octal_literals(self): + before = """ + mode = 0644 + """ + after = """ + mode = 0o644 + """ + self.convert_check(before, after) + + def test_long_int_literals(self): + before = """ + bignumber = 12345678901234567890L + """ + after = """ + bignumber = 12345678901234567890 + """ + self.convert_check(before, after) + + def test___future___import_position(self): + """ + Issue #4: __future__ imports inserted too low in file: SyntaxError + """ + code = """ + # Comments here + # and here + __version__=''' $Id$ ''' + __doc__="A Sequencer class counts things. It aids numbering and formatting lists." + __all__='Sequencer getSequencer setSequencer'.split() + # + # another comment + # + + CONSTANTS = [ 0, 01, 011, 0111, 012, 02, 021, 0211, 02111, 013 ] + _RN_LETTERS = "IVXLCDM" + + def my_func(value): + pass + + ''' Docstring-like comment here ''' + """ + self.convert(code) + + def test_issue_45(self): + """ + Tests whether running futurize -f libfuturize.fixes.fix_future_standard_library_urllib + on the code below causes a ValueError (issue #45). + """ + code = r""" + from __future__ import print_function + from urllib import urlopen, urlencode + oeis_url = 'http://oeis.org/' + def _fetch(url): + try: + f = urlopen(url) + result = f.read() + f.close() + return result + except IOError as msg: + raise IOError("%s\nError fetching %s." % (msg, url)) + """ + self.convert(code) + + def test_order_future_lines(self): + """ + Tests the internal order_future_lines() function. + """ + before = ''' + # comment here + from __future__ import print_function + from __future__ import absolute_import + # blank line or comment here + from future.utils import with_metaclass + from builtins import zzz + from builtins import aaa + from builtins import blah + # another comment + + import something_else + code_here + more_code_here + ''' + after = ''' + # comment here + from __future__ import absolute_import + from __future__ import print_function + # blank line or comment here + from future.utils import with_metaclass + from builtins import aaa + from builtins import blah + from builtins import zzz + # another comment + + import something_else + code_here + more_code_here + ''' + self.assertEqual(order_future_lines(reformat_code(before)), + reformat_code(after)) + + @unittest.expectedFailure + def test_issue_12(self): + """ + Issue #12: This code shouldn't be upset by additional imports. + __future__ imports must appear at the top of modules since about Python + 2.5. + """ + code = """ + from __future__ import with_statement + f = open('setup.py') + for i in xrange(100): + pass + """ + self.unchanged(code) + + @expectedFailurePY26 + def test_range_necessary_list_calls(self): + """ + On Py2.6 (only), the xrange_with_import fixer somehow seems to cause + l = range(10) + to be converted to: + l = list(list(range(10))) + with an extra list(...) call. + """ + before = """ + l = range(10) + assert isinstance(l, list) + for i in range(3): + print i + for i in xrange(3): + print i + """ + after = """ + from __future__ import print_function + from builtins import range + l = list(range(10)) + assert isinstance(l, list) + for i in range(3): + print(i) + for i in range(3): + print(i) + """ + self.convert_check(before, after) + + def test_basestring(self): + """ + The 2to3 basestring fixer breaks working Py2 code that uses basestring. + This tests whether something sensible is done instead. + """ + before = """ + assert isinstance('hello', basestring) + assert isinstance(u'hello', basestring) + assert isinstance(b'hello', basestring) + """ + after = """ + from past.builtins import basestring + assert isinstance('hello', basestring) + assert isinstance(u'hello', basestring) + assert isinstance(b'hello', basestring) + """ + self.convert_check(before, after) + + def test_safe_division(self): + """ + Tests whether Py2 scripts using old-style division still work + after futurization. + """ + before = """ + import random + class fraction(object): + numer = 0 + denom = 0 + def __init__(self, numer, denom): + self.numer = numer + self.denom = denom + + def total_count(self): + return self.numer * 50 + + x = 3 / 2 + y = 3. / 2 + foo = list(range(100)) + assert x == 1 and isinstance(x, int) + assert y == 1.5 and isinstance(y, float) + a = 1 + foo[len(foo) / 2] + b = 1 + foo[len(foo) * 3 / 4] + assert a == 51 + assert b == 76 + r = random.randint(0, 1000) * 1.0 / 1000 + output = { "SUCCESS": 5, "TOTAL": 10 } + output["SUCCESS"] * 100 / output["TOTAL"] + obj = fraction(1, 50) + val = float(obj.numer) / obj.denom * 1e-9 + obj.numer * obj.denom / val + obj.total_count() * val / 100 + obj.numer / obj.denom * 1e-9 + obj.numer / (obj.denom * 1e-9) + obj.numer / obj.denom / 1e-9 + obj.numer / (obj.denom / 1e-9) + original_numer = 1 + original_denom = 50 + 100 * abs(obj.numer - original_numer) / float(max(obj.denom, original_denom)) + 100 * abs(obj.numer - original_numer) / max(obj.denom, original_denom) + float(original_numer) * float(original_denom) / float(obj.numer) + """ + after = """ + from __future__ import division + from past.utils import old_div + import random + class fraction(object): + numer = 0 + denom = 0 + def __init__(self, numer, denom): + self.numer = numer + self.denom = denom + + def total_count(self): + return self.numer * 50 + + x = old_div(3, 2) + y = 3. / 2 + foo = list(range(100)) + assert x == 1 and isinstance(x, int) + assert y == 1.5 and isinstance(y, float) + a = 1 + foo[old_div(len(foo), 2)] + b = 1 + foo[old_div(len(foo) * 3, 4)] + assert a == 51 + assert b == 76 + r = random.randint(0, 1000) * 1.0 / 1000 + output = { "SUCCESS": 5, "TOTAL": 10 } + old_div(output["SUCCESS"] * 100, output["TOTAL"]) + obj = fraction(1, 50) + val = float(obj.numer) / obj.denom * 1e-9 + old_div(obj.numer * obj.denom, val) + old_div(obj.total_count() * val, 100) + old_div(obj.numer, obj.denom) * 1e-9 + old_div(obj.numer, (obj.denom * 1e-9)) + old_div(old_div(obj.numer, obj.denom), 1e-9) + old_div(obj.numer, (old_div(obj.denom, 1e-9))) + original_numer = 1 + original_denom = 50 + 100 * abs(obj.numer - original_numer) / float(max(obj.denom, original_denom)) + old_div(100 * abs(obj.numer - original_numer), max(obj.denom, original_denom)) + float(original_numer) * float(original_denom) / float(obj.numer) + """ + self.convert_check(before, after) + + def test_safe_division_overloaded(self): + """ + If division is overloaded, futurize may produce spurious old_div + calls. This test is for whether the code still works on Py2 + despite these calls. + """ + before = """ + class Path(str): + def __div__(self, other): + return self.__truediv__(other) + def __truediv__(self, other): + return Path(str(self) + '/' + str(other)) + path1 = Path('home') + path2 = Path('user') + z = path1 / path2 + assert isinstance(z, Path) + assert str(z) == 'home/user' + """ + after = """ + from __future__ import division + from past.utils import old_div + class Path(str): + def __div__(self, other): + return self.__truediv__(other) + def __truediv__(self, other): + return Path(str(self) + '/' + str(other)) + path1 = Path('home') + path2 = Path('user') + z = old_div(path1, path2) + assert isinstance(z, Path) + assert str(z) == 'home/user' + """ + self.convert_check(before, after) + + def test_basestring_issue_156(self): + before = """ + x = str(3) + allowed_types = basestring, int + assert isinstance('', allowed_types) + assert isinstance(u'', allowed_types) + assert isinstance(u'foo', basestring) + """ + after = """ + from builtins import str + from past.builtins import basestring + x = str(3) + allowed_types = basestring, int + assert isinstance('', allowed_types) + assert isinstance(u'', allowed_types) + assert isinstance(u'foo', basestring) + """ + self.convert_check(before, after) + + +class TestConservativeFuturize(CodeHandler): + @unittest.expectedFailure + def test_basestring(self): + """ + In conservative mode, futurize would not modify "basestring" + but merely import it from ``past``, and the following code would still + run on both Py2 and Py3. + """ + before = """ + assert isinstance('hello', basestring) + assert isinstance(u'hello', basestring) + assert isinstance(b'hello', basestring) + """ + after = """ + from past.builtins import basestring + assert isinstance('hello', basestring) + assert isinstance(u'hello', basestring) + assert isinstance(b'hello', basestring) + """ + self.convert_check(before, after, conservative=True) + + @unittest.expectedFailure + def test_open(self): + """ + In conservative mode, futurize would not import io.open because + this changes the default return type from bytes to text. + """ + before = """ + filename = 'temp_file_open.test' + contents = 'Temporary file contents. Delete me.' + with open(filename, 'w') as f: + f.write(contents) + + with open(filename, 'r') as f: + data = f.read() + assert isinstance(data, str) + assert data == contents + """ + after = """ + from past.builtins import open, str as oldbytes, unicode + filename = oldbytes(b'temp_file_open.test') + contents = oldbytes(b'Temporary file contents. Delete me.') + with open(filename, oldbytes(b'w')) as f: + f.write(contents) + + with open(filename, oldbytes(b'r')) as f: + data = f.read() + assert isinstance(data, oldbytes) + assert data == contents + assert isinstance(oldbytes(b'hello'), basestring) + assert isinstance(unicode(u'hello'), basestring) + assert isinstance(oldbytes(b'hello'), basestring) + """ + self.convert_check(before, after, conservative=True) + + +class TestFuturizeAllImports(CodeHandler): + """ + Tests "futurize --all-imports". + """ + @expectedFailurePY26 + def test_all_imports(self): + before = """ + import math + import os + l = range(10) + assert isinstance(l, list) + print 'Hello' + for i in xrange(100): + pass + print('Hello') + """ + after = """ + from __future__ import absolute_import + from __future__ import division + from __future__ import print_function + from __future__ import unicode_literals + from future import standard_library + standard_library.install_aliases() + from builtins import * + from builtins import range + import math + import os + l = list(range(10)) + assert isinstance(l, list) + print('Hello') + for i in range(100): + pass + print('Hello') + """ + self.convert_check(before, after, all_imports=True, ignore_imports=False) + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_html.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_html.py new file mode 100644 index 0000000..251a530 --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_html.py @@ -0,0 +1,27 @@ +""" +Tests for the html module functions. + +Adapted for the python-future module from the Python 3.3 standard library tests. +""" + +from __future__ import unicode_literals +from future import standard_library + +with standard_library.hooks(): + import html + +from future.tests.base import unittest + + +class HtmlTests(unittest.TestCase): + def test_escape(self): + self.assertEqual( + html.escape('\'\''), + ''<script>"&foo;"</script>'') + self.assertEqual( + html.escape('\'\'', False), + '\'<script>"&foo;"</script>\'') + + +if __name__ == '__main__': + unittest.main() diff --git a/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_htmlparser.py b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_htmlparser.py new file mode 100644 index 0000000..7a745ac --- /dev/null +++ b/FOSS/Python/Dependencies/future-0.18.2/tests/test_future/test_htmlparser.py @@ -0,0 +1,764 @@ +# -*- coding: utf-8 -*- +""" +Tests for the html.parser functions. + +Adapted for the python-future module from the Python 3.3 standard library +tests. +""" + +from __future__ import (absolute_import, print_function, unicode_literals) +from future import standard_library, utils +from future.builtins import * + +from future.backports.test import support +import future.backports.html.parser as html_parser + +import pprint +from future.tests.base import unittest +import sys + +# print(html_parser.__doc__, file=sys.stderr) + + +class EventCollector(html_parser.HTMLParser): + + def __init__(self, *args, **kw): + self.events = [] + self.append = self.events.append + html_parser.HTMLParser.__init__(self, *args, **kw) + + def get_events(self): + # Normalize the list of events so that buffer artefacts don't + # separate runs of contiguous characters. + L = [] + prevtype = None + for event in self.events: + type = event[0] + if type == prevtype == "data": + L[-1] = ("data", L[-1][1] + event[1]) + else: + L.append(event) + prevtype = type + self.events = L + return L + + # structure markup + + def handle_starttag(self, tag, attrs): + self.append(("starttag", tag, attrs)) + + def handle_startendtag(self, tag, attrs): + self.append(("startendtag", tag, attrs)) + + def handle_endtag(self, tag): + self.append(("endtag", tag)) + + # all other markup + + def handle_comment(self, data): + self.append(("comment", data)) + + def handle_charref(self, data): + self.append(("charref", data)) + + def handle_data(self, data): + self.append(("data", data)) + + def handle_decl(self, data): + self.append(("decl", data)) + + def handle_entityref(self, data): + self.append(("entityref", data)) + + def handle_pi(self, data): + self.append(("pi", data)) + + def unknown_decl(self, decl): + self.append(("unknown decl", decl)) + + +class EventCollectorExtra(EventCollector): + + def handle_starttag(self, tag, attrs): + EventCollector.handle_starttag(self, tag, attrs) + self.append(("starttag_text", self.get_starttag_text())) + + +class TestCaseBase(unittest.TestCase): + + def get_collector(self): + raise NotImplementedError + + def _run_check(self, source, expected_events, collector=None): + if collector is None: + collector = self.get_collector() + parser = collector + for s in source: + parser.feed(s) + parser.close() + events = parser.get_events() + if events != expected_events: + self.fail("received events did not match expected events\n" + "Expected:\n" + pprint.pformat(expected_events) + + "\nReceived:\n" + pprint.pformat(events)) + + def _run_check_extra(self, source, events): + self._run_check(source, events, EventCollectorExtra()) + + def _parse_error(self, source): + def parse(source=source): + parser = self.get_collector() + parser.feed(source) + parser.close() + self.assertRaises(html_parser.HTMLParseError, parse) + + +class HTMLParserStrictTestCase(TestCaseBase): + + def get_collector(self): + with support.check_warnings(("", DeprecationWarning), quiet=False): + return EventCollector(strict=True) + + def test_processing_instruction_only(self): + self._run_check("", [ + ("pi", "processing instruction"), + ]) + self._run_check("", [ + ("pi", "processing instruction ?"), + ]) + + def test_simple_html(self): + self._run_check(""" + +&entity; + +sample +text +“ + + +""", [ + ("data", "\n"), + ("decl", "DOCTYPE html PUBLIC 'foo'"), + ("data", "\n"), + ("starttag", "html", []), + ("entityref", "entity"), + ("charref", "32"), + ("data", "\n"), + ("comment", "comment1a\n-><&#bad;

", [ + ("starttag", "p", []), + ("data", "&#bad;"), + ("endtag", "p"), + ]) + + def test_unclosed_entityref(self): + self._run_check("&entityref foo", [ + ("entityref", "entityref"), + ("data", " foo"), + ]) + + def test_bad_nesting(self): + # Strangely, this *is* supposed to test that overlapping + # elements are allowed. HTMLParser is more geared toward + # lexing the input that parsing the structure. + self._run_check("", [ + ("starttag", "a", []), + ("starttag", "b", []), + ("endtag", "a"), + ("endtag", "b"), + ]) + + def test_bare_ampersands(self): + self._run_check("this text & contains & ampersands &", [ + ("data", "this text & contains & ampersands &"), + ]) + + def test_bare_pointy_brackets(self): + self._run_check("this < text > contains < bare>pointy< brackets", [ + ("data", "this < text > contains < bare>pointy< brackets"), + ]) + + def test_illegal_declarations(self): + self._parse_error('') + + def test_starttag_end_boundary(self): + self._run_check("""""", [("starttag", "a", [("b", "<")])]) + self._run_check("""""", [("starttag", "a", [("b", ">")])]) + + def test_buffer_artefacts(self): + output = [("starttag", "a", [("b", "<")])] + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + + output = [("starttag", "a", [("b", ">")])] + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check(["'>"], output) + self._run_check([""], output) + self._run_check([""], output) + + output = [("comment", "abc")] + self._run_check(["", ""], output) + self._run_check(["<", "!--abc-->"], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check([""], output) + self._run_check(["", ""], output) + + def test_starttag_junk_chars(self): + self._parse_error("") + self._parse_error("") + self._parse_error("") + self._parse_error("") + self._parse_error("'") + self._parse_error("" % dtd, + [('decl', 'DOCTYPE ' + dtd)]) + + def test_declaration_junk_chars(self): + self._parse_error("") + + def test_startendtag(self): + self._run_check("

", [ + ("startendtag", "p", []), + ]) + self._run_check("

", [ + ("starttag", "p", []), + ("endtag", "p"), + ]) + self._run_check("

", [ + ("starttag", "p", []), + ("startendtag", "img", [("src", "foo")]), + ("endtag", "p"), + ]) + + def test_get_starttag_text(self): + s = """""" + self._run_check_extra(s, [ + ("starttag", "foo:bar", [("one", "1"), ("two", "2")]), + ("starttag_text", s)]) + + def test_cdata_content(self): + contents = [ + ' ¬-an-entity-ref;', + "", + '

', + 'foo = "";', + 'foo = "";', + 'foo = <\n/script> ', + '', + ('\n//<\\/s\'+\'cript>\');\n//]]>'), + '\n\n', + 'foo = "";', + '', + # these two should be invalid according to the HTML 5 spec, + # section 8.1.2.2 + #'foo = ', + #'foo = ', + ] + elements = ['script', 'style', 'SCRIPT', 'STYLE', 'Script', 'Style'] + for content in contents: + for element in elements: + element_lower = element.lower() + s = '<{element}>{content}'.format(element=element, + content=content) + self._run_check(s, [("starttag", element_lower, []), + ("data", content), + ("endtag", element_lower)]) + + def test_cdata_with_closing_tags(self): + # see issue #13358 + # make sure that HTMLParser calls handle_data only once for each CDATA. + # The normal event collector normalizes the events in get_events, + # so we override it to return the original list of events. + class Collector(EventCollector): + def get_events(self): + return self.events + + content = """ ¬-an-entity-ref; +

+ ''""" + for element in [' script', 'script ', ' script ', + '\nscript', 'script\n', '\nscript\n']: + element_lower = element.lower().strip() + s = '