test_file2k.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  1. import sys
  2. import os
  3. import unittest
  4. import itertools
  5. import select
  6. import signal
  7. import stat
  8. import subprocess
  9. import time
  10. from array import array
  11. from weakref import proxy
  12. try:
  13. import threading
  14. except ImportError:
  15. threading = None
  16. from test import test_support
  17. from test.test_support import TESTFN, run_unittest, requires
  18. from UserList import UserList
  19. class AutoFileTests(unittest.TestCase):
  20. # file tests for which a test file is automatically set up
  21. def setUp(self):
  22. self.f = open(TESTFN, 'wb')
  23. def tearDown(self):
  24. if self.f:
  25. self.f.close()
  26. os.remove(TESTFN)
  27. def testWeakRefs(self):
  28. # verify weak references
  29. p = proxy(self.f)
  30. p.write('teststring')
  31. self.assertEqual(self.f.tell(), p.tell())
  32. self.f.close()
  33. self.f = None
  34. self.assertRaises(ReferenceError, getattr, p, 'tell')
  35. def testAttributes(self):
  36. # verify expected attributes exist
  37. f = self.f
  38. with test_support.check_py3k_warnings():
  39. softspace = f.softspace
  40. f.name # merely shouldn't blow up
  41. f.mode # ditto
  42. f.closed # ditto
  43. with test_support.check_py3k_warnings():
  44. # verify softspace is writable
  45. f.softspace = softspace # merely shouldn't blow up
  46. # verify the others aren't
  47. for attr in 'name', 'mode', 'closed':
  48. self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops')
  49. def testReadinto(self):
  50. # verify readinto
  51. self.f.write('12')
  52. self.f.close()
  53. a = array('c', 'x'*10)
  54. self.f = open(TESTFN, 'rb')
  55. n = self.f.readinto(a)
  56. self.assertEqual('12', a.tostring()[:n])
  57. def testWritelinesUserList(self):
  58. # verify writelines with instance sequence
  59. l = UserList(['1', '2'])
  60. self.f.writelines(l)
  61. self.f.close()
  62. self.f = open(TESTFN, 'rb')
  63. buf = self.f.read()
  64. self.assertEqual(buf, '12')
  65. def testWritelinesIntegers(self):
  66. # verify writelines with integers
  67. self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
  68. def testWritelinesIntegersUserList(self):
  69. # verify writelines with integers in UserList
  70. l = UserList([1,2,3])
  71. self.assertRaises(TypeError, self.f.writelines, l)
  72. def testWritelinesNonString(self):
  73. # verify writelines with non-string object
  74. class NonString:
  75. pass
  76. self.assertRaises(TypeError, self.f.writelines,
  77. [NonString(), NonString()])
  78. def testWritelinesBuffer(self):
  79. self.f.writelines([array('c', 'abc')])
  80. self.f.close()
  81. self.f = open(TESTFN, 'rb')
  82. buf = self.f.read()
  83. self.assertEqual(buf, 'abc')
  84. def testRepr(self):
  85. # verify repr works
  86. self.assertTrue(repr(self.f).startswith("<open file '" + TESTFN))
  87. # see issue #14161
  88. # Windows doesn't like \r\n\t" in the file name, but ' is ok
  89. fname = 'xx\rxx\nxx\'xx"xx' if sys.platform != "win32" else "xx'xx"
  90. with open(fname, 'w') as f:
  91. self.addCleanup(os.remove, fname)
  92. self.assertTrue(repr(f).startswith(
  93. "<open file %r, mode 'w' at" % fname))
  94. def testErrors(self):
  95. self.f.close()
  96. self.f = open(TESTFN, 'rb')
  97. f = self.f
  98. self.assertEqual(f.name, TESTFN)
  99. self.assertTrue(not f.isatty())
  100. self.assertTrue(not f.closed)
  101. self.assertRaises(TypeError, f.readinto, "")
  102. f.close()
  103. self.assertTrue(f.closed)
  104. def testMethods(self):
  105. methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
  106. 'readline', 'readlines', 'seek', 'tell', 'truncate',
  107. 'write', '__iter__']
  108. deprecated_methods = ['xreadlines']
  109. if sys.platform.startswith('atheos'):
  110. methods.remove('truncate')
  111. # __exit__ should close the file
  112. self.f.__exit__(None, None, None)
  113. self.assertTrue(self.f.closed)
  114. for methodname in methods:
  115. method = getattr(self.f, methodname)
  116. # should raise on closed file
  117. self.assertRaises(ValueError, method)
  118. with test_support.check_py3k_warnings():
  119. for methodname in deprecated_methods:
  120. method = getattr(self.f, methodname)
  121. self.assertRaises(ValueError, method)
  122. self.assertRaises(ValueError, self.f.writelines, [])
  123. # file is closed, __exit__ shouldn't do anything
  124. self.assertEqual(self.f.__exit__(None, None, None), None)
  125. # it must also return None if an exception was given
  126. try:
  127. 1 // 0
  128. except:
  129. self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
  130. def testReadWhenWriting(self):
  131. self.assertRaises(IOError, self.f.read)
  132. def testNastyWritelinesGenerator(self):
  133. def nasty():
  134. for i in range(5):
  135. if i == 3:
  136. self.f.close()
  137. yield str(i)
  138. self.assertRaises(ValueError, self.f.writelines, nasty())
  139. def testIssue5677(self):
  140. # Remark: Do not perform more than one test per open file,
  141. # since that does NOT catch the readline error on Windows.
  142. data = 'xxx'
  143. for mode in ['w', 'wb', 'a', 'ab']:
  144. for attr in ['read', 'readline', 'readlines']:
  145. self.f = open(TESTFN, mode)
  146. self.f.write(data)
  147. self.assertRaises(IOError, getattr(self.f, attr))
  148. self.f.close()
  149. self.f = open(TESTFN, mode)
  150. self.f.write(data)
  151. self.assertRaises(IOError, lambda: [line for line in self.f])
  152. self.f.close()
  153. self.f = open(TESTFN, mode)
  154. self.f.write(data)
  155. self.assertRaises(IOError, self.f.readinto, bytearray(len(data)))
  156. self.f.close()
  157. for mode in ['r', 'rb', 'U', 'Ub', 'Ur', 'rU', 'rbU', 'rUb']:
  158. self.f = open(TESTFN, mode)
  159. self.assertRaises(IOError, self.f.write, data)
  160. self.f.close()
  161. self.f = open(TESTFN, mode)
  162. self.assertRaises(IOError, self.f.writelines, [data, data])
  163. self.f.close()
  164. self.f = open(TESTFN, mode)
  165. self.assertRaises(IOError, self.f.truncate)
  166. self.f.close()
  167. class OtherFileTests(unittest.TestCase):
  168. def testOpenDir(self):
  169. this_dir = os.path.dirname(__file__) or os.curdir
  170. for mode in (None, "w"):
  171. try:
  172. if mode:
  173. f = open(this_dir, mode)
  174. else:
  175. f = open(this_dir)
  176. except IOError as e:
  177. self.assertEqual(e.filename, this_dir)
  178. else:
  179. self.fail("opening a directory didn't raise an IOError")
  180. def testModeStrings(self):
  181. # check invalid mode strings
  182. for mode in ("", "aU", "wU+"):
  183. try:
  184. f = open(TESTFN, mode)
  185. except ValueError:
  186. pass
  187. else:
  188. f.close()
  189. self.fail('%r is an invalid file mode' % mode)
  190. # Some invalid modes fail on Windows, but pass on Unix
  191. # Issue3965: avoid a crash on Windows when filename is unicode
  192. for name in (TESTFN, unicode(TESTFN), unicode(TESTFN + '\t')):
  193. try:
  194. f = open(name, "rr")
  195. except (IOError, ValueError):
  196. pass
  197. else:
  198. f.close()
  199. def testStdinSeek(self):
  200. if sys.platform == 'osf1V5':
  201. # This causes the interpreter to exit on OSF1 v5.1.
  202. self.skipTest('Skipping sys.stdin.seek(-1), it may crash '
  203. 'the interpreter. Test manually.')
  204. if not sys.stdin.isatty():
  205. # Issue #23168: if stdin is redirected to a file, stdin becomes
  206. # seekable
  207. self.skipTest('stdin must be a TTY in this test')
  208. self.assertRaises(IOError, sys.stdin.seek, -1)
  209. def testStdinTruncate(self):
  210. self.assertRaises(IOError, sys.stdin.truncate)
  211. def testUnicodeOpen(self):
  212. # verify repr works for unicode too
  213. f = open(unicode(TESTFN), "w")
  214. self.assertTrue(repr(f).startswith("<open file u'" + TESTFN))
  215. f.close()
  216. os.unlink(TESTFN)
  217. def testBadModeArgument(self):
  218. # verify that we get a sensible error message for bad mode argument
  219. bad_mode = "qwerty"
  220. try:
  221. f = open(TESTFN, bad_mode)
  222. except ValueError, msg:
  223. if msg.args[0] != 0:
  224. s = str(msg)
  225. if TESTFN in s or bad_mode not in s:
  226. self.fail("bad error message for invalid mode: %s" % s)
  227. # if msg.args[0] == 0, we're probably on Windows where there may
  228. # be no obvious way to discover why open() failed.
  229. else:
  230. f.close()
  231. self.fail("no error for invalid mode: %s" % bad_mode)
  232. def testSetBufferSize(self):
  233. # make sure that explicitly setting the buffer size doesn't cause
  234. # misbehaviour especially with repeated close() calls
  235. for s in (-1, 0, 1, 512):
  236. try:
  237. f = open(TESTFN, 'w', s)
  238. f.write(str(s))
  239. f.close()
  240. f.close()
  241. f = open(TESTFN, 'r', s)
  242. d = int(f.read())
  243. f.close()
  244. f.close()
  245. except IOError, msg:
  246. self.fail('error setting buffer size %d: %s' % (s, str(msg)))
  247. self.assertEqual(d, s)
  248. def testTruncateOnWindows(self):
  249. os.unlink(TESTFN)
  250. def bug801631():
  251. # SF bug <http://www.python.org/sf/801631>
  252. # "file.truncate fault on windows"
  253. f = open(TESTFN, 'wb')
  254. f.write('12345678901') # 11 bytes
  255. f.close()
  256. f = open(TESTFN,'rb+')
  257. data = f.read(5)
  258. if data != '12345':
  259. self.fail("Read on file opened for update failed %r" % data)
  260. if f.tell() != 5:
  261. self.fail("File pos after read wrong %d" % f.tell())
  262. f.truncate()
  263. if f.tell() != 5:
  264. self.fail("File pos after ftruncate wrong %d" % f.tell())
  265. f.close()
  266. size = os.path.getsize(TESTFN)
  267. if size != 5:
  268. self.fail("File size after ftruncate wrong %d" % size)
  269. try:
  270. bug801631()
  271. finally:
  272. os.unlink(TESTFN)
  273. def testIteration(self):
  274. # Test the complex interaction when mixing file-iteration and the
  275. # various read* methods. Ostensibly, the mixture could just be tested
  276. # to work when it should work according to the Python language,
  277. # instead of fail when it should fail according to the current CPython
  278. # implementation. People don't always program Python the way they
  279. # should, though, and the implemenation might change in subtle ways,
  280. # so we explicitly test for errors, too; the test will just have to
  281. # be updated when the implementation changes.
  282. dataoffset = 16384
  283. filler = "ham\n"
  284. assert not dataoffset % len(filler), \
  285. "dataoffset must be multiple of len(filler)"
  286. nchunks = dataoffset // len(filler)
  287. testlines = [
  288. "spam, spam and eggs\n",
  289. "eggs, spam, ham and spam\n",
  290. "saussages, spam, spam and eggs\n",
  291. "spam, ham, spam and eggs\n",
  292. "spam, spam, spam, spam, spam, ham, spam\n",
  293. "wonderful spaaaaaam.\n"
  294. ]
  295. methods = [("readline", ()), ("read", ()), ("readlines", ()),
  296. ("readinto", (array("c", " "*100),))]
  297. try:
  298. # Prepare the testfile
  299. bag = open(TESTFN, "w")
  300. bag.write(filler * nchunks)
  301. bag.writelines(testlines)
  302. bag.close()
  303. # Test for appropriate errors mixing read* and iteration
  304. for methodname, args in methods:
  305. f = open(TESTFN)
  306. if f.next() != filler:
  307. self.fail, "Broken testfile"
  308. meth = getattr(f, methodname)
  309. try:
  310. meth(*args)
  311. except ValueError:
  312. pass
  313. else:
  314. self.fail("%s%r after next() didn't raise ValueError" %
  315. (methodname, args))
  316. f.close()
  317. # Test to see if harmless (by accident) mixing of read* and
  318. # iteration still works. This depends on the size of the internal
  319. # iteration buffer (currently 8192,) but we can test it in a
  320. # flexible manner. Each line in the bag o' ham is 4 bytes
  321. # ("h", "a", "m", "\n"), so 4096 lines of that should get us
  322. # exactly on the buffer boundary for any power-of-2 buffersize
  323. # between 4 and 16384 (inclusive).
  324. f = open(TESTFN)
  325. for i in range(nchunks):
  326. f.next()
  327. testline = testlines.pop(0)
  328. try:
  329. line = f.readline()
  330. except ValueError:
  331. self.fail("readline() after next() with supposedly empty "
  332. "iteration-buffer failed anyway")
  333. if line != testline:
  334. self.fail("readline() after next() with empty buffer "
  335. "failed. Got %r, expected %r" % (line, testline))
  336. testline = testlines.pop(0)
  337. buf = array("c", "\x00" * len(testline))
  338. try:
  339. f.readinto(buf)
  340. except ValueError:
  341. self.fail("readinto() after next() with supposedly empty "
  342. "iteration-buffer failed anyway")
  343. line = buf.tostring()
  344. if line != testline:
  345. self.fail("readinto() after next() with empty buffer "
  346. "failed. Got %r, expected %r" % (line, testline))
  347. testline = testlines.pop(0)
  348. try:
  349. line = f.read(len(testline))
  350. except ValueError:
  351. self.fail("read() after next() with supposedly empty "
  352. "iteration-buffer failed anyway")
  353. if line != testline:
  354. self.fail("read() after next() with empty buffer "
  355. "failed. Got %r, expected %r" % (line, testline))
  356. try:
  357. lines = f.readlines()
  358. except ValueError:
  359. self.fail("readlines() after next() with supposedly empty "
  360. "iteration-buffer failed anyway")
  361. if lines != testlines:
  362. self.fail("readlines() after next() with empty buffer "
  363. "failed. Got %r, expected %r" % (line, testline))
  364. # Reading after iteration hit EOF shouldn't hurt either
  365. f = open(TESTFN)
  366. try:
  367. for line in f:
  368. pass
  369. try:
  370. f.readline()
  371. f.readinto(buf)
  372. f.read()
  373. f.readlines()
  374. except ValueError:
  375. self.fail("read* failed after next() consumed file")
  376. finally:
  377. f.close()
  378. finally:
  379. os.unlink(TESTFN)
  380. @unittest.skipUnless(os.name == 'posix', 'test requires a posix system.')
  381. def test_write_full(self):
  382. devfull = '/dev/full'
  383. if not (os.path.exists(devfull) and
  384. stat.S_ISCHR(os.stat(devfull).st_mode)):
  385. # Issue #21934: OpenBSD does not have a /dev/full character device
  386. self.skipTest('requires %r' % devfull)
  387. with open(devfull, 'wb', 1) as f:
  388. with self.assertRaises(IOError):
  389. f.write('hello\n')
  390. with open(devfull, 'wb', 1) as f:
  391. with self.assertRaises(IOError):
  392. # Issue #17976
  393. f.write('hello')
  394. f.write('\n')
  395. with open(devfull, 'wb', 0) as f:
  396. with self.assertRaises(IOError):
  397. f.write('h')
  398. @unittest.skipUnless(sys.maxsize > 2**31, "requires 64-bit system")
  399. @test_support.precisionbigmemtest(2**31, 2.5, dry_run=False)
  400. def test_very_long_line(self, size):
  401. # Issue #22526
  402. requires('largefile')
  403. with open(TESTFN, "wb") as fp:
  404. fp.seek(size - 1)
  405. fp.write("\0")
  406. with open(TESTFN, "rb") as fp:
  407. for l in fp:
  408. pass
  409. self.assertEqual(len(l), size)
  410. self.assertEqual(l.count("\0"), size)
  411. l = None
  412. class FileSubclassTests(unittest.TestCase):
  413. def testExit(self):
  414. # test that exiting with context calls subclass' close
  415. class C(file):
  416. def __init__(self, *args):
  417. self.subclass_closed = False
  418. file.__init__(self, *args)
  419. def close(self):
  420. self.subclass_closed = True
  421. file.close(self)
  422. with C(TESTFN, 'w') as f:
  423. pass
  424. self.assertTrue(f.subclass_closed)
  425. @unittest.skipUnless(threading, 'Threading required for this test.')
  426. class FileThreadingTests(unittest.TestCase):
  427. # These tests check the ability to call various methods of file objects
  428. # (including close()) concurrently without crashing the Python interpreter.
  429. # See #815646, #595601
  430. def setUp(self):
  431. self._threads = test_support.threading_setup()
  432. self.f = None
  433. self.filename = TESTFN
  434. with open(self.filename, "w") as f:
  435. f.write("\n".join("0123456789"))
  436. self._count_lock = threading.Lock()
  437. self.close_count = 0
  438. self.close_success_count = 0
  439. self.use_buffering = False
  440. def tearDown(self):
  441. if self.f:
  442. try:
  443. self.f.close()
  444. except (EnvironmentError, ValueError):
  445. pass
  446. try:
  447. os.remove(self.filename)
  448. except EnvironmentError:
  449. pass
  450. test_support.threading_cleanup(*self._threads)
  451. def _create_file(self):
  452. if self.use_buffering:
  453. self.f = open(self.filename, "w+", buffering=1024*16)
  454. else:
  455. self.f = open(self.filename, "w+")
  456. def _close_file(self):
  457. with self._count_lock:
  458. self.close_count += 1
  459. self.f.close()
  460. with self._count_lock:
  461. self.close_success_count += 1
  462. def _close_and_reopen_file(self):
  463. self._close_file()
  464. # if close raises an exception thats fine, self.f remains valid so
  465. # we don't need to reopen.
  466. self._create_file()
  467. def _run_workers(self, func, nb_workers, duration=0.2):
  468. with self._count_lock:
  469. self.close_count = 0
  470. self.close_success_count = 0
  471. self.do_continue = True
  472. threads = []
  473. try:
  474. for i in range(nb_workers):
  475. t = threading.Thread(target=func)
  476. t.start()
  477. threads.append(t)
  478. for _ in xrange(100):
  479. time.sleep(duration/100)
  480. with self._count_lock:
  481. if self.close_count-self.close_success_count > nb_workers+1:
  482. if test_support.verbose:
  483. print 'Q',
  484. break
  485. time.sleep(duration)
  486. finally:
  487. self.do_continue = False
  488. for t in threads:
  489. t.join()
  490. def _test_close_open_io(self, io_func, nb_workers=5):
  491. def worker():
  492. self._create_file()
  493. funcs = itertools.cycle((
  494. lambda: io_func(),
  495. lambda: self._close_and_reopen_file(),
  496. ))
  497. for f in funcs:
  498. if not self.do_continue:
  499. break
  500. try:
  501. f()
  502. except (IOError, ValueError):
  503. pass
  504. self._run_workers(worker, nb_workers)
  505. if test_support.verbose:
  506. # Useful verbose statistics when tuning this test to take
  507. # less time to run but still ensuring that its still useful.
  508. #
  509. # the percent of close calls that raised an error
  510. percent = 100. - 100.*self.close_success_count/self.close_count
  511. print self.close_count, ('%.4f ' % percent),
  512. def test_close_open(self):
  513. def io_func():
  514. pass
  515. self._test_close_open_io(io_func)
  516. def test_close_open_flush(self):
  517. def io_func():
  518. self.f.flush()
  519. self._test_close_open_io(io_func)
  520. def test_close_open_iter(self):
  521. def io_func():
  522. list(iter(self.f))
  523. self._test_close_open_io(io_func)
  524. def test_close_open_isatty(self):
  525. def io_func():
  526. self.f.isatty()
  527. self._test_close_open_io(io_func)
  528. def test_close_open_print(self):
  529. def io_func():
  530. print >> self.f, ''
  531. self._test_close_open_io(io_func)
  532. def test_close_open_print_buffered(self):
  533. self.use_buffering = True
  534. def io_func():
  535. print >> self.f, ''
  536. self._test_close_open_io(io_func)
  537. def test_close_open_read(self):
  538. def io_func():
  539. self.f.read(0)
  540. self._test_close_open_io(io_func)
  541. def test_close_open_readinto(self):
  542. def io_func():
  543. a = array('c', 'xxxxx')
  544. self.f.readinto(a)
  545. self._test_close_open_io(io_func)
  546. def test_close_open_readline(self):
  547. def io_func():
  548. self.f.readline()
  549. self._test_close_open_io(io_func)
  550. def test_close_open_readlines(self):
  551. def io_func():
  552. self.f.readlines()
  553. self._test_close_open_io(io_func)
  554. def test_close_open_seek(self):
  555. def io_func():
  556. self.f.seek(0, 0)
  557. self._test_close_open_io(io_func)
  558. def test_close_open_tell(self):
  559. def io_func():
  560. self.f.tell()
  561. self._test_close_open_io(io_func)
  562. def test_close_open_truncate(self):
  563. def io_func():
  564. self.f.truncate()
  565. self._test_close_open_io(io_func)
  566. def test_close_open_write(self):
  567. def io_func():
  568. self.f.write('')
  569. self._test_close_open_io(io_func)
  570. def test_close_open_writelines(self):
  571. def io_func():
  572. self.f.writelines('')
  573. self._test_close_open_io(io_func)
  574. @unittest.skipUnless(os.name == 'posix', 'test requires a posix system.')
  575. class TestFileSignalEINTR(unittest.TestCase):
  576. def _test_reading(self, data_to_write, read_and_verify_code, method_name,
  577. universal_newlines=False):
  578. """Generic buffered read method test harness to verify EINTR behavior.
  579. Also validates that Python signal handlers are run during the read.
  580. Args:
  581. data_to_write: String to write to the child process for reading
  582. before sending it a signal, confirming the signal was handled,
  583. writing a final newline char and closing the infile pipe.
  584. read_and_verify_code: Single "line" of code to read from a file
  585. object named 'infile' and validate the result. This will be
  586. executed as part of a python subprocess fed data_to_write.
  587. method_name: The name of the read method being tested, for use in
  588. an error message on failure.
  589. universal_newlines: If True, infile will be opened in universal
  590. newline mode in the child process.
  591. """
  592. if universal_newlines:
  593. # Test the \r\n -> \n conversion while we're at it.
  594. data_to_write = data_to_write.replace('\n', '\r\n')
  595. infile_setup_code = 'infile = os.fdopen(sys.stdin.fileno(), "rU")'
  596. else:
  597. infile_setup_code = 'infile = sys.stdin'
  598. # Total pipe IO in this function is smaller than the minimum posix OS
  599. # pipe buffer size of 512 bytes. No writer should block.
  600. assert len(data_to_write) < 512, 'data_to_write must fit in pipe buf.'
  601. child_code = (
  602. 'import os, signal, sys ;'
  603. 'signal.signal('
  604. 'signal.SIGINT, lambda s, f: sys.stderr.write("$\\n")) ;'
  605. + infile_setup_code + ' ;' +
  606. 'assert isinstance(infile, file) ;'
  607. 'sys.stderr.write("Go.\\n") ;'
  608. + read_and_verify_code)
  609. reader_process = subprocess.Popen(
  610. [sys.executable, '-c', child_code],
  611. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  612. stderr=subprocess.PIPE)
  613. # Wait for the signal handler to be installed.
  614. go = reader_process.stderr.read(4)
  615. if go != 'Go.\n':
  616. reader_process.kill()
  617. self.fail('Error from %s process while awaiting "Go":\n%s' % (
  618. method_name, go+reader_process.stderr.read()))
  619. reader_process.stdin.write(data_to_write)
  620. signals_sent = 0
  621. rlist = []
  622. # We don't know when the read_and_verify_code in our child is actually
  623. # executing within the read system call we want to interrupt. This
  624. # loop waits for a bit before sending the first signal to increase
  625. # the likelihood of that. Implementations without correct EINTR
  626. # and signal handling usually fail this test.
  627. while not rlist:
  628. rlist, _, _ = select.select([reader_process.stderr], (), (), 0.05)
  629. reader_process.send_signal(signal.SIGINT)
  630. # Give the subprocess time to handle it before we loop around and
  631. # send another one. On OSX the second signal happening close to
  632. # immediately after the first was causing the subprocess to crash
  633. # via the OS's default SIGINT handler.
  634. time.sleep(0.1)
  635. signals_sent += 1
  636. if signals_sent > 200:
  637. reader_process.kill()
  638. self.fail("failed to handle signal during %s." % method_name)
  639. # This assumes anything unexpected that writes to stderr will also
  640. # write a newline. That is true of the traceback printing code.
  641. signal_line = reader_process.stderr.readline()
  642. if signal_line != '$\n':
  643. reader_process.kill()
  644. self.fail('Error from %s process while awaiting signal:\n%s' % (
  645. method_name, signal_line+reader_process.stderr.read()))
  646. # We append a newline to our input so that a readline call can
  647. # end on its own before the EOF is seen.
  648. stdout, stderr = reader_process.communicate(input='\n')
  649. if reader_process.returncode != 0:
  650. self.fail('%s() process exited rc=%d.\nSTDOUT:\n%s\nSTDERR:\n%s' % (
  651. method_name, reader_process.returncode, stdout, stderr))
  652. def test_readline(self, universal_newlines=False):
  653. """file.readline must handle signals and not lose data."""
  654. self._test_reading(
  655. data_to_write='hello, world!',
  656. read_and_verify_code=(
  657. 'line = infile.readline() ;'
  658. 'expected_line = "hello, world!\\n" ;'
  659. 'assert line == expected_line, ('
  660. '"read %r expected %r" % (line, expected_line))'
  661. ),
  662. method_name='readline',
  663. universal_newlines=universal_newlines)
  664. def test_readline_with_universal_newlines(self):
  665. self.test_readline(universal_newlines=True)
  666. def test_readlines(self, universal_newlines=False):
  667. """file.readlines must handle signals and not lose data."""
  668. self._test_reading(
  669. data_to_write='hello\nworld!',
  670. read_and_verify_code=(
  671. 'lines = infile.readlines() ;'
  672. 'expected_lines = ["hello\\n", "world!\\n"] ;'
  673. 'assert lines == expected_lines, ('
  674. '"readlines returned wrong data.\\n" '
  675. '"got lines %r\\nexpected %r" '
  676. '% (lines, expected_lines))'
  677. ),
  678. method_name='readlines',
  679. universal_newlines=universal_newlines)
  680. def test_readlines_with_universal_newlines(self):
  681. self.test_readlines(universal_newlines=True)
  682. def test_readall(self):
  683. """Unbounded file.read() must handle signals and not lose data."""
  684. self._test_reading(
  685. data_to_write='hello, world!abcdefghijklm',
  686. read_and_verify_code=(
  687. 'data = infile.read() ;'
  688. 'expected_data = "hello, world!abcdefghijklm\\n";'
  689. 'assert data == expected_data, ('
  690. '"read %r expected %r" % (data, expected_data))'
  691. ),
  692. method_name='unbounded read')
  693. def test_readinto(self):
  694. """file.readinto must handle signals and not lose data."""
  695. self._test_reading(
  696. data_to_write='hello, world!',
  697. read_and_verify_code=(
  698. 'data = bytearray(50) ;'
  699. 'num_read = infile.readinto(data) ;'
  700. 'expected_data = "hello, world!\\n";'
  701. 'assert data[:num_read] == expected_data, ('
  702. '"read %r expected %r" % (data, expected_data))'
  703. ),
  704. method_name='readinto')
  705. class StdoutTests(unittest.TestCase):
  706. def test_move_stdout_on_write(self):
  707. # Issue 3242: sys.stdout can be replaced (and freed) during a
  708. # print statement; prevent a segfault in this case
  709. save_stdout = sys.stdout
  710. class File:
  711. def write(self, data):
  712. if '\n' in data:
  713. sys.stdout = save_stdout
  714. try:
  715. sys.stdout = File()
  716. print "some text"
  717. finally:
  718. sys.stdout = save_stdout
  719. def test_del_stdout_before_print(self):
  720. # Issue 4597: 'print' with no argument wasn't reporting when
  721. # sys.stdout was deleted.
  722. save_stdout = sys.stdout
  723. del sys.stdout
  724. try:
  725. print
  726. except RuntimeError as e:
  727. self.assertEqual(str(e), "lost sys.stdout")
  728. else:
  729. self.fail("Expected RuntimeError")
  730. finally:
  731. sys.stdout = save_stdout
  732. def test_unicode(self):
  733. import subprocess
  734. def get_message(encoding, *code):
  735. code = '\n'.join(code)
  736. env = os.environ.copy()
  737. env['PYTHONIOENCODING'] = encoding
  738. process = subprocess.Popen([sys.executable, "-c", code],
  739. stdout=subprocess.PIPE, env=env)
  740. stdout, stderr = process.communicate()
  741. self.assertEqual(process.returncode, 0)
  742. return stdout
  743. def check_message(text, encoding, expected):
  744. stdout = get_message(encoding,
  745. "import sys",
  746. "sys.stdout.write(%r)" % text,
  747. "sys.stdout.flush()")
  748. self.assertEqual(stdout, expected)
  749. # test the encoding
  750. check_message(u'15\u20ac', "iso-8859-15", "15\xa4")
  751. check_message(u'15\u20ac', "utf-8", '15\xe2\x82\xac')
  752. check_message(u'15\u20ac', "utf-16-le", '1\x005\x00\xac\x20')
  753. # test the error handler
  754. check_message(u'15\u20ac', "iso-8859-1:ignore", "15")
  755. check_message(u'15\u20ac', "iso-8859-1:replace", "15?")
  756. check_message(u'15\u20ac', "iso-8859-1:backslashreplace", "15\\u20ac")
  757. # test the buffer API
  758. for objtype in ('buffer', 'bytearray'):
  759. stdout = get_message('ascii',
  760. 'import sys',
  761. r'sys.stdout.write(%s("\xe9"))' % objtype,
  762. 'sys.stdout.flush()')
  763. self.assertEqual(stdout, "\xe9")
  764. def test_main():
  765. # Historically, these tests have been sloppy about removing TESTFN.
  766. # So get rid of it no matter what.
  767. try:
  768. run_unittest(AutoFileTests, OtherFileTests, FileSubclassTests,
  769. FileThreadingTests, TestFileSignalEINTR, StdoutTests)
  770. finally:
  771. if os.path.exists(TESTFN):
  772. os.unlink(TESTFN)
  773. if __name__ == '__main__':
  774. test_main()