diff --git a/bson/codec_options.py b/bson/codec_options.py index 52df204042..530f73fa14 100644 --- a/bson/codec_options.py +++ b/bson/codec_options.py @@ -401,7 +401,7 @@ def __new__( "uuid_representation must be a value from bson.binary.UuidRepresentation" ) if not isinstance(unicode_decode_error_handler, str): - raise ValueError( + raise TypeError( f"unicode_decode_error_handler must be a string, not {type(unicode_decode_error_handler)}" ) if tzinfo is not None: diff --git a/pymongo/asynchronous/auth_oidc.py b/pymongo/asynchronous/auth_oidc.py index 8d40dcf3a4..70e8fae2e9 100644 --- a/pymongo/asynchronous/auth_oidc.py +++ b/pymongo/asynchronous/auth_oidc.py @@ -180,7 +180,7 @@ async def _get_access_token(self) -> str | None: else: resp = cb.fetch(context) if not isinstance(resp, OIDCCallbackResult): - raise ValueError( + raise TypeError( f"Callback result must be of type OIDCCallbackResult, not {type(resp)}" ) self.refresh_token = resp.refresh_token diff --git a/pymongo/asynchronous/collection.py b/pymongo/asynchronous/collection.py index 25f819d5a7..d38335d44a 100644 --- a/pymongo/asynchronous/collection.py +++ b/pymongo/asynchronous/collection.py @@ -3252,7 +3252,7 @@ async def _find_and_modify( """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isinstance(return_document, bool): - raise ValueError( + raise TypeError( f"return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not {type(return_document)}" ) collation = validate_collation_or_none(kwargs.pop("collation", None)) diff --git a/pymongo/asynchronous/monitor.py b/pymongo/asynchronous/monitor.py index 245d5de131..a3aebb80b0 100644 --- a/pymongo/asynchronous/monitor.py +++ b/pymongo/asynchronous/monitor.py @@ -27,7 +27,7 @@ from pymongo._csot import MovingMinimum from pymongo._telemetry import _HeartbeatTelemetry, _monotonic_duration, log_srv_monitor_failure from pymongo.asynchronous.srv_resolver import _SrvResolver -from pymongo.errors import NetworkTimeout, _OperationCancelled +from pymongo.errors import ConfigurationError, NetworkTimeout, _OperationCancelled from pymongo.hello import Hello from pymongo.lock import _async_create_lock from pymongo.periodic_executor import _shutdown_executors @@ -375,7 +375,7 @@ async def _get_seedlist(self) -> list[tuple[str, Any]] | None: seedlist, ttl = await resolver.get_hosts_and_min_ttl() if len(seedlist) == 0: # As per the spec: this should be treated as a failure. - raise Exception + raise ConfigurationError("SRV polling returned no valid hosts.") except Exception as exc: # As per the spec, upon encountering an error: # - An error must not be raised @@ -451,7 +451,7 @@ async def _ping(self) -> float: """Run a "hello" command and return the RTT.""" async with self._pool.checkout() as conn: if self._executor._stopped: - raise Exception("_RttMonitor closed") + raise Exception("_RttMonitor closed") # noqa: TRY002 start = time.monotonic() await conn.hello() return _monotonic_duration(start) diff --git a/pymongo/client_session_shared.py b/pymongo/client_session_shared.py index 4f67dd3488..b07963a05e 100644 --- a/pymongo/client_session_shared.py +++ b/pymongo/client_session_shared.py @@ -557,7 +557,7 @@ def advance_cluster_time(self, cluster_time: Mapping[str, Any]) -> None: f"cluster_time must be a subclass of collections.Mapping, not {type(cluster_time)}" ) if not isinstance(cluster_time.get("clusterTime"), Timestamp): - raise ValueError("Invalid cluster_time") + raise TypeError("Invalid cluster_time") self._advance_cluster_time(cluster_time) def _advance_operation_time(self, operation_time: Timestamp | None) -> None: diff --git a/pymongo/common.py b/pymongo/common.py index 156ebdaaba..106c63ab03 100644 --- a/pymongo/common.py +++ b/pymongo/common.py @@ -454,7 +454,7 @@ def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, boo props: dict[str, Any] = {} if not isinstance(value, str): if not isinstance(value, dict): - raise ValueError( + raise TypeError( f"Auth mechanism properties must be given as a string or a dictionary, not {type(value)}" ) for key, value in value.items(): # noqa: B020 @@ -468,10 +468,10 @@ def validate_auth_mechanism_properties(option: str, value: Any) -> dict[str, boo from pymongo.auth_oidc_shared import OIDCCallback if not isinstance(value, OIDCCallback): - raise ValueError(f"callback must be an OIDCCallback object, not {type(value)}") + raise TypeError(f"callback must be an OIDCCallback object, not {type(value)}") props[key] = value else: - raise ValueError(f"Invalid type for auth mechanism property {key}, {type(value)}") + raise TypeError(f"Invalid type for auth mechanism property {key}, {type(value)}") return props value = validate_string(option, value) @@ -612,7 +612,7 @@ def validate_is_callable_or_none(option: Any, value: Any) -> Callable[..., Any] if value is None: return value if not callable(value): - raise ValueError(f"{option} must be a callable, not {type(value)}") + raise TypeError(f"{option} must be a callable, not {type(value)}") return value diff --git a/pymongo/pyopenssl_context.py b/pymongo/pyopenssl_context.py index e33ebe57b9..9fc29d2bad 100644 --- a/pymongo/pyopenssl_context.py +++ b/pymongo/pyopenssl_context.py @@ -131,7 +131,7 @@ def _call(self, call: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: except BLOCKING_IO_ERRORS as exc: # Do not retry if the connection is in non-blocking mode. if timeout == 0: - raise exc + raise # Check for closed socket. if self.fileno() == -1: if timeout and _time.monotonic() - start > timeout: diff --git a/pymongo/synchronous/auth_oidc.py b/pymongo/synchronous/auth_oidc.py index f81059e16c..652ee44616 100644 --- a/pymongo/synchronous/auth_oidc.py +++ b/pymongo/synchronous/auth_oidc.py @@ -180,7 +180,7 @@ def _get_access_token(self) -> str | None: else: resp = cb.fetch(context) if not isinstance(resp, OIDCCallbackResult): - raise ValueError( + raise TypeError( f"Callback result must be of type OIDCCallbackResult, not {type(resp)}" ) self.refresh_token = resp.refresh_token diff --git a/pymongo/synchronous/collection.py b/pymongo/synchronous/collection.py index 6fbed057bf..d26ccf05ee 100644 --- a/pymongo/synchronous/collection.py +++ b/pymongo/synchronous/collection.py @@ -3237,7 +3237,7 @@ def _find_and_modify( """Internal findAndModify helper.""" common.validate_is_mapping("filter", filter) if not isinstance(return_document, bool): - raise ValueError( + raise TypeError( f"return_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not {type(return_document)}" ) collation = validate_collation_or_none(kwargs.pop("collation", None)) diff --git a/pymongo/synchronous/monitor.py b/pymongo/synchronous/monitor.py index bbedff66e7..436e9eed8b 100644 --- a/pymongo/synchronous/monitor.py +++ b/pymongo/synchronous/monitor.py @@ -26,7 +26,7 @@ from pymongo import common, periodic_executor from pymongo._csot import MovingMinimum from pymongo._telemetry import _HeartbeatTelemetry, _monotonic_duration, log_srv_monitor_failure -from pymongo.errors import NetworkTimeout, _OperationCancelled +from pymongo.errors import ConfigurationError, NetworkTimeout, _OperationCancelled from pymongo.hello import Hello from pymongo.lock import _create_lock from pymongo.periodic_executor import _shutdown_executors @@ -373,7 +373,7 @@ def _get_seedlist(self) -> list[tuple[str, Any]] | None: seedlist, ttl = resolver.get_hosts_and_min_ttl() if len(seedlist) == 0: # As per the spec: this should be treated as a failure. - raise Exception + raise ConfigurationError("SRV polling returned no valid hosts.") except Exception as exc: # As per the spec, upon encountering an error: # - An error must not be raised @@ -449,7 +449,7 @@ def _ping(self) -> float: """Run a "hello" command and return the RTT.""" with self._pool.checkout() as conn: if self._executor._stopped: - raise Exception("_RttMonitor closed") + raise Exception("_RttMonitor closed") # noqa: TRY002 start = time.monotonic() conn.hello() return _monotonic_duration(start) diff --git a/pyproject.toml b/pyproject.toml index 871939af25..71a7255bc7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -247,7 +247,6 @@ ignore = [ "ICN001", # Use standard import naming conventions (pandas as pd, datetime as dt...) "BLE", # Broad `Except` exception catches (intentional) # These are all new defaults added in ruff 0.16.0. Individual tickets linked from PYTHON-5964 track enabling each one. - "TRY", # tryceratops "INT", # flake8-gettext "ISC", # flake8-implicit-str-concat "FLY", # flynt diff --git a/test/asynchronous/helpers.py b/test/asynchronous/helpers.py index ca7dbbfe65..a75668c48d 100644 --- a/test/asynchronous/helpers.py +++ b/test/asynchronous/helpers.py @@ -113,7 +113,7 @@ def __del__(self): f"EVENTS_QUEUE_FREQUENCY={common.EVENTS_QUEUE_FREQUENCY}, stack:\n{self._stack}" ) self.disable() - raise Exception(msg) + raise RuntimeError(msg) # Global knobs to speed up the test suite. diff --git a/test/asynchronous/test_auth_oidc.py b/test/asynchronous/test_auth_oidc.py index 66f4309eba..e4e4422b59 100644 --- a/test/asynchronous/test_auth_oidc.py +++ b/test/asynchronous/test_auth_oidc.py @@ -314,7 +314,7 @@ def fetch(self, ctx): client = await self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() # Close the client. await client.close() @@ -558,7 +558,7 @@ def fetch(self, a): return None client = await self.create_client(request_cb=RequestTokenNull()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() await client.close() @@ -568,7 +568,7 @@ def fetch(self, a): return {} client = await self.create_client(request_cb=CallbackInvalidToken()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() await client.close() @@ -852,7 +852,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() async def test_2_3_oidc_callback_returns_missing_data(self): @@ -866,7 +866,7 @@ def fetch(self, a): client = await self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): await client.test.coll.find_one() async def test_2_4_invalid_client_configuration_with_callback(self): diff --git a/test/asynchronous/test_client.py b/test/asynchronous/test_client.py index 02d48d8838..73b8417226 100644 --- a/test/asynchronous/test_client.py +++ b/test/asynchronous/test_client.py @@ -2236,7 +2236,7 @@ async def test_background_connections_log_on_error(self): pool = await async_get_pool(client) async def fail_connect(*args, **kwargs): - raise Exception("failed to connect") + raise ConnectionFailure("failed to connect") pool.connect = fail_connect # Un-patch Pool.connect to break the cyclic reference. diff --git a/test/asynchronous/test_dns.py b/test/asynchronous/test_dns.py index adb14c8862..fb66d45f35 100644 --- a/test/asynchronous/test_dns.py +++ b/test/asynchronous/test_dns.py @@ -386,7 +386,7 @@ async def test_10_accept_a_mixed_case_returned_address_with_srv_allowed_hosts_su self.assertEqual(["cluster.mongodb.com"], [node[0] for node in res["nodelist"]]) async def test_11_throw_when_srv_host_validator_is_not_callable(self): - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): self.simple_client("mongodb+srv://blogs.mongodb.com", srv_host_validator="notacallable") async def test_12_accept_a_reserved_single_label_as_srv_allowed_hosts_suffix(self): diff --git a/test/asynchronous/test_examples.py b/test/asynchronous/test_examples.py index 6a6d6b3d9e..35e0171a86 100644 --- a/test/asynchronous/test_examples.py +++ b/test/asynchronous/test_examples.py @@ -1113,7 +1113,7 @@ async def update_employee_info(session): async with client.start_session() as session: try: await run_transaction_with_retry(update_employee_info, session) - except Exception: + except Exception: # noqa: TRY203 # Do something with error. raise diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index ea25d43e9b..cc669abcbe 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -181,7 +181,7 @@ async def lock_pool(self): # Wait for the unlock flag. unlock_pool = await self.wait(self.unlock, 10) if not unlock_pool: - raise Exception("timed out waiting for unlock signal: deadlock?") + raise TimeoutError("timed out waiting for unlock signal: deadlock?") async def wait(self, event: Event, timeout: int): if _IS_SYNC: diff --git a/test/asynchronous/test_server_selection.py b/test/asynchronous/test_server_selection.py index 4a15b7d93a..637a9b233e 100644 --- a/test/asynchronous/test_server_selection.py +++ b/test/asynchronous/test_server_selection.py @@ -118,7 +118,7 @@ async def all_hosts_started(): async def test_invalid_server_selector(self): # Client initialization must fail if server_selector is not callable. for selector_candidate in [[], 10, "string", {}]: - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): AsyncMongoClient(connect=False, server_selector=selector_candidate) # None value for server_selector is OK. diff --git a/test/asynchronous/test_session.py b/test/asynchronous/test_session.py index 6e3a31d2a7..0e3fb96576 100644 --- a/test/asynchronous/test_session.py +++ b/test/asynchronous/test_session.py @@ -1019,7 +1019,7 @@ async def test_core(self): self.assertIsNone(sess2.cluster_time) self.assertIsNone(sess2.operation_time) self.assertRaises(TypeError, sess2.advance_cluster_time, 1) - self.assertRaises(ValueError, sess2.advance_cluster_time, {}) + self.assertRaises(TypeError, sess2.advance_cluster_time, {}) self.assertRaises(TypeError, sess2.advance_operation_time, 1) # No error assert sess.cluster_time is not None diff --git a/test/asynchronous/test_sfp.py b/test/asynchronous/test_sfp.py index d9b6350002..06f5b2e53e 100644 --- a/test/asynchronous/test_sfp.py +++ b/test/asynchronous/test_sfp.py @@ -46,7 +46,7 @@ def _require_env(name: str) -> str: value = os.environ.get(name) if not value: - raise Exception(f"Must set {name} env variable to test.") + raise ValueError(f"Must set {name} env variable to test.") return value diff --git a/test/asynchronous/utils.py b/test/asynchronous/utils.py index 3e6669a753..417af18698 100644 --- a/test/asynchronous/utils.py +++ b/test/asynchronous/utils.py @@ -215,9 +215,9 @@ async def wrapper(*args, **kwargs): passes += 1 if passes == min_passes: return result - except Exception as e: + except Exception: if i == max_runs - 1: - raise e + raise print( f"Retrying after attempt {i + 1} of {func_name or target_func.__name__} failed with ({reason})):\n" f"{traceback.format_exc()}", diff --git a/test/atlas/test_connection.py b/test/atlas/test_connection.py index 7424db83e6..3b018264f3 100644 --- a/test/atlas/test_connection.py +++ b/test/atlas/test_connection.py @@ -51,7 +51,7 @@ class TestAtlasConnect(PyMongoTestCase): def connect(self, uri): if not uri: - raise Exception("Must set env variable to test.") + raise ValueError("Must set env variable to test.") client = self.simple_client(uri) # No TLS error client.admin.command("ping") diff --git a/test/helpers.py b/test/helpers.py index e49d861bed..e183b12fe3 100644 --- a/test/helpers.py +++ b/test/helpers.py @@ -113,7 +113,7 @@ def __del__(self): f"EVENTS_QUEUE_FREQUENCY={common.EVENTS_QUEUE_FREQUENCY}, stack:\n{self._stack}" ) self.disable() - raise Exception(msg) + raise RuntimeError(msg) # Global knobs to speed up the test suite. diff --git a/test/test_auth_oidc.py b/test/test_auth_oidc.py index 0145c3f357..e08ad91805 100644 --- a/test/test_auth_oidc.py +++ b/test/test_auth_oidc.py @@ -314,7 +314,7 @@ def fetch(self, ctx): client = self.create_client(request_cb=CustomCB()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() # Close the client. client.close() @@ -558,7 +558,7 @@ def fetch(self, a): return None client = self.create_client(request_cb=RequestTokenNull()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() client.close() @@ -568,7 +568,7 @@ def fetch(self, a): return {} client = self.create_client(request_cb=CallbackInvalidToken()) - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() client.close() @@ -852,7 +852,7 @@ def fetch(self, a): client = self.create_client(request_cb=CallbackNullToken()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() def test_2_3_oidc_callback_returns_missing_data(self): @@ -866,7 +866,7 @@ def fetch(self, a): client = self.create_client(request_cb=CustomCallback()) # Perform a find operation that fails. - with self.assertRaises(ValueError): + with self.assertRaises(TypeError): client.test.coll.find_one() def test_2_4_invalid_client_configuration_with_callback(self): diff --git a/test/test_client.py b/test/test_client.py index d26f375757..c39618eadb 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -2189,7 +2189,7 @@ def test_background_connections_log_on_error(self): pool = get_pool(client) def fail_connect(*args, **kwargs): - raise Exception("failed to connect") + raise ConnectionFailure("failed to connect") pool.connect = fail_connect # Un-patch Pool.connect to break the cyclic reference. diff --git a/test/test_dns.py b/test/test_dns.py index 675fac1d81..2b37dc2fcf 100644 --- a/test/test_dns.py +++ b/test/test_dns.py @@ -382,7 +382,7 @@ def test_10_accept_a_mixed_case_returned_address_with_srv_allowed_hosts_suffix(s self.assertEqual(["cluster.mongodb.com"], [node[0] for node in res["nodelist"]]) def test_11_throw_when_srv_host_validator_is_not_callable(self): - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): self.simple_client("mongodb+srv://blogs.mongodb.com", srv_host_validator="notacallable") def test_12_accept_a_reserved_single_label_as_srv_allowed_hosts_suffix(self): diff --git a/test/test_examples.py b/test/test_examples.py index b97e1f7bfa..ea7229fb70 100644 --- a/test/test_examples.py +++ b/test/test_examples.py @@ -1111,7 +1111,7 @@ def update_employee_info(session): with client.start_session() as session: try: run_transaction_with_retry(update_employee_info, session) - except Exception: + except Exception: # noqa: TRY203 # Do something with error. raise diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index 8bd4056772..56c92d9330 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -181,7 +181,7 @@ def lock_pool(self): # Wait for the unlock flag. unlock_pool = self.wait(self.unlock, 10) if not unlock_pool: - raise Exception("timed out waiting for unlock signal: deadlock?") + raise TimeoutError("timed out waiting for unlock signal: deadlock?") def wait(self, event: Event, timeout: int): if _IS_SYNC: diff --git a/test/test_server_selection.py b/test/test_server_selection.py index d877392aaf..5f4c6d1a6d 100644 --- a/test/test_server_selection.py +++ b/test/test_server_selection.py @@ -118,7 +118,7 @@ def all_hosts_started(): def test_invalid_server_selector(self): # Client initialization must fail if server_selector is not callable. for selector_candidate in [[], 10, "string", {}]: - with self.assertRaisesRegex(ValueError, "must be a callable"): + with self.assertRaisesRegex(TypeError, "must be a callable"): MongoClient(connect=False, server_selector=selector_candidate) # None value for server_selector is OK. diff --git a/test/test_session.py b/test/test_session.py index 6cd28d27fe..2f0a98a933 100644 --- a/test/test_session.py +++ b/test/test_session.py @@ -1019,7 +1019,7 @@ def test_core(self): self.assertIsNone(sess2.cluster_time) self.assertIsNone(sess2.operation_time) self.assertRaises(TypeError, sess2.advance_cluster_time, 1) - self.assertRaises(ValueError, sess2.advance_cluster_time, {}) + self.assertRaises(TypeError, sess2.advance_cluster_time, {}) self.assertRaises(TypeError, sess2.advance_operation_time, 1) # No error assert sess.cluster_time is not None diff --git a/test/test_sfp.py b/test/test_sfp.py index b5dcfa5cc7..401891e8b0 100644 --- a/test/test_sfp.py +++ b/test/test_sfp.py @@ -46,7 +46,7 @@ def _require_env(name: str) -> str: value = os.environ.get(name) if not value: - raise Exception(f"Must set {name} env variable to test.") + raise ValueError(f"Must set {name} env variable to test.") return value diff --git a/test/unified_format_shared.py b/test/unified_format_shared.py index b3b8e28a3a..4a328467b3 100644 --- a/test/unified_format_shared.py +++ b/test/unified_format_shared.py @@ -665,7 +665,7 @@ def match_event(self, expectation, actual): elif name == "topologyClosedEvent": self.test.assertIsInstance(actual, TopologyClosedEvent) else: - raise Exception(f"Unsupported event type {name}") + raise ValueError(f"Unsupported event type {name}") self.match_event_fields(actual, spec) diff --git a/test/utils.py b/test/utils.py index e52fd336e2..7a7103d5ab 100644 --- a/test/utils.py +++ b/test/utils.py @@ -215,9 +215,9 @@ def wrapper(*args, **kwargs): passes += 1 if passes == min_passes: return result - except Exception as e: + except Exception: if i == max_runs - 1: - raise e + raise print( f"Retrying after attempt {i + 1} of {func_name or target_func.__name__} failed with ({reason})):\n" f"{traceback.format_exc()}", diff --git a/tools/fail_if_no_c.py b/tools/fail_if_no_c.py index bb50081ad5..9f6ad21de5 100644 --- a/tools/fail_if_no_c.py +++ b/tools/fail_if_no_c.py @@ -36,11 +36,11 @@ def main() -> None: try: from pymongo import _cmessage # type:ignore[attr-defined] # noqa: F401 except Exception as e: - LOGGER.exception(e) + LOGGER.exception(e) # noqa: TRY401 try: from bson import _cbson # type:ignore[attr-defined] # noqa: F401 except Exception as e: - LOGGER.exception(e) + LOGGER.exception(e) # noqa: TRY401 sys.exit("could not load C extensions") diff --git a/tools/synchro.py b/tools/synchro.py index f5b6260b5d..7cb68d4ca7 100644 --- a/tools/synchro.py +++ b/tools/synchro.py @@ -230,11 +230,11 @@ def apply_is_sync(lines: list[str], file: str) -> list[str]: index = lines.index(is_sync) is_sync = is_sync.replace("False", "True") lines[index] = is_sync - except StopIteration as e: + except StopIteration: print( f"Missing _IS_SYNC at top of async file {file.replace('synchronous', 'asynchronous')}" ) - raise e + raise return lines