@@ -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;
@@ -111,29 +116,55 @@ - (void)testPython {
111116 return ;
112117 }
113118
114- sys_module = PyImport_ImportModule (" sys" );
115- if (sys_module == NULL ) {
116- XCTFail (@" Could not import sys module" );
119+ // Add app_packages as a site directory. This both adds to sys.path,
120+ // and ensures that any .pth files in that directory will be executed.
121+ site_module = PyImport_ImportModule (" site" );
122+ if (site_module == NULL ) {
123+ XCTFail (@" Could not import site module" );
117124 return ;
118125 }
119126
120- sys_path_attr = PyObject_GetAttrString (sys_module , " path " );
121- if (sys_path_attr == NULL ) {
122- XCTFail (@" Could not access sys.path " );
127+ site_addsitedir_attr = PyObject_GetAttrString (site_module , " addsitedir " );
128+ if (site_addsitedir_attr == NULL || ! PyCallable_Check (site_addsitedir_attr) ) {
129+ XCTFail (@" Could not access site.addsitedir " );
123130 return ;
124131 }
125132
126- // Add the app packages path
127133 path = [NSString stringWithFormat: @" %@ /app_packages" , resourcePath, nil ];
128134 NSLog (@" App packages path: %@ " , path);
129135 wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
130- failed = PyList_Insert (sys_path_attr, 0 , PyUnicode_FromString ([path UTF8String ] ));
131- if (failed ) {
132- XCTFail (@" Unable to add app packages to sys.path " );
136+ app_packages_path = PyUnicode_FromWideChar (wtmp_str, wcslen (wtmp_str ));
137+ if (app_packages_path == NULL ) {
138+ XCTFail (@" Could not convert app_packages path to unicode " );
133139 return ;
134140 }
135141 PyMem_RawFree (wtmp_str);
136142
143+ method_args = Py_BuildValue (" (O)" , app_packages_path);
144+ if (method_args == NULL ) {
145+ XCTFail (@" Could not create arguments for site.addsitedir" );
146+ return ;
147+ }
148+
149+ result = PyObject_CallObject (site_addsitedir_attr, method_args);
150+ if (result == NULL ) {
151+ XCTFail (@" Could not add app_packages directory using site.addsitedir" );
152+ return ;
153+ }
154+
155+ // Add test code to sys.path
156+ sys_module = PyImport_ImportModule (" sys" );
157+ if (sys_module == NULL ) {
158+ XCTFail (@" Could not import sys module" );
159+ return ;
160+ }
161+
162+ sys_path_attr = PyObject_GetAttrString (sys_module, " path" );
163+ if (sys_path_attr == NULL ) {
164+ XCTFail (@" Could not access sys.path" );
165+ return ;
166+ }
167+
137168 path = [NSString stringWithFormat: @" %@ /app" , resourcePath, nil ];
138169 NSLog (@" App path: %@ " , path);
139170 wtmp_str = Py_DecodeLocale ([path UTF8String ], NULL );
0 commit comments