Debian Codegraph @

Lib/test/test_ucn.py

raw
1 """ Test script for the Unicode implementation.
2
3 Written by Bill Tutt.
4 Modified for Python 2.0 by Fredrik Lundh ([email protected])
5
6 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
7
8 """#"
9
10 import ast
11 import unittest
12 import unicodedata
13 import urllib.error
14
15 from test import support
16 from http.client import HTTPException
17
18 try:
19 from _testcapi import INT_MAX, PY_SSIZE_T_MAX, UINT_MAX
20 except ImportError:
21 INT_MAX = PY_SSIZE_T_MAX = UINT_MAX = 2**64 - 1
22
23 class UnicodeNamesTest(unittest.TestCase):
24
25 def checkletter(self, name, code):
26 # Helper that put all \N escapes inside eval'd raw strings,
27 # to make sure this script runs even if the compiler
28 # chokes on \N escapes
29 res = ast.literal_eval(r'"\N{%s}"' % name)
30 self.assertEqual(res, code)
31 return res
32
33 def test_general(self):
34 # General and case insensitivity test:
35 chars = [
36 "LATIN CAPITAL LETTER T",
37 "LATIN SMALL LETTER H",
38 "LATIN SMALL LETTER E",
39 "SPACE",
40 "LATIN SMALL LETTER R",
41 "LATIN CAPITAL LETTER E",
42 "LATIN SMALL LETTER D",
43 "SPACE",
44 "LATIN SMALL LETTER f",
45 "LATIN CAPITAL LeTtEr o",
46 "LATIN SMaLl LETTER x",
47 "SPACE",
48 "LATIN SMALL LETTER A",
49 "LATIN SMALL LETTER T",
50 "LATIN SMALL LETTER E",
51 "SPACE",
52 "LATIN SMALL LETTER T",
53 "LATIN SMALL LETTER H",
54 "LATIN SMALL LETTER E",
55 "SpAcE",
56 "LATIN SMALL LETTER S",
57 "LATIN SMALL LETTER H",
58 "LATIN small LETTER e",
59 "LATIN small LETTER e",
60 "LATIN SMALL LETTER P",
61 "FULL STOP"
62 ]
63 string = "The rEd fOx ate the sheep."
64
65 self.assertEqual(
66 "".join([self.checkletter(*args) for args in zip(chars, string)]),
67 string
68 )
69
70 def test_ascii_letters(self):
71 for char in "".join(map(chr, range(ord("a"), ord("z")))):
72 name = "LATIN SMALL LETTER %s" % char.upper()
73 code = unicodedata.lookup(name)
74 self.assertEqual(unicodedata.name(code), name)
75
76 def test_hangul_syllables(self):
77 self.checkletter("HANGUL SYLLABLE GA", "\uac00")
78 self.checkletter("HANGUL SYLLABLE GGWEOSS", "\uafe8")
79 self.checkletter("HANGUL SYLLABLE DOLS", "\ub3d0")
80 self.checkletter("HANGUL SYLLABLE RYAN", "\ub7b8")
81 self.checkletter("HANGUL SYLLABLE MWIK", "\ubba0")
82 self.checkletter("HANGUL SYLLABLE BBWAEM", "\ubf88")
83 self.checkletter("HANGUL SYLLABLE SSEOL", "\uc370")
84 self.checkletter("HANGUL SYLLABLE YI", "\uc758")
85 self.checkletter("HANGUL SYLLABLE JJYOSS", "\ucb40")
86 self.checkletter("HANGUL SYLLABLE KYEOLS", "\ucf28")
87 self.checkletter("HANGUL SYLLABLE PAN", "\ud310")
88 self.checkletter("HANGUL SYLLABLE HWEOK", "\ud6f8")
89 self.checkletter("HANGUL SYLLABLE HIH", "\ud7a3")
90
91 self.assertRaises(ValueError, unicodedata.name, "\ud7a4")
92
93 def test_cjk_unified_ideographs(self):
94 self.checkletter("CJK UNIFIED IDEOGRAPH-3400", "\u3400")
95 self.checkletter("CJK UNIFIED IDEOGRAPH-4DB5", "\u4db5")
96 self.checkletter("CJK UNIFIED IDEOGRAPH-4E00", "\u4e00")
97 self.checkletter("CJK UNIFIED IDEOGRAPH-9FCB", "\u9fCB")
98 self.checkletter("CJK UNIFIED IDEOGRAPH-20000", "\U00020000")
99 self.checkletter("CJK UNIFIED IDEOGRAPH-2A6D6", "\U0002a6d6")
100 self.checkletter("CJK UNIFIED IDEOGRAPH-2A700", "\U0002A700")
101 self.checkletter("CJK UNIFIED IDEOGRAPH-2B734", "\U0002B734")
102 self.checkletter("CJK UNIFIED IDEOGRAPH-2B740", "\U0002B740")
103 self.checkletter("CJK UNIFIED IDEOGRAPH-2B81D", "\U0002B81D")
104 self.checkletter("CJK UNIFIED IDEOGRAPH-3134A", "\U0003134A")
105
106 def test_bmp_characters(self):
107 for code in range(0x10000):
108 char = chr(code)
109 name = unicodedata.name(char, None)
110 if name is not None:
111 self.assertEqual(unicodedata.lookup(name), char)
112
113 def test_misc_symbols(self):
114 self.checkletter("PILCROW SIGN", "\u00b6")
115 self.checkletter("REPLACEMENT CHARACTER", "\uFFFD")
116 self.checkletter("HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK", "\uFF9F")
117 self.checkletter("FULLWIDTH LATIN SMALL LETTER A", "\uFF41")
118
119 def test_aliases(self):
120 # Check that the aliases defined in the NameAliases.txt file work.
121 # This should be updated when new aliases are added or the file
122 # should be downloaded and parsed instead. See #12753.
123 aliases = [
124 ('LATIN CAPITAL LETTER GHA', 0x01A2),
125 ('LATIN SMALL LETTER GHA', 0x01A3),
126 ('KANNADA LETTER LLLA', 0x0CDE),
127 ('LAO LETTER FO FON', 0x0E9D),
128 ('LAO LETTER FO FAY', 0x0E9F),
129 ('LAO LETTER RO', 0x0EA3),
130 ('LAO LETTER LO', 0x0EA5),
131 ('TIBETAN MARK BKA- SHOG GI MGO RGYAN', 0x0FD0),
132 ('YI SYLLABLE ITERATION MARK', 0xA015),
133 ('PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET', 0xFE18),
134 ('BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON CHROMA VASIS', 0x1D0C5)
135 ]
136 for alias, codepoint in aliases:
137 self.checkletter(alias, chr(codepoint))
138 name = unicodedata.name(chr(codepoint))
139 self.assertNotEqual(name, alias)
140 self.assertEqual(unicodedata.lookup(alias),
141 unicodedata.lookup(name))
142 with self.assertRaises(KeyError):
143 unicodedata.ucd_3_2_0.lookup(alias)
144
145 def test_aliases_names_in_pua_range(self):
146 # We are storing aliases in the PUA 15, but their names shouldn't leak
147 for cp in range(0xf0000, 0xf0100):
148 with self.assertRaises(ValueError) as cm:
149 unicodedata.name(chr(cp))
150 self.assertEqual(str(cm.exception), 'no such name')
151
152 def test_named_sequences_names_in_pua_range(self):
153 # We are storing named seq in the PUA 15, but their names shouldn't leak
154 for cp in range(0xf0100, 0xf0fff):
155 with self.assertRaises(ValueError) as cm:
156 unicodedata.name(chr(cp))
157 self.assertEqual(str(cm.exception), 'no such name')
158
159 def test_named_sequences_sample(self):
160 # Check a few named sequences. See #12753.
161 sequences = [
162 ('LATIN SMALL LETTER R WITH TILDE', '\u0072\u0303'),
163 ('TAMIL SYLLABLE SAI', '\u0BB8\u0BC8'),
164 ('TAMIL SYLLABLE MOO', '\u0BAE\u0BCB'),
165 ('TAMIL SYLLABLE NNOO', '\u0BA3\u0BCB'),
166 ('TAMIL CONSONANT KSS', '\u0B95\u0BCD\u0BB7\u0BCD'),
167 ]
168 for seqname, codepoints in sequences:
169 self.assertEqual(unicodedata.lookup(seqname), codepoints)
170 with self.assertRaises(SyntaxError):
171 self.checkletter(seqname, None)
172 with self.assertRaises(KeyError):
173 unicodedata.ucd_3_2_0.lookup(seqname)
174
175 def test_named_sequences_full(self):
176 # Check all the named sequences
177 def check_version(testfile):
178 hdr = testfile.readline()
179 return unicodedata.unidata_version in hdr
180 url = ("http://www.pythontest.net/unicode/%s/NamedSequences.txt" %
181 unicodedata.unidata_version)
182 try:
183 testdata = support.open_urlresource(url, encoding="utf-8",
184 check=check_version)
185 except urllib.error.HTTPError as exc:
186 exc.close()
187 self.skipTest(f"Could not retrieve {url}: {exc!r}")
188 except (OSError, HTTPException) as exc:
189 self.skipTest(f"Could not retrieve {url}: {exc!r}")
190 with testdata:
191 for line in testdata:
192 line = line.strip()
193 if not line or line.startswith('#'):
194 continue
195 seqname, codepoints = line.split(';')
196 codepoints = ''.join(chr(int(cp, 16)) for cp in codepoints.split())
197 self.assertEqual(unicodedata.lookup(seqname), codepoints)
198 with self.assertRaises(SyntaxError):
199 self.checkletter(seqname, None)
200 with self.assertRaises(KeyError):
201 unicodedata.ucd_3_2_0.lookup(seqname)
202
203 def test_errors(self):
204 self.assertRaises(TypeError, unicodedata.name)
205 self.assertRaises(TypeError, unicodedata.name, 'xx')
206 self.assertRaises(TypeError, unicodedata.lookup)
207 self.assertRaises(KeyError, unicodedata.lookup, 'unknown')
208
209 def test_strict_error_handling(self):
210 # bogus character name
211 self.assertRaises(
212 UnicodeError,
213 str, b"\\N{blah}", 'unicode-escape', 'strict'
214 )
215 # long bogus character name
216 self.assertRaises(
217 UnicodeError,
218 str, bytes("\\N{%s}" % ("x" * 100000), "ascii"), 'unicode-escape', 'strict'
219 )
220 # missing closing brace
221 self.assertRaises(
222 UnicodeError,
223 str, b"\\N{SPACE", 'unicode-escape', 'strict'
224 )
225 # missing opening brace
226 self.assertRaises(
227 UnicodeError,
228 str, b"\\NSPACE", 'unicode-escape', 'strict'
229 )
230
231 @support.cpython_only
232 @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX")
233 @support.bigmemtest(size=UINT_MAX + 1, memuse=2 + 1, dry_run=False)
234 def test_issue16335(self, size):
235 # very very long bogus character name
236 x = b'\\N{SPACE' + b'x' * (UINT_MAX + 1) + b'}'
237 self.assertEqual(len(x), len(b'\\N{SPACE}') + (UINT_MAX + 1))
238 self.assertRaisesRegex(UnicodeError,
239 'unknown Unicode character name',
240 x.decode, 'unicode-escape'
241 )
242
243
244 if __name__ == "__main__":
245 unittest.main()