PageRenderTime 27ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/module/__builtin__/test/test_builtin.py

https://bitbucket.org/pypy/pypy/
Python | 791 lines | 751 code | 34 blank | 6 comment | 13 complexity | 05b92b493e187611cc52967c201fc4e2 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. import sys
  2. from rpython.tool.udir import udir
  3. class AppTestBuiltinApp:
  4. def setup_class(cls):
  5. space = cls.space
  6. class X(object):
  7. def __eq__(self, other):
  8. raise OverflowError
  9. def __hash__(self):
  10. return 42
  11. d = {X(): 5}
  12. try:
  13. d[X()]
  14. except OverflowError:
  15. cls.w_sane_lookup = space.wrap(True)
  16. except KeyError:
  17. cls.w_sane_lookup = space.wrap(False)
  18. # starting with CPython 2.6, when the stack is almost out, we
  19. # can get a random error, instead of just a RuntimeError.
  20. # For example if an object x has a __getattr__, we can get
  21. # AttributeError if attempting to call x.__getattr__ runs out
  22. # of stack. That's annoying, so we just work around it.
  23. if cls.runappdirect:
  24. cls.w_safe_runtimerror = space.wrap(True)
  25. else:
  26. cls.w_safe_runtimerror = space.wrap(sys.version_info < (2, 6))
  27. emptyfile = udir.join('emptyfile.py')
  28. emptyfile.write('')
  29. nullbytes = udir.join('nullbytes.py')
  30. nullbytes.write('#abc\x00def\n')
  31. nonexistent = udir.join('builtins-nonexistent')
  32. cls.w_emptyfile = space.wrap(str(emptyfile))
  33. cls.w_nullbytes = space.wrap(str(nullbytes))
  34. cls.w_nonexistent = space.wrap(str(nonexistent))
  35. def test_builtin_names(self):
  36. import __builtin__
  37. assert __builtin__.None is None
  38. assert __builtin__.False is False
  39. assert __builtin__.True is True
  40. assert __builtin__.buffer is buffer
  41. assert __builtin__.bytes is str
  42. assert __builtin__.dict is dict
  43. assert __builtin__.memoryview is memoryview
  44. def test_bytes_alias(self):
  45. assert bytes is str
  46. assert isinstance(eval("b'hi'"), str)
  47. def test_import(self):
  48. m = __import__('pprint')
  49. assert m.pformat({}) == '{}'
  50. assert m.__name__ == "pprint"
  51. raises(ImportError, __import__, 'spamspam')
  52. raises(TypeError, __import__, 1, 2, 3, 4)
  53. def test_chr(self):
  54. assert chr(65) == 'A'
  55. raises(ValueError, chr, -1)
  56. raises(TypeError, chr, 'a')
  57. def test_bin(self):
  58. assert bin(0) == "0b0"
  59. assert bin(-1) == "-0b1"
  60. assert bin(2L) == "0b10"
  61. assert bin(-2L) == "-0b10"
  62. raises(TypeError, bin, 0.)
  63. class C(object):
  64. def __index__(self):
  65. return 42
  66. assert bin(C()) == bin(42)
  67. class D(object):
  68. def __int__(self):
  69. return 42
  70. exc = raises(TypeError, bin, D())
  71. assert "index" in exc.value.message
  72. def test_unichr(self):
  73. import sys
  74. assert unichr(65) == u'A'
  75. assert type(unicode(65)) is unicode
  76. assert unichr(0x9876) == u'\u9876'
  77. if sys.maxunicode > 0xFFFF:
  78. assert unichr(sys.maxunicode) == u'\U0010FFFF'
  79. assert unichr(0x10000) == u'\U00010000'
  80. else:
  81. assert unichr(sys.maxunicode) == u'\uFFFF'
  82. raises(ValueError, unichr, -1)
  83. raises(ValueError, unichr, sys.maxunicode+1)
  84. def test_intern(self):
  85. raises(TypeError, intern)
  86. raises(TypeError, intern, 1)
  87. class S(str):
  88. pass
  89. raises(TypeError, intern, S("hello"))
  90. s = "never interned before"
  91. s2 = intern(s)
  92. assert s == s2
  93. s3 = s.swapcase()
  94. assert s3 != s2
  95. s4 = s3.swapcase()
  96. assert intern(s4) is s2
  97. def test_globals(self):
  98. d = {"foo":"bar"}
  99. exec "def f(): return globals()" in d
  100. d2 = d["f"]()
  101. assert d2 is d
  102. def test_locals(self):
  103. def f():
  104. return locals()
  105. def g(c=0, b=0, a=0):
  106. return locals()
  107. assert f() == {}
  108. assert g() == {'a': 0, 'b': 0, 'c': 0}
  109. def test_locals_deleted_local(self):
  110. def f():
  111. a = 3
  112. locals()
  113. del a
  114. return locals()
  115. assert f() == {}
  116. def test_dir(self):
  117. def f():
  118. return dir()
  119. def g(c=0, b=0, a=0):
  120. return dir()
  121. def nosp(x): return [y for y in x if y[0]!='_']
  122. assert f() == []
  123. assert g() == ['a', 'b', 'c']
  124. class X(object): pass
  125. assert nosp(dir(X)) == []
  126. class X(object):
  127. a = 23
  128. c = 45
  129. b = 67
  130. assert nosp(dir(X)) == ['a', 'b', 'c']
  131. def test_dir_in_broken_locals(self):
  132. class C(object):
  133. def __getitem__(self, item):
  134. raise KeyError(item)
  135. def keys(self):
  136. return 'a' # not a list!
  137. raises(TypeError, eval, "dir()", {}, C())
  138. def test_dir_broken_module(self):
  139. import types
  140. class Foo(types.ModuleType):
  141. __dict__ = 8
  142. raises(TypeError, dir, Foo("foo"))
  143. def test_dir_broken_object(self):
  144. class Foo(object):
  145. x = 3
  146. def __getattribute__(self, name):
  147. return name
  148. assert dir(Foo()) == []
  149. def test_dir_custom(self):
  150. class Foo(object):
  151. def __dir__(self):
  152. return ["1", "2", "3"]
  153. f = Foo()
  154. assert dir(f) == ["1", "2", "3"]
  155. class Foo:
  156. def __dir__(self):
  157. return ["apple"]
  158. assert dir(Foo()) == ["apple"]
  159. class Foo(object):
  160. def __dir__(self):
  161. return 42
  162. f = Foo()
  163. raises(TypeError, dir, f)
  164. import types
  165. class Foo(types.ModuleType):
  166. def __dir__(self):
  167. return ["blah"]
  168. assert dir(Foo("a_mod")) == ["blah"]
  169. def test_dir_custom_lookup(self):
  170. class M(type):
  171. def __dir__(self, *args): return ["14"]
  172. class X(object):
  173. __metaclass__ = M
  174. x = X()
  175. x.__dir__ = lambda x: ["14"]
  176. assert dir(x) != ["14"]
  177. def test_format(self):
  178. assert format(4) == "4"
  179. assert format(10, "o") == "12"
  180. assert format(10, "#o") == "0o12"
  181. assert format("hi") == "hi"
  182. assert isinstance(format(4, u""), unicode)
  183. def test_vars(self):
  184. def f():
  185. return vars()
  186. def g(c=0, b=0, a=0):
  187. return vars()
  188. assert f() == {}
  189. assert g() == {'a':0, 'b':0, 'c':0}
  190. def test_sum(self):
  191. assert sum([]) ==0
  192. assert sum([42]) ==42
  193. assert sum([1,2,3]) ==6
  194. assert sum([],5) ==5
  195. assert sum([1,2,3],4) ==10
  196. #
  197. class Foo(object):
  198. def __radd__(self, other):
  199. assert other is None
  200. return 42
  201. assert sum([Foo()], None) == 42
  202. def test_type_selftest(self):
  203. assert type(type) is type
  204. def test_iter_sequence(self):
  205. raises(TypeError,iter,3)
  206. x = iter(['a','b','c'])
  207. assert x.next() =='a'
  208. assert x.next() =='b'
  209. assert x.next() =='c'
  210. raises(StopIteration,x.next)
  211. def test_iter___iter__(self):
  212. # This test assumes that dict.keys() method returns keys in
  213. # the same order as dict.__iter__().
  214. # Also, this test is not as explicit as the other tests;
  215. # it tests 4 calls to __iter__() in one assert. It could
  216. # be modified if better granularity on the assert is required.
  217. mydict = {'a':1,'b':2,'c':3}
  218. assert list(iter(mydict)) ==mydict.keys()
  219. def test_iter_callable_sentinel(self):
  220. class count(object):
  221. def __init__(self):
  222. self.value = 0
  223. def __call__(self):
  224. self.value += 1
  225. return self.value
  226. # XXX Raising errors is quite slow --
  227. # uncomment these lines when fixed
  228. #self.assertRaises(TypeError,iter,3,5)
  229. #self.assertRaises(TypeError,iter,[],5)
  230. #self.assertRaises(TypeError,iter,{},5)
  231. x = iter(count(),3)
  232. assert x.next() ==1
  233. assert x.next() ==2
  234. raises(StopIteration,x.next)
  235. def test_enumerate(self):
  236. import sys
  237. seq = range(2,4)
  238. enum = enumerate(seq)
  239. assert enum.next() == (0, 2)
  240. assert enum.next() == (1, 3)
  241. raises(StopIteration, enum.next)
  242. raises(TypeError, enumerate, 1)
  243. raises(TypeError, enumerate, None)
  244. enum = enumerate(range(5), 2)
  245. assert list(enum) == zip(range(2, 7), range(5))
  246. enum = enumerate(range(2), 2**100)
  247. assert list(enum) == [(2**100, 0), (2**100+1, 1)]
  248. enum = enumerate(range(2), sys.maxint)
  249. assert list(enum) == [(sys.maxint, 0), (sys.maxint+1, 1)]
  250. raises(TypeError, enumerate, range(2), 5.5)
  251. def test_next(self):
  252. x = iter(['a', 'b', 'c'])
  253. assert next(x) == 'a'
  254. assert next(x) == 'b'
  255. assert next(x) == 'c'
  256. raises(StopIteration, next, x)
  257. assert next(x, 42) == 42
  258. def test_next__next__(self):
  259. class Counter:
  260. def __init__(self):
  261. self.count = 0
  262. def next(self):
  263. self.count += 1
  264. return self.count
  265. x = Counter()
  266. assert next(x) == 1
  267. assert next(x) == 2
  268. assert next(x) == 3
  269. def test_xrange_args(self):
  270. raises(ValueError, xrange, 0, 1, 0)
  271. def test_xrange_repr(self):
  272. assert repr(xrange(1)) == 'xrange(1)'
  273. assert repr(xrange(1,2)) == 'xrange(1, 2)'
  274. assert repr(xrange(1,2,3)) == 'xrange(1, 4, 3)'
  275. def test_xrange_up(self):
  276. x = xrange(2)
  277. iter_x = iter(x)
  278. assert iter_x.next() == 0
  279. assert iter_x.next() == 1
  280. raises(StopIteration, iter_x.next)
  281. def test_xrange_down(self):
  282. x = xrange(4,2,-1)
  283. iter_x = iter(x)
  284. assert iter_x.next() == 4
  285. assert iter_x.next() == 3
  286. raises(StopIteration, iter_x.next)
  287. def test_xrange_has_type_identity(self):
  288. assert type(xrange(1)) == type(xrange(1))
  289. def test_xrange_len(self):
  290. x = xrange(33)
  291. assert len(x) == 33
  292. exc = raises(TypeError, xrange, 33.2)
  293. assert "integer" in str(exc.value)
  294. x = xrange(33,0,-1)
  295. assert len(x) == 33
  296. x = xrange(33,0)
  297. assert len(x) == 0
  298. exc = raises(TypeError, xrange, 33, 0.2)
  299. assert "integer" in str(exc.value)
  300. x = xrange(0,33)
  301. assert len(x) == 33
  302. x = xrange(0,33,-1)
  303. assert len(x) == 0
  304. x = xrange(0,33,2)
  305. assert len(x) == 17
  306. x = xrange(0,32,2)
  307. assert len(x) == 16
  308. def test_xrange_indexing(self):
  309. x = xrange(0,33,2)
  310. assert x[7] == 14
  311. assert x[-7] == 20
  312. raises(IndexError, x.__getitem__, 17)
  313. raises(IndexError, x.__getitem__, -18)
  314. raises(TypeError, x.__getitem__, slice(0,3,1))
  315. def test_xrange_bad_args(self):
  316. raises(TypeError, xrange, '1')
  317. raises(TypeError, xrange, None)
  318. raises(TypeError, xrange, 3+2j)
  319. raises(TypeError, xrange, 1, '1')
  320. raises(TypeError, xrange, 1, 3+2j)
  321. raises(TypeError, xrange, 1, 2, '1')
  322. raises(TypeError, xrange, 1, 2, 3+2j)
  323. def test_sorted(self):
  324. l = []
  325. sorted_l = sorted(l)
  326. assert sorted_l is not l
  327. assert sorted_l == l
  328. l = [1, 5, 2, 3]
  329. sorted_l = sorted(l)
  330. assert sorted_l == [1, 2, 3, 5]
  331. def test_sorted_with_keywords(self):
  332. l = ['a', 'C', 'b']
  333. sorted_l = sorted(l, reverse = True)
  334. assert sorted_l is not l
  335. assert sorted_l == ['b', 'a', 'C']
  336. sorted_l = sorted(l, reverse = True, key = lambda x: x.lower())
  337. assert sorted_l is not l
  338. assert sorted_l == ['C', 'b', 'a']
  339. raises(TypeError, sorted, [], reverse=None)
  340. def test_reversed_simple_sequences(self):
  341. l = range(5)
  342. rev = reversed(l)
  343. assert list(rev) == [4, 3, 2, 1, 0]
  344. assert list(l.__reversed__()) == [4, 3, 2, 1, 0]
  345. s = "abcd"
  346. assert list(reversed(s)) == ['d', 'c', 'b', 'a']
  347. def test_reversed_custom_objects(self):
  348. """make sure __reversed__ is called when defined"""
  349. class SomeClass(object):
  350. def __reversed__(self):
  351. return 42
  352. obj = SomeClass()
  353. assert reversed(obj) == 42
  354. def test_cmp(self):
  355. assert cmp(9,9) == 0
  356. assert cmp(0,9) < 0
  357. assert cmp(9,0) > 0
  358. assert cmp("abc", 12) != 0
  359. assert cmp(u"abc", 12) != 0
  360. def test_cmp_more(self):
  361. class C(object):
  362. def __eq__(self, other):
  363. return True
  364. def __cmp__(self, other):
  365. raise RuntimeError
  366. c1 = C()
  367. c2 = C()
  368. raises(RuntimeError, cmp, c1, c2)
  369. def test_cmp_cyclic(self):
  370. if not self.sane_lookup:
  371. skip("underlying Python implementation has insane dict lookup")
  372. if not self.safe_runtimerror:
  373. skip("underlying Python may raise random exceptions on stack ovf")
  374. a = []; a.append(a)
  375. b = []; b.append(b)
  376. from UserList import UserList
  377. c = UserList(); c.append(c)
  378. raises(RuntimeError, cmp, a, b)
  379. raises(RuntimeError, cmp, b, c)
  380. raises(RuntimeError, cmp, c, a)
  381. raises(RuntimeError, cmp, a, c)
  382. # okay, now break the cycles
  383. a.pop(); b.pop(); c.pop()
  384. def test_coerce(self):
  385. assert coerce(1, 2) == (1, 2)
  386. assert coerce(1L, 2L) == (1L, 2L)
  387. assert coerce(1, 2L) == (1L, 2L)
  388. assert coerce(1L, 2) == (1L, 2L)
  389. assert coerce(1, 2.0) == (1.0, 2.0)
  390. assert coerce(1.0, 2L) == (1.0, 2.0)
  391. assert coerce(1L, 2.0) == (1.0, 2.0)
  392. raises(TypeError,coerce, 1 , 'a')
  393. raises(TypeError,coerce, u'a' , 'a')
  394. def test_return_None(self):
  395. class X(object): pass
  396. x = X()
  397. assert setattr(x, 'x', 11) == None
  398. assert delattr(x, 'x') == None
  399. # To make this test, we need autopath to work in application space.
  400. assert execfile(self.emptyfile) == None
  401. def test_divmod(self):
  402. assert divmod(15,10) ==(1,5)
  403. def test_callable(self):
  404. class Call(object):
  405. def __call__(self, a):
  406. return a+2
  407. assert callable(Call()), (
  408. "Builtin function 'callable' misreads callable object")
  409. assert callable(int), (
  410. "Builtin function 'callable' misreads int")
  411. class Call:
  412. def __call__(self, a):
  413. return a+2
  414. assert callable(Call())
  415. def test_uncallable(self):
  416. # XXX TODO: I made the NoCall class explicitly newstyle to try and
  417. # remedy the failure in this test observed when running this with
  418. # the trivial objectspace, but the test _still_ fails then (it
  419. # doesn't fail with the standard objectspace, though).
  420. class NoCall(object):
  421. pass
  422. a = NoCall()
  423. assert not callable(a), (
  424. "Builtin function 'callable' misreads uncallable object")
  425. a.__call__ = lambda: "foo"
  426. assert not callable(a), (
  427. "Builtin function 'callable' tricked by instance-__call__")
  428. class NoCall:
  429. pass
  430. assert not callable(NoCall())
  431. def test_hash(self):
  432. assert hash(23) == hash(23)
  433. assert hash(2.3) == hash(2.3)
  434. assert hash('23') == hash("23")
  435. assert hash((23,)) == hash((23,))
  436. assert hash(22) != hash(23)
  437. raises(TypeError, hash, [])
  438. raises(TypeError, hash, {})
  439. def test_eval(self):
  440. assert eval("1+2") == 3
  441. assert eval(" \t1+2\n") == 3
  442. assert eval("len([])") == 0
  443. assert eval("len([])", {}) == 0
  444. # cpython 2.4 allows this (raises in 2.3)
  445. assert eval("3", None, None) == 3
  446. i = 4
  447. assert eval("i", None, None) == 4
  448. assert eval('a', None, dict(a=42)) == 42
  449. def test_compile(self):
  450. co = compile('1+2', '?', 'eval')
  451. assert eval(co) == 3
  452. co = compile(buffer('1+2'), '?', 'eval')
  453. assert eval(co) == 3
  454. exc = raises(TypeError, compile, chr(0), '?', 'eval')
  455. assert str(exc.value) == "compile() expected string without null bytes"
  456. exc = raises(TypeError, compile, unichr(0), '?', 'eval')
  457. assert str(exc.value) == "compile() expected string without null bytes"
  458. exc = raises(TypeError, compile, memoryview('1+2'), '?', 'eval')
  459. assert str(exc.value) == "expected a readable buffer object"
  460. compile("from __future__ import with_statement", "<test>", "exec")
  461. raises(SyntaxError, compile, '-', '?', 'eval')
  462. raises(ValueError, compile, '"\\xt"', '?', 'eval')
  463. raises(ValueError, compile, '1+2', '?', 'maybenot')
  464. raises(ValueError, compile, "\n", "<string>", "exec", 0xff)
  465. raises(TypeError, compile, '1+2', 12, 34)
  466. def test_compile_error_message(self):
  467. import re
  468. compile('# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
  469. compile(b'\xef\xbb\xbf\n', 'dummy', 'exec')
  470. compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec')
  471. exc = raises(SyntaxError, compile,
  472. b'# -*- coding: fake -*-\n', 'dummy', 'exec')
  473. assert 'fake' in str(exc.value)
  474. exc = raises(SyntaxError, compile,
  475. b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec')
  476. assert 'iso-8859-15' in str(exc.value)
  477. assert 'BOM' in str(exc.value)
  478. exc = raises(SyntaxError, compile,
  479. b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec')
  480. assert 'fake' in str(exc.value)
  481. assert 'BOM' in str(exc.value)
  482. def test_unicode_compile(self):
  483. try:
  484. compile(u'-', '?', 'eval')
  485. except SyntaxError as e:
  486. assert e.lineno == 1
  487. def test_unicode_encoding_compile(self):
  488. code = u"# -*- coding: utf-8 -*-\npass\n"
  489. raises(SyntaxError, compile, code, "tmp", "exec")
  490. def test_recompile_ast(self):
  491. import _ast
  492. # raise exception when node type doesn't match with compile mode
  493. co1 = compile('print 1', '<string>', 'exec', _ast.PyCF_ONLY_AST)
  494. raises(TypeError, compile, co1, '<ast>', 'eval')
  495. co2 = compile('1+1', '<string>', 'eval', _ast.PyCF_ONLY_AST)
  496. compile(co2, '<ast>', 'eval')
  497. def test_isinstance(self):
  498. assert isinstance(5, int)
  499. assert isinstance(5, object)
  500. assert not isinstance(5, float)
  501. assert isinstance(True, (int, float))
  502. assert not isinstance(True, (type, float))
  503. assert isinstance(True, ((type, float), bool))
  504. raises(TypeError, isinstance, 5, 6)
  505. raises(TypeError, isinstance, 5, (float, 6))
  506. def test_issubclass(self):
  507. assert issubclass(int, int)
  508. assert issubclass(int, object)
  509. assert not issubclass(int, float)
  510. assert issubclass(bool, (int, float))
  511. assert not issubclass(bool, (type, float))
  512. assert issubclass(bool, ((type, float), bool))
  513. raises(TypeError, issubclass, 5, int)
  514. raises(TypeError, issubclass, int, 6)
  515. raises(TypeError, issubclass, int, (float, 6))
  516. def test_staticmethod(self):
  517. class X(object):
  518. def f(*args, **kwds): return args, kwds
  519. f = staticmethod(f)
  520. assert X.f() == ((), {})
  521. assert X.f(42, x=43) == ((42,), {'x': 43})
  522. assert X().f() == ((), {})
  523. assert X().f(42, x=43) == ((42,), {'x': 43})
  524. def test_classmethod(self):
  525. class X(object):
  526. def f(*args, **kwds): return args, kwds
  527. f = classmethod(f)
  528. class Y(X):
  529. pass
  530. assert X.f() == ((X,), {})
  531. assert X.f(42, x=43) == ((X, 42), {'x': 43})
  532. assert X().f() == ((X,), {})
  533. assert X().f(42, x=43) == ((X, 42), {'x': 43})
  534. assert Y.f() == ((Y,), {})
  535. assert Y.f(42, x=43) == ((Y, 42), {'x': 43})
  536. assert Y().f() == ((Y,), {})
  537. assert Y().f(42, x=43) == ((Y, 42), {'x': 43})
  538. def test_hasattr(self):
  539. class X(object):
  540. def broken(): pass # TypeError
  541. abc = property(broken)
  542. def broken2(): raise IOError
  543. bac = property(broken2)
  544. x = X()
  545. x.foo = 42
  546. assert hasattr(x, '__class__') is True
  547. assert hasattr(x, 'foo') is True
  548. assert hasattr(x, 'bar') is False
  549. assert hasattr(x, 'abc') is False # CPython compliance
  550. assert hasattr(x, 'bac') is False # CPython compliance
  551. raises(TypeError, hasattr, x, None)
  552. raises(TypeError, hasattr, x, 42)
  553. raises(UnicodeError, hasattr, x, u'\u5678') # cannot encode attr name
  554. def test_compile_leading_newlines(self):
  555. src = """
  556. def fn(): pass
  557. """
  558. co = compile(src, 'mymod', 'exec')
  559. firstlineno = co.co_firstlineno
  560. assert firstlineno == 2
  561. def test_compile_null_bytes(self):
  562. raises(TypeError, compile, '\x00', 'mymod', 'exec', 0)
  563. src = "#abc\x00def\n"
  564. raises(TypeError, compile, src, 'mymod', 'exec')
  565. raises(TypeError, compile, src, 'mymod', 'exec', 0)
  566. execfile(self.nullbytes) # works
  567. def test_execfile_args(self):
  568. raises(TypeError, execfile, self.nonexistent, {}, ())
  569. def test_compile_null_bytes_flag(self):
  570. try:
  571. from _ast import PyCF_ACCEPT_NULL_BYTES
  572. except ImportError:
  573. skip('PyPy only (requires _ast.PyCF_ACCEPT_NULL_BYTES)')
  574. raises(SyntaxError, compile, '\x00', 'mymod', 'exec',
  575. PyCF_ACCEPT_NULL_BYTES)
  576. src = "#abc\x00def\n"
  577. compile(src, 'mymod', 'exec', PyCF_ACCEPT_NULL_BYTES) # works
  578. def test_print_function(self):
  579. import __builtin__
  580. import sys
  581. import StringIO
  582. pr = getattr(__builtin__, "print")
  583. save = sys.stdout
  584. out = sys.stdout = StringIO.StringIO()
  585. try:
  586. pr("Hello,", "person!")
  587. pr("2nd line", file=None)
  588. sys.stdout = None
  589. pr("nowhere")
  590. finally:
  591. sys.stdout = save
  592. assert out.getvalue() == "Hello, person!\n2nd line\n"
  593. out = StringIO.StringIO()
  594. pr("Hello,", "person!", file=out)
  595. assert out.getvalue() == "Hello, person!\n"
  596. out = StringIO.StringIO()
  597. pr("Hello,", "person!", file=out, end="")
  598. assert out.getvalue() == "Hello, person!"
  599. out = StringIO.StringIO()
  600. pr("Hello,", "person!", file=out, sep="X")
  601. assert out.getvalue() == "Hello,Xperson!\n"
  602. out = StringIO.StringIO()
  603. pr(u"Hello,", u"person!", file=out)
  604. result = out.getvalue()
  605. assert isinstance(result, unicode)
  606. assert result == u"Hello, person!\n"
  607. out = StringIO.StringIO()
  608. pr(None, file=out)
  609. assert out.getvalue() == "None\n"
  610. def test_print_exceptions(self):
  611. import __builtin__
  612. pr = getattr(__builtin__, "print")
  613. raises(TypeError, pr, x=3)
  614. raises(TypeError, pr, end=3)
  615. raises(TypeError, pr, sep=42)
  616. def test_round(self):
  617. assert round(11.234) == 11.0
  618. assert round(11.234, -1) == 10.0
  619. assert round(11.234, 0) == 11.0
  620. assert round(11.234, 1) == 11.2
  621. #
  622. assert round(5e15-1) == 5e15-1
  623. assert round(5e15) == 5e15
  624. assert round(-(5e15-1)) == -(5e15-1)
  625. assert round(-5e15) == -5e15
  626. #
  627. inf = 1e200 * 1e200
  628. assert round(inf) == inf
  629. assert round(-inf) == -inf
  630. nan = inf / inf
  631. assert repr(round(nan)) == repr(nan)
  632. #
  633. raises(OverflowError, round, 1.6e308, -308)
  634. #
  635. assert round(562949953421312.5, 1) == 562949953421312.5
  636. assert round(56294995342131.5, 3) == 56294995342131.5
  637. def test_vars_obscure_case(self):
  638. class C_get_vars(object):
  639. def getDict(self):
  640. return {'a':2}
  641. __dict__ = property(fget=getDict)
  642. assert vars(C_get_vars()) == {'a':2}
  643. class AppTestGetattr:
  644. spaceconfig = {}
  645. def test_getattr(self):
  646. class a(object):
  647. i = 5
  648. assert getattr(a, 'i') == 5
  649. raises(AttributeError, getattr, a, 'k')
  650. assert getattr(a, 'k', 42) == 42
  651. assert getattr(a, u'i') == 5
  652. raises(AttributeError, getattr, a, u'k')
  653. assert getattr(a, u'k', 42) == 42
  654. def test_getattr_typecheck(self):
  655. class A(object):
  656. def __getattribute__(self, name):
  657. pass
  658. def __setattr__(self, name, value):
  659. pass
  660. def __delattr__(self, name):
  661. pass
  662. raises(TypeError, getattr, A(), 42)
  663. raises(TypeError, setattr, A(), 42, 'x')
  664. raises(TypeError, delattr, A(), 42)
  665. class TestInternal:
  666. def test_execfile(self, space):
  667. fn = str(udir.join('test_execfile'))
  668. f = open(fn, 'w')
  669. print >>f, "i=42"
  670. f.close()
  671. w_execfile = space.builtin.get("execfile")
  672. w_dict = space.newdict()
  673. space.call_function(w_execfile,
  674. space.wrap(fn), w_dict, space.w_None)
  675. w_value = space.getitem(w_dict, space.wrap('i'))
  676. assert space.eq_w(w_value, space.wrap(42))
  677. def test_execfile_different_lineendings(self, space):
  678. from rpython.tool.udir import udir
  679. d = udir.ensure('lineending', dir=1)
  680. dos = d.join('dos.py')
  681. f = dos.open('wb')
  682. f.write("x=3\r\n\r\ny=4\r\n")
  683. f.close()
  684. space.appexec([space.wrap(str(dos))], """
  685. (filename):
  686. d = {}
  687. execfile(filename, d)
  688. assert d['x'] == 3
  689. assert d['y'] == 4
  690. """)
  691. unix = d.join('unix.py')
  692. f = unix.open('wb')
  693. f.write("x=5\n\ny=6\n")
  694. f.close()
  695. space.appexec([space.wrap(str(unix))], """
  696. (filename):
  697. d = {}
  698. execfile(filename, d)
  699. assert d['x'] == 5
  700. assert d['y'] == 6
  701. """)