Debian Codegraph @

pypy/module/_hpy_universal/test/_vendored/test_hpyunicode.py

raw symbols SCIP
1 # -*- encoding: utf-8 -*-
2 import sys
3
4 from .support import HPyTest
5
6 class TestUnicode(HPyTest):
7
8 def test_Check(self):
9 mod = self.make_module("""
10 HPyDef_METH(f, "f", HPyFunc_O)
11 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
12 {
13 if (HPyUnicode_Check(ctx, arg))
14 return HPy_Dup(ctx, ctx->h_True);
15 return HPy_Dup(ctx, ctx->h_False);
16 }
17 @EXPORT(f)
18 @INIT
19 """)
20 class MyUnicode(str):
21 pass
22
23 assert mod.f('hello') is True
24 assert mod.f(b'hello') is False
25 assert mod.f(MyUnicode('hello')) is True
26
27 def test_FromString(self):
28 mod = self.make_module("""
29 HPyDef_METH(f, "f", HPyFunc_NOARGS)
30 static HPy f_impl(HPyContext *ctx, HPy self)
31 {
32 return HPyUnicode_FromString(ctx, "foobar");
33 }
34 @EXPORT(f)
35 @INIT
36 """)
37 assert mod.f() == "foobar"
38
39 def test_FromWideChar(self):
40 mod = self.make_module("""
41 HPyDef_METH(f, "f", HPyFunc_O)
42 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
43 {
44 const wchar_t buf[] = { 'h', 'e', 'l', 'l', 0xf2, ' ',
45 'w', 'o', 'r', 'l', 'd', 0 };
46 long n = HPyLong_AsLong(ctx, arg);
47 return HPyUnicode_FromWideChar(ctx, buf, n);
48 }
49 @EXPORT(f)
50 @INIT
51 """)
52 assert mod.f(-1) == "hellò world"
53 assert mod.f(11) == "hellò world"
54 assert mod.f(5) == "hellò"
55
56
57 def test_AsUTF8String(self):
58 mod = self.make_module("""
59 HPyDef_METH(f, "f", HPyFunc_O)
60 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
61 {
62 return HPyUnicode_AsUTF8String(ctx, arg);
63 }
64 @EXPORT(f)
65 @INIT
66 """)
67 s = 'hellò'
68 b = mod.f(s)
69 assert type(b) is bytes
70 assert b == s.encode('utf-8')
71
72 def test_AsASCIIString(self):
73 mod = self.make_module("""
74 HPyDef_METH(f, "f", HPyFunc_O)
75 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
76 {
77 return HPyUnicode_AsASCIIString(ctx, arg);
78 }
79 @EXPORT(f)
80 @INIT
81 """)
82 s = 'world'
83 b = mod.f(s)
84 assert type(b) is bytes
85 assert b == s.encode('ascii')
86
87 def test_AsLatin1String(self):
88 mod = self.make_module("""
89 HPyDef_METH(f, "f", HPyFunc_O)
90 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
91 {
92 return HPyUnicode_AsLatin1String(ctx, arg);
93 }
94 @EXPORT(f)
95 @INIT
96 """)
97 s = "Müller"
98 b = mod.f(s)
99 assert type(b) is bytes
100 assert b == s.encode('latin1')
101
102 def test_AsUTF8AndSize(self):
103 mod = self.make_module("""
104 #include <string.h>
105
106 static HPy as_utf8_and_size(HPyContext *ctx, HPy arg, HPy_ssize_t *size)
107 {
108 HPy_ssize_t n;
109 const char* buf = HPyUnicode_AsUTF8AndSize(ctx, arg, size);
110 long res = 0;
111
112 if (size)
113 n = *size;
114 else
115 n = strlen(buf);
116
117 for(int i=0; i<n; i++)
118 res = (res * 10) + buf[i];
119 return HPyLong_FromLong(ctx, res);
120 }
121
122 HPyDef_METH(f, "f", HPyFunc_O)
123 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
124 {
125 HPy_ssize_t n;
126 return as_utf8_and_size(ctx, arg, &n);
127 }
128
129 HPyDef_METH(g, "g", HPyFunc_O)
130 static HPy g_impl(HPyContext *ctx, HPy self, HPy arg)
131 {
132 return as_utf8_and_size(ctx, arg, NULL);
133 }
134 @EXPORT(f)
135 @EXPORT(g)
136 @INIT
137 """)
138 assert mod.f('ABC') == 100*ord('A') + 10*ord('B') + ord('C')
139 assert mod.f(b'A\0C'.decode('utf-8')) == 100*ord('A') + ord('C')
140 assert mod.g('ABC') == 100*ord('A') + 10*ord('B') + ord('C')
141 assert mod.g(b'A'.decode('utf-8')) == ord('A')
142 assert mod.g(b'A\0'.decode('utf-8')) == ord('A')
143
144 def test_DecodeLatin1(self):
145 mod = self.make_module("""
146 HPyDef_METH(f, "f", HPyFunc_O)
147 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
148 {
149 const char* buf = HPyBytes_AS_STRING(ctx, arg);
150 HPy_ssize_t n = HPyBytes_Size(ctx, arg);
151 return HPyUnicode_DecodeLatin1(ctx, buf, n, "");
152 }
153 @EXPORT(f)
154 @INIT
155 """)
156 assert mod.f(b'M\xfcller') == "Müller"
157
158 def test_DecodeASCII(self):
159 mod = self.make_module("""
160 HPyDef_METH(f, "f", HPyFunc_O)
161 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
162 {
163 const char* buf = HPyBytes_AS_STRING(ctx, arg);
164 HPy_ssize_t n = HPyBytes_Size(ctx, arg);
165 return HPyUnicode_DecodeASCII(ctx, buf, n, "");
166 }
167 @EXPORT(f)
168 @INIT
169 """)
170 assert mod.f(b'hello') == "hello"
171
172 def test_ReadChar(self):
173 mod = self.make_module("""
174 HPyDef_METH(f, "f", HPyFunc_O)
175 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
176 {
177 long c = HPyUnicode_ReadChar(ctx, arg, 1);
178 return HPyLong_FromLong(ctx, c);
179 }
180 @EXPORT(f)
181 @INIT
182 """)
183 assert mod.f('ABC') == 66
184
185 def test_EncodeFSDefault(self):
186 mod = self.make_module("""
187 HPyDef_METH(f, "f", HPyFunc_O)
188 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
189 {
190 return HPyUnicode_EncodeFSDefault(ctx, arg);
191 }
192 @EXPORT(f)
193 @INIT
194 """)
195 assert mod.f('ABC') == b'ABC'
196
197 def test_DecodeFSDefault(self):
198 mod = self.make_module("""
199 HPyDef_METH(f, "f", HPyFunc_O)
200 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
201 {
202 HPy_ssize_t n;
203 const char* buf = HPyUnicode_AsUTF8AndSize(ctx, arg, &n);
204 return HPyUnicode_DecodeFSDefault(ctx, buf);
205 }
206
207 HPyDef_METH(g, "g", HPyFunc_NOARGS)
208 static HPy g_impl(HPyContext *ctx, HPy self)
209 {
210 const char buf[5] = { 'a', 'b', '\\0', 'c' };
211 return HPyUnicode_DecodeFSDefaultAndSize(ctx, buf, 4);
212 }
213
214 @EXPORT(f)
215 @EXPORT(g)
216 @INIT
217 """)
218 assert mod.f('ABC') == "ABC"
219 assert mod.g().encode('ascii') == b'ab\0c'
220
221 def test_FromFormat(self):
222 # Later we generate an HPy function for each case described below:
223 # Most of the test cases are taken from CPython:Modules/_testcapi/unicode.c
224 # Future work can improve this to add tests from Lib/test/test_capi/test_unicode.py
225 import itertools
226 import re
227 import pytest
228 cases = [
229 # Unrecognized
230 ( "%y%d", (SystemError, "invalid format string"), "'w', 42"),
231 ("%04.2y%d", (SystemError, "invalid format string"), "'w', 42"),
232 ("%u %? %u", (SystemError, "invalid format string"), "1, 2"),
233
234 # "%%" (options are rejected)
235 ( "%%", "%", "0"),
236 ("%%%c", "%w", "'w'"),
237 ( "%0%", (SystemError, "invalid format string"), "0"),
238 ("%00%", (SystemError, "invalid format string"), "0"),
239 ( "%2%", (SystemError, "invalid format string"), "0"),
240 ("%02%", (SystemError, "invalid format string"), "0"),
241 ("%.0%", (SystemError, "invalid format string"), "0"),
242 ("%.2%", (SystemError, "invalid format string"), "0"),
243
244 # "%c"
245 ( "%c", "c", "'c'"),
246
247 # Integers
248 ("%d", "123", '(int)123'),
249 ("%i", "123", '(int)123'),
250 ("%u", "123", '(unsigned int)123'),
251 ("%ld", "123", '(long)123'),
252 ("%li", "123", '(long)123'),
253 ("%lu", "123", '(unsigned long)123'),
254 ("%lld", "123", '(long long)123'),
255 ("%lli", "123", '(long long)123'),
256 ("%llu", "123",'(unsigned long long)123'),
257 ("%zd", "123", '(HPy_ssize_t)123'),
258 ("%zi", "123", '(HPy_ssize_t)123'),
259 ("%zu", "123", '(size_t)123'),
260 ("%x", "7b", '(int)123'),
261
262 ("%d", "-123", '(int)-123'),
263 ("%i", "-123", '(int)-123'),
264 ("%ld", "-123", '(long)-123'),
265 ("%li", "-123", '(long)-123'),
266 ("%lld", "-123", '(long long)-123'),
267 ("%lli", "-123", '(long long)-123'),
268 ("%zd", "-123", '(HPy_ssize_t)-123'),
269 ("%zi", "-123", '(HPy_ssize_t)-123'),
270 ("%x", "ffffff85", '(int)-123'),
271
272 # Integers: width < length
273 ("%1d", "123", '(int)123'),
274 ("%1i", "123", '(int)123'),
275 ("%1u", "123", '(unsigned int)123'),
276 ("%1ld", "123", '(long)123'),
277 ("%1li", "123", '(long)123'),
278 ("%1lu", "123", '(unsigned long)123'),
279 ("%1lld", "123", '(long long)123'),
280 ("%1lli", "123", '(long long)123'),
281 ("%1llu", "123",'(unsigned long long)123'),
282 ("%1zd", "123", '(HPy_ssize_t)123'),
283 ("%1zi", "123", '(HPy_ssize_t)123'),
284 ("%1zu", "123", '(size_t)123'),
285 ("%1x", "7b", '(int)123'),
286
287 ("%1d", "-123", '(int)-123'),
288 ("%1i", "-123", '(int)-123'),
289 ("%1ld", "-123", '(long)-123'),
290 ("%1li", "-123", '(long)-123'),
291 ("%1lld", "-123", '(long long)-123'),
292 ("%1lli", "-123", '(long long)-123'),
293 ("%1zd", "-123", '(HPy_ssize_t)-123'),
294 ("%1zi", "-123", '(HPy_ssize_t)-123'),
295 ("%1x", "ffffff85", '(int)-123'),
296
297 # Integers: width > length
298 ("%5d", " 123", '(int)123'),
299 ("%5i", " 123", '(int)123'),
300 ("%5u", " 123", '(unsigned int)123'),
301 ("%5ld", " 123", '(long)123'),
302 ("%5li", " 123", '(long)123'),
303 ("%5lu", " 123", '(unsigned long)123'),
304 ("%5lld", " 123", '(long long)123'),
305 ("%5lli", " 123", '(long long)123'),
306 ("%5llu", " 123",'(unsigned long long)123'),
307 ("%5zd", " 123", '(HPy_ssize_t)123'),
308 ("%5zi", " 123", '(HPy_ssize_t)123'),
309 ("%5zu", " 123", '(size_t)123'),
310 ("%5x", " 7b", '(int)123'),
311
312 ("%5d", " -123", '(int)-123'),
313 ("%5i", " -123", '(int)-123'),
314 ("%5ld", " -123", '(long)-123'),
315 ("%5li", " -123", '(long)-123'),
316 ("%5lld", " -123", '(long long)-123'),
317 ("%5lli", " -123", '(long long)-123'),
318 ("%5zd", " -123", '(HPy_ssize_t)-123'),
319 ("%5zi", " -123", '(HPy_ssize_t)-123'),
320 ("%9x", " ffffff85", '(int)-123'),
321
322 # Integers: width > length, 0-flag
323 ("%05d", "00123", '(int)123'),
324 ("%05i", "00123", '(int)123'),
325 ("%05u", "00123", '(unsigned int)123'),
326 ("%05ld", "00123", '(long)123'),
327 ("%05li", "00123", '(long)123'),
328 ("%05lu", "00123", '(unsigned long)123'),
329 ("%05lld", "00123", '(long long)123'),
330 ("%05lli", "00123", '(long long)123'),
331 ("%05llu", "00123",'(unsigned long long)123'),
332 ("%05zd", "00123", '(HPy_ssize_t)123'),
333 ("%05zi", "00123", '(HPy_ssize_t)123'),
334 ("%05zu", "00123", '(size_t)123'),
335 ("%05x", "0007b", '(int)123'),
336
337 ("%05d", "-0123", '(int)-123'),
338 ("%05i", "-0123", '(int)-123'),
339 ("%05ld", "-0123", '(long)-123'),
340 ("%05li", "-0123", '(long)-123'),
341 ("%05lld", "-0123", '(long long)-123'),
342 ("%05lli", "-0123", '(long long)-123'),
343 ("%05zd", "-0123", '(HPy_ssize_t)-123'),
344 ("%05zi", "-0123", '(HPy_ssize_t)-123'),
345 ("%09x", "0ffffff85", '(int)-123'),
346
347 # Integers: precision < length
348 ("%.1d", "123", '(int)123'),
349 ("%.1i", "123", '(int)123'),
350 ("%.1u", "123", '(unsigned int)123'),
351 ("%.1ld", "123", '(long)123'),
352 ("%.1li", "123", '(long)123'),
353 ("%.1lu", "123", '(unsigned long)123'),
354 ("%.1lld", "123", '(long long)123'),
355 ("%.1lli", "123", '(long long)123'),
356 ("%.1llu", "123",'(unsigned long long)123'),
357 ("%.1zd", "123", '(HPy_ssize_t)123'),
358 ("%.1zi", "123", '(HPy_ssize_t)123'),
359 ("%.1zu", "123", '(size_t)123'),
360 ("%.1x", "7b", '(int)123'),
361
362 ("%.1d", "-123", '(int)-123'),
363 ("%.1i", "-123", '(int)-123'),
364 ("%.1ld", "-123", '(long)-123'),
365 ("%.1li", "-123", '(long)-123'),
366 ("%.1lld", "-123", '(long long)-123'),
367 ("%.1lli", "-123", '(long long)-123'),
368 ("%.1zd", "-123", '(HPy_ssize_t)-123'),
369 ("%.1zi", "-123", '(HPy_ssize_t)-123'),
370 ("%.1x", "ffffff85", '(int)-123'),
371
372 # Integers: precision > length
373 ("%.5d", "00123", '(int)123'),
374 ("%.5i", "00123", '(int)123'),
375 ("%.5u", "00123", '(unsigned int)123'),
376 ("%.5ld", "00123", '(long)123'),
377 ("%.5li", "00123", '(long)123'),
378 ("%.5lu", "00123", '(unsigned long)123'),
379 ("%.5lld", "00123", '(long long)123'),
380 ("%.5lli", "00123", '(long long)123'),
381 ("%.5llu", "00123",'(unsigned long long)123'),
382 ("%.5zd", "00123", '(HPy_ssize_t)123'),
383 ("%.5zi", "00123", '(HPy_ssize_t)123'),
384 ("%.5zu", "00123", '(size_t)123'),
385 ("%.5x", "0007b", '(int)123'),
386
387 ("%.5d", "-00123", '(int)-123'),
388 ("%.5i", "-00123", '(int)-123'),
389 ("%.5ld", "-00123", '(long)-123'),
390 ("%.5li", "-00123", '(long)-123'),
391 ("%.5lld", "-00123", '(long long)-123'),
392 ("%.5lli", "-00123", '(long long)-123'),
393 ("%.5zd", "-00123", '(HPy_ssize_t)-123'),
394 ("%.5zi", "-00123", '(HPy_ssize_t)-123'),
395 ("%.9x", "0ffffff85", '(int)-123'),
396
397 # Integers: width > precision > length
398 ("%7.5d", " 00123", '(int)123'),
399 ("%7.5i", " 00123", '(int)123'),
400 ("%7.5u", " 00123", '(unsigned int)123'),
401 ("%7.5ld", " 00123", '(long)123'),
402 ("%7.5li", " 00123", '(long)123'),
403 ("%7.5lu", " 00123", '(unsigned long)123'),
404 ("%7.5lld", " 00123", '(long long)123'),
405 ("%7.5lli", " 00123", '(long long)123'),
406 ("%7.5llu", " 00123",'(unsigned long long)123'),
407 ("%7.5zd", " 00123", '(HPy_ssize_t)123'),
408 ("%7.5zi", " 00123", '(HPy_ssize_t)123'),
409 ("%7.5zu", " 00123", '(size_t)123'),
410 ("%7.5x", " 0007b", '(int)123'),
411
412 ("%7.5d", " -00123", '(int)-123'),
413 ("%7.5i", " -00123", '(int)-123'),
414 ("%7.5ld", " -00123", '(long)-123'),
415 ("%7.5li", " -00123", '(long)-123'),
416 ("%7.5lld", " -00123", '(long long)-123'),
417 ("%7.5lli", " -00123", '(long long)-123'),
418 ("%7.5zd", " -00123", '(HPy_ssize_t)-123'),
419 ("%7.5zi", " -00123", '(HPy_ssize_t)-123'),
420 ("%10.9x", " 0ffffff85", '(int)-123'),
421
422 # Integers: width > precision > length, 0-flag
423 ("%07.5d", "0000123", '(int)123'),
424 ("%07.5i", "0000123", '(int)123'),
425 ("%07.5u", "0000123", '(unsigned int)123'),
426 ("%07.5ld", "0000123", '(long)123'),
427 ("%07.5li", "0000123", '(long)123'),
428 ("%07.5lu", "0000123", '(unsigned long)123'),
429 ("%07.5lld", "0000123", '(long long)123'),
430 ("%07.5lli", "0000123", '(long long)123'),
431 ("%07.5llu", "0000123",'(unsigned long long)123'),
432 ("%07.5zd", "0000123", '(HPy_ssize_t)123'),
433 ("%07.5zi", "0000123", '(HPy_ssize_t)123'),
434 ("%07.5zu", "0000123", '(size_t)123'),
435 ("%07.5x", "000007b", '(int)123'),
436
437 ("%07.5d", "-000123", '(int)-123'),
438 ("%07.5i", "-000123", '(int)-123'),
439 ("%07.5ld", "-000123", '(long)-123'),
440 ("%07.5li", "-000123", '(long)-123'),
441 ("%07.5lld", "-000123", '(long long)-123'),
442 ("%07.5lli", "-000123", '(long long)-123'),
443 ("%07.5zd", "-000123", '(HPy_ssize_t)-123'),
444 ("%07.5zi", "-000123", '(HPy_ssize_t)-123'),
445 ("%010.9x","00ffffff85", '(int)-123'),
446
447 # Integers: precision > width > length
448 ("%5.7d", "0000123", '(int)123'),
449 ("%5.7i", "0000123", '(int)123'),
450 ("%5.7u", "0000123", '(unsigned int)123'),
451 ("%5.7ld", "0000123", '(long)123'),
452 ("%5.7li", "0000123", '(long)123'),
453 ("%5.7lu", "0000123", '(unsigned long)123'),
454 ("%5.7lld", "0000123", '(long long)123'),
455 ("%5.7lli", "0000123", '(long long)123'),
456 ("%5.7llu", "0000123",'(unsigned long long)123'),
457 ("%5.7zd", "0000123", '(HPy_ssize_t)123'),
458 ("%5.7zi", "0000123", '(HPy_ssize_t)123'),
459 ("%5.7zu", "0000123", '(size_t)123'),
460 ("%5.7x", "000007b", '(int)123'),
461
462 ("%5.7d", "-0000123", '(int)-123'),
463 ("%5.7i", "-0000123", '(int)-123'),
464 ("%5.7ld", "-0000123", '(long)-123'),
465 ("%5.7li", "-0000123", '(long)-123'),
466 ("%5.7lld", "-0000123", '(long long)-123'),
467 ("%5.7lli", "-0000123", '(long long)-123'),
468 ("%5.7zd", "-0000123", '(HPy_ssize_t)-123'),
469 ("%5.7zi", "-0000123", '(HPy_ssize_t)-123'),
470 ("%9.10x", "00ffffff85", '(int)-123'),
471
472 # Integers: precision > width > length, 0-flag
473 ("%05.7d", "0000123", '(int)123'),
474 ("%05.7i", "0000123", '(int)123'),
475 ("%05.7u", "0000123", '(unsigned int)123'),
476 ("%05.7ld", "0000123", '(long)123'),
477 ("%05.7li", "0000123", '(long)123'),
478 ("%05.7lu", "0000123", '(unsigned long)123'),
479 ("%05.7lld", "0000123", '(long long)123'),
480 ("%05.7lli", "0000123", '(long long)123'),
481 ("%05.7llu", "0000123",'(unsigned long long)123'),
482 ("%05.7zd", "0000123", '(HPy_ssize_t)123'),
483 ("%05.7zi", "0000123", '(HPy_ssize_t)123'),
484 ("%05.7zu", "0000123", '(size_t)123'),
485 ("%05.7x", "000007b", '(int)123'),
486
487 ("%05.7d", "-0000123", '(int)-123'),
488 ("%05.7i", "-0000123", '(int)-123'),
489 ("%05.7ld", "-0000123", '(long)-123'),
490 ("%05.7li", "-0000123", '(long)-123'),
491 ("%05.7lld", "-0000123", '(long long)-123'),
492 ("%05.7lli", "-0000123", '(long long)-123'),
493 ("%05.7zd", "-0000123", '(HPy_ssize_t)-123'),
494 ("%05.7zi", "-0000123", '(HPy_ssize_t)-123'),
495 ("%09.10x","00ffffff85", '(int)-123'),
496
497 # Integers: precision = 0, arg = 0 (empty string in C)
498 ("%.0d", "0", '(int)0'),
499 ("%.0i", "0", '(int)0'),
500 ("%.0u", "0", '(unsigned int)0'),
501 ("%.0ld", "0", '(long)0'),
502 ("%.0li", "0", '(long)0'),
503 ("%.0lu", "0", '(unsigned long)0'),
504 ("%.0lld", "0", '(long long)0'),
505 ("%.0lli", "0", '(long long)0'),
506 ("%.0llu", "0", '(unsigned long long)0'),
507 ("%.0zd", "0", '(HPy_ssize_t)0'),
508 ("%.0zi", "0", '(HPy_ssize_t)0'),
509 ("%.0zu", "0", '(size_t)0'),
510 ("%.0x", "0", '(int)0'),
511
512 # Strings
513 ("%s", "None", ' "None"'),
514 ("%U", "None", 'unicode'),
515 ("%A", "None", 'ctx->h_None'),
516 ("%S", "None", 'ctx->h_None'),
517 ("%R", "None", 'ctx->h_None'),
518 ("%V", "None", 'unicode, "ignored"'),
519 ("%V", "None", ' NULL, "None"'),
520
521 # Strings: width < length
522 ("%1s", "None", ' "None"'),
523 ("%1U", "None", 'unicode'),
524 ("%1A", "None", 'ctx->h_None'),
525 ("%1S", "None", 'ctx->h_None'),
526 ("%1R", "None", 'ctx->h_None'),
527 ("%1V", "None", 'unicode, "ignored"'),
528 ("%1V", "None", ' NULL, "None"'),
529
530 # Strings: width > length
531 ("%5s", " None", ' "None"'),
532 ("%5U", " None", 'unicode'),
533 ("%5A", " None", 'ctx->h_None'),
534 ("%5S", " None", 'ctx->h_None'),
535 ("%5R", " None", 'ctx->h_None'),
536 ("%5V", " None", 'unicode, "ignored"'),
537 ("%5V", " None", ' NULL, "None"'),
538
539 # Strings: precision < length
540 ("%.1s", "N", ' "None"'),
541 ("%.1U", "N", 'unicode'),
542 ("%.1A", "N", 'ctx->h_None'),
543 ("%.1S", "N", 'ctx->h_None'),
544 ("%.1R", "N", 'ctx->h_None'),
545 ("%.1V", "N", 'unicode, "ignored"'),
546 ("%.1V", "N", ' NULL, "None"'),
547
548 # Strings: precision > length
549 ("%.5s", "None", ' "None"'),
550 ("%.5U", "None", 'unicode'),
551 ("%.5A", "None", 'ctx->h_None'),
552 ("%.5S", "None", 'ctx->h_None'),
553 ("%.5R", "None", 'ctx->h_None'),
554 ("%.5V", "None", 'unicode, "ignored"'),
555 ("%.5V", "None", ' NULL, "None"'),
556
557 # Strings: precision < length, width > length
558 ("%5.1s", " N", ' "None"'),
559 ("%5.1U", " N", 'unicode'),
560 ("%5.1A", " N", 'ctx->h_None'),
561 ("%5.1S", " N", 'ctx->h_None'),
562 ("%5.1R", " N", 'ctx->h_None'),
563 ("%5.1V", " N", 'unicode, "ignored"'),
564 ("%5.1V", " N", ' NULL, "None"'),
565
566 # Strings: width < length, precision > length
567 ("%1.5s", "None", ' "None"'),
568 ("%1.5U", "None", 'unicode'),
569 ("%1.5A", "None", 'ctx->h_None'),
570 ("%1.5S", "None", 'ctx->h_None'),
571 ("%1.5R", "None", 'ctx->h_None'),
572 ("%1.5V", "None", 'unicode, "ignored"'),
573 ("%1.5V", "None", ' NULL, "None"'),
574
575 # Additional HPy tests:
576 ("%c", (OverflowError, re.escape("character argument not in range(0x110000)")), "0x10ffff + 2"),
577
578 ("check if %5d %s %6.3d is %5S or %6.3S",
579 "check if 42 == -042 is True or Fal",
580 '42, "==", -42, ctx->h_True, ctx->h_False')
581 ]
582
583 cpython_incompatible_cases = [
584 ( "%s", (SystemError, "null c string passed as value for formatting unit '%s'"), "NULL"),
585
586 ( '%4p', (SystemError, "formatting unit '%p' does not support width nor precision"), "0"),
587 ( '%04p', (SystemError, "formatting unit '%p' does not support 0-padding"), "0"),
588 ( '%.4p', (SystemError, "formatting unit '%p' does not support width nor precision"), "0"),
589 ( '%8.4p', (SystemError, "formatting unit '%p' does not support width nor precision"), "0"),
590 ('%08.4p', (SystemError, "formatting unit '%p' does not support 0-padding"), "0"),
591
592 ( '%4c', (SystemError, "formatting unit '%c' does not support width nor precision"), "0"),
593 ( '%04c', (SystemError, "formatting unit '%c' does not support 0-padding"), "0"),
594 ( '%.4c', (SystemError, "formatting unit '%c' does not support width nor precision"), "0"),
595 ( '%8.4c', (SystemError, "formatting unit '%c' does not support width nor precision"), "0"),
596 ('%08.4c', (SystemError, "formatting unit '%c' does not support 0-padding"), "0"),
597
598 ("%U", (SystemError, ".*HPy_NULL passed.*"), "HPy_NULL"),
599 ("%S", (SystemError, ".*HPy_NULL passed.*"), "HPy_NULL"),
600 ("%R", (SystemError, ".*HPy_NULL passed.*"), "HPy_NULL"),
601 ("%A", (SystemError, ".*HPy_NULL passed.*"), "HPy_NULL"),
602
603 ("%0s", (SystemError, "formatting unit '%s' does not support 0-padding"), "0"),
604 ("%0p", (SystemError, "formatting unit '%p' does not support 0-padding"), "0"),
605 ("%0U", (SystemError, "formatting unit '%U' does not support 0-padding"), "0"),
606 ("%0V", (SystemError, "formatting unit '%V' does not support 0-padding"), "0"),
607 ("%0S", (SystemError, "formatting unit '%S' does not support 0-padding"), "0"),
608 ("%0R", (SystemError, "formatting unit '%R' does not support 0-padding"), "0"),
609 ("%0A", (SystemError, "formatting unit '%A' does not support 0-padding"), "0"),
610 ]
611
612 cases += cpython_incompatible_cases
613 cpython_incompatible_cases = set(cpython_incompatible_cases)
614
615 # Generate a unique name for each test that is also valid C identifier
616 names = ['a' + str(i) for i in range(0, len(cases))]
617 cases = {name:case for (name, case) in itertools.zip_longest(names, cases)}
618
619 # ---
620 # Generate the test code from the cases:
621 def makefun(name, fmt, arg):
622 cpy_arg = arg.replace("ctx->h_None", "Py_None").replace("HPy_ssize_t", "Py_ssize_t")
623 return """
624 HPyDef_METH({name}, "{name}", HPyFunc_NOARGS)
625 static HPy {name}_impl(HPyContext *ctx, HPy self)
626 {{
627 HPy unicode = HPyUnicode_FromString(ctx, "None");
628 if (HPy_IsNull(unicode)) return HPy_NULL;
629 HPy result = HPyUnicode_FromFormat(ctx, "{fmt}", {arg});
630 HPy_Close(ctx, unicode);
631 return result;
632 }}
633
634 #ifdef CPM_WITH_CPYTHON
635 HPyDef_METH({name}_cpython, "{name}_cpython", HPyFunc_NOARGS)
636 static HPy {name}_cpython_impl(HPyContext *ctx, HPy self)
637 {{
638 PyObject *unicode = PyUnicode_FromString("None");
639 PyObject *py = PyUnicode_FromFormat("{fmt}", {cpy_arg});
640 HPy hpy = HPy_NULL;
641 if (py != NULL) {{
642 hpy = HPy_FromPyObject(ctx, py);
643 Py_DECREF(py);
644 }}
645 Py_DECREF(unicode);
646 return hpy;
647 }}
648 #endif
649 """.format(name=name, fmt=fmt, arg=arg, cpy_arg=cpy_arg)
650
651 # Change False->True to also check comparison with CPython.
652 # Works only for 3.12 or higher, lower versions have bugs that are
653 # fixed in HPy
654 compare_with_cpython = False # and \
655 # hpy_abi == 'cpython' and \
656 # sys.implementation.name == 'cpython' and \
657 # sys.implementation.version.major >= 3 and \
658 # sys.implementation.version.minor >= 12
659
660 # Create functions for each case using the "makefun" template, export them
661 lines = ['#define CPM_WITH_CPYTHON'] if compare_with_cpython else []
662 lines += [makefun(name, fmt, arg) for (name, (fmt, _, arg)) in cases.items()]
663 lines += ["@EXPORT({})".format(name) for name in cases.keys()]
664 if compare_with_cpython:
665 lines += ["@EXPORT({}_cpython)".format(name) for name in cases.keys()]
666 lines += ["@INIT"]
667
668 mod = self.make_module("\n".join(lines))
669
670 def check_cpython_raises_any(name):
671 try:
672 getattr(mod, name + "_cpython")()
673 return False
674 except:
675 return True
676
677 for (name, case) in cases.items():
678 (_, expected, _) = case
679 if isinstance(expected, tuple):
680 (expected_type, expected_message) = expected
681 with pytest.raises(expected_type, match=expected_message):
682 getattr(mod, name)()
683 if compare_with_cpython and case not in cpython_incompatible_cases:
684 check_cpython_raises_any(name)
685 continue
686
687 assert getattr(mod, name)() == expected, name + ":" + repr(case)
688 if compare_with_cpython and case not in cpython_incompatible_cases:
689 assert getattr(mod, name)() == getattr(mod, name + "_cpython")(), \
690 "CPython check: " + name + ":" + repr(case)
691
692 def test_FromFormat_Ptr(self):
693 # '%p' is platform dependent to some extent, so we need to use regex
694 import re
695 mod = self.make_module("""
696 HPyDef_METH(p, "p", HPyFunc_NOARGS)
697 static HPy p_impl(HPyContext *ctx, HPy self)
698 {
699 return HPyUnicode_FromFormat(ctx, "prefix-%p-suffix", (void*) 0xbeef);
700 }
701
702 @EXPORT(p)
703 @INIT
704 """)
705 assert re.match(r'prefix-0x[0]{,60}[bB][eE][eE][fF]-suffix', mod.p())
706
707 def test_FromFormat_PyObjs(self):
708 mod = self.make_module("""
709 HPyDef_METH(S, "S", HPyFunc_O)
710 static HPy S_impl(HPyContext *ctx, HPy self, HPy arg)
711 {
712 return HPyUnicode_FromFormat(ctx, "prefix-%S-suffix", arg);
713 }
714
715 HPyDef_METH(R, "R", HPyFunc_O)
716 static HPy R_impl(HPyContext *ctx, HPy self, HPy arg)
717 {
718 return HPyUnicode_FromFormat(ctx, "prefix-%R-suffix", arg);
719 }
720
721 HPyDef_METH(A, "A", HPyFunc_O)
722 static HPy A_impl(HPyContext *ctx, HPy self, HPy arg)
723 {
724 return HPyUnicode_FromFormat(ctx, "prefix-%A-suffix", arg);
725 }
726
727 @EXPORT(S)
728 @EXPORT(R)
729 @EXPORT(A)
730 @INIT
731 """)
732
733 class MyObj:
734 def __str__(self):
735 return "MyObj.__str__"
736
737 def __repr__(self):
738 return "MyObj.__repr__ü"
739
740 assert mod.S('ABC') == 'prefix-ABC-suffix'
741 assert mod.S(42) == 'prefix-42-suffix'
742 assert mod.S(MyObj()) == 'prefix-MyObj.__str__-suffix'
743
744 assert mod.R('ABC') == "prefix-'ABC'-suffix"
745 assert mod.R(42) == 'prefix-42-suffix'
746 assert mod.R(MyObj()) == 'prefix-MyObj.__repr__ü-suffix'
747
748 assert mod.A('ABC') == "prefix-'ABC'-suffix"
749 assert mod.A(42) == 'prefix-42-suffix'
750 assert mod.A(MyObj()) == 'prefix-MyObj.__repr__\\xfc-suffix'
751
752 def test_FromFormat_NoAsciiEncodedFmt(self):
753 import pytest
754 mod = self.make_module("""
755 HPyDef_METH(no_ascii_fmt, "no_ascii_fmt", HPyFunc_O)
756 static HPy no_ascii_fmt_impl(HPyContext *ctx, HPy self, HPy arg)
757 {
758 HPy_ssize_t s;
759 const char *fmt = HPyUnicode_AsUTF8AndSize(ctx, arg, &s);
760 return HPyUnicode_FromFormat(ctx, fmt);
761 }
762
763 @EXPORT(no_ascii_fmt)
764 @INIT
765 """)
766
767 with pytest.raises(ValueError, match="expected an ASCII-encoded format string, got a non-ASCII byte: 0xc3"):
768 mod.no_ascii_fmt("format ü")
769
770 def test_FromFormat_Unicode(self):
771 mod = self.make_module("""
772 HPyDef_METH(f, "f", HPyFunc_O)
773 static HPy f_impl(HPyContext *ctx, HPy self, HPy arg)
774 {
775 return HPyUnicode_FromFormat(ctx, "%10.5S", arg);
776 }
777
778 @EXPORT(f)
779 @INIT
780 """)
781 assert mod.f("€urΘpe") == " €urΘp"
782
783 def test_FromFormat_LongFormat(self):
784 chunk_size = 1000
785 chunks_count = 5
786 total_c_size = (chunk_size + 1) * chunks_count + 1
787 args = ','.join([str(i) for i in range(1, chunks_count+1)])
788 mod = self.make_module("""
789 #include <string.h>
790
791 HPyDef_METH(f, "f", HPyFunc_NOARGS)
792 static HPy f_impl(HPyContext *ctx, HPy self)
793 {{
794 const size_t chunk_size = {chunk_size} + 1; // for the '%d'
795 const size_t total_size = {total_size};
796 char fmt[{total_size}];
797 memset(fmt, 'a', total_size);
798 fmt[total_size - 1] = '\\0';
799 for (size_t i = 0; i < {chunks_count}; i++) {{
800 fmt[i * chunk_size] = '%';
801 fmt[(i * chunk_size)+1] = 'd';
802 }}
803 return HPyUnicode_FromFormat(ctx, fmt, {args});
804 }}
805
806 @EXPORT(f)
807 @INIT
808 """.format(chunk_size=chunk_size, chunks_count=chunks_count, total_size=total_c_size, args=args))
809 assert mod.f() == ''.join([str(i) + ("a" * (chunk_size - 1)) for i in range(1,chunks_count+1)])
810
811 def test_FromFormat_Limits(self):
812 import sys
813 import pytest
814 mod = self.make_module("""
815 #include <stdio.h>
816
817 HPyDef_METH(width, "width", HPyFunc_NOARGS)
818 static HPy width_impl(HPyContext *ctx, HPy self)
819 {{
820 char fmt[512];
821 sprintf(fmt, "%%%llud", ((unsigned long long) HPY_SSIZE_T_MAX) + 1ull);
822 return HPyUnicode_FromFormat(ctx, fmt, 42);
823 }}
824
825 HPyDef_METH(precision, "precision", HPyFunc_NOARGS)
826 static HPy precision_impl(HPyContext *ctx, HPy self)
827 {{
828 char fmt[512];
829 sprintf(fmt, "%%.%llud", ((unsigned long long) HPY_SSIZE_T_MAX) + 1ull);
830 return HPyUnicode_FromFormat(ctx, fmt, 42);
831 }}
832
833 HPyDef_METH(memory_err_width, "memory_err_width", HPyFunc_NOARGS)
834 static HPy memory_err_width_impl(HPyContext *ctx, HPy self)
835 {{
836 return HPyUnicode_FromFormat(ctx, "%{max_size}d", 42);
837 }}
838
839 HPyDef_METH(memory_err_precision, "memory_err_precision", HPyFunc_NOARGS)
840 static HPy memory_err_precision_impl(HPyContext *ctx, HPy self)
841 {{
842 return HPyUnicode_FromFormat(ctx, "%.{max_size}d", 42);
843 }}
844
845 @EXPORT(width)
846 @EXPORT(precision)
847 @INIT
848 """.format(max_size = str(sys.maxsize + 1)))
849 with pytest.raises(ValueError) as exc:
850 mod.width()
851 assert str(exc.value) == "width too big"
852 with pytest.raises(ValueError) as exc:
853 mod.precision()
854 assert str(exc.value) == "precision too big"
855
856 def test_FromEncodedObject(self):
857 import pytest
858 mod = self.make_module("""
859 static const char *as_string(HPyContext *ctx, HPy h)
860 {
861 const char *res = HPyUnicode_AsUTF8AndSize(ctx, h, NULL);
862 if (res == NULL)
863 HPyErr_Clear(ctx);
864 return res;
865 }
866
867 HPyDef_METH(f, "f", HPyFunc_VARARGS)
868 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
869 {
870 HPy h_obj;
871 const char *encoding, *errors;
872 if (nargs != 3) {
873 HPyErr_SetString(ctx, ctx->h_TypeError, "expected exactly 3 arguments");
874 return HPy_NULL;
875 }
876 h_obj = HPy_Is(ctx, args[0], ctx->h_None) ? HPy_NULL : args[0];
877 encoding = as_string(ctx, args[1]);
878 errors = as_string(ctx, args[2]);
879 return HPyUnicode_FromEncodedObject(ctx, h_obj, encoding, errors);
880 }
881 @EXPORT(f)
882 @INIT
883 """)
884 # "hellö" as UTF-8 encoded bytes
885 utf8_bytes = b"hell\xc3\xb6"
886 # "hellö" as UTF-16 encoded bytes
887 utf16_bytes = b'\xff\xfeh\x00e\x00l\x00l\x00\xf6\x00'
888 ascii_codepoints = bytes(range(1, 128))
889
890 # note: None (if passed to arguments 'encoding' or 'errors') will be
891 # translated to a NULL pointer
892
893 for errors in (None, "strict", "ignore", "replace"):
894 assert mod.f(b"hello", "ascii", errors) == "hello"
895 assert mod.f(utf8_bytes, "utf8", errors) == "hellö"
896 assert mod.f(utf16_bytes, "utf16", errors) == "hellö"
897 assert len(mod.f(ascii_codepoints, "ascii", errors)) == 127
898 assert len(mod.f(ascii_codepoints, "utf8", errors)) == 127
899
900 # None will be translated to NULL and then defaults to UTF-8 encoding
901 for encoding in (None, "utf8"):
902 assert mod.f(utf8_bytes, encoding, None) == "hellö"
903
904 with pytest.raises(UnicodeDecodeError):
905 mod.f(utf16_bytes, encoding, None)
906
907 assert mod.f(utf16_bytes, encoding, "replace") == '��h\x00e\x00l\x00l\x00�\x00'
908 assert mod.f(utf16_bytes, encoding, "ignore") == 'h\x00e\x00l\x00l\x00\x00'
909
910 # test unknown encoding
911 with pytest.raises(LookupError):
912 mod.f(b"hello", "qwertyasdf13", None)
913
914 with pytest.raises(SystemError):
915 mod.f(None, None, None)
916 with pytest.raises(TypeError):
917 mod.f("hello", None, None)
918 with pytest.raises(TypeError):
919 mod.f(123, None, None)
920
921 def test_Substring(self):
922 import pytest
923 import string
924 mod = self.make_module("""
925 HPyDef_METH(f, "f", HPyFunc_VARARGS)
926 static HPy f_impl(HPyContext *ctx, HPy self, const HPy *args, size_t nargs)
927 {
928 HPy_ssize_t start, end;
929 if (nargs != 3) {
930 HPyErr_SetString(ctx, ctx->h_TypeError, "expected exactly 3 arguments");
931 return HPy_NULL;
932 }
933
934 start = HPyLong_AsSsize_t(ctx, args[1]);
935 if (start == -1 && HPyErr_Occurred(ctx))
936 return HPy_NULL;
937
938 end = HPyLong_AsSsize_t(ctx, args[2]);
939 if (end == -1 && HPyErr_Occurred(ctx))
940 return HPy_NULL;
941
942 return HPyUnicode_Substring(ctx, args[0], start, end);
943 }
944 @EXPORT(f)
945 @INIT
946 """)
947 # start == end
948 assert mod.f("hello", 0, 0) == ""
949 assert mod.f("hello", 4, 4) == ""
950 assert mod.f("hello", 5, 0) == ""
951 # start < end
952 assert mod.f("hello", 0, 5) == "hello"
953 assert mod.f("hello", 0, 100) == "hello"
954 assert mod.f('hello', 0, 1) == 'h'
955 assert mod.f("hello", 0, 2) == "he"
956 assert mod.f("hello", 2, 5) == "llo"
957 assert mod.f("hello", 2, 4) == "ll"
958 assert mod.f("hello", 100, 105) == ""
959 # start > end
960 assert mod.f("hello", 2000, 1000) == ""
961 assert mod.f("hello", 2, 1) == ""
962
963 with pytest.raises(IndexError):
964 mod.f("hello", -2, 5)
965 with pytest.raises(IndexError):
966 mod.f("hello", 2, -1)
967
968 # The following block is a variation of CPython's
969 # 'string_tests.py: test_extended_getslice'. This compares substrings
970 # with list slicing.
971 s = string.ascii_letters + string.digits
972 n = len(s)
973 indices = (0, 1, 3, 41, 1000, n-1, n-2, n-37)
974 for start in indices:
975 for stop in indices:
976 L = list(s)[start:stop]
977 assert mod.f(s, start, stop) == "".join(L)