Skip to content

gh-94808: Add test coverage for PyObject_HasAttrString #96627

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Lib/test/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,6 +445,20 @@ def __delattr__(self, *args):
del testme.cardinal
self.assertCallStack([('__delattr__', (testme, "cardinal"))])

def testHasAttrString(self):
import sys
from test.support import import_helper
_testcapi = import_helper.import_module('_testcapi')

class A:
def __init__(self):
self.attr = 1

a = A()
self.assertEqual(_testcapi.hasattr_string(a, "attr"), True)
self.assertEqual(_testcapi.hasattr_string(a, "noattr"), False)
self.assertEqual(sys.exc_info(), (None, None, None))

def testDel(self):
x = []

Expand Down
26 changes: 26 additions & 0 deletions Modules/_testcapimodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -4846,6 +4846,31 @@ sequence_setitem(PyObject *self, PyObject *args)
}


static PyObject *
hasattr_string(PyObject *self, PyObject* args)
{
PyObject* obj;
PyObject* attr_name;

if (!PyArg_UnpackTuple(args, "hasattr_string", 2, 2, &obj, &attr_name)) {
return NULL;
}

if (!PyUnicode_Check(attr_name)) {
PyErr_SetString(PyExc_TypeError, "attribute name must a be string");
return PyErr_Occurred();
}

const char *name_str = PyUnicode_AsUTF8(attr_name);
if (PyObject_HasAttrString(obj, name_str)) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}


/* Functions for testing C calling conventions (METH_*) are named meth_*,
* e.g. "meth_varargs" for METH_VARARGS.
*
Expand Down Expand Up @@ -5705,6 +5730,7 @@ static PyMethodDef TestMethods[] = {
{"write_unraisable_exc", test_write_unraisable_exc, METH_VARARGS},
{"sequence_getitem", sequence_getitem, METH_VARARGS},
{"sequence_setitem", sequence_setitem, METH_VARARGS},
{"hasattr_string", hasattr_string, METH_VARARGS},
{"meth_varargs", meth_varargs, METH_VARARGS},
{"meth_varargs_keywords", _PyCFunction_CAST(meth_varargs_keywords), METH_VARARGS|METH_KEYWORDS},
{"meth_o", meth_o, METH_O},
Expand Down