PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

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