gh-128398: improve error messages when incorrectly using with and async with (#132218)

Improve the error message with a suggestion when an object supporting the synchronous
(resp. asynchronous) context manager protocol is entered using `async with` (resp. `with`)
instead of `with` (resp. `async with`).
This commit is contained in:
Bénédikt Tran 2025-04-19 10:44:01 +02:00 committed by GitHub
parent 95800fe6e7
commit 8a9c6c4d16
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 211 additions and 47 deletions

View file

@ -75,9 +75,17 @@ class IsolatedAsyncioTestCase(TestCase):
enter = cls.__aenter__
exit = cls.__aexit__
except AttributeError:
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
f"not support the asynchronous context manager protocol"
) from None
msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
"not support the asynchronous context manager protocol")
try:
cls.__enter__
cls.__exit__
except AttributeError:
pass
else:
msg += (" but it supports the context manager protocol. "
"Did you mean to use enterContext()?")
raise TypeError(msg) from None
result = await enter(cm)
self.addAsyncCleanup(exit, cm, None, None, None)
return result

View file

@ -111,8 +111,17 @@ def _enter_context(cm, addcleanup):
enter = cls.__enter__
exit = cls.__exit__
except AttributeError:
raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object does "
f"not support the context manager protocol") from None
msg = (f"'{cls.__module__}.{cls.__qualname__}' object does "
"not support the context manager protocol")
try:
cls.__aenter__
cls.__aexit__
except AttributeError:
pass
else:
msg += (" but it supports the asynchronous context manager "
"protocol. Did you mean to use enterAsyncContext()?")
raise TypeError(msg) from None
result = enter(cm)
addcleanup(exit, cm, None, None, None)
return result