PageRenderTime 58ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/modified-2.7/test/test_file2k.py

https://bitbucket.org/dac_io/pypy
Python | 703 lines | 625 code | 44 blank | 34 comment | 67 complexity | c926d5448d922c0a6c000c5508f50ba7 MD5 | raw file
  1. import sys
  2. import os
  3. import unittest
  4. import itertools
  5. import time
  6. from array import array
  7. from weakref import proxy
  8. try:
  9. import threading
  10. except ImportError:
  11. threading = None
  12. from test import test_support
  13. from test.test_support import TESTFN, run_unittest, gc_collect
  14. from UserList import UserList
  15. class AutoFileTests(unittest.TestCase):
  16. # file tests for which a test file is automatically set up
  17. def setUp(self):
  18. self.f = open(TESTFN, 'wb')
  19. def tearDown(self):
  20. if self.f:
  21. self.f.close()
  22. os.remove(TESTFN)
  23. def testWeakRefs(self):
  24. # verify weak references
  25. p = proxy(self.f)
  26. p.write('teststring')
  27. self.assertEqual(self.f.tell(), p.tell())
  28. self.f.close()
  29. self.f = None
  30. gc_collect()
  31. self.assertRaises(ReferenceError, getattr, p, 'tell')
  32. def testAttributes(self):
  33. # verify expected attributes exist
  34. f = self.f
  35. with test_support.check_py3k_warnings():
  36. softspace = f.softspace
  37. f.name # merely shouldn't blow up
  38. f.mode # ditto
  39. f.closed # ditto
  40. with test_support.check_py3k_warnings():
  41. # verify softspace is writable
  42. f.softspace = softspace # merely shouldn't blow up
  43. # verify the others aren't
  44. for attr in 'name', 'mode', 'closed':
  45. self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops')
  46. def testReadinto(self):
  47. # verify readinto
  48. self.f.write('12')
  49. self.f.close()
  50. a = array('c', 'x'*10)
  51. self.f = open(TESTFN, 'rb')
  52. n = self.f.readinto(a)
  53. self.assertEqual('12', a.tostring()[:n])
  54. def testWritelinesUserList(self):
  55. # verify writelines with instance sequence
  56. l = UserList(['1', '2'])
  57. self.f.writelines(l)
  58. self.f.close()
  59. self.f = open(TESTFN, 'rb')
  60. buf = self.f.read()
  61. self.assertEqual(buf, '12')
  62. def testWritelinesIntegers(self):
  63. # verify writelines with integers
  64. self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
  65. def testWritelinesIntegersUserList(self):
  66. # verify writelines with integers in UserList
  67. l = UserList([1,2,3])
  68. self.assertRaises(TypeError, self.f.writelines, l)
  69. def testWritelinesNonString(self):
  70. # verify writelines with non-string object
  71. class NonString:
  72. pass
  73. self.assertRaises(TypeError, self.f.writelines,
  74. [NonString(), NonString()])
  75. def testRepr(self):
  76. # verify repr works
  77. self.assertTrue(repr(self.f).startswith("<open file '" + TESTFN))
  78. def testErrors(self):
  79. self.f.close()
  80. self.f = open(TESTFN, 'rb')
  81. f = self.f
  82. self.assertEqual(f.name, TESTFN)
  83. self.assertTrue(not f.isatty())
  84. self.assertTrue(not f.closed)
  85. self.assertRaises(TypeError, f.readinto, "")
  86. f.close()
  87. self.assertTrue(f.closed)
  88. def testMethods(self):
  89. methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
  90. 'readline', 'readlines', 'seek', 'tell', 'truncate',
  91. 'write', '__iter__']
  92. deprecated_methods = ['xreadlines']
  93. if sys.platform.startswith('atheos'):
  94. methods.remove('truncate')
  95. # __exit__ should close the file
  96. self.f.__exit__(None, None, None)
  97. self.assertTrue(self.f.closed)
  98. for methodname in methods:
  99. method = getattr(self.f, methodname)
  100. args = {'readinto': (bytearray(''),),
  101. 'seek': (0,),
  102. 'write': ('',),
  103. }.get(methodname, ())
  104. # should raise on closed file
  105. self.assertRaises(ValueError, method, *args)
  106. with test_support.check_py3k_warnings():
  107. for methodname in deprecated_methods:
  108. method = getattr(self.f, methodname)
  109. self.assertRaises(ValueError, method)
  110. self.assertRaises(ValueError, self.f.writelines, [])
  111. # file is closed, __exit__ shouldn't do anything
  112. self.assertEqual(self.f.__exit__(None, None, None), None)
  113. # it must also return None if an exception was given
  114. try:
  115. 1 // 0
  116. except:
  117. self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
  118. def testReadWhenWriting(self):
  119. self.assertRaises(IOError, self.f.read)
  120. def testNastyWritelinesGenerator(self):
  121. def nasty():
  122. for i in range(5):
  123. if i == 3:
  124. self.f.close()
  125. yield str(i)
  126. self.assertRaises(ValueError, self.f.writelines, nasty())
  127. def testIssue5677(self):
  128. # Remark: Do not perform more than one test per open file,
  129. # since that does NOT catch the readline error on Windows.
  130. data = 'xxx'
  131. for mode in ['w', 'wb', 'a', 'ab']:
  132. for attr in ['read', 'readline', 'readlines']:
  133. self.f = open(TESTFN, mode)
  134. self.f.write(data)
  135. self.assertRaises(IOError, getattr(self.f, attr))
  136. self.f.close()
  137. self.f = open(TESTFN, mode)
  138. self.f.write(data)
  139. self.assertRaises(IOError, lambda: [line for line in self.f])
  140. self.f.close()
  141. self.f = open(TESTFN, mode)
  142. self.f.write(data)
  143. self.assertRaises(IOError, self.f.readinto, bytearray(len(data)))
  144. self.f.close()
  145. for mode in ['r', 'rb', 'U', 'Ub', 'Ur', 'rU', 'rbU', 'rUb']:
  146. self.f = open(TESTFN, mode)
  147. self.assertRaises(IOError, self.f.write, data)
  148. self.f.close()
  149. self.f = open(TESTFN, mode)
  150. self.assertRaises(IOError, self.f.writelines, [data, data])
  151. self.f.close()
  152. self.f = open(TESTFN, mode)
  153. self.assertRaises(IOError, self.f.truncate)
  154. self.f.close()
  155. class OtherFileTests(unittest.TestCase):
  156. def testOpenDir(self):
  157. this_dir = os.path.dirname(__file__) or os.curdir
  158. for mode in (None, "w"):
  159. try:
  160. if mode:
  161. f = open(this_dir, mode)
  162. else:
  163. f = open(this_dir)
  164. except IOError as e:
  165. self.assertEqual(e.filename, this_dir)
  166. else:
  167. self.fail("opening a directory didn't raise an IOError")
  168. def testModeStrings(self):
  169. # check invalid mode strings
  170. for mode in ("", "aU", "wU+"):
  171. try:
  172. f = open(TESTFN, mode)
  173. except ValueError:
  174. pass
  175. else:
  176. f.close()
  177. self.fail('%r is an invalid file mode' % mode)
  178. # Some invalid modes fail on Windows, but pass on Unix
  179. # Issue3965: avoid a crash on Windows when filename is unicode
  180. for name in (TESTFN, unicode(TESTFN), unicode(TESTFN + '\t')):
  181. try:
  182. f = open(name, "rr")
  183. except (IOError, ValueError):
  184. pass
  185. else:
  186. f.close()
  187. def testStdin(self):
  188. # This causes the interpreter to exit on OSF1 v5.1.
  189. if sys.platform != 'osf1V5':
  190. if sys.stdin.isatty():
  191. self.assertRaises(IOError, sys.stdin.seek, -1)
  192. else:
  193. print >>sys.__stdout__, (
  194. ' Skipping sys.stdin.seek(-1): stdin is not a tty.'
  195. ' Test manualy.')
  196. else:
  197. print >>sys.__stdout__, (
  198. ' Skipping sys.stdin.seek(-1), it may crash the interpreter.'
  199. ' Test manually.')
  200. self.assertRaises(IOError, sys.stdin.truncate)
  201. def testUnicodeOpen(self):
  202. # verify repr works for unicode too
  203. f = open(unicode(TESTFN), "w")
  204. self.assertTrue(repr(f).startswith("<open file u'" + TESTFN))
  205. f.close()
  206. os.unlink(TESTFN)
  207. def testBadModeArgument(self):
  208. # verify that we get a sensible error message for bad mode argument
  209. bad_mode = "qwerty"
  210. try:
  211. f = open(TESTFN, bad_mode)
  212. except ValueError, msg:
  213. if msg.args[0] != 0:
  214. s = str(msg)
  215. if TESTFN in s or bad_mode not in s:
  216. self.fail("bad error message for invalid mode: %s" % s)
  217. # if msg.args[0] == 0, we're probably on Windows where there may
  218. # be no obvious way to discover why open() failed.
  219. else:
  220. f.close()
  221. self.fail("no error for invalid mode: %s" % bad_mode)
  222. def testSetBufferSize(self):
  223. # make sure that explicitly setting the buffer size doesn't cause
  224. # misbehaviour especially with repeated close() calls
  225. for s in (-1, 0, 1, 512):
  226. try:
  227. f = open(TESTFN, 'w', s)
  228. f.write(str(s))
  229. f.close()
  230. f.close()
  231. f = open(TESTFN, 'r', s)
  232. d = int(f.read())
  233. f.close()
  234. f.close()
  235. except IOError, msg:
  236. self.fail('error setting buffer size %d: %s' % (s, str(msg)))
  237. self.assertEqual(d, s)
  238. def testTruncateOnWindows(self):
  239. os.unlink(TESTFN)
  240. def bug801631():
  241. # SF bug <http://www.python.org/sf/801631>
  242. # "file.truncate fault on windows"
  243. f = open(TESTFN, 'wb')
  244. f.write('12345678901') # 11 bytes
  245. f.close()
  246. f = open(TESTFN,'rb+')
  247. data = f.read(5)
  248. if data != '12345':
  249. self.fail("Read on file opened for update failed %r" % data)
  250. if f.tell() != 5:
  251. self.fail("File pos after read wrong %d" % f.tell())
  252. f.truncate()
  253. if f.tell() != 5:
  254. self.fail("File pos after ftruncate wrong %d" % f.tell())
  255. f.close()
  256. size = os.path.getsize(TESTFN)
  257. if size != 5:
  258. self.fail("File size after ftruncate wrong %d" % size)
  259. try:
  260. bug801631()
  261. finally:
  262. os.unlink(TESTFN)
  263. def testIteration(self):
  264. # Test the complex interaction when mixing file-iteration and the
  265. # various read* methods. Ostensibly, the mixture could just be tested
  266. # to work when it should work according to the Python language,
  267. # instead of fail when it should fail according to the current CPython
  268. # implementation. People don't always program Python the way they
  269. # should, though, and the implemenation might change in subtle ways,
  270. # so we explicitly test for errors, too; the test will just have to
  271. # be updated when the implementation changes.
  272. dataoffset = 16384
  273. filler = "ham\n"
  274. assert not dataoffset % len(filler), \
  275. "dataoffset must be multiple of len(filler)"
  276. nchunks = dataoffset // len(filler)
  277. testlines = [
  278. "spam, spam and eggs\n",
  279. "eggs, spam, ham and spam\n",
  280. "saussages, spam, spam and eggs\n",
  281. "spam, ham, spam and eggs\n",
  282. "spam, spam, spam, spam, spam, ham, spam\n",
  283. "wonderful spaaaaaam.\n"
  284. ]
  285. methods = [("readline", ()), ("read", ()), ("readlines", ()),
  286. ("readinto", (array("c", " "*100),))]
  287. try:
  288. # Prepare the testfile
  289. bag = open(TESTFN, "w")
  290. bag.write(filler * nchunks)
  291. bag.writelines(testlines)
  292. bag.close()
  293. # Test for appropriate errors mixing read* and iteration
  294. for methodname, args in methods:
  295. f = open(TESTFN)
  296. if f.next() != filler:
  297. self.fail, "Broken testfile"
  298. meth = getattr(f, methodname)
  299. try:
  300. meth(*args)
  301. except ValueError:
  302. pass
  303. else:
  304. if test_support.check_impl_detail():
  305. self.fail("%s%r after next() didn't raise ValueError" %
  306. (methodname, args))
  307. f.close()
  308. # Test to see if harmless (by accident) mixing of read* and
  309. # iteration still works. This depends on the size of the internal
  310. # iteration buffer (currently 8192,) but we can test it in a
  311. # flexible manner. Each line in the bag o' ham is 4 bytes
  312. # ("h", "a", "m", "\n"), so 4096 lines of that should get us
  313. # exactly on the buffer boundary for any power-of-2 buffersize
  314. # between 4 and 16384 (inclusive).
  315. f = open(TESTFN)
  316. for i in range(nchunks):
  317. f.next()
  318. testline = testlines.pop(0)
  319. try:
  320. line = f.readline()
  321. except ValueError:
  322. self.fail("readline() after next() with supposedly empty "
  323. "iteration-buffer failed anyway")
  324. if line != testline:
  325. self.fail("readline() after next() with empty buffer "
  326. "failed. Got %r, expected %r" % (line, testline))
  327. testline = testlines.pop(0)
  328. buf = array("c", "\x00" * len(testline))
  329. try:
  330. f.readinto(buf)
  331. except ValueError:
  332. self.fail("readinto() after next() with supposedly empty "
  333. "iteration-buffer failed anyway")
  334. line = buf.tostring()
  335. if line != testline:
  336. self.fail("readinto() after next() with empty buffer "
  337. "failed. Got %r, expected %r" % (line, testline))
  338. testline = testlines.pop(0)
  339. try:
  340. line = f.read(len(testline))
  341. except ValueError:
  342. self.fail("read() after next() with supposedly empty "
  343. "iteration-buffer failed anyway")
  344. if line != testline:
  345. self.fail("read() after next() with empty buffer "
  346. "failed. Got %r, expected %r" % (line, testline))
  347. try:
  348. lines = f.readlines()
  349. except ValueError:
  350. self.fail("readlines() after next() with supposedly empty "
  351. "iteration-buffer failed anyway")
  352. if lines != testlines:
  353. self.fail("readlines() after next() with empty buffer "
  354. "failed. Got %r, expected %r" % (line, testline))
  355. f.close()
  356. # Reading after iteration hit EOF shouldn't hurt either
  357. f = open(TESTFN)
  358. try:
  359. for line in f:
  360. pass
  361. try:
  362. f.readline()
  363. f.readinto(buf)
  364. f.read()
  365. f.readlines()
  366. except ValueError:
  367. self.fail("read* failed after next() consumed file")
  368. finally:
  369. f.close()
  370. finally:
  371. os.unlink(TESTFN)
  372. class FileSubclassTests(unittest.TestCase):
  373. def testExit(self):
  374. # test that exiting with context calls subclass' close
  375. class C(file):
  376. def __init__(self, *args):
  377. self.subclass_closed = False
  378. file.__init__(self, *args)
  379. def close(self):
  380. self.subclass_closed = True
  381. file.close(self)
  382. with C(TESTFN, 'w') as f:
  383. pass
  384. self.assertTrue(f.subclass_closed)
  385. @unittest.skipUnless(threading, 'Threading required for this test.')
  386. class FileThreadingTests(unittest.TestCase):
  387. # These tests check the ability to call various methods of file objects
  388. # (including close()) concurrently without crashing the Python interpreter.
  389. # See #815646, #595601
  390. def setUp(self):
  391. self._threads = test_support.threading_setup()
  392. self.f = None
  393. self.filename = TESTFN
  394. with open(self.filename, "w") as f:
  395. f.write("\n".join("0123456789"))
  396. self._count_lock = threading.Lock()
  397. self.close_count = 0
  398. self.close_success_count = 0
  399. self.use_buffering = False
  400. # to prevent running out of file descriptors on PyPy,
  401. # we only keep the 50 most recent files open
  402. self.all_files = [None] * 50
  403. def tearDown(self):
  404. if self.f:
  405. try:
  406. self.f.close()
  407. except (EnvironmentError, ValueError):
  408. pass
  409. try:
  410. os.remove(self.filename)
  411. except EnvironmentError:
  412. pass
  413. test_support.threading_cleanup(*self._threads)
  414. def _create_file(self):
  415. if self.use_buffering:
  416. f = open(self.filename, "w+", buffering=1024*16)
  417. else:
  418. f = open(self.filename, "w+")
  419. self.f = f
  420. self.all_files.append(f)
  421. oldf = self.all_files.pop(0)
  422. if oldf is not None:
  423. oldf.close()
  424. def _close_file(self):
  425. with self._count_lock:
  426. self.close_count += 1
  427. self.f.close()
  428. with self._count_lock:
  429. self.close_success_count += 1
  430. def _close_and_reopen_file(self):
  431. self._close_file()
  432. # if close raises an exception thats fine, self.f remains valid so
  433. # we don't need to reopen.
  434. self._create_file()
  435. def _run_workers(self, func, nb_workers, duration=0.2):
  436. with self._count_lock:
  437. self.close_count = 0
  438. self.close_success_count = 0
  439. self.do_continue = True
  440. threads = []
  441. try:
  442. for i in range(nb_workers):
  443. t = threading.Thread(target=func)
  444. t.start()
  445. threads.append(t)
  446. for _ in xrange(100):
  447. time.sleep(duration/100)
  448. with self._count_lock:
  449. if self.close_count-self.close_success_count > nb_workers+1:
  450. if test_support.verbose:
  451. print 'Q',
  452. break
  453. time.sleep(duration)
  454. finally:
  455. self.do_continue = False
  456. for t in threads:
  457. t.join()
  458. def _test_close_open_io(self, io_func, nb_workers=5):
  459. def worker():
  460. funcs = itertools.cycle((
  461. lambda: io_func(),
  462. lambda: self._close_and_reopen_file(),
  463. ))
  464. for f in funcs:
  465. if not self.do_continue:
  466. break
  467. try:
  468. f()
  469. except (IOError, ValueError):
  470. pass
  471. self._create_file()
  472. self._run_workers(worker, nb_workers)
  473. # make sure that all files can be closed now
  474. del self.all_files
  475. gc_collect()
  476. if test_support.verbose:
  477. # Useful verbose statistics when tuning this test to take
  478. # less time to run but still ensuring that its still useful.
  479. #
  480. # the percent of close calls that raised an error
  481. percent = 100. - 100.*self.close_success_count/self.close_count
  482. print self.close_count, ('%.4f ' % percent),
  483. def test_close_open(self):
  484. def io_func():
  485. pass
  486. self._test_close_open_io(io_func)
  487. def test_close_open_flush(self):
  488. def io_func():
  489. self.f.flush()
  490. self._test_close_open_io(io_func)
  491. def test_close_open_iter(self):
  492. def io_func():
  493. list(iter(self.f))
  494. self._test_close_open_io(io_func)
  495. def test_close_open_isatty(self):
  496. def io_func():
  497. self.f.isatty()
  498. self._test_close_open_io(io_func)
  499. def test_close_open_print(self):
  500. def io_func():
  501. print >> self.f, ''
  502. self._test_close_open_io(io_func)
  503. def test_close_open_print_buffered(self):
  504. self.use_buffering = True
  505. def io_func():
  506. print >> self.f, ''
  507. self._test_close_open_io(io_func)
  508. def test_close_open_read(self):
  509. def io_func():
  510. self.f.read(0)
  511. self._test_close_open_io(io_func)
  512. def test_close_open_readinto(self):
  513. def io_func():
  514. a = array('c', 'xxxxx')
  515. self.f.readinto(a)
  516. self._test_close_open_io(io_func)
  517. def test_close_open_readline(self):
  518. def io_func():
  519. self.f.readline()
  520. self._test_close_open_io(io_func)
  521. def test_close_open_readlines(self):
  522. def io_func():
  523. self.f.readlines()
  524. self._test_close_open_io(io_func)
  525. def test_close_open_seek(self):
  526. def io_func():
  527. self.f.seek(0, 0)
  528. self._test_close_open_io(io_func)
  529. def test_close_open_tell(self):
  530. def io_func():
  531. self.f.tell()
  532. self._test_close_open_io(io_func)
  533. def test_close_open_truncate(self):
  534. def io_func():
  535. self.f.truncate()
  536. self._test_close_open_io(io_func)
  537. def test_close_open_write(self):
  538. def io_func():
  539. self.f.write('')
  540. self._test_close_open_io(io_func)
  541. def test_close_open_writelines(self):
  542. def io_func():
  543. self.f.writelines('')
  544. self._test_close_open_io(io_func)
  545. class StdoutTests(unittest.TestCase):
  546. def test_move_stdout_on_write(self):
  547. # Issue 3242: sys.stdout can be replaced (and freed) during a
  548. # print statement; prevent a segfault in this case
  549. save_stdout = sys.stdout
  550. class File:
  551. def write(self, data):
  552. if '\n' in data:
  553. sys.stdout = save_stdout
  554. try:
  555. sys.stdout = File()
  556. print "some text"
  557. finally:
  558. sys.stdout = save_stdout
  559. def test_del_stdout_before_print(self):
  560. # Issue 4597: 'print' with no argument wasn't reporting when
  561. # sys.stdout was deleted.
  562. save_stdout = sys.stdout
  563. del sys.stdout
  564. try:
  565. print
  566. except RuntimeError as e:
  567. self.assertEqual(str(e), "lost sys.stdout")
  568. else:
  569. self.fail("Expected RuntimeError")
  570. finally:
  571. sys.stdout = save_stdout
  572. def test_unicode(self):
  573. import subprocess
  574. def get_message(encoding, *code):
  575. code = '\n'.join(code)
  576. env = os.environ.copy()
  577. env['PYTHONIOENCODING'] = encoding
  578. process = subprocess.Popen([sys.executable, "-c", code],
  579. stdout=subprocess.PIPE, env=env)
  580. stdout, stderr = process.communicate()
  581. self.assertEqual(process.returncode, 0)
  582. return stdout
  583. def check_message(text, encoding, expected):
  584. stdout = get_message(encoding,
  585. "import sys",
  586. "sys.stdout.write(%r)" % text,
  587. "sys.stdout.flush()")
  588. self.assertEqual(stdout, expected)
  589. # test the encoding
  590. check_message(u'15\u20ac', "iso-8859-15", "15\xa4")
  591. check_message(u'15\u20ac', "utf-8", '15\xe2\x82\xac')
  592. check_message(u'15\u20ac', "utf-16-le", '1\x005\x00\xac\x20')
  593. # test the error handler
  594. check_message(u'15\u20ac', "iso-8859-1:ignore", "15")
  595. check_message(u'15\u20ac', "iso-8859-1:replace", "15?")
  596. check_message(u'15\u20ac', "iso-8859-1:backslashreplace", "15\\u20ac")
  597. # test the buffer API
  598. for objtype in ('buffer', 'bytearray'):
  599. stdout = get_message('ascii',
  600. 'import sys',
  601. r'sys.stdout.write(%s("\xe9"))' % objtype,
  602. 'sys.stdout.flush()')
  603. self.assertEqual(stdout, "\xe9")
  604. def test_main():
  605. # Historically, these tests have been sloppy about removing TESTFN.
  606. # So get rid of it no matter what.
  607. try:
  608. run_unittest(AutoFileTests, OtherFileTests, FileSubclassTests,
  609. FileThreadingTests, StdoutTests)
  610. finally:
  611. if os.path.exists(TESTFN):
  612. os.unlink(TESTFN)
  613. if __name__ == '__main__':
  614. test_main()