You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_compat.py 28KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.python.compat}.
  5. """
  6. from __future__ import division, absolute_import
  7. import socket, sys, traceback, io, codecs
  8. from twisted.trial import unittest
  9. from twisted.python.compat import (
  10. reduce, execfile, _PY3, _PYPY, comparable, cmp, nativeString,
  11. networkString, unicode as unicodeCompat, lazyByteSlice, reraise,
  12. NativeStringIO, iterbytes, intToBytes, ioType, bytesEnviron, iteritems,
  13. _coercedUnicode, unichr, raw_input, _bytesRepr, _get_async_param,
  14. )
  15. from twisted.python.filepath import FilePath
  16. from twisted.python.runtime import platform
  17. class IOTypeTests(unittest.SynchronousTestCase):
  18. """
  19. Test cases for determining a file-like object's type.
  20. """
  21. def test_3StringIO(self):
  22. """
  23. An L{io.StringIO} accepts and returns text.
  24. """
  25. self.assertEqual(ioType(io.StringIO()), unicodeCompat)
  26. def test_3BytesIO(self):
  27. """
  28. An L{io.BytesIO} accepts and returns bytes.
  29. """
  30. self.assertEqual(ioType(io.BytesIO()), bytes)
  31. def test_3openTextMode(self):
  32. """
  33. A file opened via 'io.open' in text mode accepts and returns text.
  34. """
  35. with io.open(self.mktemp(), "w") as f:
  36. self.assertEqual(ioType(f), unicodeCompat)
  37. def test_3openBinaryMode(self):
  38. """
  39. A file opened via 'io.open' in binary mode accepts and returns bytes.
  40. """
  41. with io.open(self.mktemp(), "wb") as f:
  42. self.assertEqual(ioType(f), bytes)
  43. def test_2openTextMode(self):
  44. """
  45. The special built-in console file in Python 2 which has an 'encoding'
  46. attribute should qualify as a special type, since it accepts both bytes
  47. and text faithfully.
  48. """
  49. class VerySpecificLie(file):
  50. """
  51. In their infinite wisdom, the CPython developers saw fit not to
  52. allow us a writable 'encoding' attribute on the built-in 'file'
  53. type in Python 2, despite making it writable in C with
  54. PyFile_SetEncoding.
  55. Pretend they did not do that.
  56. """
  57. encoding = 'utf-8'
  58. self.assertEqual(ioType(VerySpecificLie(self.mktemp(), "wb")),
  59. basestring)
  60. def test_2StringIO(self):
  61. """
  62. Python 2's L{StringIO} and L{cStringIO} modules are both binary I/O.
  63. """
  64. from cStringIO import StringIO as cStringIO
  65. from StringIO import StringIO
  66. self.assertEqual(ioType(StringIO()), bytes)
  67. self.assertEqual(ioType(cStringIO()), bytes)
  68. def test_2openBinaryMode(self):
  69. """
  70. The normal 'open' builtin in Python 2 will always result in bytes I/O.
  71. """
  72. with open(self.mktemp(), "w") as f:
  73. self.assertEqual(ioType(f), bytes)
  74. if _PY3:
  75. test_2openTextMode.skip = "The 'file' type is no longer available."
  76. test_2openBinaryMode.skip = "'io.open' is now the same as 'open'."
  77. test_2StringIO.skip = ("The 'StringIO' and 'cStringIO' modules were "
  78. "subsumed by the 'io' module.")
  79. def test_codecsOpenBytes(self):
  80. """
  81. The L{codecs} module, oddly, returns a file-like object which returns
  82. bytes when not passed an 'encoding' argument.
  83. """
  84. with codecs.open(self.mktemp(), 'wb') as f:
  85. self.assertEqual(ioType(f), bytes)
  86. def test_codecsOpenText(self):
  87. """
  88. When passed an encoding, however, the L{codecs} module returns unicode.
  89. """
  90. with codecs.open(self.mktemp(), 'wb', encoding='utf-8') as f:
  91. self.assertEqual(ioType(f), unicodeCompat)
  92. def test_defaultToText(self):
  93. """
  94. When passed an object about which no sensible decision can be made, err
  95. on the side of unicode.
  96. """
  97. self.assertEqual(ioType(object()), unicodeCompat)
  98. class CompatTests(unittest.SynchronousTestCase):
  99. """
  100. Various utility functions in C{twisted.python.compat} provide same
  101. functionality as modern Python variants.
  102. """
  103. def test_set(self):
  104. """
  105. L{set} should behave like the expected set interface.
  106. """
  107. a = set()
  108. a.add('b')
  109. a.add('c')
  110. a.add('a')
  111. b = list(a)
  112. b.sort()
  113. self.assertEqual(b, ['a', 'b', 'c'])
  114. a.remove('b')
  115. b = list(a)
  116. b.sort()
  117. self.assertEqual(b, ['a', 'c'])
  118. a.discard('d')
  119. b = set(['r', 's'])
  120. d = a.union(b)
  121. b = list(d)
  122. b.sort()
  123. self.assertEqual(b, ['a', 'c', 'r', 's'])
  124. def test_frozenset(self):
  125. """
  126. L{frozenset} should behave like the expected frozenset interface.
  127. """
  128. a = frozenset(['a', 'b'])
  129. self.assertRaises(AttributeError, getattr, a, "add")
  130. self.assertEqual(sorted(a), ['a', 'b'])
  131. b = frozenset(['r', 's'])
  132. d = a.union(b)
  133. b = list(d)
  134. b.sort()
  135. self.assertEqual(b, ['a', 'b', 'r', 's'])
  136. def test_reduce(self):
  137. """
  138. L{reduce} should behave like the builtin reduce.
  139. """
  140. self.assertEqual(15, reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))
  141. self.assertEqual(16, reduce(lambda x, y: x + y, [1, 2, 3, 4, 5], 1))
  142. class IPv6Tests(unittest.SynchronousTestCase):
  143. """
  144. C{inet_pton} and C{inet_ntop} implementations support IPv6.
  145. """
  146. def testNToP(self):
  147. from twisted.python.compat import inet_ntop
  148. f = lambda a: inet_ntop(socket.AF_INET6, a)
  149. g = lambda a: inet_ntop(socket.AF_INET, a)
  150. self.assertEqual('::', f('\x00' * 16))
  151. self.assertEqual('::1', f('\x00' * 15 + '\x01'))
  152. self.assertEqual(
  153. 'aef:b01:506:1001:ffff:9997:55:170',
  154. f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01'
  155. '\x70'))
  156. self.assertEqual('1.0.1.0', g('\x01\x00\x01\x00'))
  157. self.assertEqual('170.85.170.85', g('\xaa\x55\xaa\x55'))
  158. self.assertEqual('255.255.255.255', g('\xff\xff\xff\xff'))
  159. self.assertEqual('100::', f('\x01' + '\x00' * 15))
  160. self.assertEqual('100::1', f('\x01' + '\x00' * 14 + '\x01'))
  161. def testPToN(self):
  162. """
  163. L{twisted.python.compat.inet_pton} parses IPv4 and IPv6 addresses in a
  164. manner similar to that of L{socket.inet_pton}.
  165. """
  166. from twisted.python.compat import inet_pton
  167. f = lambda a: inet_pton(socket.AF_INET6, a)
  168. g = lambda a: inet_pton(socket.AF_INET, a)
  169. self.assertEqual('\x00\x00\x00\x00', g('0.0.0.0'))
  170. self.assertEqual('\xff\x00\xff\x00', g('255.0.255.0'))
  171. self.assertEqual('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
  172. self.assertEqual('\x00' * 16, f('::'))
  173. self.assertEqual('\x00' * 16, f('0::0'))
  174. self.assertEqual('\x00\x01' + '\x00' * 14, f('1::'))
  175. self.assertEqual(
  176. '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
  177. f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae'))
  178. # Scope ID doesn't affect the binary representation.
  179. self.assertEqual(
  180. '\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
  181. f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae%en0'))
  182. self.assertEqual('\x00' * 14 + '\x00\x01', f('::1'))
  183. self.assertEqual('\x00' * 12 + '\x01\x02\x03\x04', f('::1.2.3.4'))
  184. self.assertEqual(
  185. '\x00\x01\x00\x02\x00\x03\x00\x04\x00\x05\x00\x06\x01\x02\x03\xff',
  186. f('1:2:3:4:5:6:1.2.3.255'))
  187. for badaddr in ['1:2:3:4:5:6:7:8:', ':1:2:3:4:5:6:7:8', '1::2::3',
  188. '1:::3', ':::', '1:2', '::1.2', '1.2.3.4::',
  189. 'abcd:1.2.3.4:abcd:abcd:abcd:abcd:abcd',
  190. '1234:1.2.3.4:1234:1234:1234:1234:1234:1234',
  191. '1.2.3.4', '', '%eth0']:
  192. self.assertRaises(ValueError, f, badaddr)
  193. if _PY3:
  194. IPv6Tests.skip = "These tests are only relevant to old versions of Python"
  195. class ExecfileCompatTests(unittest.SynchronousTestCase):
  196. """
  197. Tests for the Python 3-friendly L{execfile} implementation.
  198. """
  199. def writeScript(self, content):
  200. """
  201. Write L{content} to a new temporary file, returning the L{FilePath}
  202. for the new file.
  203. """
  204. path = self.mktemp()
  205. with open(path, "wb") as f:
  206. f.write(content.encode("ascii"))
  207. return FilePath(path.encode("utf-8"))
  208. def test_execfileGlobals(self):
  209. """
  210. L{execfile} executes the specified file in the given global namespace.
  211. """
  212. script = self.writeScript(u"foo += 1\n")
  213. globalNamespace = {"foo": 1}
  214. execfile(script.path, globalNamespace)
  215. self.assertEqual(2, globalNamespace["foo"])
  216. def test_execfileGlobalsAndLocals(self):
  217. """
  218. L{execfile} executes the specified file in the given global and local
  219. namespaces.
  220. """
  221. script = self.writeScript(u"foo += 1\n")
  222. globalNamespace = {"foo": 10}
  223. localNamespace = {"foo": 20}
  224. execfile(script.path, globalNamespace, localNamespace)
  225. self.assertEqual(10, globalNamespace["foo"])
  226. self.assertEqual(21, localNamespace["foo"])
  227. def test_execfileUniversalNewlines(self):
  228. """
  229. L{execfile} reads in the specified file using universal newlines so
  230. that scripts written on one platform will work on another.
  231. """
  232. for lineEnding in u"\n", u"\r", u"\r\n":
  233. script = self.writeScript(u"foo = 'okay'" + lineEnding)
  234. globalNamespace = {"foo": None}
  235. execfile(script.path, globalNamespace)
  236. self.assertEqual("okay", globalNamespace["foo"])
  237. class PY3Tests(unittest.SynchronousTestCase):
  238. """
  239. Identification of Python 2 vs. Python 3.
  240. """
  241. def test_python2(self):
  242. """
  243. On Python 2, C{_PY3} is False.
  244. """
  245. if sys.version.startswith("2."):
  246. self.assertFalse(_PY3)
  247. def test_python3(self):
  248. """
  249. On Python 3, C{_PY3} is True.
  250. """
  251. if sys.version.startswith("3."):
  252. self.assertTrue(_PY3)
  253. class PYPYTest(unittest.SynchronousTestCase):
  254. """
  255. Identification of PyPy.
  256. """
  257. def test_PYPY(self):
  258. """
  259. On PyPy, L{_PYPY} is True.
  260. """
  261. if 'PyPy' in sys.version:
  262. self.assertTrue(_PYPY)
  263. else:
  264. self.assertFalse(_PYPY)
  265. @comparable
  266. class Comparable(object):
  267. """
  268. Objects that can be compared to each other, but not others.
  269. """
  270. def __init__(self, value):
  271. self.value = value
  272. def __cmp__(self, other):
  273. if not isinstance(other, Comparable):
  274. return NotImplemented
  275. return cmp(self.value, other.value)
  276. class ComparableTests(unittest.SynchronousTestCase):
  277. """
  278. L{comparable} decorated classes emulate Python 2's C{__cmp__} semantics.
  279. """
  280. def test_equality(self):
  281. """
  282. Instances of a class that is decorated by C{comparable} support
  283. equality comparisons.
  284. """
  285. # Make explicitly sure we're using ==:
  286. self.assertTrue(Comparable(1) == Comparable(1))
  287. self.assertFalse(Comparable(2) == Comparable(1))
  288. def test_nonEquality(self):
  289. """
  290. Instances of a class that is decorated by C{comparable} support
  291. inequality comparisons.
  292. """
  293. # Make explicitly sure we're using !=:
  294. self.assertFalse(Comparable(1) != Comparable(1))
  295. self.assertTrue(Comparable(2) != Comparable(1))
  296. def test_greaterThan(self):
  297. """
  298. Instances of a class that is decorated by C{comparable} support
  299. greater-than comparisons.
  300. """
  301. self.assertTrue(Comparable(2) > Comparable(1))
  302. self.assertFalse(Comparable(0) > Comparable(3))
  303. def test_greaterThanOrEqual(self):
  304. """
  305. Instances of a class that is decorated by C{comparable} support
  306. greater-than-or-equal comparisons.
  307. """
  308. self.assertTrue(Comparable(1) >= Comparable(1))
  309. self.assertTrue(Comparable(2) >= Comparable(1))
  310. self.assertFalse(Comparable(0) >= Comparable(3))
  311. def test_lessThan(self):
  312. """
  313. Instances of a class that is decorated by C{comparable} support
  314. less-than comparisons.
  315. """
  316. self.assertTrue(Comparable(0) < Comparable(3))
  317. self.assertFalse(Comparable(2) < Comparable(0))
  318. def test_lessThanOrEqual(self):
  319. """
  320. Instances of a class that is decorated by C{comparable} support
  321. less-than-or-equal comparisons.
  322. """
  323. self.assertTrue(Comparable(3) <= Comparable(3))
  324. self.assertTrue(Comparable(0) <= Comparable(3))
  325. self.assertFalse(Comparable(2) <= Comparable(0))
  326. class Python3ComparableTests(unittest.SynchronousTestCase):
  327. """
  328. Python 3-specific functionality of C{comparable}.
  329. """
  330. def test_notImplementedEquals(self):
  331. """
  332. Instances of a class that is decorated by C{comparable} support
  333. returning C{NotImplemented} from C{__eq__} if it is returned by the
  334. underlying C{__cmp__} call.
  335. """
  336. self.assertEqual(Comparable(1).__eq__(object()), NotImplemented)
  337. def test_notImplementedNotEquals(self):
  338. """
  339. Instances of a class that is decorated by C{comparable} support
  340. returning C{NotImplemented} from C{__ne__} if it is returned by the
  341. underlying C{__cmp__} call.
  342. """
  343. self.assertEqual(Comparable(1).__ne__(object()), NotImplemented)
  344. def test_notImplementedGreaterThan(self):
  345. """
  346. Instances of a class that is decorated by C{comparable} support
  347. returning C{NotImplemented} from C{__gt__} if it is returned by the
  348. underlying C{__cmp__} call.
  349. """
  350. self.assertEqual(Comparable(1).__gt__(object()), NotImplemented)
  351. def test_notImplementedLessThan(self):
  352. """
  353. Instances of a class that is decorated by C{comparable} support
  354. returning C{NotImplemented} from C{__lt__} if it is returned by the
  355. underlying C{__cmp__} call.
  356. """
  357. self.assertEqual(Comparable(1).__lt__(object()), NotImplemented)
  358. def test_notImplementedGreaterThanEquals(self):
  359. """
  360. Instances of a class that is decorated by C{comparable} support
  361. returning C{NotImplemented} from C{__ge__} if it is returned by the
  362. underlying C{__cmp__} call.
  363. """
  364. self.assertEqual(Comparable(1).__ge__(object()), NotImplemented)
  365. def test_notImplementedLessThanEquals(self):
  366. """
  367. Instances of a class that is decorated by C{comparable} support
  368. returning C{NotImplemented} from C{__le__} if it is returned by the
  369. underlying C{__cmp__} call.
  370. """
  371. self.assertEqual(Comparable(1).__le__(object()), NotImplemented)
  372. if not _PY3:
  373. # On Python 2, we just use __cmp__ directly, so checking detailed
  374. # comparison methods doesn't makes sense.
  375. Python3ComparableTests.skip = "Python 3 only."
  376. class CmpTests(unittest.SynchronousTestCase):
  377. """
  378. L{cmp} should behave like the built-in Python 2 C{cmp}.
  379. """
  380. def test_equals(self):
  381. """
  382. L{cmp} returns 0 for equal objects.
  383. """
  384. self.assertEqual(cmp(u"a", u"a"), 0)
  385. self.assertEqual(cmp(1, 1), 0)
  386. self.assertEqual(cmp([1], [1]), 0)
  387. def test_greaterThan(self):
  388. """
  389. L{cmp} returns 1 if its first argument is bigger than its second.
  390. """
  391. self.assertEqual(cmp(4, 0), 1)
  392. self.assertEqual(cmp(b"z", b"a"), 1)
  393. def test_lessThan(self):
  394. """
  395. L{cmp} returns -1 if its first argument is smaller than its second.
  396. """
  397. self.assertEqual(cmp(0.1, 2.3), -1)
  398. self.assertEqual(cmp(b"a", b"d"), -1)
  399. class StringTests(unittest.SynchronousTestCase):
  400. """
  401. Compatibility functions and types for strings.
  402. """
  403. def assertNativeString(self, original, expected):
  404. """
  405. Raise an exception indicating a failed test if the output of
  406. C{nativeString(original)} is unequal to the expected string, or is not
  407. a native string.
  408. """
  409. self.assertEqual(nativeString(original), expected)
  410. self.assertIsInstance(nativeString(original), str)
  411. def test_nonASCIIBytesToString(self):
  412. """
  413. C{nativeString} raises a C{UnicodeError} if input bytes are not ASCII
  414. decodable.
  415. """
  416. self.assertRaises(UnicodeError, nativeString, b"\xFF")
  417. def test_nonASCIIUnicodeToString(self):
  418. """
  419. C{nativeString} raises a C{UnicodeError} if input Unicode is not ASCII
  420. encodable.
  421. """
  422. self.assertRaises(UnicodeError, nativeString, u"\u1234")
  423. def test_bytesToString(self):
  424. """
  425. C{nativeString} converts bytes to the native string format, assuming
  426. an ASCII encoding if applicable.
  427. """
  428. self.assertNativeString(b"hello", "hello")
  429. def test_unicodeToString(self):
  430. """
  431. C{nativeString} converts unicode to the native string format, assuming
  432. an ASCII encoding if applicable.
  433. """
  434. self.assertNativeString(u"Good day", "Good day")
  435. def test_stringToString(self):
  436. """
  437. C{nativeString} leaves native strings as native strings.
  438. """
  439. self.assertNativeString("Hello!", "Hello!")
  440. def test_unexpectedType(self):
  441. """
  442. C{nativeString} raises a C{TypeError} if given an object that is not a
  443. string of some sort.
  444. """
  445. self.assertRaises(TypeError, nativeString, 1)
  446. def test_unicode(self):
  447. """
  448. C{compat.unicode} is C{str} on Python 3, C{unicode} on Python 2.
  449. """
  450. if _PY3:
  451. expected = str
  452. else:
  453. expected = unicode
  454. self.assertIs(unicodeCompat, expected)
  455. def test_nativeStringIO(self):
  456. """
  457. L{NativeStringIO} is a file-like object that stores native strings in
  458. memory.
  459. """
  460. f = NativeStringIO()
  461. f.write("hello")
  462. f.write(" there")
  463. self.assertEqual(f.getvalue(), "hello there")
  464. class NetworkStringTests(unittest.SynchronousTestCase):
  465. """
  466. Tests for L{networkString}.
  467. """
  468. def test_bytes(self):
  469. """
  470. L{networkString} returns a C{bytes} object passed to it unmodified.
  471. """
  472. self.assertEqual(b"foo", networkString(b"foo"))
  473. def test_bytesOutOfRange(self):
  474. """
  475. L{networkString} raises C{UnicodeError} if passed a C{bytes} instance
  476. containing bytes not used by ASCII.
  477. """
  478. self.assertRaises(
  479. UnicodeError, networkString, u"\N{SNOWMAN}".encode('utf-8'))
  480. if _PY3:
  481. test_bytes.skip = test_bytesOutOfRange.skip = (
  482. "Bytes behavior of networkString only provided on Python 2.")
  483. def test_unicode(self):
  484. """
  485. L{networkString} returns a C{unicode} object passed to it encoded into
  486. a C{bytes} instance.
  487. """
  488. self.assertEqual(b"foo", networkString(u"foo"))
  489. def test_unicodeOutOfRange(self):
  490. """
  491. L{networkString} raises L{UnicodeError} if passed a C{unicode} instance
  492. containing characters not encodable in ASCII.
  493. """
  494. self.assertRaises(
  495. UnicodeError, networkString, u"\N{SNOWMAN}")
  496. if not _PY3:
  497. test_unicode.skip = test_unicodeOutOfRange.skip = (
  498. "Unicode behavior of networkString only provided on Python 3.")
  499. def test_nonString(self):
  500. """
  501. L{networkString} raises L{TypeError} if passed a non-string object or
  502. the wrong type of string object.
  503. """
  504. self.assertRaises(TypeError, networkString, object())
  505. if _PY3:
  506. self.assertRaises(TypeError, networkString, b"bytes")
  507. else:
  508. self.assertRaises(TypeError, networkString, u"text")
  509. class ReraiseTests(unittest.SynchronousTestCase):
  510. """
  511. L{reraise} re-raises exceptions on both Python 2 and Python 3.
  512. """
  513. def test_reraiseWithNone(self):
  514. """
  515. Calling L{reraise} with an exception instance and a traceback of
  516. L{None} re-raises it with a new traceback.
  517. """
  518. try:
  519. 1/0
  520. except:
  521. typ, value, tb = sys.exc_info()
  522. try:
  523. reraise(value, None)
  524. except:
  525. typ2, value2, tb2 = sys.exc_info()
  526. self.assertEqual(typ2, ZeroDivisionError)
  527. self.assertIs(value, value2)
  528. self.assertNotEqual(traceback.format_tb(tb)[-1],
  529. traceback.format_tb(tb2)[-1])
  530. else:
  531. self.fail("The exception was not raised.")
  532. def test_reraiseWithTraceback(self):
  533. """
  534. Calling L{reraise} with an exception instance and a traceback
  535. re-raises the exception with the given traceback.
  536. """
  537. try:
  538. 1/0
  539. except:
  540. typ, value, tb = sys.exc_info()
  541. try:
  542. reraise(value, tb)
  543. except:
  544. typ2, value2, tb2 = sys.exc_info()
  545. self.assertEqual(typ2, ZeroDivisionError)
  546. self.assertIs(value, value2)
  547. self.assertEqual(traceback.format_tb(tb)[-1],
  548. traceback.format_tb(tb2)[-1])
  549. else:
  550. self.fail("The exception was not raised.")
  551. class Python3BytesTests(unittest.SynchronousTestCase):
  552. """
  553. Tests for L{iterbytes}, L{intToBytes}, L{lazyByteSlice}.
  554. """
  555. def test_iteration(self):
  556. """
  557. When L{iterbytes} is called with a bytestring, the returned object
  558. can be iterated over, resulting in the individual bytes of the
  559. bytestring.
  560. """
  561. input = b"abcd"
  562. result = list(iterbytes(input))
  563. self.assertEqual(result, [b'a', b'b', b'c', b'd'])
  564. def test_intToBytes(self):
  565. """
  566. When L{intToBytes} is called with an integer, the result is an
  567. ASCII-encoded string representation of the number.
  568. """
  569. self.assertEqual(intToBytes(213), b"213")
  570. def test_lazyByteSliceNoOffset(self):
  571. """
  572. L{lazyByteSlice} called with some bytes returns a semantically equal
  573. version of these bytes.
  574. """
  575. data = b'123XYZ'
  576. self.assertEqual(bytes(lazyByteSlice(data)), data)
  577. def test_lazyByteSliceOffset(self):
  578. """
  579. L{lazyByteSlice} called with some bytes and an offset returns a
  580. semantically equal version of these bytes starting at the given offset.
  581. """
  582. data = b'123XYZ'
  583. self.assertEqual(bytes(lazyByteSlice(data, 2)), data[2:])
  584. def test_lazyByteSliceOffsetAndLength(self):
  585. """
  586. L{lazyByteSlice} called with some bytes, an offset and a length returns
  587. a semantically equal version of these bytes starting at the given
  588. offset, up to the given length.
  589. """
  590. data = b'123XYZ'
  591. self.assertEqual(bytes(lazyByteSlice(data, 2, 3)), data[2:5])
  592. class BytesEnvironTests(unittest.TestCase):
  593. """
  594. Tests for L{BytesEnviron}.
  595. """
  596. def test_alwaysBytes(self):
  597. """
  598. The output of L{BytesEnviron} should always be a L{dict} with L{bytes}
  599. values and L{bytes} keys.
  600. """
  601. result = bytesEnviron()
  602. types = set()
  603. for key, val in iteritems(result):
  604. types.add(type(key))
  605. types.add(type(val))
  606. self.assertEqual(list(types), [bytes])
  607. if platform.isWindows():
  608. test_alwaysBytes.skip = "Environment vars are always str on Windows."
  609. class CoercedUnicodeTests(unittest.TestCase):
  610. """
  611. Tests for L{twisted.python.compat._coercedUnicode}.
  612. """
  613. def test_unicodeASCII(self):
  614. """
  615. Unicode strings with ASCII code points are unchanged.
  616. """
  617. result = _coercedUnicode(u'text')
  618. self.assertEqual(result, u'text')
  619. self.assertIsInstance(result, unicodeCompat)
  620. def test_unicodeNonASCII(self):
  621. """
  622. Unicode strings with non-ASCII code points are unchanged.
  623. """
  624. result = _coercedUnicode(u'\N{SNOWMAN}')
  625. self.assertEqual(result, u'\N{SNOWMAN}')
  626. self.assertIsInstance(result, unicodeCompat)
  627. def test_nativeASCII(self):
  628. """
  629. Native strings with ASCII code points are unchanged.
  630. On Python 2, this verifies that ASCII-only byte strings are accepted,
  631. whereas for Python 3 it is identical to L{test_unicodeASCII}.
  632. """
  633. result = _coercedUnicode('text')
  634. self.assertEqual(result, u'text')
  635. self.assertIsInstance(result, unicodeCompat)
  636. def test_bytesPy3(self):
  637. """
  638. Byte strings are not accceptable in Python 3.
  639. """
  640. exc = self.assertRaises(TypeError, _coercedUnicode, b'bytes')
  641. self.assertEqual(str(exc), "Expected str not b'bytes' (bytes)")
  642. if not _PY3:
  643. test_bytesPy3.skip = (
  644. "Bytes behavior of _coercedUnicode only provided on Python 2.")
  645. def test_bytesNonASCII(self):
  646. """
  647. Byte strings with non-ASCII code points raise an exception.
  648. """
  649. self.assertRaises(UnicodeError, _coercedUnicode, b'\xe2\x98\x83')
  650. if _PY3:
  651. test_bytesNonASCII.skip = (
  652. "Bytes behavior of _coercedUnicode only provided on Python 2.")
  653. class UnichrTests(unittest.TestCase):
  654. """
  655. Tests for L{unichr}.
  656. """
  657. def test_unichr(self):
  658. """
  659. unichar exists and returns a unicode string with the given code point.
  660. """
  661. self.assertEqual(unichr(0x2603), u"\N{SNOWMAN}")
  662. class RawInputTests(unittest.TestCase):
  663. """
  664. Tests for L{raw_input}
  665. """
  666. def test_raw_input(self):
  667. """
  668. L{twisted.python.compat.raw_input}
  669. """
  670. class FakeStdin:
  671. def readline(self):
  672. return "User input\n"
  673. class FakeStdout:
  674. data = ""
  675. def write(self, data):
  676. self.data += data
  677. self.patch(sys, "stdin", FakeStdin())
  678. stdout = FakeStdout()
  679. self.patch(sys, "stdout", stdout)
  680. self.assertEqual(raw_input("Prompt"), "User input")
  681. self.assertEqual(stdout.data, "Prompt")
  682. class FutureBytesReprTests(unittest.TestCase):
  683. """
  684. Tests for L{twisted.python.compat._bytesRepr}.
  685. """
  686. def test_bytesReprNotBytes(self):
  687. """
  688. L{twisted.python.compat._bytesRepr} raises a
  689. L{TypeError} when called any object that is not an instance of
  690. L{bytes}.
  691. """
  692. exc = self.assertRaises(TypeError, _bytesRepr, ["not bytes"])
  693. self.assertEquals(str(exc), "Expected bytes not ['not bytes']")
  694. def test_bytesReprPrefix(self):
  695. """
  696. L{twisted.python.compat._bytesRepr} always prepends
  697. ``b`` to the returned repr on both Python 2 and 3.
  698. """
  699. self.assertEqual(_bytesRepr(b'\x00'), "b'\\x00'")
  700. class GetAsyncParamTests(unittest.SynchronousTestCase):
  701. """
  702. Tests for L{twisted.python.compat._get_async_param}
  703. """
  704. def test_get_async_param(self):
  705. """
  706. L{twisted.python.compat._get_async_param} uses isAsync by default,
  707. or deprecated async keyword argument if isAsync is None.
  708. """
  709. self.assertEqual(_get_async_param(isAsync=False), False)
  710. self.assertEqual(_get_async_param(isAsync=True), True)
  711. self.assertEqual(
  712. _get_async_param(isAsync=None, **{'async': False}), False)
  713. self.assertEqual(
  714. _get_async_param(isAsync=None, **{'async': True}), True)
  715. self.assertRaises(TypeError, _get_async_param, False, {'async': False})
  716. def test_get_async_param_deprecation(self):
  717. """
  718. L{twisted.python.compat._get_async_param} raises a deprecation
  719. warning if async keyword argument is passed.
  720. """
  721. self.assertEqual(
  722. _get_async_param(isAsync=None, **{'async': False}), False)
  723. currentWarnings = self.flushWarnings(
  724. offendingFunctions=[self.test_get_async_param_deprecation])
  725. self.assertEqual(
  726. currentWarnings[0]['message'],
  727. "'async' keyword argument is deprecated, please use isAsync")