@@ -15,6 +15,11 @@ - (void)testPython {
1515 PyStatus status;
1616 PyPreConfig preconfig;
1717 PyConfig config;
18+ PyObject *app_packages_path;
19+ PyObject *method_args;
20+ PyObject *result;
21+ PyObject *site_module;
22+ PyObject *site_addsitedir_attr;
1823 PyObject *sys_module;
1924 PyObject *sys_path_attr;
2025 NSArray *test_args;
@@ -109,29 +114,55 @@ - (void)testPython {
109114 return ;
110115 }
111116
112- sys_module = PyImport_ImportModule (" sys" );
113- if (sys_module == NULL ) {
114- XCTFail (@" Could not import sys module" );
117+ // Add app_packages as a site directory. This both adds to sys.path,
118+ // and ensures that any .pth files in that directory will be executed.
119+ site_module = PyImport_ImportModule (" site" );
120+ if (site_module == NULL ) {
121+ XCTFail (@" Could not import site module" );
115122 return ;
116123 }
117124
118- sys_path_attr = PyObject_GetAttrString (sys_module , " path " );
119- if (sys_path_attr == NULL ) {
120- XCTFail (@" Could not access sys.path " );
125+ site_addsitedir_attr = PyObject_GetAttrString (site_module , " addsitedir " );
126+ if (site_addsitedir_attr == NULL || ! PyCallable_Check (site_addsitedir_attr) ) {
127+ XCTFail (@" Could not access site.addsitedir " );
121128 return ;
122129 }
123130
124- // Add the app packages path
125131 path = [NSString stringWithFormat: @" %@ /app_packages" , resourcePath, nil ];
126132 NSLog (@" App packages path: %@ " , path);
127133 wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
128- failed = PyList_Insert (sys_path_attr, 0 , PyUnicode_FromString ([path UTF8String ] ));
129- if (failed ) {
130- XCTFail (@" Unable to add app packages to sys.path " );
134+ app_packages_path = PyUnicode_FromWideChar (wtmp_str, wcslen (wtmp_str ));
135+ if (app_packages_path == NULL ) {
136+ XCTFail (@" Could not convert app_packages path to unicode " );
131137 return ;
132138 }
133139 PyMem_RawFree (wtmp_str);
134140
141+ method_args = Py_BuildValue (" (O)" , app_packages_path);
142+ if (method_args == NULL ) {
143+ XCTFail (@" Could not create arguments for site.addsitedir" );
144+ return ;
145+ }
146+
147+ result = PyObject_CallObject (site_addsitedir_attr, method_args);
148+ if (result == NULL ) {
149+ XCTFail (@" Could not add app_packages directory using site.addsitedir" );
150+ return ;
151+ }
152+
153+ // Add test code to sys.path
154+ sys_module = PyImport_ImportModule (" sys" );
155+ if (sys_module == NULL ) {
156+ XCTFail (@" Could not import sys module" );
157+ return ;
158+ }
159+
160+ sys_path_attr = PyObject_GetAttrString (sys_module, " path" );
161+ if (sys_path_attr == NULL ) {
162+ XCTFail (@" Could not access sys.path" );
163+ return ;
164+ }
165+
135166 path = [NSString stringWithFormat: @" %@ /app" , resourcePath, nil ];
136167 NSLog (@" App path: %@ " , path);
137168 wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
0 commit comments