Back to index

python3.2  3.2.2
Classes | Public Member Functions | Static Public Member Functions | Public Attributes | Static Public Attributes
test.test_builtin.BuiltinTest Class Reference

List of all members.

Classes

class  C_get_vars

Public Member Functions

def test_import
def test_abs
def test_all
def test_any
def test_ascii
def test_neg
def test_callable
def test_chr
def test_cmp
def test_compile
def test_delattr
def test_dir
def test_divmod
def test_eval
def test_general_eval
def test_exec
def test_exec_redirected
def test_filter
def test_getattr
def test_hasattr
def test_hash
def test_hex
def test_id
def test_iter
def test_isinstance
def test_issubclass
def test_len
def test_map
def test_max
def test_min
def test_next
def test_oct
def write_testfile
def test_open
def test_ord
def test_pow
def test_input
def test_repr
def test_round
def test_round_large
def test_setattr
def test_sum
def test_type
def test_vars
def test_zip
def test_format
def test_bin
def test_bytearray_translate

Static Public Member Functions

def get_vars_f0
def get_vars_f2

Public Attributes

 x
 y
 z
 bar

Static Public Attributes

tuple linux_alpha
tuple system_round_bug = round(5e15+1)

Detailed Description

Definition at line 107 of file test_builtin.py.


Member Function Documentation

Definition at line 1138 of file test_builtin.py.

01138 
01139     def get_vars_f0():
01140         return vars()

Here is the caller graph for this function:

Definition at line 1142 of file test_builtin.py.

01142 
01143     def get_vars_f2():
01144         BuiltinTest.get_vars_f0()
01145         a = 1
01146         b = 2
01147         return vars()

Here is the caller graph for this function:

Definition at line 120 of file test_builtin.py.

00120 
00121     def test_abs(self):
00122         # int
00123         self.assertEqual(abs(0), 0)
00124         self.assertEqual(abs(1234), 1234)
00125         self.assertEqual(abs(-1234), 1234)
00126         self.assertTrue(abs(-sys.maxsize-1) > 0)
00127         # float
00128         self.assertEqual(abs(0.0), 0.0)
00129         self.assertEqual(abs(3.14), 3.14)
00130         self.assertEqual(abs(-3.14), 3.14)
00131         # str
00132         self.assertRaises(TypeError, abs, 'a')
00133         # bool
00134         self.assertEqual(abs(True), 1)
00135         self.assertEqual(abs(False), 0)
00136         # other
00137         self.assertRaises(TypeError, abs)
00138         self.assertRaises(TypeError, abs, None)
00139         class AbsClass(object):
00140             def __abs__(self):
00141                 return -5
00142         self.assertEqual(abs(AbsClass()), -5)

Here is the call graph for this function:

Definition at line 143 of file test_builtin.py.

00143 
00144     def test_all(self):
00145         self.assertEqual(all([2, 4, 6]), True)
00146         self.assertEqual(all([2, None, 6]), False)
00147         self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
00148         self.assertRaises(RuntimeError, all, TestFailingIter())
00149         self.assertRaises(TypeError, all, 10)               # Non-iterable
00150         self.assertRaises(TypeError, all)                   # No args
00151         self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
00152         self.assertEqual(all([]), True)                     # Empty iterator
00153         S = [50, 60]
00154         self.assertEqual(all(x > 42 for x in S), True)
00155         S = [50, 40, 60]
00156         self.assertEqual(all(x > 42 for x in S), False)

Here is the call graph for this function:

Definition at line 157 of file test_builtin.py.

00157 
00158     def test_any(self):
00159         self.assertEqual(any([None, None, None]), False)
00160         self.assertEqual(any([None, 4, None]), True)
00161         self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
00162         self.assertRaises(RuntimeError, all, TestFailingIter())
00163         self.assertRaises(TypeError, any, 10)               # Non-iterable
00164         self.assertRaises(TypeError, any)                   # No args
00165         self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
00166         self.assertEqual(any([]), False)                    # Empty iterator
00167         S = [40, 60, 30]
00168         self.assertEqual(any(x > 42 for x in S), True)
00169         S = [10, 20, 30]
00170         self.assertEqual(any(x > 42 for x in S), False)

Here is the call graph for this function:

Definition at line 171 of file test_builtin.py.

00171 
00172     def test_ascii(self):
00173         self.assertEqual(ascii(''), '\'\'')
00174         self.assertEqual(ascii(0), '0')
00175         self.assertEqual(ascii(()), '()')
00176         self.assertEqual(ascii([]), '[]')
00177         self.assertEqual(ascii({}), '{}')
00178         a = []
00179         a.append(a)
00180         self.assertEqual(ascii(a), '[[...]]')
00181         a = {}
00182         a[0] = a
00183         self.assertEqual(ascii(a), '{0: {...}}')
00184         # Advanced checks for unicode strings
00185         def _check_uni(s):
00186             self.assertEqual(ascii(s), repr(s))
00187         _check_uni("'")
00188         _check_uni('"')
00189         _check_uni('"\'')
00190         _check_uni('\0')
00191         _check_uni('\r\n\t .')
00192         # Unprintable non-ASCII characters
00193         _check_uni('\x85')
00194         _check_uni('\u1fff')
00195         _check_uni('\U00012fff')
00196         # Lone surrogates
00197         _check_uni('\ud800')
00198         _check_uni('\udfff')
00199         # Issue #9804: surrogates should be joined even for printable
00200         # wide characters (UCS-2 builds).
00201         self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
00202         # All together
00203         s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
00204         self.assertEqual(ascii(s),
00205             r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")

Here is the call graph for this function:

Definition at line 1316 of file test_builtin.py.

01316 
01317     def test_bin(self):
01318         self.assertEqual(bin(0), '0b0')
01319         self.assertEqual(bin(1), '0b1')
01320         self.assertEqual(bin(-1), '-0b1')
01321         self.assertEqual(bin(2**65), '0b1' + '0' * 65)
01322         self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
01323         self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
01324         self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)

Here is the call graph for this function:

Definition at line 1325 of file test_builtin.py.

01325 
01326     def test_bytearray_translate(self):
01327         x = bytearray(b"abc")
01328         self.assertRaises(ValueError, x.translate, b"1", 1)
01329         self.assertRaises(TypeError, x.translate, b"1"*256, 1)

Here is the call graph for this function:

Definition at line 211 of file test_builtin.py.

00211 
00212     def test_callable(self):
00213         self.assertTrue(callable(len))
00214         self.assertFalse(callable("a"))
00215         self.assertTrue(callable(callable))
00216         self.assertTrue(callable(lambda x, y: x + y))
00217         self.assertFalse(callable(__builtins__))
00218         def f(): pass
00219         self.assertTrue(callable(f))
00220 
00221         class C1:
00222             def meth(self): pass
00223         self.assertTrue(callable(C1))
00224         c = C1()
00225         self.assertTrue(callable(c.meth))
00226         self.assertFalse(callable(c))
00227 
00228         # __call__ is looked up on the class, not the instance
00229         c.__call__ = None
00230         self.assertFalse(callable(c))
00231         c.__call__ = lambda self: 0
00232         self.assertFalse(callable(c))
00233         del c.__call__
00234         self.assertFalse(callable(c))
00235 
00236         class C2(object):
00237             def __call__(self): pass
00238         c2 = C2()
00239         self.assertTrue(callable(c2))
00240         c2.__call__ = None
00241         self.assertTrue(callable(c2))
00242         class C3(C2): pass
00243         c3 = C3()
00244         self.assertTrue(callable(c3))

Here is the call graph for this function:

Definition at line 245 of file test_builtin.py.

00245 
00246     def test_chr(self):
00247         self.assertEqual(chr(32), ' ')
00248         self.assertEqual(chr(65), 'A')
00249         self.assertEqual(chr(97), 'a')
00250         self.assertEqual(chr(0xff), '\xff')
00251         self.assertRaises(ValueError, chr, 1<<24)
00252         self.assertEqual(chr(sys.maxunicode),
00253                          str(('\\U%08x' % (sys.maxunicode)).encode("ascii"),
00254                              'unicode-escape'))
00255         self.assertRaises(TypeError, chr)
00256         self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
00257         self.assertEqual(chr(0x00010000), "\U00010000")
00258         self.assertEqual(chr(0x00010001), "\U00010001")
00259         self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
00260         self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
00261         self.assertEqual(chr(0x00100000), "\U00100000")
00262         self.assertEqual(chr(0x00100001), "\U00100001")
00263         self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
00264         self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
00265         self.assertRaises(ValueError, chr, -1)
00266         self.assertRaises(ValueError, chr, 0x00110000)
00267         self.assertRaises((OverflowError, ValueError), chr, 2**32)

Here is the call graph for this function:

Definition at line 268 of file test_builtin.py.

00268 
00269     def test_cmp(self):
00270         self.assertTrue(not hasattr(builtins, "cmp"))

Here is the call graph for this function:

Definition at line 271 of file test_builtin.py.

00271 
00272     def test_compile(self):
00273         compile('print(1)\n', '', 'exec')
00274         bom = b'\xef\xbb\xbf'
00275         compile(bom + b'print(1)\n', '', 'exec')
00276         compile(source='pass', filename='?', mode='exec')
00277         compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
00278         compile('pass', '?', dont_inherit=1, mode='exec')
00279         compile(memoryview(b"text"), "name", "exec")
00280         self.assertRaises(TypeError, compile)
00281         self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
00282         self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
00283         self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
00284         self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
00285                           mode='eval', source='0', filename='tmp')
00286         compile('print("\xe5")\n', '', 'exec')
00287         self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
00288         self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
00289 
00290         # test the optimize argument
00291 
00292         codestr = '''def f():
00293         """doc"""
00294         try:
00295             assert False
00296         except AssertionError:
00297             return (True, f.__doc__)
00298         else:
00299             return (False, f.__doc__)
00300         '''
00301         def f(): """doc"""
00302         values = [(-1, __debug__, f.__doc__),
00303                   (0, True, 'doc'),
00304                   (1, False, 'doc'),
00305                   (2, False, None)]
00306         for optval, debugval, docstring in values:
00307             # test both direct compilation and compilation via AST
00308             codeobjs = []
00309             codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
00310             tree = ast.parse(codestr)
00311             codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
00312             for code in codeobjs:
00313                 ns = {}
00314                 exec(code, ns)
00315                 rv = ns['f']()
00316                 self.assertEqual(rv, (debugval, docstring))

Here is the call graph for this function:

Definition at line 317 of file test_builtin.py.

00317 
00318     def test_delattr(self):
00319         sys.spam = 1
00320         delattr(sys, 'spam')
00321         self.assertRaises(TypeError, delattr)

Here is the call graph for this function:

Definition at line 322 of file test_builtin.py.

00322 
00323     def test_dir(self):
00324         # dir(wrong number of arguments)
00325         self.assertRaises(TypeError, dir, 42, 42)
00326 
00327         # dir() - local scope
00328         local_var = 1
00329         self.assertIn('local_var', dir())
00330 
00331         # dir(module)
00332         self.assertIn('exit', dir(sys))
00333 
00334         # dir(module_with_invalid__dict__)
00335         class Foo(types.ModuleType):
00336             __dict__ = 8
00337         f = Foo("foo")
00338         self.assertRaises(TypeError, dir, f)
00339 
00340         # dir(type)
00341         self.assertIn("strip", dir(str))
00342         self.assertNotIn("__mro__", dir(str))
00343 
00344         # dir(obj)
00345         class Foo(object):
00346             def __init__(self):
00347                 self.x = 7
00348                 self.y = 8
00349                 self.z = 9
00350         f = Foo()
00351         self.assertIn("y", dir(f))
00352 
00353         # dir(obj_no__dict__)
00354         class Foo(object):
00355             __slots__ = []
00356         f = Foo()
00357         self.assertIn("__repr__", dir(f))
00358 
00359         # dir(obj_no__class__with__dict__)
00360         # (an ugly trick to cause getattr(f, "__class__") to fail)
00361         class Foo(object):
00362             __slots__ = ["__class__", "__dict__"]
00363             def __init__(self):
00364                 self.bar = "wow"
00365         f = Foo()
00366         self.assertNotIn("__repr__", dir(f))
00367         self.assertIn("bar", dir(f))
00368 
00369         # dir(obj_using __dir__)
00370         class Foo(object):
00371             def __dir__(self):
00372                 return ["kan", "ga", "roo"]
00373         f = Foo()
00374         self.assertTrue(dir(f) == ["ga", "kan", "roo"])
00375 
00376         # dir(obj__dir__not_list)
00377         class Foo(object):
00378             def __dir__(self):
00379                 return 7
00380         f = Foo()
00381         self.assertRaises(TypeError, dir, f)
00382 
00383         # dir(traceback)
00384         try:
00385             raise IndexError
00386         except:
00387             self.assertEqual(len(dir(sys.exc_info()[2])), 4)
00388 

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 389 of file test_builtin.py.

00389 
00390     def test_divmod(self):
00391         self.assertEqual(divmod(12, 7), (1, 5))
00392         self.assertEqual(divmod(-12, 7), (-2, 2))
00393         self.assertEqual(divmod(12, -7), (-2, -2))
00394         self.assertEqual(divmod(-12, -7), (1, -5))
00395 
00396         self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
00397 
00398         self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
00399         self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
00400         self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
00401         self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
00402 
00403         self.assertRaises(TypeError, divmod)

Here is the call graph for this function:

Definition at line 404 of file test_builtin.py.

00404 
00405     def test_eval(self):
00406         self.assertEqual(eval('1+1'), 2)
00407         self.assertEqual(eval(' 1+1\n'), 2)
00408         globals = {'a': 1, 'b': 2}
00409         locals = {'b': 200, 'c': 300}
00410         self.assertEqual(eval('a', globals) , 1)
00411         self.assertEqual(eval('a', globals, locals), 1)
00412         self.assertEqual(eval('b', globals, locals), 200)
00413         self.assertEqual(eval('c', globals, locals), 300)
00414         globals = {'a': 1, 'b': 2}
00415         locals = {'b': 200, 'c': 300}
00416         bom = b'\xef\xbb\xbf'
00417         self.assertEqual(eval(bom + b'a', globals, locals), 1)
00418         self.assertEqual(eval('"\xe5"', globals), "\xe5")
00419         self.assertRaises(TypeError, eval)
00420         self.assertRaises(TypeError, eval, ())
00421         self.assertRaises(SyntaxError, eval, bom[:2] + b'a')

Here is the call graph for this function:

Definition at line 491 of file test_builtin.py.

00491 
00492     def test_exec(self):
00493         g = {}
00494         exec('z = 1', g)
00495         if '__builtins__' in g:
00496             del g['__builtins__']
00497         self.assertEqual(g, {'z': 1})
00498 
00499         exec('z = 1+1', g)
00500         if '__builtins__' in g:
00501             del g['__builtins__']
00502         self.assertEqual(g, {'z': 2})
00503         g = {}
00504         l = {}
00505 
00506         with check_warnings():
00507             warnings.filterwarnings("ignore", "global statement",
00508                     module="<string>")
00509             exec('global a; a = 1; b = 2', g, l)
00510         if '__builtins__' in g:
00511             del g['__builtins__']
00512         if '__builtins__' in l:
00513             del l['__builtins__']
00514         self.assertEqual((g, l), ({'a': 1}, {'b': 2}))

Here is the call graph for this function:

Definition at line 515 of file test_builtin.py.

00515 
00516     def test_exec_redirected(self):
00517         savestdout = sys.stdout
00518         sys.stdout = None # Whatever that cannot flush()
00519         try:
00520             # Used to raise SystemError('error return without exception set')
00521             exec('a')
00522         except NameError:
00523             pass
00524         finally:
00525             sys.stdout = savestdout

Definition at line 526 of file test_builtin.py.

00526 
00527     def test_filter(self):
00528         self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
00529         self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
00530         self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
00531         self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
00532         self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
00533         def identity(item):
00534             return 1
00535         filter(identity, Squares(5))
00536         self.assertRaises(TypeError, filter)
00537         class BadSeq(object):
00538             def __getitem__(self, index):
00539                 if index<4:
00540                     return 42
00541                 raise ValueError
00542         self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
00543         def badfunc():
00544             pass
00545         self.assertRaises(TypeError, list, filter(badfunc, range(5)))
00546 
00547         # test bltinmodule.c::filtertuple()
00548         self.assertEqual(list(filter(None, (1, 2))), [1, 2])
00549         self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
00550         self.assertRaises(TypeError, list, filter(42, (1, 2)))

Here is the call graph for this function:

Definition at line 1206 of file test_builtin.py.

01206 
01207     def test_format(self):
01208         # Test the basic machinery of the format() builtin.  Don't test
01209         #  the specifics of the various formatters
01210         self.assertEqual(format(3, ''), '3')
01211 
01212         # Returns some classes to use for various tests.  There's
01213         #  an old-style version, and a new-style version
01214         def classes_new():
01215             class A(object):
01216                 def __init__(self, x):
01217                     self.x = x
01218                 def __format__(self, format_spec):
01219                     return str(self.x) + format_spec
01220             class DerivedFromA(A):
01221                 pass
01222 
01223             class Simple(object): pass
01224             class DerivedFromSimple(Simple):
01225                 def __init__(self, x):
01226                     self.x = x
01227                 def __format__(self, format_spec):
01228                     return str(self.x) + format_spec
01229             class DerivedFromSimple2(DerivedFromSimple): pass
01230             return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
01231 
01232         def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
01233             self.assertEqual(format(A(3), 'spec'), '3spec')
01234             self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
01235             self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
01236             self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
01237                              '10abcdef')
01238 
01239         class_test(*classes_new())
01240 
01241         def empty_format_spec(value):
01242             # test that:
01243             #  format(x, '') == str(x)
01244             #  format(x) == str(x)
01245             self.assertEqual(format(value, ""), str(value))
01246             self.assertEqual(format(value), str(value))
01247 
01248         # for builtin types, format(x, "") == str(x)
01249         empty_format_spec(17**13)
01250         empty_format_spec(1.0)
01251         empty_format_spec(3.1415e104)
01252         empty_format_spec(-3.1415e104)
01253         empty_format_spec(3.1415e-104)
01254         empty_format_spec(-3.1415e-104)
01255         empty_format_spec(object)
01256         empty_format_spec(None)
01257 
01258         # TypeError because self.__format__ returns the wrong type
01259         class BadFormatResult:
01260             def __format__(self, format_spec):
01261                 return 1.0
01262         self.assertRaises(TypeError, format, BadFormatResult(), "")
01263 
01264         # TypeError because format_spec is not unicode or str
01265         self.assertRaises(TypeError, format, object(), 4)
01266         self.assertRaises(TypeError, format, object(), object())
01267 
01268         # tests for object.__format__ really belong elsewhere, but
01269         #  there's no good place to put them
01270         x = object().__format__('')
01271         self.assertTrue(x.startswith('<object object at'))
01272 
01273         # first argument to object.__format__ must be string
01274         self.assertRaises(TypeError, object().__format__, 3)
01275         self.assertRaises(TypeError, object().__format__, object())
01276         self.assertRaises(TypeError, object().__format__, None)
01277 
01278         # --------------------------------------------------------------------
01279         # Issue #7994: object.__format__ with a non-empty format string is
01280         #  pending deprecated
01281         def test_deprecated_format_string(obj, fmt_str, should_raise_warning):
01282             with warnings.catch_warnings(record=True) as w:
01283                 warnings.simplefilter("always", PendingDeprecationWarning)
01284                 format(obj, fmt_str)
01285             if should_raise_warning:
01286                 self.assertEqual(len(w), 1)
01287                 self.assertIsInstance(w[0].message, PendingDeprecationWarning)
01288                 self.assertIn('object.__format__ with a non-empty format '
01289                               'string', str(w[0].message))
01290             else:
01291                 self.assertEqual(len(w), 0)
01292 
01293         fmt_strs = ['', 's']
01294 
01295         class A:
01296             def __format__(self, fmt_str):
01297                 return format('', fmt_str)
01298 
01299         for fmt_str in fmt_strs:
01300             test_deprecated_format_string(A(), fmt_str, False)
01301 
01302         class B:
01303             pass
01304 
01305         class C(object):
01306             pass
01307 
01308         for cls in [object, B, C]:
01309             for fmt_str in fmt_strs:
01310                 test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)
01311         # --------------------------------------------------------------------
01312 
01313         # make sure we can take a subclass of str as a format spec
01314         class DerivedFromStr(str): pass
01315         self.assertEqual(format(0, DerivedFromStr('10')), '         0')

Here is the call graph for this function:

Definition at line 422 of file test_builtin.py.

00422 
00423     def test_general_eval(self):
00424         # Tests that general mappings can be used for the locals argument
00425 
00426         class M:
00427             "Test mapping interface versus possible calls from eval()."
00428             def __getitem__(self, key):
00429                 if key == 'a':
00430                     return 12
00431                 raise KeyError
00432             def keys(self):
00433                 return list('xyz')
00434 
00435         m = M()
00436         g = globals()
00437         self.assertEqual(eval('a', g, m), 12)
00438         self.assertRaises(NameError, eval, 'b', g, m)
00439         self.assertEqual(eval('dir()', g, m), list('xyz'))
00440         self.assertEqual(eval('globals()', g, m), g)
00441         self.assertEqual(eval('locals()', g, m), m)
00442         self.assertRaises(TypeError, eval, 'a', m)
00443         class A:
00444             "Non-mapping"
00445             pass
00446         m = A()
00447         self.assertRaises(TypeError, eval, 'a', g, m)
00448 
00449         # Verify that dict subclasses work as well
00450         class D(dict):
00451             def __getitem__(self, key):
00452                 if key == 'a':
00453                     return 12
00454                 return dict.__getitem__(self, key)
00455             def keys(self):
00456                 return list('xyz')
00457 
00458         d = D()
00459         self.assertEqual(eval('a', g, d), 12)
00460         self.assertRaises(NameError, eval, 'b', g, d)
00461         self.assertEqual(eval('dir()', g, d), list('xyz'))
00462         self.assertEqual(eval('globals()', g, d), g)
00463         self.assertEqual(eval('locals()', g, d), d)
00464 
00465         # Verify locals stores (used by list comps)
00466         eval('[locals() for i in (2,3)]', g, d)
00467         eval('[locals() for i in (2,3)]', g, collections.UserDict())
00468 
00469         class SpreadSheet:
00470             "Sample application showing nested, calculated lookups."
00471             _cells = {}
00472             def __setitem__(self, key, formula):
00473                 self._cells[key] = formula
00474             def __getitem__(self, key):
00475                 return eval(self._cells[key], globals(), self)
00476 
00477         ss = SpreadSheet()
00478         ss['a1'] = '5'
00479         ss['a2'] = 'a1*6'
00480         ss['a3'] = 'a2*7'
00481         self.assertEqual(ss['a3'], 210)
00482 
00483         # Verify that dir() catches a non-list returned by eval
00484         # SF bug #1004669
00485         class C:
00486             def __getitem__(self, item):
00487                 raise KeyError(item)
00488             def keys(self):
00489                 return 1 # used to be 'a' but that's no longer an error
00490         self.assertRaises(TypeError, eval, 'dir()', globals(), C())

Here is the call graph for this function:

Definition at line 551 of file test_builtin.py.

00551 
00552     def test_getattr(self):
00553         self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
00554         self.assertRaises(TypeError, getattr, sys, 1)
00555         self.assertRaises(TypeError, getattr, sys, 1, "foo")
00556         self.assertRaises(TypeError, getattr)
00557         self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
00558         # unicode surrogates are not encodable to the default encoding (utf8)
00559         self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")

Here is the call graph for this function:

Definition at line 560 of file test_builtin.py.

00560 
00561     def test_hasattr(self):
00562         self.assertTrue(hasattr(sys, 'stdout'))
00563         self.assertRaises(TypeError, hasattr, sys, 1)
00564         self.assertRaises(TypeError, hasattr)
00565         self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
00566 
00567         # Check that hasattr propagates all exceptions outside of
00568         # AttributeError.
00569         class A:
00570             def __getattr__(self, what):
00571                 raise SystemExit
00572         self.assertRaises(SystemExit, hasattr, A(), "b")
00573         class B:
00574             def __getattr__(self, what):
00575                 raise ValueError
00576         self.assertRaises(ValueError, hasattr, B(), "b")

Here is the call graph for this function:

Definition at line 577 of file test_builtin.py.

00577 
00578     def test_hash(self):
00579         hash(None)
00580         self.assertEqual(hash(1), hash(1))
00581         self.assertEqual(hash(1), hash(1.0))
00582         hash('spam')
00583         self.assertEqual(hash('spam'), hash(b'spam'))
00584         hash((0,1,2,3))
00585         def f(): pass
00586         self.assertRaises(TypeError, hash, [])
00587         self.assertRaises(TypeError, hash, {})
00588         # Bug 1536021: Allow hash to return long objects
00589         class X:
00590             def __hash__(self):
00591                 return 2**100
00592         self.assertEqual(type(hash(X())), int)
00593         class Z(int):
00594             def __hash__(self):
00595                 return self
00596         self.assertEqual(hash(Z(42)), hash(42))

Here is the call graph for this function:

Definition at line 597 of file test_builtin.py.

00597 
00598     def test_hex(self):
00599         self.assertEqual(hex(16), '0x10')
00600         self.assertEqual(hex(-16), '-0x10')
00601         self.assertRaises(TypeError, hex, {})

Here is the call graph for this function:

Definition at line 602 of file test_builtin.py.

00602 
00603     def test_id(self):
00604         id(None)
00605         id(1)
00606         id(1.0)
00607         id('spam')
00608         id((0,1,2,3))
00609         id([0,1,2,3])
00610         id({'spam': 1, 'eggs': 2, 'ham': 3})

Definition at line 109 of file test_builtin.py.

00109 
00110     def test_import(self):
00111         __import__('sys')
00112         __import__('time')
00113         __import__('string')
00114         __import__(name='sys')
00115         __import__(name='time', level=0)
00116         self.assertRaises(ImportError, __import__, 'spamspam')
00117         self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
00118         self.assertRaises(ValueError, __import__, '')
00119         self.assertRaises(TypeError, __import__, 'sys', name='sys')

Here is the call graph for this function:

Definition at line 955 of file test_builtin.py.

00955 
00956     def test_input(self):
00957         self.write_testfile()
00958         fp = open(TESTFN, 'r')
00959         savestdin = sys.stdin
00960         savestdout = sys.stdout # Eats the echo
00961         try:
00962             sys.stdin = fp
00963             sys.stdout = BitBucket()
00964             self.assertEqual(input(), "1+1")
00965             self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
00966             self.assertEqual(input('testing\n'), 'Dear John')
00967 
00968             # SF 1535165: don't segfault on closed stdin
00969             # sys.stdout must be a regular file for triggering
00970             sys.stdout = savestdout
00971             sys.stdin.close()
00972             self.assertRaises(ValueError, input)
00973 
00974             sys.stdout = BitBucket()
00975             sys.stdin = io.StringIO("NULL\0")
00976             self.assertRaises(TypeError, input, 42, 42)
00977             sys.stdin = io.StringIO("    'whitespace'")
00978             self.assertEqual(input(), "    'whitespace'")
00979             sys.stdin = io.StringIO()
00980             self.assertRaises(EOFError, input)
00981 
00982             del sys.stdout
00983             self.assertRaises(RuntimeError, input, 'prompt')
00984             del sys.stdin
00985             self.assertRaises(RuntimeError, input, 'prompt')
00986         finally:
00987             sys.stdin = savestdin
00988             sys.stdout = savestdout
00989             fp.close()
00990             unlink(TESTFN)

Here is the call graph for this function:

Definition at line 623 of file test_builtin.py.

00623 
00624     def test_isinstance(self):
00625         class C:
00626             pass
00627         class D(C):
00628             pass
00629         class E:
00630             pass
00631         c = C()
00632         d = D()
00633         e = E()
00634         self.assertTrue(isinstance(c, C))
00635         self.assertTrue(isinstance(d, C))
00636         self.assertTrue(not isinstance(e, C))
00637         self.assertTrue(not isinstance(c, D))
00638         self.assertTrue(not isinstance('foo', E))
00639         self.assertRaises(TypeError, isinstance, E, 'foo')
00640         self.assertRaises(TypeError, isinstance)

Definition at line 641 of file test_builtin.py.

00641 
00642     def test_issubclass(self):
00643         class C:
00644             pass
00645         class D(C):
00646             pass
00647         class E:
00648             pass
00649         c = C()
00650         d = D()
00651         e = E()
00652         self.assertTrue(issubclass(D, C))
00653         self.assertTrue(issubclass(C, C))
00654         self.assertTrue(not issubclass(C, D))
00655         self.assertRaises(TypeError, issubclass, 'foo', E)
00656         self.assertRaises(TypeError, issubclass, E, 'foo')
00657         self.assertRaises(TypeError, issubclass)

Definition at line 613 of file test_builtin.py.

00613 
00614     def test_iter(self):
00615         self.assertRaises(TypeError, iter)
00616         self.assertRaises(TypeError, iter, 42, 42)
00617         lists = [("1", "2"), ["1", "2"], "12"]
00618         for l in lists:
00619             i = iter(l)
00620             self.assertEqual(next(i), '1')
00621             self.assertEqual(next(i), '2')
00622             self.assertRaises(StopIteration, next, i)

Here is the call graph for this function:

Definition at line 658 of file test_builtin.py.

00658 
00659     def test_len(self):
00660         self.assertEqual(len('123'), 3)
00661         self.assertEqual(len(()), 0)
00662         self.assertEqual(len((1, 2, 3, 4)), 4)
00663         self.assertEqual(len([1, 2, 3, 4]), 4)
00664         self.assertEqual(len({}), 0)
00665         self.assertEqual(len({'a':1, 'b': 2}), 2)
00666         class BadSeq:
00667             def __len__(self):
00668                 raise ValueError
00669         self.assertRaises(ValueError, len, BadSeq())
00670         class InvalidLen:
00671             def __len__(self):
00672                 return None
00673         self.assertRaises(TypeError, len, InvalidLen())
00674         class FloatLen:
00675             def __len__(self):
00676                 return 4.5
00677         self.assertRaises(TypeError, len, FloatLen())
00678         class HugeLen:
00679             def __len__(self):
00680                 return sys.maxsize + 1
00681         self.assertRaises(OverflowError, len, HugeLen())
00682         class NoLenMethod(object): pass
00683         self.assertRaises(TypeError, len, NoLenMethod())

Here is the call graph for this function:

Definition at line 684 of file test_builtin.py.

00684 
00685     def test_map(self):
00686         self.assertEqual(
00687             list(map(lambda x: x*x, range(1,4))),
00688             [1, 4, 9]
00689         )
00690         try:
00691             from math import sqrt
00692         except ImportError:
00693             def sqrt(x):
00694                 return pow(x, 0.5)
00695         self.assertEqual(
00696             list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
00697             [[4.0, 2.0], [9.0, 3.0]]
00698         )
00699         self.assertEqual(
00700             list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
00701             [10, 4, 6]
00702         )
00703 
00704         def plus(*v):
00705             accu = 0
00706             for i in v: accu = accu + i
00707             return accu
00708         self.assertEqual(
00709             list(map(plus, [1, 3, 7])),
00710             [1, 3, 7]
00711         )
00712         self.assertEqual(
00713             list(map(plus, [1, 3, 7], [4, 9, 2])),
00714             [1+4, 3+9, 7+2]
00715         )
00716         self.assertEqual(
00717             list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
00718             [1+4+1, 3+9+1, 7+2+0]
00719         )
00720         self.assertEqual(
00721             list(map(int, Squares(10))),
00722             [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
00723         )
00724         def Max(a, b):
00725             if a is None:
00726                 return b
00727             if b is None:
00728                 return a
00729             return max(a, b)
00730         self.assertEqual(
00731             list(map(Max, Squares(3), Squares(2))),
00732             [0, 1]
00733         )
00734         self.assertRaises(TypeError, map)
00735         self.assertRaises(TypeError, map, lambda x: x, 42)
00736         class BadSeq:
00737             def __iter__(self):
00738                 raise ValueError
00739                 yield None
00740         self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
00741         def badfunc(x):
00742             raise RuntimeError
00743         self.assertRaises(RuntimeError, list, map(badfunc, range(5)))

Here is the call graph for this function:

Definition at line 744 of file test_builtin.py.

00744 
00745     def test_max(self):
00746         self.assertEqual(max('123123'), '3')
00747         self.assertEqual(max(1, 2, 3), 3)
00748         self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
00749         self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
00750 
00751         self.assertEqual(max(1, 2, 3.0), 3.0)
00752         self.assertEqual(max(1, 2.0, 3), 3)
00753         self.assertEqual(max(1.0, 2, 3), 3)
00754 
00755         for stmt in (
00756             "max(key=int)",                 # no args
00757             "max(1, key=int)",              # single arg not iterable
00758             "max(1, 2, keystone=int)",      # wrong keyword
00759             "max(1, 2, key=int, abc=int)",  # two many keywords
00760             "max(1, 2, key=1)",             # keyfunc is not callable
00761             ):
00762             try:
00763                 exec(stmt, globals())
00764             except TypeError:
00765                 pass
00766             else:
00767                 self.fail(stmt)
00768 
00769         self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
00770         self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
00771         self.assertEqual(max(1, 2, key=neg), 1)     # two elems
00772 
00773         data = [random.randrange(200) for i in range(100)]
00774         keys = dict((elem, random.randrange(50)) for elem in data)
00775         f = keys.__getitem__
00776         self.assertEqual(max(data, key=f),
00777                          sorted(reversed(data), key=f)[-1])

Here is the call graph for this function:

Definition at line 778 of file test_builtin.py.

00778 
00779     def test_min(self):
00780         self.assertEqual(min('123123'), '1')
00781         self.assertEqual(min(1, 2, 3), 1)
00782         self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
00783         self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
00784 
00785         self.assertEqual(min(1, 2, 3.0), 1)
00786         self.assertEqual(min(1, 2.0, 3), 1)
00787         self.assertEqual(min(1.0, 2, 3), 1.0)
00788 
00789         self.assertRaises(TypeError, min)
00790         self.assertRaises(TypeError, min, 42)
00791         self.assertRaises(ValueError, min, ())
00792         class BadSeq:
00793             def __getitem__(self, index):
00794                 raise ValueError
00795         self.assertRaises(ValueError, min, BadSeq())
00796 
00797         for stmt in (
00798             "min(key=int)",                 # no args
00799             "min(1, key=int)",              # single arg not iterable
00800             "min(1, 2, keystone=int)",      # wrong keyword
00801             "min(1, 2, key=int, abc=int)",  # two many keywords
00802             "min(1, 2, key=1)",             # keyfunc is not callable
00803             ):
00804             try:
00805                 exec(stmt, globals())
00806             except TypeError:
00807                 pass
00808             else:
00809                 self.fail(stmt)
00810 
00811         self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
00812         self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
00813         self.assertEqual(min(1, 2, key=neg), 2)     # two elems
00814 
00815         data = [random.randrange(200) for i in range(100)]
00816         keys = dict((elem, random.randrange(50)) for elem in data)
00817         f = keys.__getitem__
00818         self.assertEqual(min(data, key=f),
00819                          sorted(data, key=f)[0])

Here is the call graph for this function:

Definition at line 206 of file test_builtin.py.

00206 
00207     def test_neg(self):
00208         x = -sys.maxsize-1
00209         self.assertTrue(isinstance(x, int))
00210         self.assertEqual(-x, sys.maxsize+1)

Here is the call graph for this function:

Definition at line 820 of file test_builtin.py.

00820 
00821     def test_next(self):
00822         it = iter(range(2))
00823         self.assertEqual(next(it), 0)
00824         self.assertEqual(next(it), 1)
00825         self.assertRaises(StopIteration, next, it)
00826         self.assertRaises(StopIteration, next, it)
00827         self.assertEqual(next(it, 42), 42)
00828 
00829         class Iter(object):
00830             def __iter__(self):
00831                 return self
00832             def __next__(self):
00833                 raise StopIteration
00834 
00835         it = iter(Iter())
00836         self.assertEqual(next(it, 42), 42)
00837         self.assertRaises(StopIteration, next, it)
00838 
00839         def gen():
00840             yield 1
00841             return
00842 
00843         it = gen()
00844         self.assertEqual(next(it), 1)
00845         self.assertRaises(StopIteration, next, it)
00846         self.assertEqual(next(it, 42), 42)

Here is the call graph for this function:

Definition at line 847 of file test_builtin.py.

00847 
00848     def test_oct(self):
00849         self.assertEqual(oct(100), '0o144')
00850         self.assertEqual(oct(-100), '-0o144')
00851         self.assertRaises(TypeError, oct, ())

Here is the call graph for this function:

Definition at line 865 of file test_builtin.py.

00865 
00866     def test_open(self):
00867         self.write_testfile()
00868         fp = open(TESTFN, 'r')
00869         try:
00870             self.assertEqual(fp.readline(4), '1+1\n')
00871             self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
00872             self.assertEqual(fp.readline(4), 'Dear')
00873             self.assertEqual(fp.readline(100), ' John\n')
00874             self.assertEqual(fp.read(300), 'XXX'*100)
00875             self.assertEqual(fp.read(1000), 'YYY'*100)
00876         finally:
00877             fp.close()
00878         unlink(TESTFN)

Here is the call graph for this function:

Definition at line 879 of file test_builtin.py.

00879 
00880     def test_ord(self):
00881         self.assertEqual(ord(' '), 32)
00882         self.assertEqual(ord('A'), 65)
00883         self.assertEqual(ord('a'), 97)
00884         self.assertEqual(ord('\x80'), 128)
00885         self.assertEqual(ord('\xff'), 255)
00886 
00887         self.assertEqual(ord(b' '), 32)
00888         self.assertEqual(ord(b'A'), 65)
00889         self.assertEqual(ord(b'a'), 97)
00890         self.assertEqual(ord(b'\x80'), 128)
00891         self.assertEqual(ord(b'\xff'), 255)
00892 
00893         self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
00894         self.assertRaises(TypeError, ord, 42)
00895 
00896         self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
00897         self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
00898         self.assertEqual(ord("\U00010000"), 0x00010000)
00899         self.assertEqual(ord("\U00010001"), 0x00010001)
00900         self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
00901         self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
00902         self.assertEqual(ord("\U00100000"), 0x00100000)
00903         self.assertEqual(ord("\U00100001"), 0x00100001)
00904         self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
00905         self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)

Here is the call graph for this function:

Definition at line 906 of file test_builtin.py.

00906 
00907     def test_pow(self):
00908         self.assertEqual(pow(0,0), 1)
00909         self.assertEqual(pow(0,1), 0)
00910         self.assertEqual(pow(1,0), 1)
00911         self.assertEqual(pow(1,1), 1)
00912 
00913         self.assertEqual(pow(2,0), 1)
00914         self.assertEqual(pow(2,10), 1024)
00915         self.assertEqual(pow(2,20), 1024*1024)
00916         self.assertEqual(pow(2,30), 1024*1024*1024)
00917 
00918         self.assertEqual(pow(-2,0), 1)
00919         self.assertEqual(pow(-2,1), -2)
00920         self.assertEqual(pow(-2,2), 4)
00921         self.assertEqual(pow(-2,3), -8)
00922 
00923         self.assertAlmostEqual(pow(0.,0), 1.)
00924         self.assertAlmostEqual(pow(0.,1), 0.)
00925         self.assertAlmostEqual(pow(1.,0), 1.)
00926         self.assertAlmostEqual(pow(1.,1), 1.)
00927 
00928         self.assertAlmostEqual(pow(2.,0), 1.)
00929         self.assertAlmostEqual(pow(2.,10), 1024.)
00930         self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
00931         self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
00932 
00933         self.assertAlmostEqual(pow(-2.,0), 1.)
00934         self.assertAlmostEqual(pow(-2.,1), -2.)
00935         self.assertAlmostEqual(pow(-2.,2), 4.)
00936         self.assertAlmostEqual(pow(-2.,3), -8.)
00937 
00938         for x in 2, 2.0:
00939             for y in 10, 10.0:
00940                 for z in 1000, 1000.0:
00941                     if isinstance(x, float) or \
00942                        isinstance(y, float) or \
00943                        isinstance(z, float):
00944                         self.assertRaises(TypeError, pow, x, y, z)
00945                     else:
00946                         self.assertAlmostEqual(pow(x, y, z), 24.0)
00947 
00948         self.assertAlmostEqual(pow(-1, 0.5), 1j)
00949         self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
00950 
00951         self.assertRaises(TypeError, pow, -1, -2, 3)
00952         self.assertRaises(ValueError, pow, 1, 2, 0)
00953 
00954         self.assertRaises(TypeError, pow)

Here is the call graph for this function:

Definition at line 991 of file test_builtin.py.

00991 
00992     def test_repr(self):
00993         self.assertEqual(repr(''), '\'\'')
00994         self.assertEqual(repr(0), '0')
00995         self.assertEqual(repr(()), '()')
00996         self.assertEqual(repr([]), '[]')
00997         self.assertEqual(repr({}), '{}')
00998         a = []
00999         a.append(a)
01000         self.assertEqual(repr(a), '[[...]]')
01001         a = {}
01002         a[0] = a
01003         self.assertEqual(repr(a), '{0: {...}}')

Here is the call graph for this function:

Definition at line 1004 of file test_builtin.py.

01004 
01005     def test_round(self):
01006         self.assertEqual(round(0.0), 0.0)
01007         self.assertEqual(type(round(0.0)), int)
01008         self.assertEqual(round(1.0), 1.0)
01009         self.assertEqual(round(10.0), 10.0)
01010         self.assertEqual(round(1000000000.0), 1000000000.0)
01011         self.assertEqual(round(1e20), 1e20)
01012 
01013         self.assertEqual(round(-1.0), -1.0)
01014         self.assertEqual(round(-10.0), -10.0)
01015         self.assertEqual(round(-1000000000.0), -1000000000.0)
01016         self.assertEqual(round(-1e20), -1e20)
01017 
01018         self.assertEqual(round(0.1), 0.0)
01019         self.assertEqual(round(1.1), 1.0)
01020         self.assertEqual(round(10.1), 10.0)
01021         self.assertEqual(round(1000000000.1), 1000000000.0)
01022 
01023         self.assertEqual(round(-1.1), -1.0)
01024         self.assertEqual(round(-10.1), -10.0)
01025         self.assertEqual(round(-1000000000.1), -1000000000.0)
01026 
01027         self.assertEqual(round(0.9), 1.0)
01028         self.assertEqual(round(9.9), 10.0)
01029         self.assertEqual(round(999999999.9), 1000000000.0)
01030 
01031         self.assertEqual(round(-0.9), -1.0)
01032         self.assertEqual(round(-9.9), -10.0)
01033         self.assertEqual(round(-999999999.9), -1000000000.0)
01034 
01035         self.assertEqual(round(-8.0, -1), -10.0)
01036         self.assertEqual(type(round(-8.0, -1)), float)
01037 
01038         self.assertEqual(type(round(-8.0, 0)), float)
01039         self.assertEqual(type(round(-8.0, 1)), float)
01040 
01041         # Check even / odd rounding behaviour
01042         self.assertEqual(round(5.5), 6)
01043         self.assertEqual(round(6.5), 6)
01044         self.assertEqual(round(-5.5), -6)
01045         self.assertEqual(round(-6.5), -6)
01046 
01047         # Check behavior on ints
01048         self.assertEqual(round(0), 0)
01049         self.assertEqual(round(8), 8)
01050         self.assertEqual(round(-8), -8)
01051         self.assertEqual(type(round(0)), int)
01052         self.assertEqual(type(round(-8, -1)), int)
01053         self.assertEqual(type(round(-8, 0)), int)
01054         self.assertEqual(type(round(-8, 1)), int)
01055 
01056         # test new kwargs
01057         self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
01058 
01059         self.assertRaises(TypeError, round)
01060 
01061         # test generic rounding delegation for reals
01062         class TestRound:
01063             def __round__(self):
01064                 return 23
01065 
01066         class TestNoRound:
01067             pass
01068 
01069         self.assertEqual(round(TestRound()), 23)
01070 
01071         self.assertRaises(TypeError, round, 1, 2, 3)
01072         self.assertRaises(TypeError, round, TestNoRound())
01073 
01074         t = TestNoRound()
01075         t.__round__ = lambda *args: args
01076         self.assertRaises(TypeError, round, t)
01077         self.assertRaises(TypeError, round, t, 0)

Here is the call graph for this function:

Definition at line 1091 of file test_builtin.py.

01091 
01092     def test_round_large(self):
01093         # Issue #1869: integral floats should remain unchanged
01094         self.assertEqual(round(5e15-1), 5e15-1)
01095         self.assertEqual(round(5e15), 5e15)
01096         self.assertEqual(round(5e15+1), 5e15+1)
01097         self.assertEqual(round(5e15+2), 5e15+2)
01098         self.assertEqual(round(5e15+3), 5e15+3)

Here is the call graph for this function:

Definition at line 1099 of file test_builtin.py.

01099 
01100     def test_setattr(self):
01101         setattr(sys, 'spam', 1)
01102         self.assertEqual(sys.spam, 1)
01103         self.assertRaises(TypeError, setattr, sys, 1, 'spam')
01104         self.assertRaises(TypeError, setattr)
01105 

Here is the call graph for this function:

Definition at line 1106 of file test_builtin.py.

01106 
01107     def test_sum(self):
01108         self.assertEqual(sum([]), 0)
01109         self.assertEqual(sum(list(range(2,8))), 27)
01110         self.assertEqual(sum(iter(list(range(2,8)))), 27)
01111         self.assertEqual(sum(Squares(10)), 285)
01112         self.assertEqual(sum(iter(Squares(10))), 285)
01113         self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
01114 
01115         self.assertRaises(TypeError, sum)
01116         self.assertRaises(TypeError, sum, 42)
01117         self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
01118         self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
01119         self.assertRaises(TypeError, sum, [[1], [2], [3]])
01120         self.assertRaises(TypeError, sum, [{2:3}])
01121         self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
01122 
01123         class BadSeq:
01124             def __getitem__(self, index):
01125                 raise ValueError
01126         self.assertRaises(ValueError, sum, BadSeq())
01127 
01128         empty = []
01129         sum(([x] for x in range(10)), empty)
01130         self.assertEqual(empty, [])

Here is the call graph for this function:

Definition at line 1131 of file test_builtin.py.

01131 
01132     def test_type(self):
01133         self.assertEqual(type(''),  type('123'))
01134         self.assertNotEqual(type(''), type(()))

Here is the call graph for this function:

Definition at line 1153 of file test_builtin.py.

01153 
01154     def test_vars(self):
01155         self.assertEqual(set(vars()), set(dir()))
01156         self.assertEqual(set(vars(sys)), set(dir(sys)))
01157         self.assertEqual(self.get_vars_f0(), {})
01158         self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
01159         self.assertRaises(TypeError, vars, 42, 42)
01160         self.assertRaises(TypeError, vars, 42)
01161         self.assertEqual(vars(self.C_get_vars()), {'a':2})

Here is the call graph for this function:

Definition at line 1162 of file test_builtin.py.

01162 
01163     def test_zip(self):
01164         a = (1, 2, 3)
01165         b = (4, 5, 6)
01166         t = [(1, 4), (2, 5), (3, 6)]
01167         self.assertEqual(list(zip(a, b)), t)
01168         b = [4, 5, 6]
01169         self.assertEqual(list(zip(a, b)), t)
01170         b = (4, 5, 6, 7)
01171         self.assertEqual(list(zip(a, b)), t)
01172         class I:
01173             def __getitem__(self, i):
01174                 if i < 0 or i > 2: raise IndexError
01175                 return i + 4
01176         self.assertEqual(list(zip(a, I())), t)
01177         self.assertEqual(list(zip()), [])
01178         self.assertEqual(list(zip(*[])), [])
01179         self.assertRaises(TypeError, zip, None)
01180         class G:
01181             pass
01182         self.assertRaises(TypeError, zip, a, G())
01183         self.assertRaises(RuntimeError, zip, a, TestFailingIter())
01184 
01185         # Make sure zip doesn't try to allocate a billion elements for the
01186         # result list when one of its arguments doesn't say how long it is.
01187         # A MemoryError is the most likely failure mode.
01188         class SequenceWithoutALength:
01189             def __getitem__(self, i):
01190                 if i == 5:
01191                     raise IndexError
01192                 else:
01193                     return i
01194         self.assertEqual(
01195             list(zip(SequenceWithoutALength(), range(2**30))),
01196             list(enumerate(range(5)))
01197         )
01198 
01199         class BadSeq:
01200             def __getitem__(self, i):
01201                 if i == 5:
01202                     raise ValueError
01203                 else:
01204                     return i
01205         self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))

Here is the call graph for this function:

Definition at line 852 of file test_builtin.py.

00852 
00853     def write_testfile(self):
00854         # NB the first 4 lines are also used to test input, below
00855         fp = open(TESTFN, 'w')
00856         try:
00857             fp.write('1+1\n')
00858             fp.write('The quick brown fox jumps over the lazy dog')
00859             fp.write('.\n')
00860             fp.write('Dear John\n')
00861             fp.write('XXX'*100)
00862             fp.write('YYY'*100)
00863         finally:
00864             fp.close()

Here is the caller graph for this function:


Member Data Documentation

Definition at line 363 of file test_builtin.py.

Initial value:
(platform.system().startswith('Linux') and
                   platform.machine().startswith('alpha'))

Definition at line 1085 of file test_builtin.py.

Definition at line 1087 of file test_builtin.py.

Definition at line 346 of file test_builtin.py.

Definition at line 347 of file test_builtin.py.

Definition at line 348 of file test_builtin.py.


The documentation for this class was generated from the following file: