Skip to content

Commit 9a66c04

Browse files
committed
style: fix error [SIM117] - Use a single with statement with multiple contexts instead of nested with statements.
Used Ruff (vscode and pre-commit) to: - Black-compatible code formatting. - fix all auto-fixable violations. - isort-compatible import sorting. - flake8-simplify manual fixes. Signed-off-by: Paulo Vital <paulo.vital@ibm.com>
1 parent 387ef49 commit 9a66c04

6 files changed

Lines changed: 108 additions & 75 deletions

File tree

tests/clients/boto3/test_boto3_s3.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@
44

55
import os
66
from io import BytesIO
7+
from typing import Generator
78

8-
import pytest
99
import boto3
10-
from typing import Generator
10+
import pytest
1111
from moto import mock_aws
1212

1313
from instana.singletons import agent, get_tracer
@@ -157,7 +157,7 @@ def test_s3_upload_file(self) -> None:
157157
def test_s3_upload_file_obj(self) -> None:
158158
self.s3.create_bucket(Bucket=self.bucket_name)
159159

160-
with self.tracer.start_as_current_span("test"):
160+
with self.tracer.start_as_current_span("test"): # noqa: SIM117
161161
with open(upload_filename, "rb") as fd:
162162
self.s3.upload_fileobj(fd, self.bucket_name, self.object_name)
163163

@@ -214,7 +214,7 @@ def test_s3_download_file_obj(self) -> None:
214214
self.s3.create_bucket(Bucket=self.bucket_name)
215215
self.s3.upload_file(upload_filename, self.bucket_name, self.object_name)
216216

217-
with self.tracer.start_as_current_span("test"):
217+
with self.tracer.start_as_current_span("test"): # noqa: SIM117
218218
with open(download_target_filename, "wb") as fd:
219219
self.s3.download_fileobj(self.bucket_name, self.object_name, fd)
220220

tests/clients/test_google-cloud-storage.py

Lines changed: 45 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -406,12 +406,10 @@ def test_objects_compose(self, mock_requests: Mock) -> None:
406406
)
407407

408408
with self.tracer.start_as_current_span("test"):
409-
client.bucket("test bucket").blob("dest object").compose(
410-
[
411-
storage.blob.Blob("object 1", "test bucket"),
412-
storage.blob.Blob("object 2", "test bucket"),
413-
]
414-
)
409+
client.bucket("test bucket").blob("dest object").compose([
410+
storage.blob.Blob("object 1", "test bucket"),
411+
storage.blob.Blob("object 2", "test bucket"),
412+
])
415413

416414
spans = self.recorder.queued_spans()
417415

@@ -1046,10 +1044,9 @@ def test_batch_operation(self, mock_requests: Mock) -> None:
10461044
)
10471045
bucket = client.bucket("test-bucket")
10481046

1049-
with self.tracer.start_as_current_span("test"):
1050-
with client.batch():
1051-
for obj in ["obj1", "obj2"]:
1052-
bucket.delete_blob(obj)
1047+
with self.tracer.start_as_current_span("test"), client.batch():
1048+
for obj in ["obj1", "obj2"]:
1049+
bucket.delete_blob(obj)
10531050

10541051
spans = self.recorder.queued_spans()
10551052

@@ -1064,9 +1061,12 @@ def test_execute_with_instana_without_tags(self, mock_requests: Mock) -> None:
10641061
client = self._client(
10651062
credentials=AnonymousCredentials(), project="test-project"
10661063
)
1067-
with self.tracer.start_as_current_span("test"), patch(
1068-
"instana.instrumentation.google.cloud.storage._collect_attributes",
1069-
return_value=None,
1064+
with (
1065+
self.tracer.start_as_current_span("test"),
1066+
patch(
1067+
"instana.instrumentation.google.cloud.storage._collect_attributes",
1068+
return_value=None,
1069+
),
10701070
):
10711071
buckets = client.list_buckets()
10721072
for b in buckets:
@@ -1077,9 +1077,12 @@ def test_execute_with_instana_is_tracing_off(self) -> None:
10771077
client = self._client(
10781078
credentials=AnonymousCredentials(), project="test-project"
10791079
)
1080-
with self.tracer.start_as_current_span("test"), patch(
1081-
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1082-
return_value=(None, None, None),
1080+
with (
1081+
self.tracer.start_as_current_span("test"),
1082+
patch(
1083+
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1084+
return_value=(None, None, None),
1085+
),
10831086
):
10841087
response = client.list_buckets()
10851088
assert isinstance(response.client, storage.Client)
@@ -1096,12 +1099,16 @@ def test_download_with_instana_is_tracing_off(self, mock_requests: Mock) -> None
10961099
client = self._client(
10971100
credentials=AnonymousCredentials(), project="test-project"
10981101
)
1099-
with self.tracer.start_as_current_span("test"), patch(
1100-
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1101-
return_value=(None, None, None),
1102+
with (
1103+
self.tracer.start_as_current_span("test"),
1104+
patch(
1105+
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1106+
return_value=(None, None, None),
1107+
),
11021108
):
11031109
response = (
1104-
client.bucket("test bucket")
1110+
client
1111+
.bucket("test bucket")
11051112
.blob("test object")
11061113
.download_to_file(
11071114
io.BytesIO(),
@@ -1120,12 +1127,16 @@ def test_upload_with_instana_is_tracing_off(self, mock_requests: Mock) -> None:
11201127
credentials=AnonymousCredentials(), project="test-project"
11211128
)
11221129

1123-
with self.tracer.start_as_current_span("test"), patch(
1124-
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1125-
return_value=(None, None, None),
1130+
with (
1131+
self.tracer.start_as_current_span("test"),
1132+
patch(
1133+
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1134+
return_value=(None, None, None),
1135+
),
11261136
):
11271137
response = (
1128-
client.bucket("test bucket")
1138+
client
1139+
.bucket("test bucket")
11291140
.blob("test object")
11301141
.upload_from_string("CONTENT")
11311142
)
@@ -1144,14 +1155,17 @@ def test_finish_batch_operation_is_tracing_off(self, mock_requests: Mock) -> Non
11441155
)
11451156
bucket = client.bucket("test-bucket")
11461157

1147-
with self.tracer.start_as_current_span("test"), patch(
1148-
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1149-
return_value=(None, None, None),
1158+
with (
1159+
self.tracer.start_as_current_span("test"),
1160+
patch(
1161+
"instana.instrumentation.google.cloud.storage.get_tracer_tuple",
1162+
return_value=(None, None, None),
1163+
),
1164+
client.batch() as batch_response,
11501165
):
1151-
with client.batch() as batch_response:
1152-
for obj in ["obj1", "obj2"]:
1153-
bucket.delete_blob(obj)
1154-
assert batch_response
1166+
for obj in ["obj1", "obj2"]:
1167+
bucket.delete_blob(obj)
1168+
assert batch_response
11551169

11561170
def _client(self, *args, **kwargs) -> storage.Client:
11571171
# override the HTTP client to bypass the authorization

tests/clients/test_logging.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,14 @@ def test_root_exit_span(self) -> None:
100100
assert spans[0].data["log"].get("message") == "foo bar"
101101

102102
def test_exception(self) -> None:
103-
with self.tracer.start_as_current_span("test"):
104-
with patch(
103+
with (
104+
self.tracer.start_as_current_span("test"),
105+
patch(
105106
"instana.span.span.InstanaSpan.add_event",
106107
side_effect=Exception("mocked error"),
107-
):
108-
self.logger.warning("foo %s", "bar")
108+
),
109+
):
110+
self.logger.warning("foo %s", "bar")
109111

110112
spans = self.recorder.queued_spans()
111113

tests/clients/test_mysqlclient.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44

55
import sys
6+
67
import MySQLdb
78
import pytest
89

@@ -229,10 +230,9 @@ def test_error_capture(self):
229230
assert db_span.data["mysql"]["port"] == testenv["mysql_port"]
230231

231232
def test_connect_cursor_ctx_mgr(self):
232-
with self.tracer.start_as_current_span("test"):
233-
with self.db as connection:
234-
with connection.cursor() as cursor:
235-
affected_rows = cursor.execute("""SELECT * from users""")
233+
with self.tracer.start_as_current_span("test"), self.db as connection: # noqa: SIM117
234+
with connection.cursor() as cursor:
235+
affected_rows = cursor.execute("""SELECT * from users""")
236236

237237
assert affected_rows == 1
238238
spans = self.recorder.queued_spans()
@@ -254,10 +254,9 @@ def test_connect_cursor_ctx_mgr(self):
254254
assert db_span.data["mysql"]["port"] == testenv["mysql_port"]
255255

256256
def test_connect_ctx_mgr(self):
257-
with self.tracer.start_as_current_span("test"):
258-
with self.db as connection:
259-
cursor = connection.cursor()
260-
cursor.execute("""SELECT * from users""")
257+
with self.tracer.start_as_current_span("test"), self.db as connection:
258+
cursor = connection.cursor()
259+
cursor.execute("""SELECT * from users""")
261260

262261
spans = self.recorder.queued_spans()
263262
assert len(spans) == 2

tests/clients/test_pymysql.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
# (c) Copyright Instana Inc. 2020
33

44

5-
import pytest
5+
from typing import Generator
66

77
import pymysql
8+
import pytest
89

9-
from typing import Generator
10-
from tests.helpers import testenv
1110
from instana.singletons import agent, get_tracer
11+
from tests.helpers import testenv
1212

1313

1414
class TestPyMySQL:
@@ -255,10 +255,9 @@ def test_error_capture(self) -> None:
255255
assert db_span.data["mysql"]["port"] == testenv["mysql_port"]
256256

257257
def test_connect_cursor_ctx_mgr(self) -> None:
258-
with self.tracer.start_as_current_span("test"):
259-
with self.db as connection:
260-
with connection.cursor() as cursor:
261-
affected_rows = cursor.execute("""SELECT * from users""")
258+
with self.tracer.start_as_current_span("test"), self.db as connection: # noqa: SIM117
259+
with connection.cursor() as cursor:
260+
affected_rows = cursor.execute("""SELECT * from users""")
262261

263262
assert affected_rows == 1
264263
spans = self.recorder.queued_spans()
@@ -280,10 +279,9 @@ def test_connect_cursor_ctx_mgr(self) -> None:
280279
assert db_span.data["mysql"]["port"] == testenv["mysql_port"]
281280

282281
def test_connect_ctx_mgr(self) -> None:
283-
with self.tracer.start_as_current_span("test"):
284-
with self.db as connection:
285-
cursor = connection.cursor()
286-
cursor.execute("""SELECT * from users""")
282+
with self.tracer.start_as_current_span("test"), self.db as connection:
283+
cursor = connection.cursor()
284+
cursor.execute("""SELECT * from users""")
287285

288286
spans = self.recorder.queued_spans()
289287
assert len(spans) == 2

tests/test_fsm_cmdline.py

Lines changed: 37 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -121,13 +121,13 @@ def test_get_cmdline_linux_proc(
121121

122122
def test_get_cmdline_linux_proc_file_not_found(self) -> None:
123123
"""Test _get_cmdline_linux_proc when file doesn't exist."""
124-
with patch("builtins.open", side_effect=FileNotFoundError()):
124+
with patch("builtins.open", side_effect=FileNotFoundError()): # noqa: SIM117
125125
with pytest.raises(FileNotFoundError):
126126
self.machine._get_cmdline_linux_proc()
127127

128128
def test_get_cmdline_linux_proc_permission_error(self) -> None:
129129
"""Test _get_cmdline_linux_proc with permission error."""
130-
with patch("builtins.open", side_effect=PermissionError()):
130+
with patch("builtins.open", side_effect=PermissionError()): # noqa: SIM117
131131
with pytest.raises(PermissionError):
132132
self.machine._get_cmdline_linux_proc()
133133

@@ -187,11 +187,13 @@ def test_get_cmdline_unix_ps_empty_output(self) -> None:
187187

188188
def test_get_cmdline_unix_ps_subprocess_error(self) -> None:
189189
"""Test _get_cmdline_unix_ps when subprocess fails."""
190-
with patch(
191-
"subprocess.Popen", side_effect=subprocess.SubprocessError("Test error")
190+
with (
191+
patch(
192+
"subprocess.Popen", side_effect=subprocess.SubprocessError("Test error")
193+
),
194+
pytest.raises(subprocess.SubprocessError),
192195
):
193-
with pytest.raises(subprocess.SubprocessError):
194-
self.machine._get_cmdline_unix_ps(1234)
196+
self.machine._get_cmdline_unix_ps(1234)
195197

196198
@pytest.mark.parametrize(
197199
"proc_exists,proc_content,expected_output",
@@ -263,18 +265,28 @@ def test_get_cmdline_platform_detection(
263265

264266
def test_get_cmdline_windows_exception_fallback(self) -> None:
265267
"""Test _get_cmdline falls back to sys.argv on Windows exception."""
266-
with patch("instana.fsm.is_windows", return_value=True), patch.object(
267-
self.machine, "_get_cmdline_windows", side_effect=Exception("Test error")
268-
), patch("instana.fsm.logger.debug") as mock_logger:
268+
with (
269+
patch("instana.fsm.is_windows", return_value=True),
270+
patch.object(
271+
self.machine,
272+
"_get_cmdline_windows",
273+
side_effect=Exception("Test error"),
274+
),
275+
patch("instana.fsm.logger.debug") as mock_logger,
276+
):
269277
result = self.machine._get_cmdline(1234)
270278
assert result == sys.argv
271279
mock_logger.assert_called_once()
272280

273281
def test_get_cmdline_unix_exception_fallback(self) -> None:
274282
"""Test _get_cmdline falls back to sys.argv on Unix exception."""
275-
with patch("instana.fsm.is_windows", return_value=False), patch.object(
276-
self.machine, "_get_cmdline_unix", side_effect=Exception("Test error")
277-
), patch("instana.fsm.logger.debug") as mock_logger:
283+
with (
284+
patch("instana.fsm.is_windows", return_value=False),
285+
patch.object(
286+
self.machine, "_get_cmdline_unix", side_effect=Exception("Test error")
287+
),
288+
patch("instana.fsm.logger.debug") as mock_logger,
289+
):
278290
result = self.machine._get_cmdline(1234)
279291
assert result == sys.argv
280292
mock_logger.assert_called_once()
@@ -298,18 +310,26 @@ def test_get_cmdline_unix_exception_fallback(self) -> None:
298310
)
299311
def test_get_cmdline_various_exceptions(self, exception_type: type) -> None:
300312
"""Test _get_cmdline handles various exception types gracefully."""
301-
with patch("instana.fsm.is_windows", return_value=False), patch.object(
302-
self.machine, "_get_cmdline_unix", side_effect=exception_type("Test error")
313+
with (
314+
patch("instana.fsm.is_windows", return_value=False),
315+
patch.object(
316+
self.machine,
317+
"_get_cmdline_unix",
318+
side_effect=exception_type("Test error"),
319+
),
303320
):
304321
result = self.machine._get_cmdline(1234)
305322
assert result == sys.argv
306323

307324
def test_get_cmdline_with_actual_pid(self) -> None:
308325
"""Test _get_cmdline with actual process ID."""
309326
current_pid = os.getpid()
310-
with patch("instana.fsm.is_windows", return_value=False), patch.object(
311-
self.machine, "_get_cmdline_unix", return_value=["test_cmd"]
312-
) as mock_method:
327+
with (
328+
patch("instana.fsm.is_windows", return_value=False),
329+
patch.object(
330+
self.machine, "_get_cmdline_unix", return_value=["test_cmd"]
331+
) as mock_method,
332+
):
313333
result = self.machine._get_cmdline(current_pid)
314334
assert result == ["test_cmd"]
315335
mock_method.assert_called_once_with(current_pid)

0 commit comments

Comments
 (0)