diff --git a/P4API.cpp b/P4API.cpp index 657fd09..8ce8feb 100644 --- a/P4API.cpp +++ b/P4API.cpp @@ -1194,14 +1194,34 @@ static PyObject * return NULL; PyObject * p4Module = PyImport_ImportModule("P4"); + if (!p4Module) + return NULL; PyObject * p4Dict = PyModule_GetDict(p4Module); + if (!p4Dict) { + Py_DECREF(p4Module); + return NULL; + } PyObject * mapClass = PyDict_GetItemString(p4Dict, "Map"); if (mapClass == NULL) { - cout << "Could not find class P4.Map" << endl; - return NULL; + Py_DECREF(p4Module); + PyErr_SetString(PyExc_AttributeError, "Could not find class P4.Map"); + return NULL; } result = (P4Map *) PyObject_CallObject(mapClass, NULL); + Py_DECREF(p4Module); + if (!result) + return NULL; + int isMap = PyObject_IsInstance((PyObject *) result, (PyObject *) &P4MapType); + if (isMap < 0) { + Py_DECREF((PyObject *) result); + return NULL; + } + if (!isMap) { + Py_DECREF((PyObject *) result); + PyErr_SetString(PyExc_TypeError, "P4.Map constructor did not return a P4Map"); + return NULL; + } delete result->map; result->map = p4py::P4MapMaker::Join(left->map, right->map); return (PyObject *) result; diff --git a/p4test.py b/p4test.py index 16acaf1..62f69a4 100644 --- a/p4test.py +++ b/p4test.py @@ -944,6 +944,32 @@ def testMap(self): self.assertEqual( map.translate("a/foo", 0), "//depot/a/foo", "P4Map.translate not handled correctly") self.assertEqual( map.translate_array("//depot/a/foo"), ["b/foo", "a/foo"], "P4Map.translate not handled correctly") + def testMapJoinConstructorErrors(self): + from unittest.mock import patch + + left, right = P4.Map(), P4.Map() + join = P4.Map.join + original_refcount = sys.getrefcount(P4) + for _ in range(10): + self.assertIsInstance(join(left, right), P4.Map) + self.assertEqual(sys.getrefcount(P4), original_refcount) + + with patch.object(P4, 'Map', return_value=object()): + with self.assertRaisesRegex(TypeError, 'did not return a P4Map'): + join(left, right) + + with patch.object(P4, 'Map', side_effect=ValueError('constructor failed')): + with self.assertRaisesRegex(ValueError, 'constructor failed'): + join(left, right) + + map_class = P4.Map + try: + del P4.Map + with self.assertRaisesRegex(AttributeError, 'Could not find class P4.Map'): + join(left, right) + finally: + P4.Map = map_class + def testThreads( self ): import threading