Merged revisions 81782 via svnmerge from
[python/dscho.git] / Modules / _testcapimodule.c
blob3e356d52a5c5fe08c33c81ed0ac0654cf2bac612
1 /*
2 * C Extension module to test Python interpreter C APIs.
4 * The 'test_*' functions exported by this module are run as part of the
5 * standard Python regression test, via Lib/test/test_capi.py.
6 */
8 #define PY_SSIZE_T_CLEAN
10 #include "Python.h"
11 #include <float.h>
12 #include "structmember.h"
14 #ifdef WITH_THREAD
15 #include "pythread.h"
16 #endif /* WITH_THREAD */
17 static PyObject *TestError; /* set to exception object in init */
19 /* Raise TestError with test_name + ": " + msg, and return NULL. */
21 static PyObject *
22 raiseTestError(const char* test_name, const char* msg)
24 char buf[2048];
26 if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
27 PyErr_SetString(TestError, "internal error msg too large");
28 else {
29 PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
30 PyErr_SetString(TestError, buf);
32 return NULL;
35 /* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
37 The ones derived from autoconf on the UNIX-like OSes can be relied
38 upon (in the absence of sloppy cross-compiling), but the Windows
39 platforms have these hardcoded. Better safe than sorry.
41 static PyObject*
42 sizeof_error(const char* fatname, const char* typname,
43 int expected, int got)
45 char buf[1024];
46 PyOS_snprintf(buf, sizeof(buf),
47 "%.200s #define == %d but sizeof(%.200s) == %d",
48 fatname, expected, typname, got);
49 PyErr_SetString(TestError, buf);
50 return (PyObject*)NULL;
53 static PyObject*
54 test_config(PyObject *self)
56 #define CHECK_SIZEOF(FATNAME, TYPE) \
57 if (FATNAME != sizeof(TYPE)) \
58 return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
60 CHECK_SIZEOF(SIZEOF_SHORT, short);
61 CHECK_SIZEOF(SIZEOF_INT, int);
62 CHECK_SIZEOF(SIZEOF_LONG, long);
63 CHECK_SIZEOF(SIZEOF_VOID_P, void*);
64 CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
65 #ifdef HAVE_LONG_LONG
66 CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
67 #endif
69 #undef CHECK_SIZEOF
71 Py_INCREF(Py_None);
72 return Py_None;
75 static PyObject*
76 test_list_api(PyObject *self)
78 PyObject* list;
79 int i;
81 /* SF bug 132008: PyList_Reverse segfaults */
82 #define NLIST 30
83 list = PyList_New(NLIST);
84 if (list == (PyObject*)NULL)
85 return (PyObject*)NULL;
86 /* list = range(NLIST) */
87 for (i = 0; i < NLIST; ++i) {
88 PyObject* anint = PyLong_FromLong(i);
89 if (anint == (PyObject*)NULL) {
90 Py_DECREF(list);
91 return (PyObject*)NULL;
93 PyList_SET_ITEM(list, i, anint);
95 /* list.reverse(), via PyList_Reverse() */
96 i = PyList_Reverse(list); /* should not blow up! */
97 if (i != 0) {
98 Py_DECREF(list);
99 return (PyObject*)NULL;
101 /* Check that list == range(29, -1, -1) now */
102 for (i = 0; i < NLIST; ++i) {
103 PyObject* anint = PyList_GET_ITEM(list, i);
104 if (PyLong_AS_LONG(anint) != NLIST-1-i) {
105 PyErr_SetString(TestError,
106 "test_list_api: reverse screwed up");
107 Py_DECREF(list);
108 return (PyObject*)NULL;
111 Py_DECREF(list);
112 #undef NLIST
114 Py_INCREF(Py_None);
115 return Py_None;
118 static int
119 test_dict_inner(int count)
121 Py_ssize_t pos = 0, iterations = 0;
122 int i;
123 PyObject *dict = PyDict_New();
124 PyObject *v, *k;
126 if (dict == NULL)
127 return -1;
129 for (i = 0; i < count; i++) {
130 v = PyLong_FromLong(i);
131 PyDict_SetItem(dict, v, v);
132 Py_DECREF(v);
135 while (PyDict_Next(dict, &pos, &k, &v)) {
136 PyObject *o;
137 iterations++;
139 i = PyLong_AS_LONG(v) + 1;
140 o = PyLong_FromLong(i);
141 if (o == NULL)
142 return -1;
143 if (PyDict_SetItem(dict, k, o) < 0) {
144 Py_DECREF(o);
145 return -1;
147 Py_DECREF(o);
150 Py_DECREF(dict);
152 if (iterations != count) {
153 PyErr_SetString(
154 TestError,
155 "test_dict_iteration: dict iteration went wrong ");
156 return -1;
157 } else {
158 return 0;
162 static PyObject*
163 test_dict_iteration(PyObject* self)
165 int i;
167 for (i = 0; i < 200; i++) {
168 if (test_dict_inner(i) < 0) {
169 return NULL;
173 Py_INCREF(Py_None);
174 return Py_None;
178 /* Issue #4701: Check that PyObject_Hash implicitly calls
179 * PyType_Ready if it hasn't already been called
181 static PyTypeObject _HashInheritanceTester_Type = {
182 PyVarObject_HEAD_INIT(NULL, 0)
183 "hashinheritancetester", /* Name of this type */
184 sizeof(PyObject), /* Basic object size */
185 0, /* Item size for varobject */
186 (destructor)PyObject_Del, /* tp_dealloc */
187 0, /* tp_print */
188 0, /* tp_getattr */
189 0, /* tp_setattr */
190 0, /* tp_reserved */
191 0, /* tp_repr */
192 0, /* tp_as_number */
193 0, /* tp_as_sequence */
194 0, /* tp_as_mapping */
195 0, /* tp_hash */
196 0, /* tp_call */
197 0, /* tp_str */
198 PyObject_GenericGetAttr, /* tp_getattro */
199 0, /* tp_setattro */
200 0, /* tp_as_buffer */
201 Py_TPFLAGS_DEFAULT, /* tp_flags */
202 0, /* tp_doc */
203 0, /* tp_traverse */
204 0, /* tp_clear */
205 0, /* tp_richcompare */
206 0, /* tp_weaklistoffset */
207 0, /* tp_iter */
208 0, /* tp_iternext */
209 0, /* tp_methods */
210 0, /* tp_members */
211 0, /* tp_getset */
212 0, /* tp_base */
213 0, /* tp_dict */
214 0, /* tp_descr_get */
215 0, /* tp_descr_set */
216 0, /* tp_dictoffset */
217 0, /* tp_init */
218 0, /* tp_alloc */
219 PyType_GenericNew, /* tp_new */
222 static PyObject*
223 test_lazy_hash_inheritance(PyObject* self)
225 PyTypeObject *type;
226 PyObject *obj;
227 long hash;
229 type = &_HashInheritanceTester_Type;
231 if (type->tp_dict != NULL)
232 /* The type has already been initialized. This probably means
233 -R is being used. */
234 Py_RETURN_NONE;
237 obj = PyObject_New(PyObject, type);
238 if (obj == NULL) {
239 PyErr_Clear();
240 PyErr_SetString(
241 TestError,
242 "test_lazy_hash_inheritance: failed to create object");
243 return NULL;
246 if (type->tp_dict != NULL) {
247 PyErr_SetString(
248 TestError,
249 "test_lazy_hash_inheritance: type initialised too soon");
250 Py_DECREF(obj);
251 return NULL;
254 hash = PyObject_Hash(obj);
255 if ((hash == -1) && PyErr_Occurred()) {
256 PyErr_Clear();
257 PyErr_SetString(
258 TestError,
259 "test_lazy_hash_inheritance: could not hash object");
260 Py_DECREF(obj);
261 return NULL;
264 if (type->tp_dict == NULL) {
265 PyErr_SetString(
266 TestError,
267 "test_lazy_hash_inheritance: type not initialised by hash()");
268 Py_DECREF(obj);
269 return NULL;
272 if (type->tp_hash != PyType_Type.tp_hash) {
273 PyErr_SetString(
274 TestError,
275 "test_lazy_hash_inheritance: unexpected hash function");
276 Py_DECREF(obj);
277 return NULL;
280 Py_DECREF(obj);
282 Py_RETURN_NONE;
286 /* Issue #7385: Check that memoryview() does not crash
287 * when bf_getbuffer returns an error
290 static int
291 broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags)
293 PyErr_SetString(
294 TestError,
295 "test_broken_memoryview: expected error in bf_getbuffer");
296 return -1;
299 static PyBufferProcs memoryviewtester_as_buffer = {
300 (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
301 0, /* bf_releasebuffer */
304 static PyTypeObject _MemoryViewTester_Type = {
305 PyVarObject_HEAD_INIT(NULL, 0)
306 "memoryviewtester", /* Name of this type */
307 sizeof(PyObject), /* Basic object size */
308 0, /* Item size for varobject */
309 (destructor)PyObject_Del, /* tp_dealloc */
310 0, /* tp_print */
311 0, /* tp_getattr */
312 0, /* tp_setattr */
313 0, /* tp_compare */
314 0, /* tp_repr */
315 0, /* tp_as_number */
316 0, /* tp_as_sequence */
317 0, /* tp_as_mapping */
318 0, /* tp_hash */
319 0, /* tp_call */
320 0, /* tp_str */
321 PyObject_GenericGetAttr, /* tp_getattro */
322 0, /* tp_setattro */
323 &memoryviewtester_as_buffer, /* tp_as_buffer */
324 Py_TPFLAGS_DEFAULT, /* tp_flags */
325 0, /* tp_doc */
326 0, /* tp_traverse */
327 0, /* tp_clear */
328 0, /* tp_richcompare */
329 0, /* tp_weaklistoffset */
330 0, /* tp_iter */
331 0, /* tp_iternext */
332 0, /* tp_methods */
333 0, /* tp_members */
334 0, /* tp_getset */
335 0, /* tp_base */
336 0, /* tp_dict */
337 0, /* tp_descr_get */
338 0, /* tp_descr_set */
339 0, /* tp_dictoffset */
340 0, /* tp_init */
341 0, /* tp_alloc */
342 PyType_GenericNew, /* tp_new */
345 static PyObject*
346 test_broken_memoryview(PyObject* self)
348 PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
349 PyObject *res;
351 if (obj == NULL) {
352 PyErr_Clear();
353 PyErr_SetString(
354 TestError,
355 "test_broken_memoryview: failed to create object");
356 return NULL;
359 res = PyMemoryView_FromObject(obj);
360 if (res || !PyErr_Occurred()){
361 PyErr_SetString(
362 TestError,
363 "test_broken_memoryview: memoryview() didn't raise an Exception");
364 Py_XDECREF(res);
365 Py_DECREF(obj);
366 return NULL;
369 PyErr_Clear();
370 Py_DECREF(obj);
371 Py_RETURN_NONE;
375 /* Tests of PyLong_{As, From}{Unsigned,}Long(), and (#ifdef HAVE_LONG_LONG)
376 PyLong_{As, From}{Unsigned,}LongLong().
378 Note that the meat of the test is contained in testcapi_long.h.
379 This is revolting, but delicate code duplication is worse: "almost
380 exactly the same" code is needed to test PY_LONG_LONG, but the ubiquitous
381 dependence on type names makes it impossible to use a parameterized
382 function. A giant macro would be even worse than this. A C++ template
383 would be perfect.
385 The "report an error" functions are deliberately not part of the #include
386 file: if the test fails, you can set a breakpoint in the appropriate
387 error function directly, and crawl back from there in the debugger.
390 #define UNBIND(X) Py_DECREF(X); (X) = NULL
392 static PyObject *
393 raise_test_long_error(const char* msg)
395 return raiseTestError("test_long_api", msg);
398 #define TESTNAME test_long_api_inner
399 #define TYPENAME long
400 #define F_S_TO_PY PyLong_FromLong
401 #define F_PY_TO_S PyLong_AsLong
402 #define F_U_TO_PY PyLong_FromUnsignedLong
403 #define F_PY_TO_U PyLong_AsUnsignedLong
405 #include "testcapi_long.h"
407 static PyObject *
408 test_long_api(PyObject* self)
410 return TESTNAME(raise_test_long_error);
413 #undef TESTNAME
414 #undef TYPENAME
415 #undef F_S_TO_PY
416 #undef F_PY_TO_S
417 #undef F_U_TO_PY
418 #undef F_PY_TO_U
420 #ifdef HAVE_LONG_LONG
422 static PyObject *
423 raise_test_longlong_error(const char* msg)
425 return raiseTestError("test_longlong_api", msg);
428 #define TESTNAME test_longlong_api_inner
429 #define TYPENAME PY_LONG_LONG
430 #define F_S_TO_PY PyLong_FromLongLong
431 #define F_PY_TO_S PyLong_AsLongLong
432 #define F_U_TO_PY PyLong_FromUnsignedLongLong
433 #define F_PY_TO_U PyLong_AsUnsignedLongLong
435 #include "testcapi_long.h"
437 static PyObject *
438 test_longlong_api(PyObject* self, PyObject *args)
440 return TESTNAME(raise_test_longlong_error);
443 #undef TESTNAME
444 #undef TYPENAME
445 #undef F_S_TO_PY
446 #undef F_PY_TO_S
447 #undef F_U_TO_PY
448 #undef F_PY_TO_U
450 /* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG
451 for both long and int arguments. The test may leak a little memory if
452 it fails.
454 static PyObject *
455 test_L_code(PyObject *self)
457 PyObject *tuple, *num;
458 PY_LONG_LONG value;
460 tuple = PyTuple_New(1);
461 if (tuple == NULL)
462 return NULL;
464 num = PyLong_FromLong(42);
465 if (num == NULL)
466 return NULL;
468 PyTuple_SET_ITEM(tuple, 0, num);
470 value = -1;
471 if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
472 return NULL;
473 if (value != 42)
474 return raiseTestError("test_L_code",
475 "L code returned wrong value for long 42");
477 Py_DECREF(num);
478 num = PyLong_FromLong(42);
479 if (num == NULL)
480 return NULL;
482 PyTuple_SET_ITEM(tuple, 0, num);
484 value = -1;
485 if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
486 return NULL;
487 if (value != 42)
488 return raiseTestError("test_L_code",
489 "L code returned wrong value for int 42");
491 Py_DECREF(tuple);
492 Py_INCREF(Py_None);
493 return Py_None;
496 #endif /* ifdef HAVE_LONG_LONG */
498 /* Test tuple argument processing */
499 static PyObject *
500 getargs_tuple(PyObject *self, PyObject *args)
502 int a, b, c;
503 if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
504 return NULL;
505 return Py_BuildValue("iii", a, b, c);
508 /* test PyArg_ParseTupleAndKeywords */
509 static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
511 static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
512 static char *fmt="(ii)i|(i(ii))(iii)i";
513 int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
515 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
516 &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
517 &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
518 return NULL;
519 return Py_BuildValue("iiiiiiiiii",
520 int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
521 int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
524 /* Functions to call PyArg_ParseTuple with integer format codes,
525 and return the result.
527 static PyObject *
528 getargs_b(PyObject *self, PyObject *args)
530 unsigned char value;
531 if (!PyArg_ParseTuple(args, "b", &value))
532 return NULL;
533 return PyLong_FromUnsignedLong((unsigned long)value);
536 static PyObject *
537 getargs_B(PyObject *self, PyObject *args)
539 unsigned char value;
540 if (!PyArg_ParseTuple(args, "B", &value))
541 return NULL;
542 return PyLong_FromUnsignedLong((unsigned long)value);
545 static PyObject *
546 getargs_H(PyObject *self, PyObject *args)
548 unsigned short value;
549 if (!PyArg_ParseTuple(args, "H", &value))
550 return NULL;
551 return PyLong_FromUnsignedLong((unsigned long)value);
554 static PyObject *
555 getargs_I(PyObject *self, PyObject *args)
557 unsigned int value;
558 if (!PyArg_ParseTuple(args, "I", &value))
559 return NULL;
560 return PyLong_FromUnsignedLong((unsigned long)value);
563 static PyObject *
564 getargs_k(PyObject *self, PyObject *args)
566 unsigned long value;
567 if (!PyArg_ParseTuple(args, "k", &value))
568 return NULL;
569 return PyLong_FromUnsignedLong(value);
572 static PyObject *
573 getargs_i(PyObject *self, PyObject *args)
575 int value;
576 if (!PyArg_ParseTuple(args, "i", &value))
577 return NULL;
578 return PyLong_FromLong((long)value);
581 static PyObject *
582 getargs_l(PyObject *self, PyObject *args)
584 long value;
585 if (!PyArg_ParseTuple(args, "l", &value))
586 return NULL;
587 return PyLong_FromLong(value);
590 static PyObject *
591 getargs_n(PyObject *self, PyObject *args)
593 Py_ssize_t value;
594 if (!PyArg_ParseTuple(args, "n", &value))
595 return NULL;
596 return PyLong_FromSsize_t(value);
599 #ifdef HAVE_LONG_LONG
600 static PyObject *
601 getargs_L(PyObject *self, PyObject *args)
603 PY_LONG_LONG value;
604 if (!PyArg_ParseTuple(args, "L", &value))
605 return NULL;
606 return PyLong_FromLongLong(value);
609 static PyObject *
610 getargs_K(PyObject *self, PyObject *args)
612 unsigned PY_LONG_LONG value;
613 if (!PyArg_ParseTuple(args, "K", &value))
614 return NULL;
615 return PyLong_FromUnsignedLongLong(value);
617 #endif
619 /* This function not only tests the 'k' getargs code, but also the
620 PyLong_AsUnsignedLongMask() and PyLong_AsUnsignedLongMask() functions. */
621 static PyObject *
622 test_k_code(PyObject *self)
624 PyObject *tuple, *num;
625 unsigned long value;
627 tuple = PyTuple_New(1);
628 if (tuple == NULL)
629 return NULL;
631 /* a number larger than ULONG_MAX even on 64-bit platforms */
632 num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
633 if (num == NULL)
634 return NULL;
636 value = PyLong_AsUnsignedLongMask(num);
637 if (value != ULONG_MAX)
638 return raiseTestError("test_k_code",
639 "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
641 PyTuple_SET_ITEM(tuple, 0, num);
643 value = 0;
644 if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
645 return NULL;
646 if (value != ULONG_MAX)
647 return raiseTestError("test_k_code",
648 "k code returned wrong value for long 0xFFF...FFF");
650 Py_DECREF(num);
651 num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
652 if (num == NULL)
653 return NULL;
655 value = PyLong_AsUnsignedLongMask(num);
656 if (value != (unsigned long)-0x42)
657 return raiseTestError("test_k_code",
658 "PyLong_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
660 PyTuple_SET_ITEM(tuple, 0, num);
662 value = 0;
663 if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
664 return NULL;
665 if (value != (unsigned long)-0x42)
666 return raiseTestError("test_k_code",
667 "k code returned wrong value for long -0xFFF..000042");
669 Py_DECREF(tuple);
670 Py_INCREF(Py_None);
671 return Py_None;
675 /* Test the s and z codes for PyArg_ParseTuple.
677 static PyObject *
678 test_s_code(PyObject *self)
680 /* Unicode strings should be accepted */
681 PyObject *tuple, *obj;
682 char *value;
684 tuple = PyTuple_New(1);
685 if (tuple == NULL)
686 return NULL;
688 obj = PyUnicode_Decode("t\xeate", strlen("t\xeate"),
689 "latin-1", NULL);
690 if (obj == NULL)
691 return NULL;
693 PyTuple_SET_ITEM(tuple, 0, obj);
695 /* These two blocks used to raise a TypeError:
696 * "argument must be string without null bytes, not str"
698 if (PyArg_ParseTuple(tuple, "s:test_s_code1", &value) < 0)
699 return NULL;
701 if (PyArg_ParseTuple(tuple, "z:test_s_code2", &value) < 0)
702 return NULL;
704 Py_DECREF(tuple);
705 Py_RETURN_NONE;
708 static PyObject *
709 test_bug_7414(PyObject *self)
711 /* Issue #7414: for PyArg_ParseTupleAndKeywords, 'C' code wasn't being
712 skipped properly in skipitem() */
713 int a = 0, b = 0, result;
714 char *kwlist[] = {"a", "b", NULL};
715 PyObject *tuple = NULL, *dict = NULL, *b_str;
717 tuple = PyTuple_New(0);
718 if (tuple == NULL)
719 goto failure;
720 dict = PyDict_New();
721 if (dict == NULL)
722 goto failure;
723 b_str = PyUnicode_FromString("b");
724 if (b_str == NULL)
725 goto failure;
726 result = PyDict_SetItemString(dict, "b", b_str);
727 Py_DECREF(b_str);
728 if (result < 0)
729 goto failure;
731 result = PyArg_ParseTupleAndKeywords(tuple, dict, "|CC",
732 kwlist, &a, &b);
733 if (!result)
734 goto failure;
736 if (a != 0)
737 return raiseTestError("test_bug_7414",
738 "C format code not skipped properly");
739 if (b != 'b')
740 return raiseTestError("test_bug_7414",
741 "C format code returned wrong value");
743 Py_DECREF(dict);
744 Py_DECREF(tuple);
745 Py_RETURN_NONE;
747 failure:
748 Py_XDECREF(dict);
749 Py_XDECREF(tuple);
750 return NULL;
754 static volatile int x;
756 /* Test the u and u# codes for PyArg_ParseTuple. May leak memory in case
757 of an error.
759 static PyObject *
760 test_u_code(PyObject *self)
762 PyObject *tuple, *obj;
763 Py_UNICODE *value;
764 Py_ssize_t len;
765 int x;
767 /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
768 /* Just use the macro and check that it compiles */
769 x = Py_UNICODE_ISSPACE(25);
771 tuple = PyTuple_New(1);
772 if (tuple == NULL)
773 return NULL;
775 obj = PyUnicode_Decode("test", strlen("test"),
776 "ascii", NULL);
777 if (obj == NULL)
778 return NULL;
780 PyTuple_SET_ITEM(tuple, 0, obj);
782 value = 0;
783 if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
784 return NULL;
785 if (value != PyUnicode_AS_UNICODE(obj))
786 return raiseTestError("test_u_code",
787 "u code returned wrong value for u'test'");
788 value = 0;
789 if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
790 return NULL;
791 if (value != PyUnicode_AS_UNICODE(obj) ||
792 len != PyUnicode_GET_SIZE(obj))
793 return raiseTestError("test_u_code",
794 "u# code returned wrong values for u'test'");
796 Py_DECREF(tuple);
797 Py_INCREF(Py_None);
798 return Py_None;
801 /* Test Z and Z# codes for PyArg_ParseTuple */
802 static PyObject *
803 test_Z_code(PyObject *self)
805 PyObject *tuple, *obj;
806 Py_UNICODE *value1, *value2;
807 Py_ssize_t len1, len2;
809 tuple = PyTuple_New(2);
810 if (tuple == NULL)
811 return NULL;
813 obj = PyUnicode_FromString("test");
814 PyTuple_SET_ITEM(tuple, 0, obj);
815 Py_INCREF(Py_None);
816 PyTuple_SET_ITEM(tuple, 1, Py_None);
818 /* swap values on purpose */
819 value1 = NULL;
820 value2 = PyUnicode_AS_UNICODE(obj);
822 /* Test Z for both values */
823 if (PyArg_ParseTuple(tuple, "ZZ:test_Z_code", &value1, &value2) < 0)
824 return NULL;
825 if (value1 != PyUnicode_AS_UNICODE(obj))
826 return raiseTestError("test_Z_code",
827 "Z code returned wrong value for 'test'");
828 if (value2 != NULL)
829 return raiseTestError("test_Z_code",
830 "Z code returned wrong value for None");
832 value1 = NULL;
833 value2 = PyUnicode_AS_UNICODE(obj);
834 len1 = -1;
835 len2 = -1;
837 /* Test Z# for both values */
838 if (PyArg_ParseTuple(tuple, "Z#Z#:test_Z_code", &value1, &len1,
839 &value2, &len2) < 0)
840 return NULL;
841 if (value1 != PyUnicode_AS_UNICODE(obj) ||
842 len1 != PyUnicode_GET_SIZE(obj))
843 return raiseTestError("test_Z_code",
844 "Z# code returned wrong values for 'test'");
845 if (value2 != NULL ||
846 len2 != 0)
847 return raiseTestError("test_Z_code",
848 "Z# code returned wrong values for None'");
850 Py_DECREF(tuple);
851 Py_RETURN_NONE;
854 static PyObject *
855 test_widechar(PyObject *self)
857 #if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
858 const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
859 size_t wtextlen = 1;
860 #else
861 const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
862 size_t wtextlen = 2;
863 #endif
864 PyObject *wide, *utf8;
866 wide = PyUnicode_FromWideChar(wtext, wtextlen);
867 if (wide == NULL)
868 return NULL;
870 utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
871 if (utf8 == NULL) {
872 Py_DECREF(wide);
873 return NULL;
876 if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
877 Py_DECREF(wide);
878 Py_DECREF(utf8);
879 return raiseTestError("test_widechar",
880 "wide string and utf8 string "
881 "have different length");
883 if (PyUnicode_Compare(wide, utf8)) {
884 Py_DECREF(wide);
885 Py_DECREF(utf8);
886 if (PyErr_Occurred())
887 return NULL;
888 return raiseTestError("test_widechar",
889 "wide string and utf8 string "
890 "are different");
893 Py_DECREF(wide);
894 Py_DECREF(utf8);
895 Py_RETURN_NONE;
898 static PyObject *
899 test_empty_argparse(PyObject *self)
901 /* Test that formats can begin with '|'. See issue #4720. */
902 PyObject *tuple, *dict = NULL;
903 static char *kwlist[] = {NULL};
904 int result;
905 tuple = PyTuple_New(0);
906 if (!tuple)
907 return NULL;
908 if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
909 goto done;
910 dict = PyDict_New();
911 if (!dict)
912 goto done;
913 result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
914 done:
915 Py_DECREF(tuple);
916 Py_XDECREF(dict);
917 if (result < 0)
918 return NULL;
919 else {
920 Py_RETURN_NONE;
924 static PyObject *
925 codec_incrementalencoder(PyObject *self, PyObject *args)
927 const char *encoding, *errors = NULL;
928 if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
929 &encoding, &errors))
930 return NULL;
931 return PyCodec_IncrementalEncoder(encoding, errors);
934 static PyObject *
935 codec_incrementaldecoder(PyObject *self, PyObject *args)
937 const char *encoding, *errors = NULL;
938 if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
939 &encoding, &errors))
940 return NULL;
941 return PyCodec_IncrementalDecoder(encoding, errors);
945 /* Simple test of _PyLong_NumBits and _PyLong_Sign. */
946 static PyObject *
947 test_long_numbits(PyObject *self)
949 struct triple {
950 long input;
951 size_t nbits;
952 int sign;
953 } testcases[] = {{0, 0, 0},
954 {1L, 1, 1},
955 {-1L, 1, -1},
956 {2L, 2, 1},
957 {-2L, 2, -1},
958 {3L, 2, 1},
959 {-3L, 2, -1},
960 {4L, 3, 1},
961 {-4L, 3, -1},
962 {0x7fffL, 15, 1}, /* one Python long digit */
963 {-0x7fffL, 15, -1},
964 {0xffffL, 16, 1},
965 {-0xffffL, 16, -1},
966 {0xfffffffL, 28, 1},
967 {-0xfffffffL, 28, -1}};
968 int i;
970 for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
971 PyObject *plong = PyLong_FromLong(testcases[i].input);
972 size_t nbits = _PyLong_NumBits(plong);
973 int sign = _PyLong_Sign(plong);
975 Py_DECREF(plong);
976 if (nbits != testcases[i].nbits)
977 return raiseTestError("test_long_numbits",
978 "wrong result for _PyLong_NumBits");
979 if (sign != testcases[i].sign)
980 return raiseTestError("test_long_numbits",
981 "wrong result for _PyLong_Sign");
983 Py_INCREF(Py_None);
984 return Py_None;
987 /* Example passing NULLs to PyObject_Str(NULL). */
989 static PyObject *
990 test_null_strings(PyObject *self)
992 PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Str(NULL);
993 PyObject *tuple = PyTuple_Pack(2, o1, o2);
994 Py_XDECREF(o1);
995 Py_XDECREF(o2);
996 return tuple;
999 static PyObject *
1000 raise_exception(PyObject *self, PyObject *args)
1002 PyObject *exc;
1003 PyObject *exc_args, *v;
1004 int num_args, i;
1006 if (!PyArg_ParseTuple(args, "Oi:raise_exception",
1007 &exc, &num_args))
1008 return NULL;
1010 exc_args = PyTuple_New(num_args);
1011 if (exc_args == NULL)
1012 return NULL;
1013 for (i = 0; i < num_args; ++i) {
1014 v = PyLong_FromLong(i);
1015 if (v == NULL) {
1016 Py_DECREF(exc_args);
1017 return NULL;
1019 PyTuple_SET_ITEM(exc_args, i, v);
1021 PyErr_SetObject(exc, exc_args);
1022 Py_DECREF(exc_args);
1023 return NULL;
1026 #ifdef WITH_THREAD
1028 /* test_thread_state spawns a thread of its own, and that thread releases
1029 * `thread_done` when it's finished. The driver code has to know when the
1030 * thread finishes, because the thread uses a PyObject (the callable) that
1031 * may go away when the driver finishes. The former lack of this explicit
1032 * synchronization caused rare segfaults, so rare that they were seen only
1033 * on a Mac buildbot (although they were possible on any box).
1035 static PyThread_type_lock thread_done = NULL;
1037 static int
1038 _make_call(void *callable)
1040 PyObject *rc;
1041 int success;
1042 PyGILState_STATE s = PyGILState_Ensure();
1043 rc = PyObject_CallFunction((PyObject *)callable, "");
1044 success = (rc != NULL);
1045 Py_XDECREF(rc);
1046 PyGILState_Release(s);
1047 return success;
1050 /* Same thing, but releases `thread_done` when it returns. This variant
1051 * should be called only from threads spawned by test_thread_state().
1053 static void
1054 _make_call_from_thread(void *callable)
1056 _make_call(callable);
1057 PyThread_release_lock(thread_done);
1060 static PyObject *
1061 test_thread_state(PyObject *self, PyObject *args)
1063 PyObject *fn;
1064 int success = 1;
1066 if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
1067 return NULL;
1069 if (!PyCallable_Check(fn)) {
1070 PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
1071 fn->ob_type->tp_name);
1072 return NULL;
1075 /* Ensure Python is set up for threading */
1076 PyEval_InitThreads();
1077 thread_done = PyThread_allocate_lock();
1078 if (thread_done == NULL)
1079 return PyErr_NoMemory();
1080 PyThread_acquire_lock(thread_done, 1);
1082 /* Start a new thread with our callback. */
1083 PyThread_start_new_thread(_make_call_from_thread, fn);
1084 /* Make the callback with the thread lock held by this thread */
1085 success &= _make_call(fn);
1086 /* Do it all again, but this time with the thread-lock released */
1087 Py_BEGIN_ALLOW_THREADS
1088 success &= _make_call(fn);
1089 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
1090 Py_END_ALLOW_THREADS
1092 /* And once more with and without a thread
1093 XXX - should use a lock and work out exactly what we are trying
1094 to test <wink>
1096 Py_BEGIN_ALLOW_THREADS
1097 PyThread_start_new_thread(_make_call_from_thread, fn);
1098 success &= _make_call(fn);
1099 PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
1100 Py_END_ALLOW_THREADS
1102 /* Release lock we acquired above. This is required on HP-UX. */
1103 PyThread_release_lock(thread_done);
1105 PyThread_free_lock(thread_done);
1106 if (!success)
1107 return NULL;
1108 Py_RETURN_NONE;
1111 /* test Py_AddPendingCalls using threads */
1112 static int _pending_callback(void *arg)
1114 /* we assume the argument is callable object to which we own a reference */
1115 PyObject *callable = (PyObject *)arg;
1116 PyObject *r = PyObject_CallObject(callable, NULL);
1117 Py_DECREF(callable);
1118 Py_XDECREF(r);
1119 return r != NULL ? 0 : -1;
1122 /* The following requests n callbacks to _pending_callback. It can be
1123 * run from any python thread.
1125 PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
1127 PyObject *callable;
1128 int r;
1129 if (PyArg_ParseTuple(arg, "O", &callable) == 0)
1130 return NULL;
1132 /* create the reference for the callbackwhile we hold the lock */
1133 Py_INCREF(callable);
1135 Py_BEGIN_ALLOW_THREADS
1136 r = Py_AddPendingCall(&_pending_callback, callable);
1137 Py_END_ALLOW_THREADS
1139 if (r<0) {
1140 Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
1141 Py_INCREF(Py_False);
1142 return Py_False;
1144 Py_INCREF(Py_True);
1145 return Py_True;
1147 #endif
1149 /* Some tests of PyUnicode_FromFormat(). This needs more tests. */
1150 static PyObject *
1151 test_string_from_format(PyObject *self, PyObject *args)
1153 PyObject *result;
1154 char *msg;
1156 #define CHECK_1_FORMAT(FORMAT, TYPE) \
1157 result = PyUnicode_FromFormat(FORMAT, (TYPE)1); \
1158 if (result == NULL) \
1159 return NULL; \
1160 if (strcmp(_PyUnicode_AsString(result), "1")) { \
1161 msg = FORMAT " failed at 1"; \
1162 goto Fail; \
1164 Py_DECREF(result)
1166 CHECK_1_FORMAT("%d", int);
1167 CHECK_1_FORMAT("%ld", long);
1168 /* The z width modifier was added in Python 2.5. */
1169 CHECK_1_FORMAT("%zd", Py_ssize_t);
1171 /* The u type code was added in Python 2.5. */
1172 CHECK_1_FORMAT("%u", unsigned int);
1173 CHECK_1_FORMAT("%lu", unsigned long);
1174 CHECK_1_FORMAT("%zu", size_t);
1176 Py_RETURN_NONE;
1178 Fail:
1179 Py_XDECREF(result);
1180 return raiseTestError("test_string_from_format", msg);
1182 #undef CHECK_1_FORMAT
1186 static PyObject *
1187 test_unicode_compare_with_ascii(PyObject *self) {
1188 PyObject *py_s = PyUnicode_FromStringAndSize("str\0", 4);
1189 int result;
1190 if (py_s == NULL)
1191 return NULL;
1192 result = PyUnicode_CompareWithASCIIString(py_s, "str");
1193 Py_DECREF(py_s);
1194 if (!result) {
1195 PyErr_SetString(TestError, "Python string ending in NULL "
1196 "should not compare equal to c string.");
1197 return NULL;
1199 Py_RETURN_NONE;
1202 /* This is here to provide a docstring for test_descr. */
1203 static PyObject *
1204 test_with_docstring(PyObject *self)
1206 Py_RETURN_NONE;
1209 /* Test PyOS_string_to_double. */
1210 static PyObject *
1211 test_string_to_double(PyObject *self) {
1212 double result;
1213 char *msg;
1215 #define CHECK_STRING(STR, expected) \
1216 result = PyOS_string_to_double(STR, NULL, NULL); \
1217 if (result == -1.0 && PyErr_Occurred()) \
1218 return NULL; \
1219 if (result != expected) { \
1220 msg = "conversion of " STR " to float failed"; \
1221 goto fail; \
1224 #define CHECK_INVALID(STR) \
1225 result = PyOS_string_to_double(STR, NULL, NULL); \
1226 if (result == -1.0 && PyErr_Occurred()) { \
1227 if (PyErr_ExceptionMatches(PyExc_ValueError)) \
1228 PyErr_Clear(); \
1229 else \
1230 return NULL; \
1232 else { \
1233 msg = "conversion of " STR " didn't raise ValueError"; \
1234 goto fail; \
1237 CHECK_STRING("0.1", 0.1);
1238 CHECK_STRING("1.234", 1.234);
1239 CHECK_STRING("-1.35", -1.35);
1240 CHECK_STRING(".1e01", 1.0);
1241 CHECK_STRING("2.e-2", 0.02);
1243 CHECK_INVALID(" 0.1");
1244 CHECK_INVALID("\t\n-3");
1245 CHECK_INVALID(".123 ");
1246 CHECK_INVALID("3\n");
1247 CHECK_INVALID("123abc");
1249 Py_RETURN_NONE;
1250 fail:
1251 return raiseTestError("test_string_to_double", msg);
1252 #undef CHECK_STRING
1253 #undef CHECK_INVALID
1257 /* Coverage testing of capsule objects. */
1259 static const char *capsule_name = "capsule name";
1260 static char *capsule_pointer = "capsule pointer";
1261 static char *capsule_context = "capsule context";
1262 static const char *capsule_error = NULL;
1263 static int
1264 capsule_destructor_call_count = 0;
1266 static void
1267 capsule_destructor(PyObject *o) {
1268 capsule_destructor_call_count++;
1269 if (PyCapsule_GetContext(o) != capsule_context) {
1270 capsule_error = "context did not match in destructor!";
1271 } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
1272 capsule_error = "destructor did not match in destructor! (woah!)";
1273 } else if (PyCapsule_GetName(o) != capsule_name) {
1274 capsule_error = "name did not match in destructor!";
1275 } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
1276 capsule_error = "pointer did not match in destructor!";
1280 typedef struct {
1281 char *name;
1282 char *module;
1283 char *attribute;
1284 } known_capsule;
1286 static PyObject *
1287 test_capsule(PyObject *self, PyObject *args)
1289 PyObject *object;
1290 const char *error = NULL;
1291 void *pointer;
1292 void *pointer2;
1293 known_capsule known_capsules[] = {
1294 #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
1295 KNOWN_CAPSULE("_socket", "CAPI"),
1296 KNOWN_CAPSULE("_curses", "_C_API"),
1297 KNOWN_CAPSULE("datetime", "datetime_CAPI"),
1298 { NULL, NULL },
1300 known_capsule *known = &known_capsules[0];
1302 #define FAIL(x) { error = (x); goto exit; }
1304 #define CHECK_DESTRUCTOR \
1305 if (capsule_error) { \
1306 FAIL(capsule_error); \
1308 else if (!capsule_destructor_call_count) { \
1309 FAIL("destructor not called!"); \
1311 capsule_destructor_call_count = 0; \
1313 object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
1314 PyCapsule_SetContext(object, capsule_context);
1315 capsule_destructor(object);
1316 CHECK_DESTRUCTOR;
1317 Py_DECREF(object);
1318 CHECK_DESTRUCTOR;
1320 object = PyCapsule_New(known, "ignored", NULL);
1321 PyCapsule_SetPointer(object, capsule_pointer);
1322 PyCapsule_SetName(object, capsule_name);
1323 PyCapsule_SetDestructor(object, capsule_destructor);
1324 PyCapsule_SetContext(object, capsule_context);
1325 capsule_destructor(object);
1326 CHECK_DESTRUCTOR;
1327 /* intentionally access using the wrong name */
1328 pointer2 = PyCapsule_GetPointer(object, "the wrong name");
1329 if (!PyErr_Occurred()) {
1330 FAIL("PyCapsule_GetPointer should have failed but did not!");
1332 PyErr_Clear();
1333 if (pointer2) {
1334 if (pointer2 == capsule_pointer) {
1335 FAIL("PyCapsule_GetPointer should not have"
1336 " returned the internal pointer!");
1337 } else {
1338 FAIL("PyCapsule_GetPointer should have "
1339 "returned NULL pointer but did not!");
1342 PyCapsule_SetDestructor(object, NULL);
1343 Py_DECREF(object);
1344 if (capsule_destructor_call_count) {
1345 FAIL("destructor called when it should not have been!");
1348 for (known = &known_capsules[0]; known->module != NULL; known++) {
1349 /* yeah, ordinarily I wouldn't do this either,
1350 but it's fine for this test harness.
1352 static char buffer[256];
1353 #undef FAIL
1354 #define FAIL(x) \
1356 sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
1357 x, known->module, known->attribute); \
1358 error = buffer; \
1359 goto exit; \
1362 PyObject *module = PyImport_ImportModule(known->module);
1363 if (module) {
1364 pointer = PyCapsule_Import(known->name, 0);
1365 if (!pointer) {
1366 Py_DECREF(module);
1367 FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
1369 object = PyObject_GetAttrString(module, known->attribute);
1370 if (!object) {
1371 Py_DECREF(module);
1372 return NULL;
1374 pointer2 = PyCapsule_GetPointer(object,
1375 "weebles wobble but they don't fall down");
1376 if (!PyErr_Occurred()) {
1377 Py_DECREF(object);
1378 Py_DECREF(module);
1379 FAIL("PyCapsule_GetPointer should have failed but did not!");
1381 PyErr_Clear();
1382 if (pointer2) {
1383 Py_DECREF(module);
1384 Py_DECREF(object);
1385 if (pointer2 == pointer) {
1386 FAIL("PyCapsule_GetPointer should not have"
1387 " returned its internal pointer!");
1388 } else {
1389 FAIL("PyCapsule_GetPointer should have"
1390 " returned NULL pointer but did not!");
1393 Py_DECREF(object);
1394 Py_DECREF(module);
1396 else
1397 PyErr_Clear();
1400 exit:
1401 if (error) {
1402 return raiseTestError("test_capsule", error);
1404 Py_RETURN_NONE;
1405 #undef FAIL
1408 #ifdef HAVE_GETTIMEOFDAY
1409 /* Profiling of integer performance */
1410 static void print_delta(int test, struct timeval *s, struct timeval *e)
1412 e->tv_sec -= s->tv_sec;
1413 e->tv_usec -= s->tv_usec;
1414 if (e->tv_usec < 0) {
1415 e->tv_sec -=1;
1416 e->tv_usec += 1000000;
1418 printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, (int)e->tv_usec);
1421 static PyObject *
1422 profile_int(PyObject *self, PyObject* args)
1424 int i, k;
1425 struct timeval start, stop;
1426 PyObject *single, **multiple, *op1, *result;
1428 /* Test 1: Allocate and immediately deallocate
1429 many small integers */
1430 gettimeofday(&start, NULL);
1431 for(k=0; k < 20000; k++)
1432 for(i=0; i < 1000; i++) {
1433 single = PyLong_FromLong(i);
1434 Py_DECREF(single);
1436 gettimeofday(&stop, NULL);
1437 print_delta(1, &start, &stop);
1439 /* Test 2: Allocate and immediately deallocate
1440 many large integers */
1441 gettimeofday(&start, NULL);
1442 for(k=0; k < 20000; k++)
1443 for(i=0; i < 1000; i++) {
1444 single = PyLong_FromLong(i+1000000);
1445 Py_DECREF(single);
1447 gettimeofday(&stop, NULL);
1448 print_delta(2, &start, &stop);
1450 /* Test 3: Allocate a few integers, then release
1451 them all simultaneously. */
1452 multiple = malloc(sizeof(PyObject*) * 1000);
1453 gettimeofday(&start, NULL);
1454 for(k=0; k < 20000; k++) {
1455 for(i=0; i < 1000; i++) {
1456 multiple[i] = PyLong_FromLong(i+1000000);
1458 for(i=0; i < 1000; i++) {
1459 Py_DECREF(multiple[i]);
1462 gettimeofday(&stop, NULL);
1463 print_delta(3, &start, &stop);
1465 /* Test 4: Allocate many integers, then release
1466 them all simultaneously. */
1467 multiple = malloc(sizeof(PyObject*) * 1000000);
1468 gettimeofday(&start, NULL);
1469 for(k=0; k < 20; k++) {
1470 for(i=0; i < 1000000; i++) {
1471 multiple[i] = PyLong_FromLong(i+1000000);
1473 for(i=0; i < 1000000; i++) {
1474 Py_DECREF(multiple[i]);
1477 gettimeofday(&stop, NULL);
1478 print_delta(4, &start, &stop);
1480 /* Test 5: Allocate many integers < 32000 */
1481 multiple = malloc(sizeof(PyObject*) * 1000000);
1482 gettimeofday(&start, NULL);
1483 for(k=0; k < 10; k++) {
1484 for(i=0; i < 1000000; i++) {
1485 multiple[i] = PyLong_FromLong(i+1000);
1487 for(i=0; i < 1000000; i++) {
1488 Py_DECREF(multiple[i]);
1491 gettimeofday(&stop, NULL);
1492 print_delta(5, &start, &stop);
1494 /* Test 6: Perform small int addition */
1495 op1 = PyLong_FromLong(1);
1496 gettimeofday(&start, NULL);
1497 for(i=0; i < 10000000; i++) {
1498 result = PyNumber_Add(op1, op1);
1499 Py_DECREF(result);
1501 gettimeofday(&stop, NULL);
1502 Py_DECREF(op1);
1503 print_delta(6, &start, &stop);
1505 /* Test 7: Perform medium int addition */
1506 op1 = PyLong_FromLong(1000);
1507 gettimeofday(&start, NULL);
1508 for(i=0; i < 10000000; i++) {
1509 result = PyNumber_Add(op1, op1);
1510 Py_DECREF(result);
1512 gettimeofday(&stop, NULL);
1513 Py_DECREF(op1);
1514 print_delta(7, &start, &stop);
1516 Py_INCREF(Py_None);
1517 return Py_None;
1519 #endif
1521 /* To test the format of tracebacks as printed out. */
1522 static PyObject *
1523 traceback_print(PyObject *self, PyObject *args)
1525 PyObject *file;
1526 PyObject *traceback;
1527 int result;
1529 if (!PyArg_ParseTuple(args, "OO:traceback_print",
1530 &traceback, &file))
1531 return NULL;
1533 result = PyTraceBack_Print(traceback, file);
1534 if (result < 0)
1535 return NULL;
1536 Py_RETURN_NONE;
1539 /* To test the format of exceptions as printed out. */
1540 static PyObject *
1541 exception_print(PyObject *self, PyObject *args)
1543 PyObject *value;
1544 PyObject *tb;
1546 if (!PyArg_ParseTuple(args, "O:exception_print",
1547 &value))
1548 return NULL;
1549 if (!PyExceptionInstance_Check(value)) {
1550 PyErr_Format(PyExc_TypeError, "an exception instance is required");
1551 return NULL;
1554 tb = PyException_GetTraceback(value);
1555 PyErr_Display((PyObject *) Py_TYPE(value), value, tb);
1556 Py_XDECREF(tb);
1558 Py_RETURN_NONE;
1564 /* reliably raise a MemoryError */
1565 static PyObject *
1566 raise_memoryerror(PyObject *self)
1568 PyErr_NoMemory();
1569 return NULL;
1572 /* Issue 6012 */
1573 static PyObject *str1, *str2;
1574 static int
1575 failing_converter(PyObject *obj, void *arg)
1577 /* Clone str1, then let the conversion fail. */
1578 assert(str1);
1579 str2 = str1;
1580 Py_INCREF(str2);
1581 return 0;
1583 static PyObject*
1584 argparsing(PyObject *o, PyObject *args)
1586 PyObject *res;
1587 str1 = str2 = NULL;
1588 if (!PyArg_ParseTuple(args, "O&O&",
1589 PyUnicode_FSConverter, &str1,
1590 failing_converter, &str2)) {
1591 if (!str2)
1592 /* argument converter not called? */
1593 return NULL;
1594 /* Should be 1 */
1595 res = PyLong_FromLong(Py_REFCNT(str2));
1596 Py_DECREF(str2);
1597 PyErr_Clear();
1598 return res;
1600 Py_RETURN_NONE;
1603 static PyMethodDef TestMethods[] = {
1604 {"raise_exception", raise_exception, METH_VARARGS},
1605 {"raise_memoryerror", (PyCFunction)raise_memoryerror, METH_NOARGS},
1606 {"test_config", (PyCFunction)test_config, METH_NOARGS},
1607 {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
1608 {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
1609 {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
1610 {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
1611 {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
1612 {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
1613 {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
1614 {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
1615 {"test_bug_7414", (PyCFunction)test_bug_7414, METH_NOARGS},
1616 {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
1617 {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
1618 {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
1619 PyDoc_STR("This is a pretty normal docstring.")},
1620 {"test_string_to_double", (PyCFunction)test_string_to_double, METH_NOARGS},
1621 {"test_unicode_compare_with_ascii", (PyCFunction)test_unicode_compare_with_ascii, METH_NOARGS},
1622 {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
1623 {"getargs_tuple", getargs_tuple, METH_VARARGS},
1624 {"getargs_keywords", (PyCFunction)getargs_keywords,
1625 METH_VARARGS|METH_KEYWORDS},
1626 {"getargs_b", getargs_b, METH_VARARGS},
1627 {"getargs_B", getargs_B, METH_VARARGS},
1628 {"getargs_H", getargs_H, METH_VARARGS},
1629 {"getargs_I", getargs_I, METH_VARARGS},
1630 {"getargs_k", getargs_k, METH_VARARGS},
1631 {"getargs_i", getargs_i, METH_VARARGS},
1632 {"getargs_l", getargs_l, METH_VARARGS},
1633 {"getargs_n", getargs_n, METH_VARARGS},
1634 #ifdef HAVE_LONG_LONG
1635 {"getargs_L", getargs_L, METH_VARARGS},
1636 {"getargs_K", getargs_K, METH_VARARGS},
1637 {"test_longlong_api", test_longlong_api, METH_NOARGS},
1638 {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
1639 {"codec_incrementalencoder",
1640 (PyCFunction)codec_incrementalencoder, METH_VARARGS},
1641 {"codec_incrementaldecoder",
1642 (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
1643 #endif
1644 {"test_s_code", (PyCFunction)test_s_code, METH_NOARGS},
1645 {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
1646 {"test_Z_code", (PyCFunction)test_Z_code, METH_NOARGS},
1647 {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
1648 #ifdef WITH_THREAD
1649 {"_test_thread_state", test_thread_state, METH_VARARGS},
1650 {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
1651 #endif
1652 #ifdef HAVE_GETTIMEOFDAY
1653 {"profile_int", profile_int, METH_NOARGS},
1654 #endif
1655 {"traceback_print", traceback_print, METH_VARARGS},
1656 {"exception_print", exception_print, METH_VARARGS},
1657 {"argparsing", argparsing, METH_VARARGS},
1658 {NULL, NULL} /* sentinel */
1661 #define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
1663 typedef struct {
1664 char bool_member;
1665 char byte_member;
1666 unsigned char ubyte_member;
1667 short short_member;
1668 unsigned short ushort_member;
1669 int int_member;
1670 unsigned int uint_member;
1671 long long_member;
1672 unsigned long ulong_member;
1673 Py_ssize_t pyssizet_member;
1674 float float_member;
1675 double double_member;
1676 char inplace_member[6];
1677 #ifdef HAVE_LONG_LONG
1678 PY_LONG_LONG longlong_member;
1679 unsigned PY_LONG_LONG ulonglong_member;
1680 #endif
1681 } all_structmembers;
1683 typedef struct {
1684 PyObject_HEAD
1685 all_structmembers structmembers;
1686 } test_structmembers;
1688 static struct PyMemberDef test_members[] = {
1689 {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
1690 {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
1691 {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
1692 {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
1693 {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
1694 {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
1695 {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
1696 {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
1697 {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
1698 {"T_PYSSIZET", T_PYSSIZET, offsetof(test_structmembers, structmembers.pyssizet_member), 0, NULL},
1699 {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
1700 {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
1701 {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
1702 #ifdef HAVE_LONG_LONG
1703 {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
1704 {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
1705 #endif
1706 {NULL}
1710 static PyObject *
1711 test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1713 static char *keywords[] = {
1714 "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
1715 "T_INT", "T_UINT", "T_LONG", "T_ULONG", "T_PYSSIZET",
1716 "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
1717 #ifdef HAVE_LONG_LONG
1718 "T_LONGLONG", "T_ULONGLONG",
1719 #endif
1720 NULL};
1721 static char *fmt = "|bbBhHiIlknfds#"
1722 #ifdef HAVE_LONG_LONG
1723 "LK"
1724 #endif
1726 test_structmembers *ob;
1727 const char *s = NULL;
1728 Py_ssize_t string_len = 0;
1729 ob = PyObject_New(test_structmembers, type);
1730 if (ob == NULL)
1731 return NULL;
1732 memset(&ob->structmembers, 0, sizeof(all_structmembers));
1733 if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
1734 &ob->structmembers.bool_member,
1735 &ob->structmembers.byte_member,
1736 &ob->structmembers.ubyte_member,
1737 &ob->structmembers.short_member,
1738 &ob->structmembers.ushort_member,
1739 &ob->structmembers.int_member,
1740 &ob->structmembers.uint_member,
1741 &ob->structmembers.long_member,
1742 &ob->structmembers.ulong_member,
1743 &ob->structmembers.pyssizet_member,
1744 &ob->structmembers.float_member,
1745 &ob->structmembers.double_member,
1746 &s, &string_len
1747 #ifdef HAVE_LONG_LONG
1748 , &ob->structmembers.longlong_member,
1749 &ob->structmembers.ulonglong_member
1750 #endif
1751 )) {
1752 Py_DECREF(ob);
1753 return NULL;
1755 if (s != NULL) {
1756 if (string_len > 5) {
1757 Py_DECREF(ob);
1758 PyErr_SetString(PyExc_ValueError, "string too long");
1759 return NULL;
1761 strcpy(ob->structmembers.inplace_member, s);
1763 else {
1764 strcpy(ob->structmembers.inplace_member, "");
1766 return (PyObject *)ob;
1769 static void
1770 test_structmembers_free(PyObject *ob)
1772 PyObject_FREE(ob);
1775 static PyTypeObject test_structmembersType = {
1776 PyVarObject_HEAD_INIT(NULL, 0)
1777 "test_structmembersType",
1778 sizeof(test_structmembers), /* tp_basicsize */
1779 0, /* tp_itemsize */
1780 test_structmembers_free, /* destructor tp_dealloc */
1781 0, /* tp_print */
1782 0, /* tp_getattr */
1783 0, /* tp_setattr */
1784 0, /* tp_reserved */
1785 0, /* tp_repr */
1786 0, /* tp_as_number */
1787 0, /* tp_as_sequence */
1788 0, /* tp_as_mapping */
1789 0, /* tp_hash */
1790 0, /* tp_call */
1791 0, /* tp_str */
1792 PyObject_GenericGetAttr, /* tp_getattro */
1793 PyObject_GenericSetAttr, /* tp_setattro */
1794 0, /* tp_as_buffer */
1795 0, /* tp_flags */
1796 "Type containing all structmember types",
1797 0, /* traverseproc tp_traverse */
1798 0, /* tp_clear */
1799 0, /* tp_richcompare */
1800 0, /* tp_weaklistoffset */
1801 0, /* tp_iter */
1802 0, /* tp_iternext */
1803 0, /* tp_methods */
1804 test_members, /* tp_members */
1813 test_structmembers_new, /* tp_new */
1818 static struct PyModuleDef _testcapimodule = {
1819 PyModuleDef_HEAD_INIT,
1820 "_testcapi",
1821 NULL,
1823 TestMethods,
1824 NULL,
1825 NULL,
1826 NULL,
1827 NULL
1830 PyMODINIT_FUNC
1831 PyInit__testcapi(void)
1833 PyObject *m;
1835 m = PyModule_Create(&_testcapimodule);
1836 if (m == NULL)
1837 return NULL;
1839 Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
1840 Py_TYPE(&_MemoryViewTester_Type)=&PyType_Type;
1842 Py_TYPE(&test_structmembersType)=&PyType_Type;
1843 Py_INCREF(&test_structmembersType);
1844 /* don't use a name starting with "test", since we don't want
1845 test_capi to automatically call this */
1846 PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
1848 PyModule_AddObject(m, "CHAR_MAX", PyLong_FromLong(CHAR_MAX));
1849 PyModule_AddObject(m, "CHAR_MIN", PyLong_FromLong(CHAR_MIN));
1850 PyModule_AddObject(m, "UCHAR_MAX", PyLong_FromLong(UCHAR_MAX));
1851 PyModule_AddObject(m, "SHRT_MAX", PyLong_FromLong(SHRT_MAX));
1852 PyModule_AddObject(m, "SHRT_MIN", PyLong_FromLong(SHRT_MIN));
1853 PyModule_AddObject(m, "USHRT_MAX", PyLong_FromLong(USHRT_MAX));
1854 PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
1855 PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
1856 PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
1857 PyModule_AddObject(m, "LONG_MAX", PyLong_FromLong(LONG_MAX));
1858 PyModule_AddObject(m, "LONG_MIN", PyLong_FromLong(LONG_MIN));
1859 PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
1860 PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
1861 PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
1862 PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
1863 PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
1864 PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
1865 PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
1866 PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
1867 PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1868 PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyLong_FromSsize_t(PY_SSIZE_T_MIN));
1869 PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyLong_FromSsize_t(sizeof(PyGC_Head)));
1870 Py_INCREF(&PyInstanceMethod_Type);
1871 PyModule_AddObject(m, "instancemethod", (PyObject *)&PyInstanceMethod_Type);
1873 TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
1874 Py_INCREF(TestError);
1875 PyModule_AddObject(m, "error", TestError);
1876 return m;