home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_unicode.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  27.8 KB  |  777 lines

  1. """ Test script for the Unicode implementation.
  2.  
  3. Written by Marc-Andre Lemburg (mal@lemburg.com).
  4.  
  5. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  6.  
  7. """#"
  8. from test_support import verify, verbose, TestFailed
  9. import sys, string
  10.  
  11. if not sys.platform.startswith('java'):
  12.     # Test basic sanity of repr()
  13.     verify(repr(u'abc') == "u'abc'")
  14.     verify(repr(u'ab\\c') == "u'ab\\\\c'")
  15.     verify(repr(u'ab\\') == "u'ab\\\\'")
  16.     verify(repr(u'\\c') == "u'\\\\c'")
  17.     verify(repr(u'\\') == "u'\\\\'")
  18.     verify(repr(u'\n') == "u'\\n'")
  19.     verify(repr(u'\r') == "u'\\r'")
  20.     verify(repr(u'\t') == "u'\\t'")
  21.     verify(repr(u'\b') == "u'\\x08'")
  22.     verify(repr(u"'\"") == """u'\\'"'""")
  23.     verify(repr(u"'\"") == """u'\\'"'""")
  24.     verify(repr(u"'") == '''u"'"''')
  25.     verify(repr(u'"') == """u'"'""")
  26.     verify(repr(u''.join(map(unichr, range(256)))) ==
  27.        "u'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
  28.        "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
  29.        "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
  30.        "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
  31.        "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
  32.        "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
  33.        "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
  34.        "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
  35.        "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
  36.        "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
  37.        "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
  38.        "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
  39.        "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
  40.        "\\xfe\\xff'")
  41.  
  42. def test(method, input, output, *args):
  43.     if verbose:
  44.         print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)),
  45.     try:
  46.         f = getattr(input, method)
  47.         value = apply(f, args)
  48.     except:
  49.         value = sys.exc_type
  50.         exc = sys.exc_info()[:2]
  51.     else:
  52.         exc = None
  53.     if value == output and type(value) is type(output):
  54.         # if the original is returned make sure that
  55.         # this doesn't happen with subclasses
  56.         if value is input:
  57.             class usub(unicode):
  58.                 def __repr__(self):
  59.                     return 'usub(%r)' % unicode.__repr__(self)
  60.             input = usub(input)
  61.             try:
  62.                 f = getattr(input, method)
  63.                 value = apply(f, args)
  64.             except:
  65.                 value = sys.exc_type
  66.                 exc = sys.exc_info()[:2]
  67.             if value is input:
  68.                 if verbose:
  69.                     print 'no'
  70.                 print '*',f, `input`, `output`, `value`
  71.                 return
  72.     if value != output or type(value) is not type(output):
  73.         if verbose:
  74.             print 'no'
  75.         print '*',f, `input`, `output`, `value`
  76.         if exc:
  77.             print '  value == %s: %s' % (exc)
  78.     else:
  79.         if verbose:
  80.             print 'yes'
  81.  
  82. test('capitalize', u' hello ', u' hello ')
  83. test('capitalize', u'hello ', u'Hello ')
  84. test('capitalize', u'aaaa', u'Aaaa')
  85. test('capitalize', u'AaAa', u'Aaaa')
  86.  
  87. test('count', u'aaa', 3, u'a')
  88. test('count', u'aaa', 0, u'b')
  89. test('count', 'aaa', 3, u'a')
  90. test('count', 'aaa', 0, u'b')
  91. test('count', u'aaa', 3, 'a')
  92. test('count', u'aaa', 0, 'b')
  93.  
  94. test('title', u' hello ', u' Hello ')
  95. test('title', u'hello ', u'Hello ')
  96. test('title', u"fOrMaT thIs aS titLe String", u'Format This As Title String')
  97. test('title', u"fOrMaT,thIs-aS*titLe;String", u'Format,This-As*Title;String')
  98. test('title', u"getInt", u'Getint')
  99.  
  100. test('find', u'abcdefghiabc', 0, u'abc')
  101. test('find', u'abcdefghiabc', 9, u'abc', 1)
  102. test('find', u'abcdefghiabc', -1, u'def', 4)
  103.  
  104. test('rfind', u'abcdefghiabc', 9, u'abc')
  105. test('rfind', 'abcdefghiabc', 9, u'abc')
  106. test('rfind', 'abcdefghiabc', 12, u'')
  107. test('rfind', u'abcdefghiabc', 12, '')
  108. test('rfind', u'abcdefghiabc', 12, u'')
  109.  
  110. test('lower', u'HeLLo', u'hello')
  111. test('lower', u'hello', u'hello')
  112.  
  113. test('upper', u'HeLLo', u'HELLO')
  114. test('upper', u'HELLO', u'HELLO')
  115.  
  116. if 0:
  117.     transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`xyzdefghijklmnopqrstuvwxyz{|}~\177\200\201\202\203\204\205\206\207\210\211\212\213\214\215\216\217\220\221\222\223\224\225\226\227\230\231\232\233\234\235\236\237\240\241\242\243\244\245\246\247\250\251\252\253\254\255\256\257\260\261\262\263\264\265\266\267\270\271\272\273\274\275\276\277\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317\320\321\322\323\324\325\326\327\330\331\332\333\334\335\336\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356\357\360\361\362\363\364\365\366\367\370\371\372\373\374\375\376\377'
  118.  
  119.     test('maketrans', u'abc', transtable, u'xyz')
  120.     test('maketrans', u'abc', ValueError, u'xyzq')
  121.  
  122. test('split', u'this is the split function',
  123.      [u'this', u'is', u'the', u'split', u'function'])
  124. test('split', u'a|b|c|d', [u'a', u'b', u'c', u'd'], u'|')
  125. test('split', u'a|b|c|d', [u'a', u'b', u'c|d'], u'|', 2)
  126. test('split', u'a b c d', [u'a', u'b c d'], None, 1)
  127. test('split', u'a b c d', [u'a', u'b', u'c d'], None, 2)
  128. test('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 3)
  129. test('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 4)
  130. test('split', u'a b c d', [u'a b c d'], None, 0)
  131. test('split', u'a  b  c  d', [u'a', u'b', u'c  d'], None, 2)
  132. test('split', u'a b c d ', [u'a', u'b', u'c', u'd'])
  133. test('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//')
  134. test('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], '//')
  135. test('split', 'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//')
  136. test('split', u'endcase test', [u'endcase ', u''], u'test')
  137. test('split', u'endcase test', [u'endcase ', u''], 'test')
  138. test('split', 'endcase test', [u'endcase ', u''], u'test')
  139.  
  140.  
  141. # join now works with any sequence type
  142. class Sequence:
  143.     def __init__(self, seq): self.seq = seq
  144.     def __len__(self): return len(self.seq)
  145.     def __getitem__(self, i): return self.seq[i]
  146.  
  147. test('join', u' ', u'a b c d', [u'a', u'b', u'c', u'd'])
  148. test('join', u' ', u'a b c d', ['a', 'b', u'c', u'd'])
  149. test('join', u'', u'abcd', (u'a', u'b', u'c', u'd'))
  150. test('join', u' ', u'w x y z', Sequence('wxyz'))
  151. test('join', u' ', TypeError, 7)
  152. test('join', u' ', TypeError, Sequence([7, u'hello', 123L]))
  153. test('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd'])
  154. test('join', ' ', u'a b c d', ['a', 'b', u'c', u'd'])
  155. test('join', '', u'abcd', (u'a', u'b', u'c', u'd'))
  156. test('join', ' ', u'w x y z', Sequence(u'wxyz'))
  157. test('join', ' ', TypeError, 7)
  158.  
  159. result = u''
  160. for i in range(10):
  161.     if i > 0:
  162.         result = result + u':'
  163.     result = result + u'x'*10
  164. test('join', u':', result, [u'x' * 10] * 10)
  165. test('join', u':', result, (u'x' * 10,) * 10)
  166.  
  167. test('strip', u'   hello   ', u'hello')
  168. test('lstrip', u'   hello   ', u'hello   ')
  169. test('rstrip', u'   hello   ', u'   hello')
  170. test('strip', u'hello', u'hello')
  171.  
  172. # strip/lstrip/rstrip with None arg
  173. test('strip', u'   hello   ', u'hello', None)
  174. test('lstrip', u'   hello   ', u'hello   ', None)
  175. test('rstrip', u'   hello   ', u'   hello', None)
  176. test('strip', u'hello', u'hello', None)
  177.  
  178. # strip/lstrip/rstrip with unicode arg
  179. test('strip', u'xyzzyhelloxyzzy', u'hello', u'xyz')
  180. test('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', u'xyz')
  181. test('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', u'xyz')
  182. test('strip', u'hello', u'hello', u'xyz')
  183.  
  184. # strip/lstrip/rstrip with str arg
  185. test('strip', u'xyzzyhelloxyzzy', u'hello', 'xyz')
  186. test('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', 'xyz')
  187. test('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', 'xyz')
  188. test('strip', u'hello', u'hello', 'xyz')
  189.  
  190. test('swapcase', u'HeLLo cOmpUteRs', u'hEllO CoMPuTErS')
  191.  
  192. if 0:
  193.     test('translate', u'xyzabcdef', u'xyzxyz', transtable, u'def')
  194.  
  195.     table = string.maketrans('a', u'A')
  196.     test('translate', u'abc', u'Abc', table)
  197.     test('translate', u'xyz', u'xyz', table)
  198.  
  199. test('replace', u'one!two!three!', u'one@two!three!', u'!', u'@', 1)
  200. test('replace', u'one!two!three!', u'onetwothree', '!', '')
  201. test('replace', u'one!two!three!', u'one@two@three!', u'!', u'@', 2)
  202. test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 3)
  203. test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 4)
  204. test('replace', u'one!two!three!', u'one!two!three!', u'!', u'@', 0)
  205. test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@')
  206. test('replace', u'one!two!three!', u'one!two!three!', u'x', u'@')
  207. test('replace', u'one!two!three!', u'one!two!three!', u'x', u'@', 2)
  208. test('replace', u'abc', u'abc', u'ab', u'--', 0)
  209. test('replace', u'abc', u'abc', u'xy', u'--')
  210.  
  211. test('startswith', u'hello', 1, u'he')
  212. test('startswith', u'hello', 1, u'hello')
  213. test('startswith', u'hello', 0, u'hello world')
  214. test('startswith', u'hello', 1, u'')
  215. test('startswith', u'hello', 0, u'ello')
  216. test('startswith', u'hello', 1, u'ello', 1)
  217. test('startswith', u'hello', 1, u'o', 4)
  218. test('startswith', u'hello', 0, u'o', 5)
  219. test('startswith', u'hello', 1, u'', 5)
  220. test('startswith', u'hello', 0, u'lo', 6)
  221. test('startswith', u'helloworld', 1, u'lowo', 3)
  222. test('startswith', u'helloworld', 1, u'lowo', 3, 7)
  223. test('startswith', u'helloworld', 0, u'lowo', 3, 6)
  224.  
  225. test('endswith', u'hello', 1, u'lo')
  226. test('endswith', u'hello', 0, u'he')
  227. test('endswith', u'hello', 1, u'')
  228. test('endswith', u'hello', 0, u'hello world')
  229. test('endswith', u'helloworld', 0, u'worl')
  230. test('endswith', u'helloworld', 1, u'worl', 3, 9)
  231. test('endswith', u'helloworld', 1, u'world', 3, 12)
  232. test('endswith', u'helloworld', 1, u'lowo', 1, 7)
  233. test('endswith', u'helloworld', 1, u'lowo', 2, 7)
  234. test('endswith', u'helloworld', 1, u'lowo', 3, 7)
  235. test('endswith', u'helloworld', 0, u'lowo', 4, 7)
  236. test('endswith', u'helloworld', 0, u'lowo', 3, 8)
  237. test('endswith', u'ab', 0, u'ab', 0, 1)
  238. test('endswith', u'ab', 0, u'ab', 0, 0)
  239. test('endswith', 'helloworld', 1, u'd')
  240. test('endswith', 'helloworld', 0, u'l')
  241.  
  242. test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab      def\ng       hi')
  243. test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab      def\ng       hi', 8)
  244. test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab  def\ng   hi', 4)
  245. test('expandtabs', u'abc\r\nab\tdef\ng\thi', u'abc\r\nab  def\ng   hi', 4)
  246.  
  247. if 0:
  248.     test('capwords', u'abc def ghi', u'Abc Def Ghi')
  249.     test('capwords', u'abc\tdef\nghi', u'Abc Def Ghi')
  250.     test('capwords', u'abc\t   def  \nghi', u'Abc Def Ghi')
  251.  
  252. test('zfill', u'123', u'123', 2)
  253. test('zfill', u'123', u'123', 3)
  254. test('zfill', u'123', u'0123', 4)
  255. test('zfill', u'+123', u'+123', 3)
  256. test('zfill', u'+123', u'+123', 4)
  257. test('zfill', u'+123', u'+0123', 5)
  258. test('zfill', u'-123', u'-123', 3)
  259. test('zfill', u'-123', u'-123', 4)
  260. test('zfill', u'-123', u'-0123', 5)
  261. test('zfill', u'', u'000', 3)
  262. test('zfill', u'34', u'34', 1)
  263. test('zfill', u'34', u'00034', 5)
  264.  
  265. # Comparisons:
  266. print 'Testing Unicode comparisons...',
  267. verify(u'abc' == 'abc')
  268. verify('abc' == u'abc')
  269. verify(u'abc' == u'abc')
  270. verify(u'abcd' > 'abc')
  271. verify('abcd' > u'abc')
  272. verify(u'abcd' > u'abc')
  273. verify(u'abc' < 'abcd')
  274. verify('abc' < u'abcd')
  275. verify(u'abc' < u'abcd')
  276. print 'done.'
  277.  
  278. if 0:
  279.     # Move these tests to a Unicode collation module test...
  280.  
  281.     print 'Testing UTF-16 code point order comparisons...',
  282.     #No surrogates, no fixup required.
  283.     verify(u'\u0061' < u'\u20ac')
  284.     # Non surrogate below surrogate value, no fixup required
  285.     verify(u'\u0061' < u'\ud800\udc02')
  286.  
  287.     # Non surrogate above surrogate value, fixup required
  288.     def test_lecmp(s, s2):
  289.         verify(s <  s2 , "comparison failed on %s < %s" % (s, s2))
  290.  
  291.     def test_fixup(s):
  292.         s2 = u'\ud800\udc01'
  293.         test_lecmp(s, s2)
  294.         s2 = u'\ud900\udc01'
  295.         test_lecmp(s, s2)
  296.         s2 = u'\uda00\udc01'
  297.         test_lecmp(s, s2)
  298.         s2 = u'\udb00\udc01'
  299.         test_lecmp(s, s2)
  300.         s2 = u'\ud800\udd01'
  301.         test_lecmp(s, s2)
  302.         s2 = u'\ud900\udd01'
  303.         test_lecmp(s, s2)
  304.         s2 = u'\uda00\udd01'
  305.         test_lecmp(s, s2)
  306.         s2 = u'\udb00\udd01'
  307.         test_lecmp(s, s2)
  308.         s2 = u'\ud800\ude01'
  309.         test_lecmp(s, s2)
  310.         s2 = u'\ud900\ude01'
  311.         test_lecmp(s, s2)
  312.         s2 = u'\uda00\ude01'
  313.         test_lecmp(s, s2)
  314.         s2 = u'\udb00\ude01'
  315.         test_lecmp(s, s2)
  316.         s2 = u'\ud800\udfff'
  317.         test_lecmp(s, s2)
  318.         s2 = u'\ud900\udfff'
  319.         test_lecmp(s, s2)
  320.         s2 = u'\uda00\udfff'
  321.         test_lecmp(s, s2)
  322.         s2 = u'\udb00\udfff'
  323.         test_lecmp(s, s2)
  324.  
  325.     test_fixup(u'\ue000')
  326.     test_fixup(u'\uff61')
  327.  
  328.     # Surrogates on both sides, no fixup required
  329.     verify(u'\ud800\udc02' < u'\ud84d\udc56')
  330.     print 'done.'
  331.  
  332. test('ljust', u'abc',  u'abc       ', 10)
  333. test('rjust', u'abc',  u'       abc', 10)
  334. test('center', u'abc', u'   abc    ', 10)
  335. test('ljust', u'abc',  u'abc   ', 6)
  336. test('rjust', u'abc',  u'   abc', 6)
  337. test('center', u'abc', u' abc  ', 6)
  338. test('ljust', u'abc', u'abc', 2)
  339. test('rjust', u'abc', u'abc', 2)
  340. test('center', u'abc', u'abc', 2)
  341.  
  342. test('islower', u'a', 1)
  343. test('islower', u'A', 0)
  344. test('islower', u'\n', 0)
  345. test('islower', u'\u1FFc', 0)
  346. test('islower', u'abc', 1)
  347. test('islower', u'aBc', 0)
  348. test('islower', u'abc\n', 1)
  349.  
  350. test('isupper', u'a', 0)
  351. test('isupper', u'A', 1)
  352. test('isupper', u'\n', 0)
  353. if sys.platform[:4] != 'java':
  354.     test('isupper', u'\u1FFc', 0)
  355. test('isupper', u'ABC', 1)
  356. test('isupper', u'AbC', 0)
  357. test('isupper', u'ABC\n', 1)
  358.  
  359. test('istitle', u'a', 0)
  360. test('istitle', u'A', 1)
  361. test('istitle', u'\n', 0)
  362. test('istitle', u'\u1FFc', 1)
  363. test('istitle', u'A Titlecased Line', 1)
  364. test('istitle', u'A\nTitlecased Line', 1)
  365. test('istitle', u'A Titlecased, Line', 1)
  366. test('istitle', u'Greek \u1FFcitlecases ...', 1)
  367. test('istitle', u'Not a capitalized String', 0)
  368. test('istitle', u'Not\ta Titlecase String', 0)
  369. test('istitle', u'Not--a Titlecase String', 0)
  370.  
  371. test('isalpha', u'a', 1)
  372. test('isalpha', u'A', 1)
  373. test('isalpha', u'\n', 0)
  374. test('isalpha', u'\u1FFc', 1)
  375. test('isalpha', u'abc', 1)
  376. test('isalpha', u'aBc123', 0)
  377. test('isalpha', u'abc\n', 0)
  378.  
  379. test('isalnum', u'a', 1)
  380. test('isalnum', u'A', 1)
  381. test('isalnum', u'\n', 0)
  382. test('isalnum', u'123abc456', 1)
  383. test('isalnum', u'a1b3c', 1)
  384. test('isalnum', u'aBc000 ', 0)
  385. test('isalnum', u'abc\n', 0)
  386.  
  387. test('splitlines', u"abc\ndef\n\rghi", [u'abc', u'def', u'', u'ghi'])
  388. test('splitlines', u"abc\ndef\n\r\nghi", [u'abc', u'def', u'', u'ghi'])
  389. test('splitlines', u"abc\ndef\r\nghi", [u'abc', u'def', u'ghi'])
  390. test('splitlines', u"abc\ndef\r\nghi\n", [u'abc', u'def', u'ghi'])
  391. test('splitlines', u"abc\ndef\r\nghi\n\r", [u'abc', u'def', u'ghi', u''])
  392. test('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'', u'abc', u'def', u'ghi', u''])
  393. test('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'\n', u'abc\n', u'def\r\n', u'ghi\n', u'\r'], 1)
  394.  
  395. test('translate', u"abababc", u'bbbc', {ord('a'):None})
  396. test('translate', u"abababc", u'iiic', {ord('a'):None, ord('b'):ord('i')})
  397. test('translate', u"abababc", u'iiix', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'})
  398.  
  399. # Contains:
  400. print 'Testing Unicode contains method...',
  401. verify(('a' in u'abdb') == 1)
  402. verify(('a' in u'bdab') == 1)
  403. verify(('a' in u'bdaba') == 1)
  404. verify(('a' in u'bdba') == 1)
  405. verify(('a' in u'bdba') == 1)
  406. verify((u'a' in u'bdba') == 1)
  407. verify((u'a' in u'bdb') == 0)
  408. verify((u'a' in 'bdb') == 0)
  409. verify((u'a' in 'bdba') == 1)
  410. verify((u'a' in ('a',1,None)) == 1)
  411. verify((u'a' in (1,None,'a')) == 1)
  412. verify((u'a' in (1,None,u'a')) == 1)
  413. verify(('a' in ('a',1,None)) == 1)
  414. verify(('a' in (1,None,'a')) == 1)
  415. verify(('a' in (1,None,u'a')) == 1)
  416. verify(('a' in ('x',1,u'y')) == 0)
  417. verify(('a' in ('x',1,None)) == 0)
  418. print 'done.'
  419.  
  420. # Formatting:
  421. print 'Testing Unicode formatting strings...',
  422. verify(u"%s, %s" % (u"abc", "abc") == u'abc, abc')
  423. verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, 2, 3) == u'abc, abc, 1, 2.000000,  3.00')
  424. verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, -2, 3) == u'abc, abc, 1, -2.000000,  3.00')
  425. verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.5) == u'abc, abc, -1, -2.000000,  3.50')
  426. verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57) == u'abc, abc, -1, -2.000000,  3.57')
  427. verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57) == u'abc, abc, -1, -2.000000, 1003.57')
  428. verify(u"%c" % (u"a",) == u'a')
  429. verify(u"%c" % ("a",) == u'a')
  430. verify(u"%c" % (34,) == u'"')
  431. verify(u"%c" % (36,) == u'$')
  432. if sys.platform[:4] != 'java':
  433.     value = u"%r, %r" % (u"abc", "abc")
  434.     if value != u"u'abc', 'abc'":
  435.         print '*** formatting failed for "%s"' % 'u"%r, %r" % (u"abc", "abc")'
  436.  
  437. verify(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"} == u'abc, def')
  438. try:
  439.     value = u"%(x)s, %(Σ)s" % {'x':u"abc", u'Σ':"def"}
  440. except KeyError:
  441.     print '*** formatting failed for "%s"' % "u'abc, def'"
  442. else:
  443.     verify(value == u'abc, def')
  444.  
  445. for ordinal in (-100, 0x200000):
  446.     try:
  447.         u"%c" % ordinal
  448.     except ValueError:
  449.         pass
  450.     else:
  451.         print '*** formatting u"%%c" %% %i should give a ValueError' % ordinal
  452.  
  453. # formatting jobs delegated from the string implementation:
  454. verify('...%(foo)s...' % {'foo':u"abc"} == u'...abc...')
  455. verify('...%(foo)s...' % {'foo':"abc"} == '...abc...')
  456. verify('...%(foo)s...' % {u'foo':"abc"} == '...abc...')
  457. verify('...%(foo)s...' % {u'foo':u"abc"} == u'...abc...')
  458. verify('...%(foo)s...' % {u'foo':u"abc",'def':123} ==  u'...abc...')
  459. verify('...%(foo)s...' % {u'foo':u"abc",u'def':123} == u'...abc...')
  460. verify('...%s...%s...%s...%s...' % (1,2,3,u"abc") == u'...1...2...3...abc...')
  461. verify('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,u"abc") == u'...%...%s...1...2...3...abc...')
  462. verify('...%s...' % u"abc" == u'...abc...')
  463. verify('%*s' % (5,u'abc',) == u'  abc')
  464. verify('%*s' % (-5,u'abc',) == u'abc  ')
  465. verify('%*.*s' % (5,2,u'abc',) == u'   ab')
  466. verify('%*.*s' % (5,3,u'abc',) == u'  abc')
  467. verify('%i %*.*s' % (10, 5,3,u'abc',) == u'10   abc')
  468. verify('%i%s %*.*s' % (10, 3, 5,3,u'abc',) == u'103   abc')
  469. print 'done.'
  470.  
  471. print 'Testing builtin unicode()...',
  472.  
  473. # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
  474.  
  475. verify(unicode(u'unicode remains unicode') == u'unicode remains unicode')
  476.  
  477. class UnicodeSubclass(unicode):
  478.     pass
  479.  
  480. verify(unicode(UnicodeSubclass('unicode subclass becomes unicode'))
  481.        == u'unicode subclass becomes unicode')
  482.  
  483. verify(unicode('strings are converted to unicode')
  484.        == u'strings are converted to unicode')
  485.  
  486. class UnicodeCompat:
  487.     def __init__(self, x):
  488.         self.x = x
  489.     def __unicode__(self):
  490.         return self.x
  491.  
  492. verify(unicode(UnicodeCompat('__unicode__ compatible objects are recognized'))
  493.        == u'__unicode__ compatible objects are recognized')
  494.  
  495. class StringCompat:
  496.     def __init__(self, x):
  497.         self.x = x
  498.     def __str__(self):
  499.         return self.x
  500.  
  501. verify(unicode(StringCompat('__str__ compatible objects are recognized'))
  502.        == u'__str__ compatible objects are recognized')
  503.  
  504. # unicode(obj) is compatible to str():
  505.  
  506. o = StringCompat('unicode(obj) is compatible to str()')
  507. verify(unicode(o) == u'unicode(obj) is compatible to str()')
  508. verify(str(o) == 'unicode(obj) is compatible to str()')
  509.  
  510. for obj in (123, 123.45, 123L):
  511.     verify(unicode(obj) == unicode(str(obj)))
  512.  
  513. # unicode(obj, encoding, error) tests (this maps to
  514. # PyUnicode_FromEncodedObject() at C level)
  515.  
  516. if not sys.platform.startswith('java'):
  517.     try:
  518.         unicode(u'decoding unicode is not supported', 'utf-8', 'strict')
  519.     except TypeError:
  520.         pass
  521.     else:
  522.         raise TestFailed, "decoding unicode should NOT be supported"
  523.  
  524. verify(unicode('strings are decoded to unicode', 'utf-8', 'strict')
  525.        == u'strings are decoded to unicode')
  526.  
  527. if not sys.platform.startswith('java'):
  528.     verify(unicode(buffer('character buffers are decoded to unicode'),
  529.                    'utf-8', 'strict')
  530.            == u'character buffers are decoded to unicode')
  531.  
  532. print 'done.'
  533.  
  534. # Test builtin codecs
  535. print 'Testing builtin codecs...',
  536.  
  537. # UTF-7 specific encoding tests:
  538. utfTests = [(u'A\u2262\u0391.', 'A+ImIDkQ.'),  # RFC2152 example
  539.  (u'Hi Mom -\u263a-!', 'Hi Mom -+Jjo--!'),     # RFC2152 example
  540.  (u'\u65E5\u672C\u8A9E', '+ZeVnLIqe-'),        # RFC2152 example
  541.  (u'Item 3 is \u00a31.', 'Item 3 is +AKM-1.'), # RFC2152 example
  542.  (u'+', '+-'),
  543.  (u'+-', '+--'),
  544.  (u'+?', '+-?'),
  545.  (u'\?', '+AFw?'),
  546.  (u'+?', '+-?'),
  547.  (ur'\\?', '+AFwAXA?'),
  548.  (ur'\\\?', '+AFwAXABc?'),
  549.  (ur'++--', '+-+---')]
  550.  
  551. for x,y in utfTests:
  552.     verify( x.encode('utf-7') == y )
  553.  
  554. try:
  555.     unicode('+3ADYAA-', 'utf-7') # surrogates not supported
  556. except UnicodeError:
  557.     pass
  558. else:
  559.     raise TestFailed, "unicode('+3ADYAA-', 'utf-7') failed to raise an exception"
  560.  
  561. verify(unicode('+3ADYAA-', 'utf-7', 'replace') == u'\ufffd')
  562.  
  563. # UTF-8 specific encoding tests:
  564. verify(u''.encode('utf-8') == '')
  565. verify(u'\u20ac'.encode('utf-8') == '\xe2\x82\xac')
  566. verify(u'\ud800\udc02'.encode('utf-8') == '\xf0\x90\x80\x82')
  567. verify(u'\ud84d\udc56'.encode('utf-8') == '\xf0\xa3\x91\x96')
  568. verify(u'\ud800'.encode('utf-8') == '\xed\xa0\x80')
  569. verify(u'\udc00'.encode('utf-8') == '\xed\xb0\x80')
  570. verify((u'\ud800\udc02'*1000).encode('utf-8') ==
  571.        '\xf0\x90\x80\x82'*1000)
  572. verify(u'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
  573.        u'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
  574.        u'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
  575.        u'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
  576.        u'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
  577.        u' Nunstuck git und'.encode('utf-8') ==
  578.        '\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
  579.        '\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
  580.        '\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
  581.        '\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
  582.        '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
  583.        '\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
  584.        '\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
  585.        '\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
  586.        '\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
  587.        '\xe3\x80\x8cWenn ist das Nunstuck git und')
  588.  
  589. # UTF-8 specific decoding tests
  590. verify(unicode('\xf0\xa3\x91\x96', 'utf-8') == u'\U00023456' )
  591. verify(unicode('\xf0\x90\x80\x82', 'utf-8') == u'\U00010002' )
  592. verify(unicode('\xe2\x82\xac', 'utf-8') == u'\u20ac' )
  593. # test UTF-8 2.2.1 bug work-around
  594. verify(unicode('\xa0\x80', 'utf-8') == u'\ud800' )
  595. verify(unicode('\xaf\xbf', 'utf-8') == u'\udbff' )
  596. verify(unicode('\xed\xb0\x80', 'utf-8') == u'\udc00' )
  597. verify(unicode('\xed\xbf\xbf', 'utf-8') == u'\udfff' )
  598.  
  599. # Other possible utf-8 test cases:
  600. # * strict decoding testing for all of the
  601. #   UTF8_ERROR cases in PyUnicode_DecodeUTF8
  602.  
  603. verify(unicode('hello','ascii') == u'hello')
  604. verify(unicode('hello','utf-8') == u'hello')
  605. verify(unicode('hello','utf8') == u'hello')
  606. verify(unicode('hello','latin-1') == u'hello')
  607.  
  608. # Error handling
  609. try:
  610.     u'Andr\202 x'.encode('ascii')
  611.     u'Andr\202 x'.encode('ascii','strict')
  612. except ValueError:
  613.     pass
  614. else:
  615.     raise TestFailed, "u'Andr\202'.encode('ascii') failed to raise an exception"
  616. verify(u'Andr\202 x'.encode('ascii','ignore') == "Andr x")
  617. verify(u'Andr\202 x'.encode('ascii','replace') == "Andr? x")
  618.  
  619. try:
  620.     unicode('Andr\202 x','ascii')
  621.     unicode('Andr\202 x','ascii','strict')
  622. except ValueError:
  623.     pass
  624. else:
  625.     raise TestFailed, "unicode('Andr\202') failed to raise an exception"
  626. verify(unicode('Andr\202 x','ascii','ignore') == u"Andr x")
  627. verify(unicode('Andr\202 x','ascii','replace') == u'Andr\uFFFD x')
  628.  
  629. verify("\\N{foo}xx".decode("unicode-escape", "ignore") == u"xx")
  630. try:
  631.     "\\".decode("unicode-escape")
  632. except ValueError:
  633.     pass
  634. else:
  635.     raise TestFailed, '"\\".decode("unicode-escape") should fail'
  636.  
  637. verify(u'hello'.encode('ascii') == 'hello')
  638. verify(u'hello'.encode('utf-7') == 'hello')
  639. verify(u'hello'.encode('utf-8') == 'hello')
  640. verify(u'hello'.encode('utf8') == 'hello')
  641. verify(u'hello'.encode('utf-16-le') == 'h\000e\000l\000l\000o\000')
  642. verify(u'hello'.encode('utf-16-be') == '\000h\000e\000l\000l\000o')
  643. verify(u'hello'.encode('latin-1') == 'hello')
  644.  
  645. # Roundtrip safety for BMP (just the first 1024 chars)
  646. u = u''.join(map(unichr, range(1024)))
  647. for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
  648.                  'raw_unicode_escape', 'unicode_escape', 'unicode_internal'):
  649.     verify(unicode(u.encode(encoding),encoding) == u)
  650.  
  651. # Roundtrip safety for non-BMP (just a few chars)
  652. u = u'\U00010001\U00020002\U00030003\U00040004\U00050005'
  653. for encoding in ('utf-8',
  654.                  'utf-16', 'utf-16-le', 'utf-16-be',
  655.                  #'raw_unicode_escape',
  656.                  'unicode_escape', 'unicode_internal'):
  657.     verify(unicode(u.encode(encoding),encoding) == u)
  658.  
  659. u = u''.join(map(unichr, range(256)))
  660. for encoding in (
  661.     'latin-1',
  662.     ):
  663.     try:
  664.         verify(unicode(u.encode(encoding),encoding) == u)
  665.     except TestFailed:
  666.         print '*** codec "%s" failed round-trip' % encoding
  667.     except ValueError,why:
  668.         print '*** codec for "%s" failed: %s' % (encoding, why)
  669.  
  670. u = u''.join(map(unichr, range(128)))
  671. for encoding in (
  672.     'ascii',
  673.     ):
  674.     try:
  675.         verify(unicode(u.encode(encoding),encoding) == u)
  676.     except TestFailed:
  677.         print '*** codec "%s" failed round-trip' % encoding
  678.     except ValueError,why:
  679.         print '*** codec for "%s" failed: %s' % (encoding, why)
  680.  
  681. print 'done.'
  682.  
  683. print 'Testing standard mapping codecs...',
  684.  
  685. print '0-127...',
  686. s = ''.join(map(chr, range(128)))
  687. for encoding in (
  688.     'cp037', 'cp1026',
  689.     'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
  690.     'cp852', 'cp855', 'cp860', 'cp861', 'cp862',
  691.     'cp863', 'cp865', 'cp866',
  692.     'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
  693.     'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
  694.     'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
  695.     'mac_cyrillic', 'mac_latin2',
  696.  
  697.     'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
  698.     'cp1256', 'cp1257', 'cp1258',
  699.     'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
  700.  
  701.     'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
  702.     'cp1006', 'iso8859_8',
  703.  
  704.     ### These have undefined mappings:
  705.     #'cp424',
  706.  
  707.     ### These fail the round-trip:
  708.     #'cp875'
  709.  
  710.     ):
  711.     try:
  712.         verify(unicode(s,encoding).encode(encoding) == s)
  713.     except TestFailed:
  714.         print '*** codec "%s" failed round-trip' % encoding
  715.     except ValueError,why:
  716.         print '*** codec for "%s" failed: %s' % (encoding, why)
  717.  
  718. print '128-255...',
  719. s = ''.join(map(chr, range(128,256)))
  720. for encoding in (
  721.     'cp037', 'cp1026',
  722.     'cp437', 'cp500', 'cp737', 'cp775', 'cp850',
  723.     'cp852', 'cp855', 'cp860', 'cp861', 'cp862',
  724.     'cp863', 'cp865', 'cp866',
  725.     'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
  726.     'iso8859_2', 'iso8859_4', 'iso8859_5',
  727.     'iso8859_9', 'koi8_r', 'latin_1',
  728.     'mac_cyrillic', 'mac_latin2',
  729.  
  730.     ### These have undefined mappings:
  731.     #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
  732.     #'cp1256', 'cp1257', 'cp1258',
  733.     #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
  734.     #'iso8859_3', 'iso8859_6', 'iso8859_7',
  735.     #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
  736.  
  737.     ### These fail the round-trip:
  738.     #'cp1006', 'cp875', 'iso8859_8',
  739.  
  740.     ):
  741.     try:
  742.         verify(unicode(s,encoding).encode(encoding) == s)
  743.     except TestFailed:
  744.         print '*** codec "%s" failed round-trip' % encoding
  745.     except ValueError,why:
  746.         print '*** codec for "%s" failed: %s' % (encoding, why)
  747.  
  748. # UTF-8 must be roundtrip safe for all UCS-2 code points
  749. # This excludes surrogates: in the full range, there would be
  750. # a surrogate pair (\udbff\udc00), which gets converted back
  751. # to a non-BMP character (\U0010fc00)
  752. u = u''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000)))
  753. for encoding in ('utf-8',):
  754.     verify(unicode(u.encode(encoding),encoding) == u)
  755.  
  756. print 'done.'
  757.  
  758. print 'Testing Unicode string concatenation...',
  759. verify((u"abc" u"def") == u"abcdef")
  760. verify(("abc" u"def") == u"abcdef")
  761. verify((u"abc" "def") == u"abcdef")
  762. verify((u"abc" u"def" "ghi") == u"abcdefghi")
  763. verify(("abc" "def" u"ghi") == u"abcdefghi")
  764. print 'done.'
  765.  
  766. print 'Testing Unicode printing...',
  767. print u'abc'
  768. print u'abc', u'def'
  769. print u'abc', 'def'
  770. print 'abc', u'def'
  771. print u'abc\n'
  772. print u'abc\n',
  773. print u'abc\n',
  774. print u'def\n'
  775. print u'def\n'
  776. print 'done.'
  777.