test_unicodedata.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. """ Tests for the unicodedata module.
  2. Written by Marc-Andre Lemburg (mal@lemburg.com).
  3. (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
  4. """
  5. import hashlib
  6. from http.client import HTTPException
  7. import sys
  8. import unicodedata
  9. import unittest
  10. from test.support import (open_urlresource, requires_resource, script_helper,
  11. cpython_only, check_disallow_instantiation,
  12. ResourceDenied)
  13. class UnicodeMethodsTest(unittest.TestCase):
  14. # update this, if the database changes
  15. expectedchecksum = '4739770dd4d0e5f1b1677accfc3552ed3c8ef326'
  16. @requires_resource('cpu')
  17. def test_method_checksum(self):
  18. h = hashlib.sha1()
  19. for i in range(sys.maxunicode + 1):
  20. char = chr(i)
  21. data = [
  22. # Predicates (single char)
  23. "01"[char.isalnum()],
  24. "01"[char.isalpha()],
  25. "01"[char.isdecimal()],
  26. "01"[char.isdigit()],
  27. "01"[char.islower()],
  28. "01"[char.isnumeric()],
  29. "01"[char.isspace()],
  30. "01"[char.istitle()],
  31. "01"[char.isupper()],
  32. # Predicates (multiple chars)
  33. "01"[(char + 'abc').isalnum()],
  34. "01"[(char + 'abc').isalpha()],
  35. "01"[(char + '123').isdecimal()],
  36. "01"[(char + '123').isdigit()],
  37. "01"[(char + 'abc').islower()],
  38. "01"[(char + '123').isnumeric()],
  39. "01"[(char + ' \t').isspace()],
  40. "01"[(char + 'abc').istitle()],
  41. "01"[(char + 'ABC').isupper()],
  42. # Mappings (single char)
  43. char.lower(),
  44. char.upper(),
  45. char.title(),
  46. # Mappings (multiple chars)
  47. (char + 'abc').lower(),
  48. (char + 'ABC').upper(),
  49. (char + 'abc').title(),
  50. (char + 'ABC').title(),
  51. ]
  52. h.update(''.join(data).encode('utf-8', 'surrogatepass'))
  53. result = h.hexdigest()
  54. self.assertEqual(result, self.expectedchecksum)
  55. class UnicodeDatabaseTest(unittest.TestCase):
  56. db = unicodedata
  57. class UnicodeFunctionsTest(UnicodeDatabaseTest):
  58. # Update this if the database changes. Make sure to do a full rebuild
  59. # (e.g. 'make distclean && make') to get the correct checksum.
  60. expectedchecksum = '98d602e1f69d5c5bb8a5910c40bbbad4e18e8370'
  61. @requires_resource('cpu')
  62. def test_function_checksum(self):
  63. data = []
  64. h = hashlib.sha1()
  65. for i in range(sys.maxunicode + 1):
  66. char = chr(i)
  67. data = [
  68. # Properties
  69. format(self.db.digit(char, -1), '.12g'),
  70. format(self.db.numeric(char, -1), '.12g'),
  71. format(self.db.decimal(char, -1), '.12g'),
  72. self.db.category(char),
  73. self.db.bidirectional(char),
  74. self.db.decomposition(char),
  75. str(self.db.mirrored(char)),
  76. str(self.db.combining(char)),
  77. ]
  78. h.update(''.join(data).encode("ascii"))
  79. result = h.hexdigest()
  80. self.assertEqual(result, self.expectedchecksum)
  81. @requires_resource('cpu')
  82. def test_name_inverse_lookup(self):
  83. for i in range(sys.maxunicode + 1):
  84. char = chr(i)
  85. if looked_name := self.db.name(char, None):
  86. self.assertEqual(self.db.lookup(looked_name), char)
  87. def test_digit(self):
  88. self.assertEqual(self.db.digit('A', None), None)
  89. self.assertEqual(self.db.digit('9'), 9)
  90. self.assertEqual(self.db.digit('\u215b', None), None)
  91. self.assertEqual(self.db.digit('\u2468'), 9)
  92. self.assertEqual(self.db.digit('\U00020000', None), None)
  93. self.assertEqual(self.db.digit('\U0001D7FD'), 7)
  94. self.assertRaises(TypeError, self.db.digit)
  95. self.assertRaises(TypeError, self.db.digit, 'xx')
  96. self.assertRaises(ValueError, self.db.digit, 'x')
  97. def test_numeric(self):
  98. self.assertEqual(self.db.numeric('A',None), None)
  99. self.assertEqual(self.db.numeric('9'), 9)
  100. self.assertEqual(self.db.numeric('\u215b'), 0.125)
  101. self.assertEqual(self.db.numeric('\u2468'), 9.0)
  102. self.assertEqual(self.db.numeric('\ua627'), 7.0)
  103. self.assertEqual(self.db.numeric('\U00020000', None), None)
  104. self.assertEqual(self.db.numeric('\U0001012A'), 9000)
  105. self.assertRaises(TypeError, self.db.numeric)
  106. self.assertRaises(TypeError, self.db.numeric, 'xx')
  107. self.assertRaises(ValueError, self.db.numeric, 'x')
  108. def test_decimal(self):
  109. self.assertEqual(self.db.decimal('A',None), None)
  110. self.assertEqual(self.db.decimal('9'), 9)
  111. self.assertEqual(self.db.decimal('\u215b', None), None)
  112. self.assertEqual(self.db.decimal('\u2468', None), None)
  113. self.assertEqual(self.db.decimal('\U00020000', None), None)
  114. self.assertEqual(self.db.decimal('\U0001D7FD'), 7)
  115. self.assertRaises(TypeError, self.db.decimal)
  116. self.assertRaises(TypeError, self.db.decimal, 'xx')
  117. self.assertRaises(ValueError, self.db.decimal, 'x')
  118. def test_category(self):
  119. self.assertEqual(self.db.category('\uFFFE'), 'Cn')
  120. self.assertEqual(self.db.category('a'), 'Ll')
  121. self.assertEqual(self.db.category('A'), 'Lu')
  122. self.assertEqual(self.db.category('\U00020000'), 'Lo')
  123. self.assertEqual(self.db.category('\U0001012A'), 'No')
  124. self.assertRaises(TypeError, self.db.category)
  125. self.assertRaises(TypeError, self.db.category, 'xx')
  126. def test_bidirectional(self):
  127. self.assertEqual(self.db.bidirectional('\uFFFE'), '')
  128. self.assertEqual(self.db.bidirectional(' '), 'WS')
  129. self.assertEqual(self.db.bidirectional('A'), 'L')
  130. self.assertEqual(self.db.bidirectional('\U00020000'), 'L')
  131. self.assertRaises(TypeError, self.db.bidirectional)
  132. self.assertRaises(TypeError, self.db.bidirectional, 'xx')
  133. def test_decomposition(self):
  134. self.assertEqual(self.db.decomposition('\uFFFE'),'')
  135. self.assertEqual(self.db.decomposition('\u00bc'), '<fraction> 0031 2044 0034')
  136. self.assertRaises(TypeError, self.db.decomposition)
  137. self.assertRaises(TypeError, self.db.decomposition, 'xx')
  138. def test_mirrored(self):
  139. self.assertEqual(self.db.mirrored('\uFFFE'), 0)
  140. self.assertEqual(self.db.mirrored('a'), 0)
  141. self.assertEqual(self.db.mirrored('\u2201'), 1)
  142. self.assertEqual(self.db.mirrored('\U00020000'), 0)
  143. self.assertRaises(TypeError, self.db.mirrored)
  144. self.assertRaises(TypeError, self.db.mirrored, 'xx')
  145. def test_combining(self):
  146. self.assertEqual(self.db.combining('\uFFFE'), 0)
  147. self.assertEqual(self.db.combining('a'), 0)
  148. self.assertEqual(self.db.combining('\u20e1'), 230)
  149. self.assertEqual(self.db.combining('\U00020000'), 0)
  150. self.assertRaises(TypeError, self.db.combining)
  151. self.assertRaises(TypeError, self.db.combining, 'xx')
  152. def test_pr29(self):
  153. # https://www.unicode.org/review/pr-29.html
  154. # See issues #1054943 and #10254.
  155. composed = ("\u0b47\u0300\u0b3e", "\u1100\u0300\u1161",
  156. 'Li\u030dt-s\u1e73\u0301',
  157. '\u092e\u093e\u0930\u094d\u0915 \u091c\u093c'
  158. + '\u0941\u0915\u0947\u0930\u092c\u0930\u094d\u0917',
  159. '\u0915\u093f\u0930\u094d\u0917\u093f\u091c\u093c'
  160. + '\u0938\u094d\u0924\u093e\u0928')
  161. for text in composed:
  162. self.assertEqual(self.db.normalize('NFC', text), text)
  163. def test_issue10254(self):
  164. # Crash reported in #10254
  165. a = 'C\u0338' * 20 + 'C\u0327'
  166. b = 'C\u0338' * 20 + '\xC7'
  167. self.assertEqual(self.db.normalize('NFC', a), b)
  168. def test_issue29456(self):
  169. # Fix #29456
  170. u1176_str_a = '\u1100\u1176\u11a8'
  171. u1176_str_b = '\u1100\u1176\u11a8'
  172. u11a7_str_a = '\u1100\u1175\u11a7'
  173. u11a7_str_b = '\uae30\u11a7'
  174. u11c3_str_a = '\u1100\u1175\u11c3'
  175. u11c3_str_b = '\uae30\u11c3'
  176. self.assertEqual(self.db.normalize('NFC', u1176_str_a), u1176_str_b)
  177. self.assertEqual(self.db.normalize('NFC', u11a7_str_a), u11a7_str_b)
  178. self.assertEqual(self.db.normalize('NFC', u11c3_str_a), u11c3_str_b)
  179. def test_east_asian_width(self):
  180. eaw = self.db.east_asian_width
  181. self.assertRaises(TypeError, eaw, b'a')
  182. self.assertRaises(TypeError, eaw, bytearray())
  183. self.assertRaises(TypeError, eaw, '')
  184. self.assertRaises(TypeError, eaw, 'ra')
  185. self.assertEqual(eaw('\x1e'), 'N')
  186. self.assertEqual(eaw('\x20'), 'Na')
  187. self.assertEqual(eaw('\uC894'), 'W')
  188. self.assertEqual(eaw('\uFF66'), 'H')
  189. self.assertEqual(eaw('\uFF1F'), 'F')
  190. self.assertEqual(eaw('\u2010'), 'A')
  191. self.assertEqual(eaw('\U00020000'), 'W')
  192. def test_east_asian_width_9_0_changes(self):
  193. self.assertEqual(self.db.ucd_3_2_0.east_asian_width('\u231a'), 'N')
  194. self.assertEqual(self.db.east_asian_width('\u231a'), 'W')
  195. class UnicodeMiscTest(UnicodeDatabaseTest):
  196. @cpython_only
  197. def test_disallow_instantiation(self):
  198. # Ensure that the type disallows instantiation (bpo-43916)
  199. check_disallow_instantiation(self, unicodedata.UCD)
  200. def test_failed_import_during_compiling(self):
  201. # Issue 4367
  202. # Decoding \N escapes requires the unicodedata module. If it can't be
  203. # imported, we shouldn't segfault.
  204. # This program should raise a SyntaxError in the eval.
  205. code = "import sys;" \
  206. "sys.modules['unicodedata'] = None;" \
  207. """eval("'\\\\N{SOFT HYPHEN}'")"""
  208. # We use a separate process because the unicodedata module may already
  209. # have been loaded in this process.
  210. result = script_helper.assert_python_failure("-c", code)
  211. error = "SyntaxError: (unicode error) \\N escapes not supported " \
  212. "(can't load unicodedata module)"
  213. self.assertIn(error, result.err.decode("ascii"))
  214. def test_decimal_numeric_consistent(self):
  215. # Test that decimal and numeric are consistent,
  216. # i.e. if a character has a decimal value,
  217. # its numeric value should be the same.
  218. count = 0
  219. for i in range(0x10000):
  220. c = chr(i)
  221. dec = self.db.decimal(c, -1)
  222. if dec != -1:
  223. self.assertEqual(dec, self.db.numeric(c))
  224. count += 1
  225. self.assertTrue(count >= 10) # should have tested at least the ASCII digits
  226. def test_digit_numeric_consistent(self):
  227. # Test that digit and numeric are consistent,
  228. # i.e. if a character has a digit value,
  229. # its numeric value should be the same.
  230. count = 0
  231. for i in range(0x10000):
  232. c = chr(i)
  233. dec = self.db.digit(c, -1)
  234. if dec != -1:
  235. self.assertEqual(dec, self.db.numeric(c))
  236. count += 1
  237. self.assertTrue(count >= 10) # should have tested at least the ASCII digits
  238. def test_bug_1704793(self):
  239. self.assertEqual(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346')
  240. def test_ucd_510(self):
  241. import unicodedata
  242. # In UCD 5.1.0, a mirrored property changed wrt. UCD 3.2.0
  243. self.assertTrue(unicodedata.mirrored("\u0f3a"))
  244. self.assertTrue(not unicodedata.ucd_3_2_0.mirrored("\u0f3a"))
  245. # Also, we now have two ways of representing
  246. # the upper-case mapping: as delta, or as absolute value
  247. self.assertTrue("a".upper()=='A')
  248. self.assertTrue("\u1d79".upper()=='\ua77d')
  249. self.assertTrue(".".upper()=='.')
  250. def test_bug_5828(self):
  251. self.assertEqual("\u1d79".lower(), "\u1d79")
  252. # Only U+0000 should have U+0000 as its upper/lower/titlecase variant
  253. self.assertEqual(
  254. [
  255. c for c in range(sys.maxunicode+1)
  256. if "\x00" in chr(c).lower()+chr(c).upper()+chr(c).title()
  257. ],
  258. [0]
  259. )
  260. def test_bug_4971(self):
  261. # LETTER DZ WITH CARON: DZ, Dz, dz
  262. self.assertEqual("\u01c4".title(), "\u01c5")
  263. self.assertEqual("\u01c5".title(), "\u01c5")
  264. self.assertEqual("\u01c6".title(), "\u01c5")
  265. def test_linebreak_7643(self):
  266. for i in range(0x10000):
  267. lines = (chr(i) + 'A').splitlines()
  268. if i in (0x0a, 0x0b, 0x0c, 0x0d, 0x85,
  269. 0x1c, 0x1d, 0x1e, 0x2028, 0x2029):
  270. self.assertEqual(len(lines), 2,
  271. r"\u%.4x should be a linebreak" % i)
  272. else:
  273. self.assertEqual(len(lines), 1,
  274. r"\u%.4x should not be a linebreak" % i)
  275. class NormalizationTest(unittest.TestCase):
  276. @staticmethod
  277. def check_version(testfile):
  278. hdr = testfile.readline()
  279. return unicodedata.unidata_version in hdr
  280. @staticmethod
  281. def unistr(data):
  282. data = [int(x, 16) for x in data.split(" ")]
  283. return "".join([chr(x) for x in data])
  284. @requires_resource('network')
  285. def test_normalization(self):
  286. TESTDATAFILE = "NormalizationTest.txt"
  287. TESTDATAURL = f"http://www.pythontest.net/unicode/{unicodedata.unidata_version}/{TESTDATAFILE}"
  288. # Hit the exception early
  289. try:
  290. testdata = open_urlresource(TESTDATAURL, encoding="utf-8",
  291. check=self.check_version)
  292. except PermissionError:
  293. self.skipTest(f"Permission error when downloading {TESTDATAURL} "
  294. f"into the test data directory")
  295. except (OSError, HTTPException) as exc:
  296. self.skipTest(f"Failed to download {TESTDATAURL}: {exc}")
  297. with testdata:
  298. self.run_normalization_tests(testdata)
  299. def run_normalization_tests(self, testdata):
  300. part = None
  301. part1_data = {}
  302. def NFC(str):
  303. return unicodedata.normalize("NFC", str)
  304. def NFKC(str):
  305. return unicodedata.normalize("NFKC", str)
  306. def NFD(str):
  307. return unicodedata.normalize("NFD", str)
  308. def NFKD(str):
  309. return unicodedata.normalize("NFKD", str)
  310. for line in testdata:
  311. if '#' in line:
  312. line = line.split('#')[0]
  313. line = line.strip()
  314. if not line:
  315. continue
  316. if line.startswith("@Part"):
  317. part = line.split()[0]
  318. continue
  319. c1,c2,c3,c4,c5 = [self.unistr(x) for x in line.split(';')[:-1]]
  320. # Perform tests
  321. self.assertTrue(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
  322. self.assertTrue(c4 == NFC(c4) == NFC(c5), line)
  323. self.assertTrue(c3 == NFD(c1) == NFD(c2) == NFD(c3), line)
  324. self.assertTrue(c5 == NFD(c4) == NFD(c5), line)
  325. self.assertTrue(c4 == NFKC(c1) == NFKC(c2) == \
  326. NFKC(c3) == NFKC(c4) == NFKC(c5),
  327. line)
  328. self.assertTrue(c5 == NFKD(c1) == NFKD(c2) == \
  329. NFKD(c3) == NFKD(c4) == NFKD(c5),
  330. line)
  331. self.assertTrue(unicodedata.is_normalized("NFC", c2))
  332. self.assertTrue(unicodedata.is_normalized("NFC", c4))
  333. self.assertTrue(unicodedata.is_normalized("NFD", c3))
  334. self.assertTrue(unicodedata.is_normalized("NFD", c5))
  335. self.assertTrue(unicodedata.is_normalized("NFKC", c4))
  336. self.assertTrue(unicodedata.is_normalized("NFKD", c5))
  337. # Record part 1 data
  338. if part == "@Part1":
  339. part1_data[c1] = 1
  340. # Perform tests for all other data
  341. for c in range(sys.maxunicode+1):
  342. X = chr(c)
  343. if X in part1_data:
  344. continue
  345. self.assertTrue(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)
  346. def test_edge_cases(self):
  347. self.assertRaises(TypeError, unicodedata.normalize)
  348. self.assertRaises(ValueError, unicodedata.normalize, 'unknown', 'xx')
  349. self.assertEqual(unicodedata.normalize('NFKC', ''), '')
  350. def test_bug_834676(self):
  351. # Check for bug 834676
  352. unicodedata.normalize('NFC', '\ud55c\uae00')
  353. if __name__ == "__main__":
  354. unittest.main()