Skip to content

Commit 2d99fe2

Browse files
authored
Fix crash on connection attribute lookup with non-string names (#810)
1 parent 58850aa commit 2d99fe2

2 files changed

Lines changed: 30 additions & 3 deletions

File tree

‎src/MySQLdb/_mysql.c‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2968,9 +2968,8 @@ _mysql_ConnectionObject_getattro(
29682968
_mysql_ConnectionObject *self,
29692969
PyObject *name)
29702970
{
2971-
const char *cname;
2972-
cname = PyUnicode_AsUTF8(name);
2973-
if (strcmp(cname, "closed") == 0)
2971+
if (PyUnicode_Check(name) &&
2972+
PyUnicode_CompareWithASCIIString(name, "closed") == 0)
29742973
return PyLong_FromLong((long)!(self->open));
29752974

29762975
return PyObject_GenericGetAttr((PyObject *)self, name);

‎tests/test__mysql.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,36 @@
11
import pytest
22

33
from MySQLdb import _mysql
4+
from MySQLdb.connections import Connection
45

56

67
def test_result_type():
78
with pytest.raises(TypeError):
89
_mysql.result(b"xyz")
10+
11+
12+
@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection])
13+
@pytest.mark.parametrize("name", [5, None, b"closed", [], {}])
14+
def test_connection_getattribute_non_string(connection_type, name):
15+
conn = connection_type.__new__(connection_type)
16+
with pytest.raises(TypeError):
17+
conn.__getattribute__(name)
18+
19+
20+
@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection])
21+
@pytest.mark.parametrize("name", ["missing", "closed\x00suffix", "\ud800"])
22+
def test_connection_getattribute_missing(connection_type, name):
23+
conn = connection_type.__new__(connection_type)
24+
with pytest.raises(AttributeError):
25+
conn.__getattribute__(name)
26+
27+
28+
@pytest.mark.parametrize("connection_type", [_mysql.connection, Connection])
29+
def test_connection_getattribute(connection_type):
30+
class AttributeName(str):
31+
pass
32+
33+
conn = connection_type.__new__(connection_type)
34+
assert conn.closed == 1
35+
assert conn.__getattribute__(AttributeName("closed")) == 1
36+
assert conn.__class__ is connection_type

0 commit comments

Comments
 (0)