diff --git a/src/App/DocumentPyImp.cpp b/src/App/DocumentPyImp.cpp index 5dd05fb682..390fd2a72e 100644 --- a/src/App/DocumentPyImp.cpp +++ b/src/App/DocumentPyImp.cpp @@ -564,20 +564,33 @@ PyObject* DocumentPy::purgeTouched(PyObject* args) Py_Return; } -PyObject* DocumentPy::getObject(PyObject *args) +PyObject* DocumentPy::getObject(PyObject *args) { - long id = -1; - char *sName = 0; - if (!PyArg_ParseTuple(args, "s",&sName)) { - if (!PyArg_ParseTuple(args, "l", &id)) - return nullptr; - } + DocumentObject* obj = nullptr; - DocumentObject *pcFtr = sName?getDocumentPtr()->getObject(sName):getDocumentPtr()->getObjectByID(id); - if (pcFtr) - return pcFtr->getPyObject(); - else - Py_Return; + do { + char* name = nullptr; + if (PyArg_ParseTuple(args, "s", &name)) { + obj = getDocumentPtr()->getObject(name); + break; + } + + PyErr_Clear(); + long id = -1; + if (PyArg_ParseTuple(args, "l", &id)) { + obj = getDocumentPtr()->getObjectByID(id); + break; + } + + PyErr_SetString(PyExc_TypeError, "a string or integer is required"); + return nullptr; + } + while (0); + + if (obj) + return obj->getPyObject(); + + Py_Return; } PyObject* DocumentPy::getObjectsByLabel(PyObject *args) diff --git a/src/Mod/Test/Document.py b/src/Mod/Test/Document.py index 8438ab977f..cda69b9f2f 100644 --- a/src/Mod/Test/Document.py +++ b/src/Mod/Test/Document.py @@ -33,6 +33,17 @@ class DocumentBasicCases(unittest.TestCase): def setUp(self): self.Doc = FreeCAD.newDocument("CreateTest") + def testAccessByNameOrID(self): + obj = self.Doc.addObject("App::DocumentObject", "MyName") + + with self.assertRaises(TypeError): + self.Doc.getObject([1]) + + self.assertEqual(self.Doc.getObject(obj.Name), obj) + self.assertEqual(self.Doc.getObject("Unknown"), None) + self.assertEqual(self.Doc.getObject(obj.ID), obj) + self.assertEqual(self.Doc.getObject(obj.ID+1), None) + def testCreateDestroy(self): #FIXME: Causes somehow a ref count error but it's _not_ FreeCAD.getDocument()!!! #If we remove the whole method no error appears.