Skip to content

Commit 9520b6f

Browse files
committed
transaction: Fix error messages; test that __aenter__ returns None
1 parent 49efcd9 commit 9520b6f

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

asyncpg/transaction.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def __init__(self, connection, isolation, readonly, deferrable):
4848
async def __aenter__(self):
4949
if self._managed:
5050
raise apg_errors.InterfaceError(
51-
'cannot enter context: already in an `async def` block')
51+
'cannot enter context: already in an `async with` block')
5252
self._managed = True
5353
await self.start()
5454

@@ -168,13 +168,13 @@ async def __rollback(self):
168168
async def commit(self):
169169
if self._managed:
170170
raise apg_errors.InterfaceError(
171-
'cannot manually commit from within an `async def` block')
171+
'cannot manually commit from within an `async with` block')
172172
await self.__commit()
173173

174174
async def rollback(self):
175175
if self._managed:
176176
raise apg_errors.InterfaceError(
177-
'cannot manually rollback from within an `async def` block')
177+
'cannot manually rollback from within an `async with` block')
178178
await self.__rollback()
179179

180180
def __repr__(self):

tests/test_transaction.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,14 @@ async def test_transaction_regular(self):
1111
self.assertIsNone(self.con._top_xact)
1212

1313
with self.assertRaises(ZeroDivisionError):
14-
async with tr:
14+
async with tr as with_tr:
1515
self.assertIs(self.con._top_xact, tr)
1616

17+
# We don't return the transaction object from __aenter__,
18+
# to make it harder for people to use '.rollback()' and
19+
# '.commit()' from within an 'async with' block.
20+
self.assertIsNone(with_tr)
21+
1722
await self.con.execute('''
1823
CREATE TABLE mytab (a int);
1924
''')
@@ -107,23 +112,23 @@ async def test_transaction_interface_errors(self):
107112

108113
tr = self.con.transaction()
109114
with self.assertRaisesRegex(asyncpg.InterfaceError,
110-
'cannot manually commit.*async def'):
115+
'cannot manually commit.*async with'):
111116
async with tr:
112117
await tr.commit()
113118

114119
self.assertIsNone(self.con._top_xact)
115120

116121
tr = self.con.transaction()
117122
with self.assertRaisesRegex(asyncpg.InterfaceError,
118-
'cannot manually rollback.*async def'):
123+
'cannot manually rollback.*async with'):
119124
async with tr:
120125
await tr.rollback()
121126

122127
self.assertIsNone(self.con._top_xact)
123128

124129
tr = self.con.transaction()
125130
with self.assertRaisesRegex(asyncpg.InterfaceError,
126-
'cannot enter context'):
131+
'cannot enter context:.*async with'):
127132
async with tr:
128133
async with tr:
129134
pass

0 commit comments

Comments
 (0)