PYTHON-4024 Use ruff formatter (#1419)

This commit is contained in:
Steven Silvester 2023-11-02 12:46:40 -05:00 committed by GitHub
parent 7936708d97
commit 923c8a5abe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 72 additions and 38 deletions

View File

@ -17,19 +17,13 @@ repos:
exclude: .patch
exclude_types: [json]
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.10.1
hooks:
- id: black
files: \.py$
args: [--line-length=100]
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format
- repo: https://github.com/adamchainz/blacken-docs
rev: "1.16.0"

View File

@ -159,7 +159,9 @@ class SON(Dict[_Key, _Value]):
if kwargs:
self.update(kwargs)
def get(self, key: _Key, default: Optional[Union[_Value, _T]] = None) -> Union[_Value, _T, None]: # type: ignore[override]
def get( # type: ignore[override]
self, key: _Key, default: Optional[Union[_Value, _T]] = None
) -> Union[_Value, _T, None]:
try:
return self[key]
except KeyError:

View File

@ -98,7 +98,8 @@ python {sys.argv[0]} --help-frameworks."""
sys.exit(1)
run(
args[0], *args[1:] # Framework name.
args[0],
*args[1:], # Framework name.
) # Command line args to pytest, like what test to run.

View File

@ -551,7 +551,10 @@ class Database(common.BaseObject, Generic[_DocumentType]):
user_fields={"cursor": {"firstBatch": 1}},
)
return self.client._retryable_read(
cmd.get_cursor, cmd.get_read_preference(s), s, retryable=not cmd._performs_write # type: ignore[arg-type]
cmd.get_cursor,
cmd.get_read_preference(s), # type: ignore[arg-type]
s,
retryable=not cmd._performs_write,
)
def watch(

View File

@ -23,7 +23,8 @@ except ImportError:
HAVE_STRINGPREP = False
def saslprep(
data: Any, prohibit_unassigned_code_points: Optional[bool] = True # noqa: ARG001
data: Any,
prohibit_unassigned_code_points: Optional[bool] = True, # noqa: ARG001
) -> Any:
"""SASLprep dummy"""
if isinstance(data, str):

View File

@ -144,7 +144,6 @@ select = [
"C4", # flake8-comprehensions
"EM", # flake8-errmsg
"ICN", # flake8-import-conventions
"ISC", # flake8-implicit-str-concat
"G", # flake8-logging-format
"PGH", # pygrep-hooks
"PIE", # flake8-pie

View File

@ -130,7 +130,12 @@ def create_response():
# Reset the numbers.
def reset():
global open_connections, heartbeat_count, total_heartbeat_duration, total_commands, total_command_duration
global \
open_connections, \
heartbeat_count, \
total_heartbeat_duration, \
total_commands, \
total_command_duration
open_connections = 0
heartbeat_count = 0
total_heartbeat_duration = 0

View File

@ -131,8 +131,7 @@ def main(options, mode, urls):
if options.verbose:
print(
"Getting {} {} times total in {} threads, "
"{} times per thread".format(
"Getting {} {} times total in {} threads, " "{} times per thread".format(
urls,
nrequests_per_thread * options.nthreads,
options.nthreads,

View File

@ -47,7 +47,7 @@ class MockPool(Pool):
assert host_and_port in (
client.mock_standalones + client.mock_members + client.mock_mongoses
), ("bad host: %s" % host_and_port)
), "bad host: %s" % host_and_port
with Pool.checkout(self, handler) as conn:
conn.mock_host = self.mock_host

View File

@ -783,7 +783,9 @@ class TestBSON(unittest.TestCase):
self.assertEqual(0, bson_re1.flags)
doc1 = {"r": bson_re1}
doc1_bson = b"\x11\x00\x00\x00\x0br\x00[\\w-\\.]\x00\x00\x00" # document length # r: regex # document terminator
doc1_bson = (
b"\x11\x00\x00\x00\x0br\x00[\\w-\\.]\x00\x00\x00"
) # document length # r: regex # document terminator
self.assertEqual(doc1_bson, encode(doc1))
self.assertEqual(doc1, decode(doc1_bson))
@ -794,7 +796,9 @@ class TestBSON(unittest.TestCase):
doc2_with_re = {"r": re2}
doc2_with_bson_re = {"r": bson_re2}
doc2_bson = b"\x11\x00\x00\x00\x0br\x00.*\x00imsux\x00\x00" # document length # r: regex # document terminator
doc2_bson = (
b"\x11\x00\x00\x00\x0br\x00.*\x00imsux\x00\x00"
) # document length # r: regex # document terminator
self.assertEqual(doc2_bson, encode(doc2_with_re))
self.assertEqual(doc2_bson, encode(doc2_with_bson_re))

View File

@ -42,7 +42,12 @@ class Empty:
class TestComment(IntegrationTest):
def _test_ops(
self, helpers, already_supported, listener, db=Empty(), coll=Empty() # noqa: B008
self,
helpers,
already_supported,
listener,
db=Empty(), # noqa: B008
coll=Empty(), # noqa: B008
):
for h, args in helpers:
c = "testing comment with " + h.__name__

View File

@ -503,7 +503,10 @@ class TestExplicitSimple(EncryptionIntegrationTest):
def test_codec_options(self):
with self.assertRaisesRegex(TypeError, "codec_options must be"):
ClientEncryption(
KMS_PROVIDERS, "keyvault.datakeys", client_context.client, None # type: ignore[arg-type]
KMS_PROVIDERS,
"keyvault.datakeys",
client_context.client,
None, # type: ignore[arg-type]
)
opts = CodecOptions(uuid_representation=UuidRepresentation.JAVA_LEGACY)
@ -1072,7 +1075,9 @@ class TestCorpus(EncryptionIntegrationTest):
try:
encrypted_val = client_encryption.encrypt(
value["value"], algo, **kwargs # type: ignore[arg-type]
value["value"],
algo,
**kwargs, # type: ignore[arg-type]
)
if not value["allowed"]:
self.fail(f"encrypt should have failed: {key!r}: {value!r}")

View File

@ -1191,7 +1191,9 @@ class TestEventClasses(unittest.TestCase):
)
delta = 0.1
event = monitoring.ServerHeartbeatSucceededEvent(
delta, {"ok": 1}, connection_id # type: ignore[arg-type]
delta,
{"ok": 1}, # type: ignore[arg-type]
connection_id,
)
self.assertEqual(
repr(event),
@ -1199,7 +1201,9 @@ class TestEventClasses(unittest.TestCase):
"duration: 0.1, awaited: False, reply: {'ok': 1}>",
)
event = monitoring.ServerHeartbeatFailedEvent(
delta, "ERROR", connection_id # type: ignore[arg-type]
delta,
"ERROR", # type: ignore[arg-type]
connection_id,
)
self.assertEqual(
repr(event),
@ -1216,7 +1220,10 @@ class TestEventClasses(unittest.TestCase):
"<ServerOpeningEvent ('localhost', 27017) topology_id: 000000000000000000000001>",
)
event = monitoring.ServerDescriptionChangedEvent(
"PREV", "NEW", server_address, topology_id # type: ignore[arg-type]
"PREV", # type: ignore[arg-type]
"NEW", # type: ignore[arg-type]
server_address,
topology_id,
)
self.assertEqual(
repr(event),
@ -1233,7 +1240,9 @@ class TestEventClasses(unittest.TestCase):
event = monitoring.TopologyOpenedEvent(topology_id)
self.assertEqual(repr(event), "<TopologyOpenedEvent topology_id: 000000000000000000000001>")
event = monitoring.TopologyDescriptionChangedEvent(
"PREV", "NEW", topology_id # type: ignore[arg-type]
"PREV", # type: ignore[arg-type]
"NEW", # type: ignore[arg-type]
topology_id,
)
self.assertEqual(
repr(event),

View File

@ -83,8 +83,9 @@ def compare_events(expected_dict, actual):
if expected["address"] != "{}:{}".format(*actual.server_address):
return (
False,
"ServerOpeningEvent published with wrong address (expected"
" {}, got {}".format(expected["address"], actual.server_address),
"ServerOpeningEvent published with wrong address (expected" " {}, got {}".format(
expected["address"], actual.server_address
),
)
elif expected_type == "server_description_changed_event":
@ -93,8 +94,9 @@ def compare_events(expected_dict, actual):
if expected["address"] != "{}:{}".format(*actual.server_address):
return (
False,
"ServerDescriptionChangedEvent has wrong address"
" (expected {}, got {}".format(expected["address"], actual.server_address),
"ServerDescriptionChangedEvent has wrong address" " (expected {}, got {}".format(
expected["address"], actual.server_address
),
)
if not compare_server_descriptions(expected["newDescription"], actual.new_description):
@ -113,8 +115,9 @@ def compare_events(expected_dict, actual):
if expected["address"] != "{}:{}".format(*actual.server_address):
return (
False,
"ServerClosedEvent published with wrong address"
" (expected {}, got {}".format(expected["address"], actual.server_address),
"ServerClosedEvent published with wrong address" " (expected {}, got {}".format(
expected["address"], actual.server_address
),
)
elif expected_type == "topology_opening_event":

View File

@ -447,7 +447,8 @@ class TestSSL(IntegrationTest):
# Server cert and hostname are verified.
connected(
MongoClient(
"mongodb://localhost/?ssl=true&serverSelectionTimeoutMS=1000", **self.credentials # type: ignore[arg-type]
"mongodb://localhost/?ssl=true&serverSelectionTimeoutMS=1000",
**self.credentials, # type: ignore[arg-type]
)
)

View File

@ -452,7 +452,9 @@ class TestMultiServerTopology(TopologyTest):
# Discovering a replica set without the setName supplied by the user
# is not yet supported by MongoClient, but Topology can do it.
topology_settings = SetNameDiscoverySettings(
seeds=[address], pool_class=MockPool, monitor_class=DummyMonitor # type: ignore[arg-type]
seeds=[address],
pool_class=MockPool, # type: ignore[arg-type]
monitor_class=DummyMonitor, # type: ignore[arg-type]
)
t = Topology(topology_settings)
@ -480,7 +482,9 @@ class TestMultiServerTopology(TopologyTest):
# Discovering a replica set without the setName supplied by the user
# is not yet supported by MongoClient, but Topology can do it.
topology_settings = SetNameDiscoverySettings(
seeds=[address], pool_class=MockPool, monitor_class=DummyMonitor # type: ignore[arg-type]
seeds=[address],
pool_class=MockPool, # type: ignore[arg-type]
monitor_class=DummyMonitor, # type: ignore[arg-type]
)
t = Topology(topology_settings)

View File

@ -1404,8 +1404,9 @@ class UnifiedSpecTestMixinV1(IntegrationTest):
session = self.entity_map[spec["session"]]
if not session._pinned_address:
self.fail(
"Cannot use targetedFailPoint operation with unpinned "
"session {}".format(spec["session"])
"Cannot use targetedFailPoint operation with unpinned " "session {}".format(
spec["session"]
)
)
client = single_client("{}:{}".format(*session._pinned_address))

View File

@ -156,8 +156,6 @@ deps =
https://github.com/ajdavis/mongo-mockup-db/archive/master.zip
extras =
{[testenv:test]extras}
allowlist_externals =
.evergreen/check-c-extensions.sh
passenv = *
allowlist_externals =
{[testenv:test]allowlist_externals}