• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import unittest
2import math
3import string
4import sys
5from test import support
6from test.support import import_helper
7from test.support import warnings_helper
8# Skip this test if the _testcapi module isn't available.
9_testcapi = import_helper.import_module('_testcapi')
10from _testcapi import getargs_keywords, getargs_keyword_only
11
12# > How about the following counterproposal. This also changes some of
13# > the other format codes to be a little more regular.
14# >
15# > Code C type Range check
16# >
17# > b unsigned char 0..UCHAR_MAX
18# > h signed short SHRT_MIN..SHRT_MAX
19# > B unsigned char none **
20# > H unsigned short none **
21# > k * unsigned long none
22# > I * unsigned int 0..UINT_MAX
23#
24#
25# > i int INT_MIN..INT_MAX
26# > l long LONG_MIN..LONG_MAX
27#
28# > K * unsigned long long none
29# > L long long LLONG_MIN..LLONG_MAX
30#
31# > Notes:
32# >
33# > * New format codes.
34# >
35# > ** Changed from previous "range-and-a-half" to "none"; the
36# > range-and-a-half checking wasn't particularly useful.
37#
38# Plus a C API or two, e.g. PyLong_AsUnsignedLongMask() ->
39# unsigned long and PyLong_AsUnsignedLongLongMask() -> unsigned
40# long long (if that exists).
41
42LARGE = 0x7FFFFFFF
43VERY_LARGE = 0xFF0000121212121212121242
44
45from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \
46     INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, \
47     SHRT_MIN, SHRT_MAX, FLT_MIN, FLT_MAX, DBL_MIN, DBL_MAX
48
49DBL_MAX_EXP = sys.float_info.max_exp
50INF = float('inf')
51NAN = float('nan')
52
53# fake, they are not defined in Python's header files
54LLONG_MAX = 2**63-1
55LLONG_MIN = -2**63
56ULLONG_MAX = 2**64-1
57
58class Index:
59    def __index__(self):
60        return 99
61
62class IndexIntSubclass(int):
63    def __index__(self):
64        return 99
65
66class BadIndex:
67    def __index__(self):
68        return 1.0
69
70class BadIndex2:
71    def __index__(self):
72        return True
73
74class BadIndex3(int):
75    def __index__(self):
76        return True
77
78
79class Int:
80    def __int__(self):
81        return 99
82
83class IntSubclass(int):
84    def __int__(self):
85        return 99
86
87class BadInt:
88    def __int__(self):
89        return 1.0
90
91class BadInt2:
92    def __int__(self):
93        return True
94
95class BadInt3(int):
96    def __int__(self):
97        return True
98
99
100class Float:
101    def __float__(self):
102        return 4.25
103
104class FloatSubclass(float):
105    pass
106
107class FloatSubclass2(float):
108    def __float__(self):
109        return 4.25
110
111class BadFloat:
112    def __float__(self):
113        return 687
114
115class BadFloat2:
116    def __float__(self):
117        return FloatSubclass(4.25)
118
119class BadFloat3(float):
120    def __float__(self):
121        return FloatSubclass(4.25)
122
123
124class Complex:
125    def __complex__(self):
126        return 4.25+0.5j
127
128class ComplexSubclass(complex):
129    pass
130
131class ComplexSubclass2(complex):
132    def __complex__(self):
133        return 4.25+0.5j
134
135class BadComplex:
136    def __complex__(self):
137        return 1.25
138
139class BadComplex2:
140    def __complex__(self):
141        return ComplexSubclass(4.25+0.5j)
142
143class BadComplex3(complex):
144    def __complex__(self):
145        return ComplexSubclass(4.25+0.5j)
146
147
148class TupleSubclass(tuple):
149    pass
150
151class DictSubclass(dict):
152    pass
153
154
155class Unsigned_TestCase(unittest.TestCase):
156    def test_b(self):
157        from _testcapi import getargs_b
158        # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX)
159        self.assertRaises(TypeError, getargs_b, 3.14)
160        self.assertEqual(99, getargs_b(Index()))
161        self.assertEqual(0, getargs_b(IndexIntSubclass()))
162        self.assertRaises(TypeError, getargs_b, BadIndex())
163        with self.assertWarns(DeprecationWarning):
164            self.assertEqual(1, getargs_b(BadIndex2()))
165        self.assertEqual(0, getargs_b(BadIndex3()))
166        self.assertRaises(TypeError, getargs_b, Int())
167        self.assertEqual(0, getargs_b(IntSubclass()))
168        self.assertRaises(TypeError, getargs_b, BadInt())
169        self.assertRaises(TypeError, getargs_b, BadInt2())
170        self.assertEqual(0, getargs_b(BadInt3()))
171
172        self.assertRaises(OverflowError, getargs_b, -1)
173        self.assertEqual(0, getargs_b(0))
174        self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))
175        self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)
176
177        self.assertEqual(42, getargs_b(42))
178        self.assertRaises(OverflowError, getargs_b, VERY_LARGE)
179
180    def test_B(self):
181        from _testcapi import getargs_B
182        # B returns 'unsigned char', no range checking
183        self.assertRaises(TypeError, getargs_B, 3.14)
184        self.assertEqual(99, getargs_B(Index()))
185        self.assertEqual(0, getargs_B(IndexIntSubclass()))
186        self.assertRaises(TypeError, getargs_B, BadIndex())
187        with self.assertWarns(DeprecationWarning):
188            self.assertEqual(1, getargs_B(BadIndex2()))
189        self.assertEqual(0, getargs_B(BadIndex3()))
190        self.assertRaises(TypeError, getargs_B, Int())
191        self.assertEqual(0, getargs_B(IntSubclass()))
192        self.assertRaises(TypeError, getargs_B, BadInt())
193        self.assertRaises(TypeError, getargs_B, BadInt2())
194        self.assertEqual(0, getargs_B(BadInt3()))
195
196        self.assertEqual(UCHAR_MAX, getargs_B(-1))
197        self.assertEqual(0, getargs_B(0))
198        self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
199        self.assertEqual(0, getargs_B(UCHAR_MAX+1))
200
201        self.assertEqual(42, getargs_B(42))
202        self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
203
204    def test_H(self):
205        from _testcapi import getargs_H
206        # H returns 'unsigned short', no range checking
207        self.assertRaises(TypeError, getargs_H, 3.14)
208        self.assertEqual(99, getargs_H(Index()))
209        self.assertEqual(0, getargs_H(IndexIntSubclass()))
210        self.assertRaises(TypeError, getargs_H, BadIndex())
211        with self.assertWarns(DeprecationWarning):
212            self.assertEqual(1, getargs_H(BadIndex2()))
213        self.assertEqual(0, getargs_H(BadIndex3()))
214        self.assertRaises(TypeError, getargs_H, Int())
215        self.assertEqual(0, getargs_H(IntSubclass()))
216        self.assertRaises(TypeError, getargs_H, BadInt())
217        self.assertRaises(TypeError, getargs_H, BadInt2())
218        self.assertEqual(0, getargs_H(BadInt3()))
219
220        self.assertEqual(USHRT_MAX, getargs_H(-1))
221        self.assertEqual(0, getargs_H(0))
222        self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX))
223        self.assertEqual(0, getargs_H(USHRT_MAX+1))
224
225        self.assertEqual(42, getargs_H(42))
226
227        self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
228
229    def test_I(self):
230        from _testcapi import getargs_I
231        # I returns 'unsigned int', no range checking
232        self.assertRaises(TypeError, getargs_I, 3.14)
233        self.assertEqual(99, getargs_I(Index()))
234        self.assertEqual(0, getargs_I(IndexIntSubclass()))
235        self.assertRaises(TypeError, getargs_I, BadIndex())
236        with self.assertWarns(DeprecationWarning):
237            self.assertEqual(1, getargs_I(BadIndex2()))
238        self.assertEqual(0, getargs_I(BadIndex3()))
239        self.assertRaises(TypeError, getargs_I, Int())
240        self.assertEqual(0, getargs_I(IntSubclass()))
241        self.assertRaises(TypeError, getargs_I, BadInt())
242        self.assertRaises(TypeError, getargs_I, BadInt2())
243        self.assertEqual(0, getargs_I(BadInt3()))
244
245        self.assertEqual(UINT_MAX, getargs_I(-1))
246        self.assertEqual(0, getargs_I(0))
247        self.assertEqual(UINT_MAX, getargs_I(UINT_MAX))
248        self.assertEqual(0, getargs_I(UINT_MAX+1))
249
250        self.assertEqual(42, getargs_I(42))
251
252        self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
253
254    def test_k(self):
255        from _testcapi import getargs_k
256        # k returns 'unsigned long', no range checking
257        # it does not accept float, or instances with __int__
258        self.assertRaises(TypeError, getargs_k, 3.14)
259        self.assertRaises(TypeError, getargs_k, Index())
260        self.assertEqual(0, getargs_k(IndexIntSubclass()))
261        self.assertRaises(TypeError, getargs_k, BadIndex())
262        self.assertRaises(TypeError, getargs_k, BadIndex2())
263        self.assertEqual(0, getargs_k(BadIndex3()))
264        self.assertRaises(TypeError, getargs_k, Int())
265        self.assertEqual(0, getargs_k(IntSubclass()))
266        self.assertRaises(TypeError, getargs_k, BadInt())
267        self.assertRaises(TypeError, getargs_k, BadInt2())
268        self.assertEqual(0, getargs_k(BadInt3()))
269
270        self.assertEqual(ULONG_MAX, getargs_k(-1))
271        self.assertEqual(0, getargs_k(0))
272        self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX))
273        self.assertEqual(0, getargs_k(ULONG_MAX+1))
274
275        self.assertEqual(42, getargs_k(42))
276
277        self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
278
279class Signed_TestCase(unittest.TestCase):
280    def test_h(self):
281        from _testcapi import getargs_h
282        # h returns 'short', and does range checking (SHRT_MIN ... SHRT_MAX)
283        self.assertRaises(TypeError, getargs_h, 3.14)
284        self.assertEqual(99, getargs_h(Index()))
285        self.assertEqual(0, getargs_h(IndexIntSubclass()))
286        self.assertRaises(TypeError, getargs_h, BadIndex())
287        with self.assertWarns(DeprecationWarning):
288            self.assertEqual(1, getargs_h(BadIndex2()))
289        self.assertEqual(0, getargs_h(BadIndex3()))
290        self.assertRaises(TypeError, getargs_h, Int())
291        self.assertEqual(0, getargs_h(IntSubclass()))
292        self.assertRaises(TypeError, getargs_h, BadInt())
293        self.assertRaises(TypeError, getargs_h, BadInt2())
294        self.assertEqual(0, getargs_h(BadInt3()))
295
296        self.assertRaises(OverflowError, getargs_h, SHRT_MIN-1)
297        self.assertEqual(SHRT_MIN, getargs_h(SHRT_MIN))
298        self.assertEqual(SHRT_MAX, getargs_h(SHRT_MAX))
299        self.assertRaises(OverflowError, getargs_h, SHRT_MAX+1)
300
301        self.assertEqual(42, getargs_h(42))
302        self.assertRaises(OverflowError, getargs_h, VERY_LARGE)
303
304    def test_i(self):
305        from _testcapi import getargs_i
306        # i returns 'int', and does range checking (INT_MIN ... INT_MAX)
307        self.assertRaises(TypeError, getargs_i, 3.14)
308        self.assertEqual(99, getargs_i(Index()))
309        self.assertEqual(0, getargs_i(IndexIntSubclass()))
310        self.assertRaises(TypeError, getargs_i, BadIndex())
311        with self.assertWarns(DeprecationWarning):
312            self.assertEqual(1, getargs_i(BadIndex2()))
313        self.assertEqual(0, getargs_i(BadIndex3()))
314        self.assertRaises(TypeError, getargs_i, Int())
315        self.assertEqual(0, getargs_i(IntSubclass()))
316        self.assertRaises(TypeError, getargs_i, BadInt())
317        self.assertRaises(TypeError, getargs_i, BadInt2())
318        self.assertEqual(0, getargs_i(BadInt3()))
319
320        self.assertRaises(OverflowError, getargs_i, INT_MIN-1)
321        self.assertEqual(INT_MIN, getargs_i(INT_MIN))
322        self.assertEqual(INT_MAX, getargs_i(INT_MAX))
323        self.assertRaises(OverflowError, getargs_i, INT_MAX+1)
324
325        self.assertEqual(42, getargs_i(42))
326        self.assertRaises(OverflowError, getargs_i, VERY_LARGE)
327
328    def test_l(self):
329        from _testcapi import getargs_l
330        # l returns 'long', and does range checking (LONG_MIN ... LONG_MAX)
331        self.assertRaises(TypeError, getargs_l, 3.14)
332        self.assertEqual(99, getargs_l(Index()))
333        self.assertEqual(0, getargs_l(IndexIntSubclass()))
334        self.assertRaises(TypeError, getargs_l, BadIndex())
335        with self.assertWarns(DeprecationWarning):
336            self.assertEqual(1, getargs_l(BadIndex2()))
337        self.assertEqual(0, getargs_l(BadIndex3()))
338        self.assertRaises(TypeError, getargs_l, Int())
339        self.assertEqual(0, getargs_l(IntSubclass()))
340        self.assertRaises(TypeError, getargs_l, BadInt())
341        self.assertRaises(TypeError, getargs_l, BadInt2())
342        self.assertEqual(0, getargs_l(BadInt3()))
343
344        self.assertRaises(OverflowError, getargs_l, LONG_MIN-1)
345        self.assertEqual(LONG_MIN, getargs_l(LONG_MIN))
346        self.assertEqual(LONG_MAX, getargs_l(LONG_MAX))
347        self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)
348
349        self.assertEqual(42, getargs_l(42))
350        self.assertRaises(OverflowError, getargs_l, VERY_LARGE)
351
352    def test_n(self):
353        from _testcapi import getargs_n
354        # n returns 'Py_ssize_t', and does range checking
355        # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX)
356        self.assertRaises(TypeError, getargs_n, 3.14)
357        self.assertEqual(99, getargs_n(Index()))
358        self.assertEqual(0, getargs_n(IndexIntSubclass()))
359        self.assertRaises(TypeError, getargs_n, BadIndex())
360        with self.assertWarns(DeprecationWarning):
361            self.assertEqual(1, getargs_n(BadIndex2()))
362        self.assertEqual(0, getargs_n(BadIndex3()))
363        self.assertRaises(TypeError, getargs_n, Int())
364        self.assertEqual(0, getargs_n(IntSubclass()))
365        self.assertRaises(TypeError, getargs_n, BadInt())
366        self.assertRaises(TypeError, getargs_n, BadInt2())
367        self.assertEqual(0, getargs_n(BadInt3()))
368
369        self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1)
370        self.assertEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN))
371        self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX))
372        self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1)
373
374        self.assertEqual(42, getargs_n(42))
375        self.assertRaises(OverflowError, getargs_n, VERY_LARGE)
376
377
378class LongLong_TestCase(unittest.TestCase):
379    def test_L(self):
380        from _testcapi import getargs_L
381        # L returns 'long long', and does range checking (LLONG_MIN
382        # ... LLONG_MAX)
383        self.assertRaises(TypeError, getargs_L, 3.14)
384        self.assertRaises(TypeError, getargs_L, "Hello")
385        self.assertEqual(99, getargs_L(Index()))
386        self.assertEqual(0, getargs_L(IndexIntSubclass()))
387        self.assertRaises(TypeError, getargs_L, BadIndex())
388        with self.assertWarns(DeprecationWarning):
389            self.assertEqual(1, getargs_L(BadIndex2()))
390        self.assertEqual(0, getargs_L(BadIndex3()))
391        self.assertRaises(TypeError, getargs_L, Int())
392        self.assertEqual(0, getargs_L(IntSubclass()))
393        self.assertRaises(TypeError, getargs_L, BadInt())
394        self.assertRaises(TypeError, getargs_L, BadInt2())
395        self.assertEqual(0, getargs_L(BadInt3()))
396
397        self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1)
398        self.assertEqual(LLONG_MIN, getargs_L(LLONG_MIN))
399        self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX))
400        self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)
401
402        self.assertEqual(42, getargs_L(42))
403        self.assertRaises(OverflowError, getargs_L, VERY_LARGE)
404
405    def test_K(self):
406        from _testcapi import getargs_K
407        # K return 'unsigned long long', no range checking
408        self.assertRaises(TypeError, getargs_K, 3.14)
409        self.assertRaises(TypeError, getargs_K, Index())
410        self.assertEqual(0, getargs_K(IndexIntSubclass()))
411        self.assertRaises(TypeError, getargs_K, BadIndex())
412        self.assertRaises(TypeError, getargs_K, BadIndex2())
413        self.assertEqual(0, getargs_K(BadIndex3()))
414        self.assertRaises(TypeError, getargs_K, Int())
415        self.assertEqual(0, getargs_K(IntSubclass()))
416        self.assertRaises(TypeError, getargs_K, BadInt())
417        self.assertRaises(TypeError, getargs_K, BadInt2())
418        self.assertEqual(0, getargs_K(BadInt3()))
419
420        self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))
421        self.assertEqual(0, getargs_K(0))
422        self.assertEqual(0, getargs_K(ULLONG_MAX+1))
423
424        self.assertEqual(42, getargs_K(42))
425
426        self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
427
428
429class Float_TestCase(unittest.TestCase):
430    def assertEqualWithSign(self, actual, expected):
431        self.assertEqual(actual, expected)
432        self.assertEqual(math.copysign(1, actual), math.copysign(1, expected))
433
434    def test_f(self):
435        from _testcapi import getargs_f
436        self.assertEqual(getargs_f(4.25), 4.25)
437        self.assertEqual(getargs_f(4), 4.0)
438        self.assertRaises(TypeError, getargs_f, 4.25+0j)
439        self.assertEqual(getargs_f(Float()), 4.25)
440        self.assertEqual(getargs_f(FloatSubclass(7.5)), 7.5)
441        self.assertEqual(getargs_f(FloatSubclass2(7.5)), 7.5)
442        self.assertRaises(TypeError, getargs_f, BadFloat())
443        with self.assertWarns(DeprecationWarning):
444            self.assertEqual(getargs_f(BadFloat2()), 4.25)
445        self.assertEqual(getargs_f(BadFloat3(7.5)), 7.5)
446        self.assertEqual(getargs_f(Index()), 99.0)
447        self.assertRaises(TypeError, getargs_f, Int())
448
449        for x in (FLT_MIN, -FLT_MIN, FLT_MAX, -FLT_MAX, INF, -INF):
450            self.assertEqual(getargs_f(x), x)
451        if FLT_MAX < DBL_MAX:
452            self.assertEqual(getargs_f(DBL_MAX), INF)
453            self.assertEqual(getargs_f(-DBL_MAX), -INF)
454        if FLT_MIN > DBL_MIN:
455            self.assertEqualWithSign(getargs_f(DBL_MIN), 0.0)
456            self.assertEqualWithSign(getargs_f(-DBL_MIN), -0.0)
457        self.assertEqualWithSign(getargs_f(0.0), 0.0)
458        self.assertEqualWithSign(getargs_f(-0.0), -0.0)
459        r = getargs_f(NAN)
460        self.assertNotEqual(r, r)
461
462    @support.requires_IEEE_754
463    def test_f_rounding(self):
464        from _testcapi import getargs_f
465        self.assertEqual(getargs_f(3.40282356e38), FLT_MAX)
466        self.assertEqual(getargs_f(-3.40282356e38), -FLT_MAX)
467
468    def test_d(self):
469        from _testcapi import getargs_d
470        self.assertEqual(getargs_d(4.25), 4.25)
471        self.assertEqual(getargs_d(4), 4.0)
472        self.assertRaises(TypeError, getargs_d, 4.25+0j)
473        self.assertEqual(getargs_d(Float()), 4.25)
474        self.assertEqual(getargs_d(FloatSubclass(7.5)), 7.5)
475        self.assertEqual(getargs_d(FloatSubclass2(7.5)), 7.5)
476        self.assertRaises(TypeError, getargs_d, BadFloat())
477        with self.assertWarns(DeprecationWarning):
478            self.assertEqual(getargs_d(BadFloat2()), 4.25)
479        self.assertEqual(getargs_d(BadFloat3(7.5)), 7.5)
480        self.assertEqual(getargs_d(Index()), 99.0)
481        self.assertRaises(TypeError, getargs_d, Int())
482
483        for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF):
484            self.assertEqual(getargs_d(x), x)
485        self.assertRaises(OverflowError, getargs_d, 1<<DBL_MAX_EXP)
486        self.assertRaises(OverflowError, getargs_d, -1<<DBL_MAX_EXP)
487        self.assertEqualWithSign(getargs_d(0.0), 0.0)
488        self.assertEqualWithSign(getargs_d(-0.0), -0.0)
489        r = getargs_d(NAN)
490        self.assertNotEqual(r, r)
491
492    def test_D(self):
493        from _testcapi import getargs_D
494        self.assertEqual(getargs_D(4.25+0.5j), 4.25+0.5j)
495        self.assertEqual(getargs_D(4.25), 4.25+0j)
496        self.assertEqual(getargs_D(4), 4.0+0j)
497        self.assertEqual(getargs_D(Complex()), 4.25+0.5j)
498        self.assertEqual(getargs_D(ComplexSubclass(7.5+0.25j)), 7.5+0.25j)
499        self.assertEqual(getargs_D(ComplexSubclass2(7.5+0.25j)), 7.5+0.25j)
500        self.assertRaises(TypeError, getargs_D, BadComplex())
501        with self.assertWarns(DeprecationWarning):
502            self.assertEqual(getargs_D(BadComplex2()), 4.25+0.5j)
503        self.assertEqual(getargs_D(BadComplex3(7.5+0.25j)), 7.5+0.25j)
504        self.assertEqual(getargs_D(Index()), 99.0+0j)
505        self.assertRaises(TypeError, getargs_D, Int())
506
507        for x in (DBL_MIN, -DBL_MIN, DBL_MAX, -DBL_MAX, INF, -INF):
508            c = complex(x, 1.0)
509            self.assertEqual(getargs_D(c), c)
510            c = complex(1.0, x)
511            self.assertEqual(getargs_D(c), c)
512        self.assertEqualWithSign(getargs_D(complex(0.0, 1.0)).real, 0.0)
513        self.assertEqualWithSign(getargs_D(complex(-0.0, 1.0)).real, -0.0)
514        self.assertEqualWithSign(getargs_D(complex(1.0, 0.0)).imag, 0.0)
515        self.assertEqualWithSign(getargs_D(complex(1.0, -0.0)).imag, -0.0)
516
517
518class Paradox:
519    "This statement is false."
520    def __bool__(self):
521        raise NotImplementedError
522
523class Boolean_TestCase(unittest.TestCase):
524    def test_p(self):
525        from _testcapi import getargs_p
526        self.assertEqual(0, getargs_p(False))
527        self.assertEqual(0, getargs_p(None))
528        self.assertEqual(0, getargs_p(0))
529        self.assertEqual(0, getargs_p(0.0))
530        self.assertEqual(0, getargs_p(0j))
531        self.assertEqual(0, getargs_p(''))
532        self.assertEqual(0, getargs_p(()))
533        self.assertEqual(0, getargs_p([]))
534        self.assertEqual(0, getargs_p({}))
535
536        self.assertEqual(1, getargs_p(True))
537        self.assertEqual(1, getargs_p(1))
538        self.assertEqual(1, getargs_p(1.0))
539        self.assertEqual(1, getargs_p(1j))
540        self.assertEqual(1, getargs_p('x'))
541        self.assertEqual(1, getargs_p((1,)))
542        self.assertEqual(1, getargs_p([1]))
543        self.assertEqual(1, getargs_p({1:2}))
544        self.assertEqual(1, getargs_p(unittest.TestCase))
545
546        self.assertRaises(NotImplementedError, getargs_p, Paradox())
547
548
549class Tuple_TestCase(unittest.TestCase):
550    def test_args(self):
551        from _testcapi import get_args
552
553        ret = get_args(1, 2)
554        self.assertEqual(ret, (1, 2))
555        self.assertIs(type(ret), tuple)
556
557        ret = get_args(1, *(2, 3))
558        self.assertEqual(ret, (1, 2, 3))
559        self.assertIs(type(ret), tuple)
560
561        ret = get_args(*[1, 2])
562        self.assertEqual(ret, (1, 2))
563        self.assertIs(type(ret), tuple)
564
565        ret = get_args(*TupleSubclass([1, 2]))
566        self.assertEqual(ret, (1, 2))
567        self.assertIs(type(ret), tuple)
568
569        ret = get_args()
570        self.assertIn(ret, ((), None))
571        self.assertIn(type(ret), (tuple, type(None)))
572
573        ret = get_args(*())
574        self.assertIn(ret, ((), None))
575        self.assertIn(type(ret), (tuple, type(None)))
576
577    def test_tuple(self):
578        from _testcapi import getargs_tuple
579
580        ret = getargs_tuple(1, (2, 3))
581        self.assertEqual(ret, (1,2,3))
582
583        # make sure invalid tuple arguments are handled correctly
584        class seq:
585            def __len__(self):
586                return 2
587            def __getitem__(self, n):
588                raise ValueError
589        self.assertRaises(TypeError, getargs_tuple, 1, seq())
590
591class Keywords_TestCase(unittest.TestCase):
592    def test_kwargs(self):
593        from _testcapi import get_kwargs
594
595        ret = get_kwargs(a=1, b=2)
596        self.assertEqual(ret, {'a': 1, 'b': 2})
597        self.assertIs(type(ret), dict)
598
599        ret = get_kwargs(a=1, **{'b': 2, 'c': 3})
600        self.assertEqual(ret, {'a': 1, 'b': 2, 'c': 3})
601        self.assertIs(type(ret), dict)
602
603        ret = get_kwargs(**DictSubclass({'a': 1, 'b': 2}))
604        self.assertEqual(ret, {'a': 1, 'b': 2})
605        self.assertIs(type(ret), dict)
606
607        ret = get_kwargs()
608        self.assertIn(ret, ({}, None))
609        self.assertIn(type(ret), (dict, type(None)))
610
611        ret = get_kwargs(**{})
612        self.assertIn(ret, ({}, None))
613        self.assertIn(type(ret), (dict, type(None)))
614
615    def test_positional_args(self):
616        # using all positional args
617        self.assertEqual(
618            getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10),
619            (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
620            )
621
622    def test_mixed_args(self):
623        # positional and keyword args
624        self.assertEqual(
625            getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10),
626            (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
627            )
628
629    def test_keyword_args(self):
630        # all keywords
631        self.assertEqual(
632            getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10),
633            (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
634            )
635
636    def test_optional_args(self):
637        # missing optional keyword args, skipping tuples
638        self.assertEqual(
639            getargs_keywords(arg1=(1,2), arg2=3, arg5=10),
640            (1, 2, 3, -1, -1, -1, -1, -1, -1, 10)
641            )
642
643    def test_required_args(self):
644        # required arg missing
645        try:
646            getargs_keywords(arg1=(1,2))
647        except TypeError as err:
648            self.assertEqual(
649                str(err), "function missing required argument 'arg2' (pos 2)")
650        else:
651            self.fail('TypeError should have been raised')
652
653    def test_too_many_args(self):
654        try:
655            getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111)
656        except TypeError as err:
657            self.assertEqual(str(err), "function takes at most 5 arguments (6 given)")
658        else:
659            self.fail('TypeError should have been raised')
660
661    def test_invalid_keyword(self):
662        # extraneous keyword arg
663        try:
664            getargs_keywords((1,2),3,arg5=10,arg666=666)
665        except TypeError as err:
666            self.assertEqual(str(err), "'arg666' is an invalid keyword argument for this function")
667        else:
668            self.fail('TypeError should have been raised')
669
670    def test_surrogate_keyword(self):
671        try:
672            getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10})
673        except TypeError as err:
674            self.assertEqual(str(err), "'\udc80' is an invalid keyword argument for this function")
675        else:
676            self.fail('TypeError should have been raised')
677
678class KeywordOnly_TestCase(unittest.TestCase):
679    def test_positional_args(self):
680        # using all possible positional args
681        self.assertEqual(
682            getargs_keyword_only(1, 2),
683            (1, 2, -1)
684            )
685
686    def test_mixed_args(self):
687        # positional and keyword args
688        self.assertEqual(
689            getargs_keyword_only(1, 2, keyword_only=3),
690            (1, 2, 3)
691            )
692
693    def test_keyword_args(self):
694        # all keywords
695        self.assertEqual(
696            getargs_keyword_only(required=1, optional=2, keyword_only=3),
697            (1, 2, 3)
698            )
699
700    def test_optional_args(self):
701        # missing optional keyword args, skipping tuples
702        self.assertEqual(
703            getargs_keyword_only(required=1, optional=2),
704            (1, 2, -1)
705            )
706        self.assertEqual(
707            getargs_keyword_only(required=1, keyword_only=3),
708            (1, -1, 3)
709            )
710
711    def test_required_args(self):
712        self.assertEqual(
713            getargs_keyword_only(1),
714            (1, -1, -1)
715            )
716        self.assertEqual(
717            getargs_keyword_only(required=1),
718            (1, -1, -1)
719            )
720        # required arg missing
721        with self.assertRaisesRegex(TypeError,
722            r"function missing required argument 'required' \(pos 1\)"):
723            getargs_keyword_only(optional=2)
724
725        with self.assertRaisesRegex(TypeError,
726            r"function missing required argument 'required' \(pos 1\)"):
727            getargs_keyword_only(keyword_only=3)
728
729    def test_too_many_args(self):
730        with self.assertRaisesRegex(TypeError,
731            r"function takes at most 2 positional arguments \(3 given\)"):
732            getargs_keyword_only(1, 2, 3)
733
734        with self.assertRaisesRegex(TypeError,
735            r"function takes at most 3 arguments \(4 given\)"):
736            getargs_keyword_only(1, 2, 3, keyword_only=5)
737
738    def test_invalid_keyword(self):
739        # extraneous keyword arg
740        with self.assertRaisesRegex(TypeError,
741            "'monster' is an invalid keyword argument for this function"):
742            getargs_keyword_only(1, 2, monster=666)
743
744    def test_surrogate_keyword(self):
745        with self.assertRaisesRegex(TypeError,
746            "'\udc80' is an invalid keyword argument for this function"):
747            getargs_keyword_only(1, 2, **{'\uDC80': 10})
748
749
750class PositionalOnlyAndKeywords_TestCase(unittest.TestCase):
751    from _testcapi import getargs_positional_only_and_keywords as getargs
752
753    def test_positional_args(self):
754        # using all possible positional args
755        self.assertEqual(self.getargs(1, 2, 3), (1, 2, 3))
756
757    def test_mixed_args(self):
758        # positional and keyword args
759        self.assertEqual(self.getargs(1, 2, keyword=3), (1, 2, 3))
760
761    def test_optional_args(self):
762        # missing optional args
763        self.assertEqual(self.getargs(1, 2), (1, 2, -1))
764        self.assertEqual(self.getargs(1, keyword=3), (1, -1, 3))
765
766    def test_required_args(self):
767        self.assertEqual(self.getargs(1), (1, -1, -1))
768        # required positional arg missing
769        with self.assertRaisesRegex(TypeError,
770            r"function takes at least 1 positional argument \(0 given\)"):
771            self.getargs()
772
773        with self.assertRaisesRegex(TypeError,
774            r"function takes at least 1 positional argument \(0 given\)"):
775            self.getargs(keyword=3)
776
777    def test_empty_keyword(self):
778        with self.assertRaisesRegex(TypeError,
779            "'' is an invalid keyword argument for this function"):
780            self.getargs(1, 2, **{'': 666})
781
782
783class Bytes_TestCase(unittest.TestCase):
784    def test_c(self):
785        from _testcapi import getargs_c
786        self.assertRaises(TypeError, getargs_c, b'abc')  # len > 1
787        self.assertEqual(getargs_c(b'a'), 97)
788        self.assertEqual(getargs_c(bytearray(b'a')), 97)
789        self.assertRaises(TypeError, getargs_c, memoryview(b'a'))
790        self.assertRaises(TypeError, getargs_c, 's')
791        self.assertRaises(TypeError, getargs_c, 97)
792        self.assertRaises(TypeError, getargs_c, None)
793
794    def test_y(self):
795        from _testcapi import getargs_y
796        self.assertRaises(TypeError, getargs_y, 'abc\xe9')
797        self.assertEqual(getargs_y(b'bytes'), b'bytes')
798        self.assertRaises(ValueError, getargs_y, b'nul:\0')
799        self.assertRaises(TypeError, getargs_y, bytearray(b'bytearray'))
800        self.assertRaises(TypeError, getargs_y, memoryview(b'memoryview'))
801        self.assertRaises(TypeError, getargs_y, None)
802
803    def test_y_star(self):
804        from _testcapi import getargs_y_star
805        self.assertRaises(TypeError, getargs_y_star, 'abc\xe9')
806        self.assertEqual(getargs_y_star(b'bytes'), b'bytes')
807        self.assertEqual(getargs_y_star(b'nul:\0'), b'nul:\0')
808        self.assertEqual(getargs_y_star(bytearray(b'bytearray')), b'bytearray')
809        self.assertEqual(getargs_y_star(memoryview(b'memoryview')), b'memoryview')
810        self.assertRaises(TypeError, getargs_y_star, None)
811
812    def test_y_hash(self):
813        from _testcapi import getargs_y_hash
814        self.assertRaises(TypeError, getargs_y_hash, 'abc\xe9')
815        self.assertEqual(getargs_y_hash(b'bytes'), b'bytes')
816        self.assertEqual(getargs_y_hash(b'nul:\0'), b'nul:\0')
817        self.assertRaises(TypeError, getargs_y_hash, bytearray(b'bytearray'))
818        self.assertRaises(TypeError, getargs_y_hash, memoryview(b'memoryview'))
819        self.assertRaises(TypeError, getargs_y_hash, None)
820
821    def test_w_star(self):
822        # getargs_w_star() modifies first and last byte
823        from _testcapi import getargs_w_star
824        self.assertRaises(TypeError, getargs_w_star, 'abc\xe9')
825        self.assertRaises(TypeError, getargs_w_star, b'bytes')
826        self.assertRaises(TypeError, getargs_w_star, b'nul:\0')
827        self.assertRaises(TypeError, getargs_w_star, memoryview(b'bytes'))
828        buf = bytearray(b'bytearray')
829        self.assertEqual(getargs_w_star(buf), b'[ytearra]')
830        self.assertEqual(buf, bytearray(b'[ytearra]'))
831        buf = bytearray(b'memoryview')
832        self.assertEqual(getargs_w_star(memoryview(buf)), b'[emoryvie]')
833        self.assertEqual(buf, bytearray(b'[emoryvie]'))
834        self.assertRaises(TypeError, getargs_w_star, None)
835
836
837class String_TestCase(unittest.TestCase):
838    def test_C(self):
839        from _testcapi import getargs_C
840        self.assertRaises(TypeError, getargs_C, 'abc')  # len > 1
841        self.assertEqual(getargs_C('a'), 97)
842        self.assertEqual(getargs_C('\u20ac'), 0x20ac)
843        self.assertEqual(getargs_C('\U0001f40d'), 0x1f40d)
844        self.assertRaises(TypeError, getargs_C, b'a')
845        self.assertRaises(TypeError, getargs_C, bytearray(b'a'))
846        self.assertRaises(TypeError, getargs_C, memoryview(b'a'))
847        self.assertRaises(TypeError, getargs_C, 97)
848        self.assertRaises(TypeError, getargs_C, None)
849
850    def test_s(self):
851        from _testcapi import getargs_s
852        self.assertEqual(getargs_s('abc\xe9'), b'abc\xc3\xa9')
853        self.assertRaises(ValueError, getargs_s, 'nul:\0')
854        self.assertRaises(TypeError, getargs_s, b'bytes')
855        self.assertRaises(TypeError, getargs_s, bytearray(b'bytearray'))
856        self.assertRaises(TypeError, getargs_s, memoryview(b'memoryview'))
857        self.assertRaises(TypeError, getargs_s, None)
858
859    def test_s_star(self):
860        from _testcapi import getargs_s_star
861        self.assertEqual(getargs_s_star('abc\xe9'), b'abc\xc3\xa9')
862        self.assertEqual(getargs_s_star('nul:\0'), b'nul:\0')
863        self.assertEqual(getargs_s_star(b'bytes'), b'bytes')
864        self.assertEqual(getargs_s_star(bytearray(b'bytearray')), b'bytearray')
865        self.assertEqual(getargs_s_star(memoryview(b'memoryview')), b'memoryview')
866        self.assertRaises(TypeError, getargs_s_star, None)
867
868    def test_s_hash(self):
869        from _testcapi import getargs_s_hash
870        self.assertEqual(getargs_s_hash('abc\xe9'), b'abc\xc3\xa9')
871        self.assertEqual(getargs_s_hash('nul:\0'), b'nul:\0')
872        self.assertEqual(getargs_s_hash(b'bytes'), b'bytes')
873        self.assertRaises(TypeError, getargs_s_hash, bytearray(b'bytearray'))
874        self.assertRaises(TypeError, getargs_s_hash, memoryview(b'memoryview'))
875        self.assertRaises(TypeError, getargs_s_hash, None)
876
877    def test_s_hash_int(self):
878        # "s#" without PY_SSIZE_T_CLEAN defined.
879        from _testcapi import getargs_s_hash_int
880        self.assertRaises(SystemError, getargs_s_hash_int, "abc")
881        self.assertRaises(SystemError, getargs_s_hash_int, x=42)
882        # getargs_s_hash_int() don't raise SystemError because skipitem() is not called.
883
884    def test_z(self):
885        from _testcapi import getargs_z
886        self.assertEqual(getargs_z('abc\xe9'), b'abc\xc3\xa9')
887        self.assertRaises(ValueError, getargs_z, 'nul:\0')
888        self.assertRaises(TypeError, getargs_z, b'bytes')
889        self.assertRaises(TypeError, getargs_z, bytearray(b'bytearray'))
890        self.assertRaises(TypeError, getargs_z, memoryview(b'memoryview'))
891        self.assertIsNone(getargs_z(None))
892
893    def test_z_star(self):
894        from _testcapi import getargs_z_star
895        self.assertEqual(getargs_z_star('abc\xe9'), b'abc\xc3\xa9')
896        self.assertEqual(getargs_z_star('nul:\0'), b'nul:\0')
897        self.assertEqual(getargs_z_star(b'bytes'), b'bytes')
898        self.assertEqual(getargs_z_star(bytearray(b'bytearray')), b'bytearray')
899        self.assertEqual(getargs_z_star(memoryview(b'memoryview')), b'memoryview')
900        self.assertIsNone(getargs_z_star(None))
901
902    def test_z_hash(self):
903        from _testcapi import getargs_z_hash
904        self.assertEqual(getargs_z_hash('abc\xe9'), b'abc\xc3\xa9')
905        self.assertEqual(getargs_z_hash('nul:\0'), b'nul:\0')
906        self.assertEqual(getargs_z_hash(b'bytes'), b'bytes')
907        self.assertRaises(TypeError, getargs_z_hash, bytearray(b'bytearray'))
908        self.assertRaises(TypeError, getargs_z_hash, memoryview(b'memoryview'))
909        self.assertIsNone(getargs_z_hash(None))
910
911    def test_es(self):
912        from _testcapi import getargs_es
913        self.assertEqual(getargs_es('abc\xe9'), b'abc\xc3\xa9')
914        self.assertEqual(getargs_es('abc\xe9', 'latin1'), b'abc\xe9')
915        self.assertRaises(UnicodeEncodeError, getargs_es, 'abc\xe9', 'ascii')
916        self.assertRaises(LookupError, getargs_es, 'abc\xe9', 'spam')
917        self.assertRaises(TypeError, getargs_es, b'bytes', 'latin1')
918        self.assertRaises(TypeError, getargs_es, bytearray(b'bytearray'), 'latin1')
919        self.assertRaises(TypeError, getargs_es, memoryview(b'memoryview'), 'latin1')
920        self.assertRaises(TypeError, getargs_es, None, 'latin1')
921        self.assertRaises(TypeError, getargs_es, 'nul:\0', 'latin1')
922
923    def test_et(self):
924        from _testcapi import getargs_et
925        self.assertEqual(getargs_et('abc\xe9'), b'abc\xc3\xa9')
926        self.assertEqual(getargs_et('abc\xe9', 'latin1'), b'abc\xe9')
927        self.assertRaises(UnicodeEncodeError, getargs_et, 'abc\xe9', 'ascii')
928        self.assertRaises(LookupError, getargs_et, 'abc\xe9', 'spam')
929        self.assertEqual(getargs_et(b'bytes', 'latin1'), b'bytes')
930        self.assertEqual(getargs_et(bytearray(b'bytearray'), 'latin1'), b'bytearray')
931        self.assertRaises(TypeError, getargs_et, memoryview(b'memoryview'), 'latin1')
932        self.assertRaises(TypeError, getargs_et, None, 'latin1')
933        self.assertRaises(TypeError, getargs_et, 'nul:\0', 'latin1')
934        self.assertRaises(TypeError, getargs_et, b'nul:\0', 'latin1')
935        self.assertRaises(TypeError, getargs_et, bytearray(b'nul:\0'), 'latin1')
936
937    def test_es_hash(self):
938        from _testcapi import getargs_es_hash
939        self.assertEqual(getargs_es_hash('abc\xe9'), b'abc\xc3\xa9')
940        self.assertEqual(getargs_es_hash('abc\xe9', 'latin1'), b'abc\xe9')
941        self.assertRaises(UnicodeEncodeError, getargs_es_hash, 'abc\xe9', 'ascii')
942        self.assertRaises(LookupError, getargs_es_hash, 'abc\xe9', 'spam')
943        self.assertRaises(TypeError, getargs_es_hash, b'bytes', 'latin1')
944        self.assertRaises(TypeError, getargs_es_hash, bytearray(b'bytearray'), 'latin1')
945        self.assertRaises(TypeError, getargs_es_hash, memoryview(b'memoryview'), 'latin1')
946        self.assertRaises(TypeError, getargs_es_hash, None, 'latin1')
947        self.assertEqual(getargs_es_hash('nul:\0', 'latin1'), b'nul:\0')
948
949        buf = bytearray(b'x'*8)
950        self.assertEqual(getargs_es_hash('abc\xe9', 'latin1', buf), b'abc\xe9')
951        self.assertEqual(buf, bytearray(b'abc\xe9\x00xxx'))
952        buf = bytearray(b'x'*5)
953        self.assertEqual(getargs_es_hash('abc\xe9', 'latin1', buf), b'abc\xe9')
954        self.assertEqual(buf, bytearray(b'abc\xe9\x00'))
955        buf = bytearray(b'x'*4)
956        self.assertRaises(ValueError, getargs_es_hash, 'abc\xe9', 'latin1', buf)
957        self.assertEqual(buf, bytearray(b'x'*4))
958        buf = bytearray()
959        self.assertRaises(ValueError, getargs_es_hash, 'abc\xe9', 'latin1', buf)
960
961    def test_et_hash(self):
962        from _testcapi import getargs_et_hash
963        self.assertEqual(getargs_et_hash('abc\xe9'), b'abc\xc3\xa9')
964        self.assertEqual(getargs_et_hash('abc\xe9', 'latin1'), b'abc\xe9')
965        self.assertRaises(UnicodeEncodeError, getargs_et_hash, 'abc\xe9', 'ascii')
966        self.assertRaises(LookupError, getargs_et_hash, 'abc\xe9', 'spam')
967        self.assertEqual(getargs_et_hash(b'bytes', 'latin1'), b'bytes')
968        self.assertEqual(getargs_et_hash(bytearray(b'bytearray'), 'latin1'), b'bytearray')
969        self.assertRaises(TypeError, getargs_et_hash, memoryview(b'memoryview'), 'latin1')
970        self.assertRaises(TypeError, getargs_et_hash, None, 'latin1')
971        self.assertEqual(getargs_et_hash('nul:\0', 'latin1'), b'nul:\0')
972        self.assertEqual(getargs_et_hash(b'nul:\0', 'latin1'), b'nul:\0')
973        self.assertEqual(getargs_et_hash(bytearray(b'nul:\0'), 'latin1'), b'nul:\0')
974
975        buf = bytearray(b'x'*8)
976        self.assertEqual(getargs_et_hash('abc\xe9', 'latin1', buf), b'abc\xe9')
977        self.assertEqual(buf, bytearray(b'abc\xe9\x00xxx'))
978        buf = bytearray(b'x'*5)
979        self.assertEqual(getargs_et_hash('abc\xe9', 'latin1', buf), b'abc\xe9')
980        self.assertEqual(buf, bytearray(b'abc\xe9\x00'))
981        buf = bytearray(b'x'*4)
982        self.assertRaises(ValueError, getargs_et_hash, 'abc\xe9', 'latin1', buf)
983        self.assertEqual(buf, bytearray(b'x'*4))
984        buf = bytearray()
985        self.assertRaises(ValueError, getargs_et_hash, 'abc\xe9', 'latin1', buf)
986
987    @support.requires_legacy_unicode_capi
988    def test_u(self):
989        from _testcapi import getargs_u
990        with self.assertWarns(DeprecationWarning):
991            self.assertEqual(getargs_u('abc\xe9'), 'abc\xe9')
992        with self.assertWarns(DeprecationWarning):
993            self.assertRaises(ValueError, getargs_u, 'nul:\0')
994        with self.assertWarns(DeprecationWarning):
995            self.assertRaises(TypeError, getargs_u, b'bytes')
996        with self.assertWarns(DeprecationWarning):
997            self.assertRaises(TypeError, getargs_u, bytearray(b'bytearray'))
998        with self.assertWarns(DeprecationWarning):
999            self.assertRaises(TypeError, getargs_u, memoryview(b'memoryview'))
1000        with self.assertWarns(DeprecationWarning):
1001            self.assertRaises(TypeError, getargs_u, None)
1002
1003    @support.requires_legacy_unicode_capi
1004    def test_u_hash(self):
1005        from _testcapi import getargs_u_hash
1006        with self.assertWarns(DeprecationWarning):
1007            self.assertEqual(getargs_u_hash('abc\xe9'), 'abc\xe9')
1008        with self.assertWarns(DeprecationWarning):
1009            self.assertEqual(getargs_u_hash('nul:\0'), 'nul:\0')
1010        with self.assertWarns(DeprecationWarning):
1011            self.assertRaises(TypeError, getargs_u_hash, b'bytes')
1012        with self.assertWarns(DeprecationWarning):
1013            self.assertRaises(TypeError, getargs_u_hash, bytearray(b'bytearray'))
1014        with self.assertWarns(DeprecationWarning):
1015            self.assertRaises(TypeError, getargs_u_hash, memoryview(b'memoryview'))
1016        with self.assertWarns(DeprecationWarning):
1017            self.assertRaises(TypeError, getargs_u_hash, None)
1018
1019    @support.requires_legacy_unicode_capi
1020    def test_Z(self):
1021        from _testcapi import getargs_Z
1022        with self.assertWarns(DeprecationWarning):
1023            self.assertEqual(getargs_Z('abc\xe9'), 'abc\xe9')
1024        with self.assertWarns(DeprecationWarning):
1025            self.assertRaises(ValueError, getargs_Z, 'nul:\0')
1026        with self.assertWarns(DeprecationWarning):
1027            self.assertRaises(TypeError, getargs_Z, b'bytes')
1028        with self.assertWarns(DeprecationWarning):
1029            self.assertRaises(TypeError, getargs_Z, bytearray(b'bytearray'))
1030        with self.assertWarns(DeprecationWarning):
1031            self.assertRaises(TypeError, getargs_Z, memoryview(b'memoryview'))
1032        with self.assertWarns(DeprecationWarning):
1033            self.assertIsNone(getargs_Z(None))
1034
1035    @support.requires_legacy_unicode_capi
1036    def test_Z_hash(self):
1037        from _testcapi import getargs_Z_hash
1038        with self.assertWarns(DeprecationWarning):
1039            self.assertEqual(getargs_Z_hash('abc\xe9'), 'abc\xe9')
1040        with self.assertWarns(DeprecationWarning):
1041            self.assertEqual(getargs_Z_hash('nul:\0'), 'nul:\0')
1042        with self.assertWarns(DeprecationWarning):
1043            self.assertRaises(TypeError, getargs_Z_hash, b'bytes')
1044        with self.assertWarns(DeprecationWarning):
1045            self.assertRaises(TypeError, getargs_Z_hash, bytearray(b'bytearray'))
1046        with self.assertWarns(DeprecationWarning):
1047            self.assertRaises(TypeError, getargs_Z_hash, memoryview(b'memoryview'))
1048        with self.assertWarns(DeprecationWarning):
1049            self.assertIsNone(getargs_Z_hash(None))
1050
1051
1052class Object_TestCase(unittest.TestCase):
1053    def test_S(self):
1054        from _testcapi import getargs_S
1055        obj = b'bytes'
1056        self.assertIs(getargs_S(obj), obj)
1057        self.assertRaises(TypeError, getargs_S, bytearray(b'bytearray'))
1058        self.assertRaises(TypeError, getargs_S, 'str')
1059        self.assertRaises(TypeError, getargs_S, None)
1060        self.assertRaises(TypeError, getargs_S, memoryview(obj))
1061
1062    def test_Y(self):
1063        from _testcapi import getargs_Y
1064        obj = bytearray(b'bytearray')
1065        self.assertIs(getargs_Y(obj), obj)
1066        self.assertRaises(TypeError, getargs_Y, b'bytes')
1067        self.assertRaises(TypeError, getargs_Y, 'str')
1068        self.assertRaises(TypeError, getargs_Y, None)
1069        self.assertRaises(TypeError, getargs_Y, memoryview(obj))
1070
1071    def test_U(self):
1072        from _testcapi import getargs_U
1073        obj = 'str'
1074        self.assertIs(getargs_U(obj), obj)
1075        self.assertRaises(TypeError, getargs_U, b'bytes')
1076        self.assertRaises(TypeError, getargs_U, bytearray(b'bytearray'))
1077        self.assertRaises(TypeError, getargs_U, None)
1078
1079
1080# Bug #6012
1081class Test6012(unittest.TestCase):
1082    def test(self):
1083        self.assertEqual(_testcapi.argparsing("Hello", "World"), 1)
1084
1085
1086class SkipitemTest(unittest.TestCase):
1087
1088    # u, and Z raises DeprecationWarning
1089    @warnings_helper.ignore_warnings(category=DeprecationWarning)
1090    def test_skipitem(self):
1091        """
1092        If this test failed, you probably added a new "format unit"
1093        in Python/getargs.c, but neglected to update our poor friend
1094        skipitem() in the same file.  (If so, shame on you!)
1095
1096        With a few exceptions**, this function brute-force tests all
1097        printable ASCII*** characters (32 to 126 inclusive) as format units,
1098        checking to see that PyArg_ParseTupleAndKeywords() return consistent
1099        errors both when the unit is attempted to be used and when it is
1100        skipped.  If the format unit doesn't exist, we'll get one of two
1101        specific error messages (one for used, one for skipped); if it does
1102        exist we *won't* get that error--we'll get either no error or some
1103        other error.  If we get the specific "does not exist" error for one
1104        test and not for the other, there's a mismatch, and the test fails.
1105
1106           ** Some format units have special funny semantics and it would
1107              be difficult to accommodate them here.  Since these are all
1108              well-established and properly skipped in skipitem() we can
1109              get away with not testing them--this test is really intended
1110              to catch *new* format units.
1111
1112          *** Python C source files must be ASCII.  Therefore it's impossible
1113              to have non-ASCII format units.
1114
1115        """
1116        empty_tuple = ()
1117        tuple_1 = (0,)
1118        dict_b = {'b':1}
1119        keywords = ["a", "b"]
1120
1121        for i in range(32, 127):
1122            c = chr(i)
1123
1124            # skip parentheses, the error reporting is inconsistent about them
1125            # skip 'e', it's always a two-character code
1126            # skip '|' and '$', they don't represent arguments anyway
1127            if c in '()e|$':
1128                continue
1129
1130            # test the format unit when not skipped
1131            format = c + "i"
1132            try:
1133                _testcapi.parse_tuple_and_keywords(tuple_1, dict_b,
1134                    format, keywords)
1135                when_not_skipped = False
1136            except SystemError as e:
1137                s = "argument 1 (impossible<bad format char>)"
1138                when_not_skipped = (str(e) == s)
1139            except TypeError:
1140                when_not_skipped = False
1141
1142            # test the format unit when skipped
1143            optional_format = "|" + format
1144            try:
1145                _testcapi.parse_tuple_and_keywords(empty_tuple, dict_b,
1146                    optional_format, keywords)
1147                when_skipped = False
1148            except SystemError as e:
1149                s = "impossible<bad format char>: '{}'".format(format)
1150                when_skipped = (str(e) == s)
1151
1152            message = ("test_skipitem_parity: "
1153                "detected mismatch between convertsimple and skipitem "
1154                "for format unit '{}' ({}), not skipped {}, skipped {}".format(
1155                    c, i, when_skipped, when_not_skipped))
1156            self.assertIs(when_skipped, when_not_skipped, message)
1157
1158    def test_skipitem_with_suffix(self):
1159        parse = _testcapi.parse_tuple_and_keywords
1160        empty_tuple = ()
1161        tuple_1 = (0,)
1162        dict_b = {'b':1}
1163        keywords = ["a", "b"]
1164
1165        supported = ('s#', 's*', 'z#', 'z*', 'u#', 'Z#', 'y#', 'y*', 'w#', 'w*')
1166        for c in string.ascii_letters:
1167            for c2 in '#*':
1168                f = c + c2
1169                with self.subTest(format=f):
1170                    optional_format = "|" + f + "i"
1171                    if f in supported:
1172                        parse(empty_tuple, dict_b, optional_format, keywords)
1173                    else:
1174                        with self.assertRaisesRegex(SystemError,
1175                                    'impossible<bad format char>'):
1176                            parse(empty_tuple, dict_b, optional_format, keywords)
1177
1178        for c in map(chr, range(32, 128)):
1179            f = 'e' + c
1180            optional_format = "|" + f + "i"
1181            with self.subTest(format=f):
1182                if c in 'st':
1183                    parse(empty_tuple, dict_b, optional_format, keywords)
1184                else:
1185                    with self.assertRaisesRegex(SystemError,
1186                                'impossible<bad format char>'):
1187                        parse(empty_tuple, dict_b, optional_format, keywords)
1188
1189
1190class ParseTupleAndKeywords_Test(unittest.TestCase):
1191
1192    def test_parse_tuple_and_keywords(self):
1193        # Test handling errors in the parse_tuple_and_keywords helper itself
1194        self.assertRaises(TypeError, _testcapi.parse_tuple_and_keywords,
1195                          (), {}, 42, [])
1196        self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
1197                          (), {}, '', 42)
1198        self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
1199                          (), {}, '', [''] * 42)
1200        self.assertRaises(ValueError, _testcapi.parse_tuple_and_keywords,
1201                          (), {}, '', [42])
1202
1203    def test_bad_use(self):
1204        # Test handling invalid format and keywords in
1205        # PyArg_ParseTupleAndKeywords()
1206        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1207                          (1,), {}, '||O', ['a'])
1208        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1209                          (1, 2), {}, '|O|O', ['a', 'b'])
1210        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1211                          (), {'a': 1}, '$$O', ['a'])
1212        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1213                          (), {'a': 1, 'b': 2}, '$O$O', ['a', 'b'])
1214        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1215                          (), {'a': 1}, '$|O', ['a'])
1216        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1217                          (), {'a': 1, 'b': 2}, '$O|O', ['a', 'b'])
1218        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1219                          (1,), {}, '|O', ['a', 'b'])
1220        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1221                          (1,), {}, '|OO', ['a'])
1222        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1223                          (), {}, '|$O', [''])
1224        self.assertRaises(SystemError, _testcapi.parse_tuple_and_keywords,
1225                          (), {}, '|OO', ['a', ''])
1226
1227    def test_positional_only(self):
1228        parse = _testcapi.parse_tuple_and_keywords
1229
1230        parse((1, 2, 3), {}, 'OOO', ['', '', 'a'])
1231        parse((1, 2), {'a': 3}, 'OOO', ['', '', 'a'])
1232        with self.assertRaisesRegex(TypeError,
1233               r'function takes at least 2 positional arguments \(1 given\)'):
1234            parse((1,), {'a': 3}, 'OOO', ['', '', 'a'])
1235        parse((1,), {}, 'O|OO', ['', '', 'a'])
1236        with self.assertRaisesRegex(TypeError,
1237               r'function takes at least 1 positional argument \(0 given\)'):
1238            parse((), {}, 'O|OO', ['', '', 'a'])
1239        parse((1, 2), {'a': 3}, 'OO$O', ['', '', 'a'])
1240        with self.assertRaisesRegex(TypeError,
1241               r'function takes exactly 2 positional arguments \(1 given\)'):
1242            parse((1,), {'a': 3}, 'OO$O', ['', '', 'a'])
1243        parse((1,), {}, 'O|O$O', ['', '', 'a'])
1244        with self.assertRaisesRegex(TypeError,
1245               r'function takes at least 1 positional argument \(0 given\)'):
1246            parse((), {}, 'O|O$O', ['', '', 'a'])
1247        with self.assertRaisesRegex(SystemError, r'Empty parameter name after \$'):
1248            parse((1,), {}, 'O|$OO', ['', '', 'a'])
1249        with self.assertRaisesRegex(SystemError, 'Empty keyword'):
1250            parse((1,), {}, 'O|OO', ['', 'a', ''])
1251
1252
1253class Test_testcapi(unittest.TestCase):
1254    locals().update((name, getattr(_testcapi, name))
1255                    for name in dir(_testcapi)
1256                    if name.startswith('test_') and name.endswith('_code'))
1257
1258    @warnings_helper.ignore_warnings(category=DeprecationWarning)
1259    def test_u_code(self):
1260        _testcapi.test_u_code()
1261
1262    @warnings_helper.ignore_warnings(category=DeprecationWarning)
1263    def test_Z_code(self):
1264        _testcapi.test_Z_code()
1265
1266
1267if __name__ == "__main__":
1268    unittest.main()
1269