@@ -197,16 +197,10 @@ test_gc(PyObject *self, PyObject *ignored)
197197}
198198
199199
200- static PyObject *
201- test_module (PyObject * self , PyObject * ignored )
200+ // test PyModule_AddType()
201+ static int
202+ test_module_add_type (PyObject * module )
202203{
203- PyObject * module = PyImport_ImportModule ("sys" );
204- if (module == NULL ) {
205- return NULL ;
206- }
207- assert (PyModule_Check (module ));
208-
209- // test PyModule_AddType()
210204 PyTypeObject * type = & PyUnicode_Type ;
211205#ifdef PYTHON3
212206 const char * type_name = "str" ;
@@ -216,21 +210,69 @@ test_module(PyObject *self, PyObject *ignored)
216210 Py_ssize_t refcnt = Py_REFCNT (type );
217211
218212 if (PyModule_AddType (module , type ) < 0 ) {
219- goto error ;
213+ return -1 ;
220214 }
221215 assert (Py_REFCNT (type ) == refcnt + 1 );
222216
223217 PyObject * attr = PyObject_GetAttrString (module , type_name );
224218 if (attr == NULL ) {
225- goto error ;
219+ return -1 ;
226220 }
227221 assert (attr == (PyObject * )type );
228222 Py_DECREF (attr );
229223
230224 if (PyObject_DelAttrString (module , type_name ) < 0 ) {
231- goto error ;
225+ return -1 ;
232226 }
233227 assert (Py_REFCNT (type ) == refcnt );
228+ return 0 ;
229+ }
230+
231+
232+ // test PyModule_AddObjectRef()
233+ static int
234+ test_module_addobjectref (PyObject * module )
235+ {
236+ PyObject * obj = Py_True ;
237+ Py_ssize_t refcnt = Py_REFCNT (obj );
238+ const char * name = "test_module_addobjectref" ;
239+
240+ if (PyModule_AddObjectRef (module , name , obj ) < 0 ) {
241+ assert (Py_REFCNT (obj ) == refcnt );
242+ return -1 ;
243+ }
244+ assert (Py_REFCNT (obj ) == refcnt + 1 );
245+
246+ if (PyObject_DelAttrString (module , name ) < 0 ) {
247+ return -1 ;
248+ }
249+ assert (Py_REFCNT (obj ) == refcnt );
250+
251+ // PyModule_AddObjectRef() with value=NULL must not crash
252+ int res = PyModule_AddObjectRef (module , name , NULL );
253+ assert (res < 0 );
254+ PyErr_Clear ();
255+
256+ return 0 ;
257+ }
258+
259+
260+ static PyObject *
261+ test_module (PyObject * self , PyObject * ignored )
262+ {
263+ PyObject * module = PyImport_ImportModule ("sys" );
264+ if (module == NULL ) {
265+ return NULL ;
266+ }
267+ assert (PyModule_Check (module ));
268+
269+ if (test_module_add_type (module ) < 0 ) {
270+ goto error ;
271+ }
272+
273+ if (test_module_addobjectref (module ) < 0 ) {
274+ goto error ;
275+ }
234276
235277 Py_DECREF (module );
236278 Py_RETURN_NONE ;
0 commit comments