Skip to content

Commit 1ef6c58

Browse files
authored
Deprecate context manager interface of Connection (PyMySQL#742)
1 parent 15eaee5 commit 1ef6c58

File tree

2 files changed

+20
-13
lines changed

2 files changed

+20
-13
lines changed

pymysql/connections.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,9 @@ def cursor(self, cursor=None):
492492

493493
def __enter__(self):
494494
"""Context manager that returns a Cursor"""
495+
warnings.warn(
496+
"Context manager API of Connection object is deprecated; Use conn.begin()",
497+
DeprecationWarning)
495498
return self.cursor()
496499

497500
def __exit__(self, exc, value, traceback):

pymysql/tests/test_connection.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from pymysql._compat import text_type
88
from pymysql.constants import CLIENT
99

10+
import pytest
11+
1012

1113
class TempUser:
1214
def __init__(self, c, user, db, auth=None, authdata=None, password=None):
@@ -451,21 +453,23 @@ def test_read_default_group(self):
451453
def test_context(self):
452454
with self.assertRaises(ValueError):
453455
c = self.connect()
456+
with pytest.warns(DeprecationWarning):
457+
with c as cur:
458+
cur.execute('create table test ( a int ) ENGINE=InnoDB')
459+
c.begin()
460+
cur.execute('insert into test values ((1))')
461+
raise ValueError('pseudo abort')
462+
c = self.connect()
463+
with pytest.warns(DeprecationWarning):
454464
with c as cur:
455-
cur.execute('create table test ( a int ) ENGINE=InnoDB')
456-
c.begin()
465+
cur.execute('select count(*) from test')
466+
self.assertEqual(0, cur.fetchone()[0])
457467
cur.execute('insert into test values ((1))')
458-
raise ValueError('pseudo abort')
459-
c.commit()
460-
c = self.connect()
461-
with c as cur:
462-
cur.execute('select count(*) from test')
463-
self.assertEqual(0, cur.fetchone()[0])
464-
cur.execute('insert into test values ((1))')
465-
with c as cur:
466-
cur.execute('select count(*) from test')
467-
self.assertEqual(1,cur.fetchone()[0])
468-
cur.execute('drop table test')
468+
with pytest.warns(DeprecationWarning):
469+
with c as cur:
470+
cur.execute('select count(*) from test')
471+
self.assertEqual(1,cur.fetchone()[0])
472+
cur.execute('drop table test')
469473

470474
def test_set_charset(self):
471475
c = self.connect()

0 commit comments

Comments
 (0)