blob: 99772eacbdc42af1a5b2ae63d2e03c37115d9dc0 [file] [log] [blame]
Antoine Pitrou8e605772011-04-25 21:21:07 +02001#include <Python.h>
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01002#include "pythread.h"
Eric Snowe3774162017-05-22 19:46:40 -07003#include <inttypes.h>
Antoine Pitrou8e605772011-04-25 21:21:07 +02004#include <stdio.h>
Nick Coghlanbc77eff2018-03-25 20:44:30 +10005#include <wchar.h>
Antoine Pitrou8e605772011-04-25 21:21:07 +02006
Nick Coghlan7d270ee2013-10-17 22:35:35 +10007/*********************************************************
8 * Embedded interpreter tests that need a custom exe
9 *
10 * Executed via 'EmbeddingTests' in Lib/test/test_capi.py
11 *********************************************************/
12
13static void _testembed_Py_Initialize(void)
14{
15 /* HACK: the "./" at front avoids a search along the PATH in
16 Modules/getpath.c */
17 Py_SetProgramName(L"./_testembed");
18 Py_Initialize();
19}
20
21
22/*****************************************************
Martin Panter8f265652016-04-19 04:03:41 +000023 * Test repeated initialisation and subinterpreters
Nick Coghlan7d270ee2013-10-17 22:35:35 +100024 *****************************************************/
25
26static void print_subinterp(void)
Antoine Pitrou8e605772011-04-25 21:21:07 +020027{
Eric Snowe3774162017-05-22 19:46:40 -070028 /* Output information about the interpreter in the format
29 expected in Lib/test/test_capi.py (test_subinterps). */
Antoine Pitrou8e605772011-04-25 21:21:07 +020030 PyThreadState *ts = PyThreadState_Get();
Eric Snowe3774162017-05-22 19:46:40 -070031 PyInterpreterState *interp = ts->interp;
32 int64_t id = PyInterpreterState_GetID(interp);
Eric Snowd1c3c132017-05-24 17:19:47 -070033 printf("interp %" PRId64 " <0x%" PRIXPTR ">, thread state <0x%" PRIXPTR ">: ",
Eric Snowe3774162017-05-22 19:46:40 -070034 id, (uintptr_t)interp, (uintptr_t)ts);
Antoine Pitrou8e605772011-04-25 21:21:07 +020035 fflush(stdout);
36 PyRun_SimpleString(
37 "import sys;"
38 "print('id(modules) =', id(sys.modules));"
39 "sys.stdout.flush()"
40 );
41}
42
Steve Dowerea74f0c2017-01-01 20:25:03 -080043static int test_repeated_init_and_subinterpreters(void)
Antoine Pitrou8e605772011-04-25 21:21:07 +020044{
45 PyThreadState *mainstate, *substate;
46 PyGILState_STATE gilstate;
47 int i, j;
48
Ned Deily939231b2016-08-16 00:17:42 -040049 for (i=0; i<15; i++) {
Antoine Pitrou8e605772011-04-25 21:21:07 +020050 printf("--- Pass %d ---\n", i);
Nick Coghlan7d270ee2013-10-17 22:35:35 +100051 _testembed_Py_Initialize();
Antoine Pitrou8e605772011-04-25 21:21:07 +020052 mainstate = PyThreadState_Get();
53
54 PyEval_InitThreads();
55 PyEval_ReleaseThread(mainstate);
56
57 gilstate = PyGILState_Ensure();
58 print_subinterp();
59 PyThreadState_Swap(NULL);
60
61 for (j=0; j<3; j++) {
62 substate = Py_NewInterpreter();
63 print_subinterp();
64 Py_EndInterpreter(substate);
65 }
66
67 PyThreadState_Swap(mainstate);
68 print_subinterp();
69 PyGILState_Release(gilstate);
Antoine Pitrou8e605772011-04-25 21:21:07 +020070
71 PyEval_RestoreThread(mainstate);
72 Py_Finalize();
73 }
Steve Dowerea74f0c2017-01-01 20:25:03 -080074 return 0;
Nick Coghlan7d270ee2013-10-17 22:35:35 +100075}
76
77/*****************************************************
78 * Test forcing a particular IO encoding
79 *****************************************************/
80
81static void check_stdio_details(const char *encoding, const char * errors)
82{
83 /* Output info for the test case to check */
84 if (encoding) {
85 printf("Expected encoding: %s\n", encoding);
86 } else {
87 printf("Expected encoding: default\n");
88 }
89 if (errors) {
90 printf("Expected errors: %s\n", errors);
91 } else {
92 printf("Expected errors: default\n");
93 }
94 fflush(stdout);
95 /* Force the given IO encoding */
96 Py_SetStandardStreamEncoding(encoding, errors);
97 _testembed_Py_Initialize();
98 PyRun_SimpleString(
99 "import sys;"
100 "print('stdin: {0.encoding}:{0.errors}'.format(sys.stdin));"
101 "print('stdout: {0.encoding}:{0.errors}'.format(sys.stdout));"
102 "print('stderr: {0.encoding}:{0.errors}'.format(sys.stderr));"
103 "sys.stdout.flush()"
104 );
105 Py_Finalize();
106}
107
Steve Dowerea74f0c2017-01-01 20:25:03 -0800108static int test_forced_io_encoding(void)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000109{
110 /* Check various combinations */
111 printf("--- Use defaults ---\n");
112 check_stdio_details(NULL, NULL);
113 printf("--- Set errors only ---\n");
Victor Stinnerb2bef622014-03-18 02:38:12 +0100114 check_stdio_details(NULL, "ignore");
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000115 printf("--- Set encoding only ---\n");
Victor Stinner9e4994d2018-08-28 23:26:33 +0200116 check_stdio_details("iso8859-1", NULL);
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000117 printf("--- Set encoding and errors ---\n");
Victor Stinner9e4994d2018-08-28 23:26:33 +0200118 check_stdio_details("iso8859-1", "replace");
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000119
120 /* Check calling after initialization fails */
121 Py_Initialize();
122
123 if (Py_SetStandardStreamEncoding(NULL, NULL) == 0) {
124 printf("Unexpected success calling Py_SetStandardStreamEncoding");
125 }
126 Py_Finalize();
Steve Dowerea74f0c2017-01-01 20:25:03 -0800127 return 0;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000128}
129
Victor Stinner9e87e772017-11-24 12:09:24 +0100130/*********************************************************
131 * Test parts of the C-API that work before initialization
132 *********************************************************/
133
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000134/* The pre-initialization tests tend to break by segfaulting, so explicitly
135 * flushed progress messages make the broken API easier to find when they fail.
136 */
137#define _Py_EMBED_PREINIT_CHECK(msg) \
138 do {printf(msg); fflush(stdout);} while (0);
139
Victor Stinner9e87e772017-11-24 12:09:24 +0100140static int test_pre_initialization_api(void)
141{
Nick Coghlan42746092017-11-26 14:19:13 +1000142 /* Leading "./" ensures getpath.c can still find the standard library */
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000143 _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n");
Nick Coghlan42746092017-11-26 14:19:13 +1000144 wchar_t *program = Py_DecodeLocale("./spam", NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +0100145 if (program == NULL) {
146 fprintf(stderr, "Fatal error: cannot decode program name\n");
147 return 1;
148 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000149 _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100150 Py_SetProgramName(program);
151
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000152 _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100153 Py_Initialize();
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000154 _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
155 PyRun_SimpleString("import sys; "
156 "print('sys.executable:', sys.executable)");
157 _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100158 Py_Finalize();
159
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000160 _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100161 PyMem_RawFree(program);
162 return 0;
163}
164
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000165
166/* bpo-33042: Ensure embedding apps can predefine sys module options */
167static int test_pre_initialization_sys_options(void)
168{
Nick Coghlan69f5c732018-03-30 15:36:42 +1000169 /* We allocate a couple of the options dynamically, and then delete
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000170 * them before calling Py_Initialize. This ensures the interpreter isn't
171 * relying on the caller to keep the passed in strings alive.
172 */
Nick Coghlan69f5c732018-03-30 15:36:42 +1000173 const wchar_t *static_warnoption = L"once";
174 const wchar_t *static_xoption = L"also_not_an_option=2";
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000175 size_t warnoption_len = wcslen(static_warnoption);
176 size_t xoption_len = wcslen(static_xoption);
Nick Coghlan69f5c732018-03-30 15:36:42 +1000177 wchar_t *dynamic_once_warnoption = \
178 (wchar_t *) calloc(warnoption_len+1, sizeof(wchar_t));
179 wchar_t *dynamic_xoption = \
180 (wchar_t *) calloc(xoption_len+1, sizeof(wchar_t));
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000181 wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
182 wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);
183
184 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
185 PySys_AddWarnOption(L"default");
186 _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
187 PySys_ResetWarnOptions();
188 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
189 PySys_AddWarnOption(dynamic_once_warnoption);
190 PySys_AddWarnOption(L"module");
191 PySys_AddWarnOption(L"default");
192 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
193 PySys_AddXOption(L"not_an_option=1");
194 PySys_AddXOption(dynamic_xoption);
195
196 /* Delete the dynamic options early */
197 free(dynamic_once_warnoption);
198 dynamic_once_warnoption = NULL;
199 free(dynamic_xoption);
200 dynamic_xoption = NULL;
201
202 _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
203 _testembed_Py_Initialize();
204 _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
205 PyRun_SimpleString("import sys; "
206 "print('sys.warnoptions:', sys.warnoptions); "
207 "print('sys._xoptions:', sys._xoptions); "
208 "warnings = sys.modules['warnings']; "
209 "latest_filters = [f[0] for f in warnings.filters[:3]]; "
210 "print('warnings.filters[:3]:', latest_filters)");
211 _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
212 Py_Finalize();
213
214 return 0;
215}
216
217
218/* bpo-20891: Avoid race condition when initialising the GIL */
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100219static void bpo20891_thread(void *lockp)
220{
221 PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
222
223 PyGILState_STATE state = PyGILState_Ensure();
224 if (!PyGILState_Check()) {
225 fprintf(stderr, "PyGILState_Check failed!");
226 abort();
227 }
228
229 PyGILState_Release(state);
230
231 PyThread_release_lock(lock);
232
233 PyThread_exit_thread();
234}
235
236static int test_bpo20891(void)
237{
238 /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
239 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
240 call PyEval_InitThreads() for us in this case. */
241 PyThread_type_lock lock = PyThread_allocate_lock();
242 if (!lock) {
243 fprintf(stderr, "PyThread_allocate_lock failed!");
244 return 1;
245 }
246
247 _testembed_Py_Initialize();
248
249 unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
250 if (thrd == PYTHREAD_INVALID_THREAD_ID) {
251 fprintf(stderr, "PyThread_start_new_thread failed!");
252 return 1;
253 }
254 PyThread_acquire_lock(lock, WAIT_LOCK);
255
256 Py_BEGIN_ALLOW_THREADS
257 /* wait until the thread exit */
258 PyThread_acquire_lock(lock, WAIT_LOCK);
259 Py_END_ALLOW_THREADS
260
261 PyThread_free_lock(lock);
262
263 return 0;
264}
265
Victor Stinner209abf72018-06-22 19:14:51 +0200266static int test_initialize_twice(void)
267{
268 _testembed_Py_Initialize();
269
270 /* bpo-33932: Calling Py_Initialize() twice should do nothing
271 * (and not crash!). */
272 Py_Initialize();
273
274 Py_Finalize();
275
276 return 0;
277}
278
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200279static int test_initialize_pymain(void)
280{
281 wchar_t *argv[] = {L"PYTHON", L"-c",
282 L"import sys; print(f'Py_Main() after Py_Initialize: sys.argv={sys.argv}')",
283 L"arg2"};
284 _testembed_Py_Initialize();
285
286 /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */
287 Py_Main(Py_ARRAY_LENGTH(argv), argv);
288
289 Py_Finalize();
290
291 return 0;
292}
293
Victor Stinner9e87e772017-11-24 12:09:24 +0100294
Victor Stinner56b29b62018-07-26 18:57:56 +0200295static void
296dump_config(void)
297{
298#define ASSERT_EQUAL(a, b) \
299 if ((a) != (b)) { \
300 printf("ERROR: %s != %s (%i != %i)\n", #a, #b, (a), (b)); \
301 exit(1); \
302 }
303#define ASSERT_STR_EQUAL(a, b) \
304 if ((a) == NULL || (b == NULL) || wcscmp((a), (b)) != 0) { \
305 printf("ERROR: %s != %s ('%ls' != '%ls')\n", #a, #b, (a), (b)); \
306 exit(1); \
307 }
308
Victor Stinnercaba55b2018-08-03 15:33:52 +0200309 PyInterpreterState *interp = _PyInterpreterState_Get();
Victor Stinner56b29b62018-07-26 18:57:56 +0200310 _PyCoreConfig *config = &interp->core_config;
311
312 printf("install_signal_handlers = %i\n", config->install_signal_handlers);
313
314 printf("use_environment = %i\n", config->use_environment);
315 ASSERT_EQUAL(config->use_environment, !Py_IgnoreEnvironmentFlag);
316
317 printf("use_hash_seed = %i\n", config->use_hash_seed);
318 printf("hash_seed = %lu\n", config->hash_seed);
319
320 printf("allocator = %s\n", config->allocator);
321
322 printf("dev_mode = %i\n", config->dev_mode);
323 printf("faulthandler = %i\n", config->faulthandler);
324 printf("tracemalloc = %i\n", config->tracemalloc);
325 printf("import_time = %i\n", config->import_time);
326 printf("show_ref_count = %i\n", config->show_ref_count);
327 printf("show_alloc_count = %i\n", config->show_alloc_count);
328 printf("dump_refs = %i\n", config->dump_refs);
329 printf("malloc_stats = %i\n", config->malloc_stats);
330
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200331 printf("filesystem_encoding = %s\n", config->filesystem_encoding);
332 printf("filesystem_errors = %s\n", config->filesystem_errors);
Victor Stinner56b29b62018-07-26 18:57:56 +0200333 printf("coerce_c_locale = %i\n", config->coerce_c_locale);
334 printf("coerce_c_locale_warn = %i\n", config->coerce_c_locale_warn);
335 printf("utf8_mode = %i\n", config->utf8_mode);
336
337 printf("pycache_prefix = %ls\n", config->pycache_prefix);
338 printf("program_name = %ls\n", config->program_name);
339 ASSERT_STR_EQUAL(config->program_name, Py_GetProgramName());
Victor Stinnerea68d832018-08-01 03:07:18 +0200340
341 printf("argc = %i\n", config->argc);
342 printf("argv = [");
343 for (int i=0; i < config->argc; i++) {
344 if (i) {
345 printf(", ");
346 }
347 printf("\"%ls\"", config->argv[i]);
348 }
349 printf("]\n");
350
Victor Stinner56b29b62018-07-26 18:57:56 +0200351 printf("program = %ls\n", config->program);
352 /* FIXME: test xoptions */
353 /* FIXME: test warnoptions */
354 /* FIXME: test module_search_path_env */
355 /* FIXME: test home */
356 /* FIXME: test module_search_paths */
357 /* FIXME: test executable */
358 /* FIXME: test prefix */
359 /* FIXME: test base_prefix */
360 /* FIXME: test exec_prefix */
361 /* FIXME: test base_exec_prefix */
362 /* FIXME: test dll_path */
363
364 printf("isolated = %i\n", config->isolated);
365 ASSERT_EQUAL(config->isolated, Py_IsolatedFlag);
366 printf("site_import = %i\n", config->site_import);
367 printf("bytes_warning = %i\n", config->bytes_warning);
368 printf("inspect = %i\n", config->inspect);
369 printf("interactive = %i\n", config->interactive);
370 printf("optimization_level = %i\n", config->optimization_level);
Victor Stinner98512272018-08-01 03:07:00 +0200371 printf("parser_debug = %i\n", config->parser_debug);
Victor Stinner56b29b62018-07-26 18:57:56 +0200372 printf("write_bytecode = %i\n", config->write_bytecode);
373 printf("verbose = %i\n", config->verbose);
374 ASSERT_EQUAL(config->verbose, Py_VerboseFlag);
375 printf("quiet = %i\n", config->quiet);
376 printf("user_site_directory = %i\n", config->user_site_directory);
Victor Stinner98512272018-08-01 03:07:00 +0200377 printf("buffered_stdio = %i\n", config->buffered_stdio);
Victor Stinner5a953fd2018-08-03 22:49:07 +0200378 ASSERT_EQUAL(config->buffered_stdio, !Py_UnbufferedStdioFlag);
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200379 printf("stdio_encoding = %s\n", config->stdio_encoding);
380 printf("stdio_errors = %s\n", config->stdio_errors);
Victor Stinner5a953fd2018-08-03 22:49:07 +0200381
Victor Stinner56b29b62018-07-26 18:57:56 +0200382 /* FIXME: test legacy_windows_fs_encoding */
383 /* FIXME: test legacy_windows_stdio */
384
385 printf("_install_importlib = %i\n", config->_install_importlib);
386 printf("_check_hash_pycs_mode = %s\n", config->_check_hash_pycs_mode);
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200387 printf("_frozen = %i\n", config->_frozen);
Victor Stinner56b29b62018-07-26 18:57:56 +0200388
389#undef ASSERT_EQUAL
390#undef ASSERT_STR_EQUAL
391}
392
393
394static int test_init_default_config(void)
395{
396 _testembed_Py_Initialize();
397 dump_config();
398 Py_Finalize();
399 return 0;
400}
401
402
403static int test_init_global_config(void)
404{
405 /* FIXME: test Py_IgnoreEnvironmentFlag */
406
407 putenv("PYTHONUTF8=0");
408 Py_UTF8Mode = 1;
409
410 /* Test initialization from global configuration variables (Py_xxx) */
411 Py_SetProgramName(L"./globalvar");
412
413 /* Py_IsolatedFlag is not tested */
414 Py_NoSiteFlag = 1;
415 Py_BytesWarningFlag = 1;
416
417 putenv("PYTHONINSPECT=");
418 Py_InspectFlag = 1;
419
420 putenv("PYTHONOPTIMIZE=0");
421 Py_InteractiveFlag = 1;
422
423 putenv("PYTHONDEBUG=0");
424 Py_OptimizeFlag = 2;
425
426 /* Py_DebugFlag is not tested */
427
428 putenv("PYTHONDONTWRITEBYTECODE=");
429 Py_DontWriteBytecodeFlag = 1;
430
431 putenv("PYTHONVERBOSE=0");
432 Py_VerboseFlag = 1;
433
434 Py_QuietFlag = 1;
435 Py_NoUserSiteDirectory = 1;
436
437 putenv("PYTHONUNBUFFERED=");
438 Py_UnbufferedStdioFlag = 1;
439
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200440 Py_FrozenFlag = 1;
441
Victor Stinner56b29b62018-07-26 18:57:56 +0200442 /* FIXME: test Py_LegacyWindowsFSEncodingFlag */
443 /* FIXME: test Py_LegacyWindowsStdioFlag */
444
Victor Stinner56b29b62018-07-26 18:57:56 +0200445 Py_Initialize();
446 dump_config();
447 Py_Finalize();
448 return 0;
449}
450
451
452static int test_init_from_config(void)
453{
454 /* Test _Py_InitializeFromConfig() */
455 _PyCoreConfig config = _PyCoreConfig_INIT;
456 config.install_signal_handlers = 0;
457
458 /* FIXME: test use_environment */
459
460 putenv("PYTHONHASHSEED=42");
461 config.use_hash_seed = 1;
462 config.hash_seed = 123;
463
464 putenv("PYTHONMALLOC=malloc");
465 config.allocator = "malloc_debug";
466
467 /* dev_mode=1 is tested in test_init_dev_mode() */
468
469 putenv("PYTHONFAULTHANDLER=");
470 config.faulthandler = 1;
471
472 putenv("PYTHONTRACEMALLOC=0");
473 config.tracemalloc = 2;
474
475 putenv("PYTHONPROFILEIMPORTTIME=0");
476 config.import_time = 1;
477
478 config.show_ref_count = 1;
479 config.show_alloc_count = 1;
480 /* FIXME: test dump_refs: bpo-34223 */
481
482 putenv("PYTHONMALLOCSTATS=0");
483 config.malloc_stats = 1;
484
485 /* FIXME: test coerce_c_locale and coerce_c_locale_warn */
486
487 putenv("PYTHONUTF8=0");
488 Py_UTF8Mode = 0;
489 config.utf8_mode = 1;
490
491 putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
492 config.pycache_prefix = L"conf_pycache_prefix";
493
494 Py_SetProgramName(L"./globalvar");
495 config.program_name = L"./conf_program_name";
496
497 /* FIXME: test argc/argv */
498 config.program = L"conf_program";
499 /* FIXME: test xoptions */
500 /* FIXME: test warnoptions */
501 /* FIXME: test module_search_path_env */
502 /* FIXME: test home */
503 /* FIXME: test path config: module_search_path .. dll_path */
504
505 putenv("PYTHONVERBOSE=0");
506 Py_VerboseFlag = 0;
507 config.verbose = 1;
508
509 Py_NoSiteFlag = 0;
510 config.site_import = 0;
511
512 Py_BytesWarningFlag = 0;
513 config.bytes_warning = 1;
514
515 putenv("PYTHONINSPECT=");
516 Py_InspectFlag = 0;
517 config.inspect = 1;
518
519 Py_InteractiveFlag = 0;
520 config.interactive = 1;
521
522 putenv("PYTHONOPTIMIZE=0");
523 Py_OptimizeFlag = 1;
524 config.optimization_level = 2;
525
Victor Stinner98512272018-08-01 03:07:00 +0200526 /* FIXME: test parser_debug */
Victor Stinner56b29b62018-07-26 18:57:56 +0200527
528 putenv("PYTHONDONTWRITEBYTECODE=");
529 Py_DontWriteBytecodeFlag = 0;
530 config.write_bytecode = 0;
531
532 Py_QuietFlag = 0;
533 config.quiet = 1;
534
535 putenv("PYTHONUNBUFFERED=");
536 Py_UnbufferedStdioFlag = 0;
Victor Stinner98512272018-08-01 03:07:00 +0200537 config.buffered_stdio = 0;
Victor Stinner56b29b62018-07-26 18:57:56 +0200538
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200539 putenv("PYTHONIOENCODING=cp424");
540 Py_SetStandardStreamEncoding("ascii", "ignore");
541 config.stdio_encoding = "iso8859-1";
542 config.stdio_errors = "replace";
543
Victor Stinner56b29b62018-07-26 18:57:56 +0200544 putenv("PYTHONNOUSERSITE=");
545 Py_NoUserSiteDirectory = 0;
546 config.user_site_directory = 0;
547
548 config._check_hash_pycs_mode = "always";
549
Victor Stinnerb75d7e22018-08-01 02:13:04 +0200550 Py_FrozenFlag = 0;
551 config._frozen = 1;
552
Victor Stinner56b29b62018-07-26 18:57:56 +0200553 _PyInitError err = _Py_InitializeFromConfig(&config);
554 /* Don't call _PyCoreConfig_Clear() since all strings are static */
555 if (_Py_INIT_FAILED(err)) {
556 _Py_FatalInitError(err);
557 }
558 dump_config();
559 Py_Finalize();
560 return 0;
561}
562
563
564static void test_init_env_putenvs(void)
565{
566 putenv("PYTHONHASHSEED=42");
567 putenv("PYTHONMALLOC=malloc_debug");
568 putenv("PYTHONTRACEMALLOC=2");
569 putenv("PYTHONPROFILEIMPORTTIME=1");
570 putenv("PYTHONMALLOCSTATS=1");
571 putenv("PYTHONUTF8=1");
572 putenv("PYTHONVERBOSE=1");
573 putenv("PYTHONINSPECT=1");
574 putenv("PYTHONOPTIMIZE=2");
575 putenv("PYTHONDONTWRITEBYTECODE=1");
576 putenv("PYTHONUNBUFFERED=1");
577 putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
578 putenv("PYTHONNOUSERSITE=1");
579 putenv("PYTHONFAULTHANDLER=1");
580 putenv("PYTHONDEVMODE=1");
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200581 putenv("PYTHONIOENCODING=iso8859-1:replace");
Victor Stinner56b29b62018-07-26 18:57:56 +0200582 /* FIXME: test PYTHONWARNINGS */
583 /* FIXME: test PYTHONEXECUTABLE */
584 /* FIXME: test PYTHONHOME */
585 /* FIXME: test PYTHONDEBUG */
586 /* FIXME: test PYTHONDUMPREFS */
587 /* FIXME: test PYTHONCOERCECLOCALE */
588 /* FIXME: test PYTHONPATH */
589}
590
591
592static int test_init_env(void)
593{
594 /* Test initialization from environment variables */
595 Py_IgnoreEnvironmentFlag = 0;
596 test_init_env_putenvs();
597 _testembed_Py_Initialize();
598 dump_config();
599 Py_Finalize();
600 return 0;
601}
602
603
604static int test_init_isolated(void)
605{
606 /* Test _PyCoreConfig.isolated=1 */
607 _PyCoreConfig config = _PyCoreConfig_INIT;
608
609 /* Set coerce_c_locale and utf8_mode to not depend on the locale */
610 config.coerce_c_locale = 0;
611 config.utf8_mode = 0;
612 /* Use path starting with "./" avoids a search along the PATH */
613 config.program_name = L"./_testembed";
614
615 Py_IsolatedFlag = 0;
616 config.isolated = 1;
617
618 test_init_env_putenvs();
619 _PyInitError err = _Py_InitializeFromConfig(&config);
620 if (_Py_INIT_FAILED(err)) {
621 _Py_FatalInitError(err);
622 }
623 dump_config();
624 Py_Finalize();
625 return 0;
626}
627
628
629static int test_init_dev_mode(void)
630{
631 _PyCoreConfig config = _PyCoreConfig_INIT;
632 putenv("PYTHONFAULTHANDLER=");
633 putenv("PYTHONMALLOC=");
634 config.dev_mode = 1;
635 config.program_name = L"./_testembed";
636 _PyInitError err = _Py_InitializeFromConfig(&config);
637 if (_Py_INIT_FAILED(err)) {
638 _Py_FatalInitError(err);
639 }
640 dump_config();
641 Py_Finalize();
642 return 0;
643}
644
645
Steve Dowerea74f0c2017-01-01 20:25:03 -0800646/* *********************************************************
647 * List of test cases and the function that implements it.
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300648 *
Steve Dowerea74f0c2017-01-01 20:25:03 -0800649 * Names are compared case-sensitively with the first
650 * argument. If no match is found, or no first argument was
651 * provided, the names of all test cases are printed and
652 * the exit code will be -1.
653 *
654 * The int returned from test functions is used as the exit
655 * code, and test_capi treats all non-zero exit codes as a
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300656 * failed test.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800657 *********************************************************/
658struct TestCase
659{
660 const char *name;
661 int (*func)(void);
662};
663
664static struct TestCase TestCases[] = {
665 { "forced_io_encoding", test_forced_io_encoding },
666 { "repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters },
Victor Stinner9e87e772017-11-24 12:09:24 +0100667 { "pre_initialization_api", test_pre_initialization_api },
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000668 { "pre_initialization_sys_options", test_pre_initialization_sys_options },
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100669 { "bpo20891", test_bpo20891 },
Victor Stinner209abf72018-06-22 19:14:51 +0200670 { "initialize_twice", test_initialize_twice },
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200671 { "initialize_pymain", test_initialize_pymain },
Victor Stinner56b29b62018-07-26 18:57:56 +0200672 { "init_default_config", test_init_default_config },
673 { "init_global_config", test_init_global_config },
674 { "init_from_config", test_init_from_config },
675 { "init_env", test_init_env },
676 { "init_dev_mode", test_init_dev_mode },
677 { "init_isolated", test_init_isolated },
Steve Dowerea74f0c2017-01-01 20:25:03 -0800678 { NULL, NULL }
679};
680
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000681int main(int argc, char *argv[])
682{
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000683 if (argc > 1) {
Steve Dowerea74f0c2017-01-01 20:25:03 -0800684 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
685 if (strcmp(argv[1], tc->name) == 0)
686 return (*tc->func)();
687 }
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000688 }
Steve Dowerea74f0c2017-01-01 20:25:03 -0800689
690 /* No match found, or no test name provided, so display usage */
691 printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000692 "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
Steve Dowerea74f0c2017-01-01 20:25:03 -0800693 "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
694 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
695 printf(" %s\n", tc->name);
696 }
697
Nick Coghlanbc77eff2018-03-25 20:44:30 +1000698 /* Non-zero exit code will cause test_embed.py tests to fail.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800699 This is intentional. */
700 return -1;
Antoine Pitrou8e605772011-04-25 21:21:07 +0200701}