Skip to content
Prev Previous commit
Next Next commit
Address Serhiy's review
* Add more tests
* Add 'const'
  • Loading branch information
vstinner committed Jan 26, 2025
commit 4fc2e10ee4855abe7121140fd3d32d1bdea7af4b
15 changes: 15 additions & 0 deletions Lib/test/test_capi/test_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,21 @@ def check_getmoduleattr(self, getmoduleattr):
self.assertIs(getmoduleattr('sys', 'argv'), sys.argv)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check also a module name containing dots.

Check errors:

  • non-existent module
  • relative module name
  • non-existent attribute
  • attribute name containing dots

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added requested tests.

attribute name containing dots

getmoduleattr('sys', 'implementation.name') raises an AttributeError. I prefer to not implement "nested" getattr(). One should write getmoduleattr('sys', 'implementation') + PyObject_GetAttrString(attr, "name").

self.assertIs(getmoduleattr('types', 'ModuleType'), types.ModuleType)

# module name containing a dot
attr = getmoduleattr('email.message', 'Message')
from email.message import Message
self.assertIs(attr, Message)

with self.assertRaises(ImportError):
# nonexistent module
getmoduleattr('nonexistentmodule', 'attr')
with self.assertRaises(AttributeError):
# nonexistent attribute
getmoduleattr('sys', 'nonexistentattr')
with self.assertRaises(AttributeError):
# attribute name containing a dot
getmoduleattr('sys', 'implementation.name')

def test_getmoduleattr(self):
# Test PyImport_GetModuleAttr()
getmoduleattr = _testcapi.PyImport_GetModuleAttr
Expand Down
2 changes: 1 addition & 1 deletion Modules/_testcapi/import.c
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pyimport_getmoduleattr(PyObject *self, PyObject *args)
static PyObject *
pyimport_getmoduleattrstring(PyObject *self, PyObject *args)
{
char *mod_name, *attr_name;
const char *mod_name, *attr_name;
Py_ssize_t len;
if (!PyArg_ParseTuple(args, "z#z#", &mod_name, &len, &attr_name, &len)) {
return NULL;
Expand Down