Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion bson/codec_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/auth_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Comment thread
NoahStapp marked this conversation as resolved.
Resolved
f"Callback result must be of type OIDCCallbackResult, not {type(resp)}"
)
self.refresh_token = resp.refresh_token
Expand Down
2 changes: 1 addition & 1 deletion pymongo/asynchronous/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 3 additions & 3 deletions pymongo/asynchronous/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion pymongo/client_session_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Comment thread
NoahStapp marked this conversation as resolved.
Resolved
self._advance_cluster_time(cluster_time)

def _advance_operation_time(self, operation_time: Timestamp | None) -> None:
Expand Down
8 changes: 4 additions & 4 deletions pymongo/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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)}")
Comment thread
NoahStapp marked this conversation as resolved.
Resolved
return value


Expand Down
2 changes: 1 addition & 1 deletion pymongo/pyopenssl_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion pymongo/synchronous/auth_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pymongo/synchronous/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
6 changes: 3 additions & 3 deletions pymongo/synchronous/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions test/asynchronous/test_auth_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()

Expand All @@ -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()

Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_load_balancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_server_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion test/asynchronous/test_sfp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
4 changes: 2 additions & 2 deletions test/asynchronous/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()}",
Expand Down
2 changes: 1 addition & 1 deletion test/atlas/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion test/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 5 additions & 5 deletions test/test_auth_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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()

Expand All @@ -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()

Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion test/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion test/test_dns.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion test/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion test/test_load_balancer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion test/test_server_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading