Skip to content

Commit 09a331f

Browse files
committed
chore: ruff formatting
1 parent d92aa07 commit 09a331f

5 files changed

Lines changed: 95 additions & 92 deletions

File tree

newrelic/hooks/external_pyzeebe.py

Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -26,54 +26,56 @@
2626

2727
CLIENT_ATTRIBUTES_WARNING_LOG_MSG = "Exception occurred in PyZeebe instrumentation: Failed to add client attributes."
2828

29+
2930
# Adds client method params as txn or span attributes
3031
def _add_client_input_attributes(method_name, txn, args, kwargs):
3132
try:
3233
if method_name in ("run_process", "run_process_with_result"):
3334
bpmn_id = kwargs.get("bpmn_process_id", args[0] if args else None)
3435
if bpmn_id:
3536
txn._add_agent_attribute("zeebe.client.bpmnProcessId", bpmn_id)
36-
#add_attr("zeebe.client.bpmnProcessId", bpmn_id)
37+
# add_attr("zeebe.client.bpmnProcessId", bpmn_id)
3738
elif method_name == "publish_message":
3839
msg_name = kwargs.get("name", args[0] if args else None)
3940
if msg_name:
4041
txn._add_agent_attribute("zeebe.client.messageName", msg_name)
41-
#add_attr("zeebe.client.messageName", msg_name)
42+
# add_attr("zeebe.client.messageName", msg_name)
4243
correlation_key = kwargs.get("correlation_key", args[1] if args and len(args) > 1 else None)
4344
if correlation_key:
4445
txn._add_agent_attribute("zeebe.client.correlationKey", correlation_key)
45-
#add_attr("zeebe.client.correlationKey", correlation_key)
46+
# add_attr("zeebe.client.correlationKey", correlation_key)
4647
message_id = kwargs.get("message_id")
4748
if message_id and len(args) > 4:
4849
message_id = args[4]
4950
if message_id:
5051
txn._add_agent_attribute("zeebe.client.messageId", message_id)
51-
#add_attr("zeebe.client.messageId", message_id)
52+
# add_attr("zeebe.client.messageId", message_id)
5253
elif method_name == "deploy_resource":
5354
resources = list(args)
5455
if len(resources) == 1 and isinstance(resources[0], (list, tuple)):
5556
resources = list(resources[0])
5657
if resources:
5758
txn._add_agent_attribute("zeebe.client.resourceCount", len(resources))
58-
#add_attr("zeebe.client.resourceCount", len(resources))
59+
# add_attr("zeebe.client.resourceCount", len(resources))
5960
if len(resources) == 1:
6061
try:
6162
txn._add_agent_attribute("zeebe.client.resourceFile", str(resources[0]))
62-
#add_attr("zeebe.client.resourceFile", str(resources[0]))
63+
# add_attr("zeebe.client.resourceFile", str(resources[0]))
6364
except Exception:
6465
txn._add_agent_attribute("zeebe.client.resourceFile", str(resources[0]))
65-
#add_attr("zeebe.client.resourceFile", repr(resources[0]))
66+
# add_attr("zeebe.client.resourceFile", repr(resources[0]))
6667
except Exception:
6768
_logger.warning(CLIENT_ATTRIBUTES_WARNING_LOG_MSG, exc_info=True)
6869

70+
6971
# Async wrapper that instruments router/worker annotations`
7072
async def _nr_wrapper_execute_one_job(wrapped, instance, args, kwargs):
7173
job = args[0] if args else kwargs.get("job")
7274
process_id = getattr(job, "bpmn_process_id", None) or "UnknownProcess"
7375
task_type = getattr(job, "type", None) or "UnknownType"
7476
txn_name = f"{process_id}/{task_type}"
7577

76-
with BackgroundTask(application_instance(), txn_name, group="ZeebeTask"):
78+
with BackgroundTask(application_instance(), txn_name, group="ZeebeTask"):
7779
if job is not None:
7880
if hasattr(job, "key"):
7981
add_custom_attribute("zeebe.job.key", job.key)
@@ -89,6 +91,7 @@ async def _nr_wrapper_execute_one_job(wrapped, instance, args, kwargs):
8991
result = await wrapped(*args, **kwargs)
9092
return result
9193

94+
9295
# Async wrapper that instruments a ZeebeClient method.
9396
def _nr_client_wrapper(method_name):
9497
async def wrapper(wrapped, instance, args, kwargs):
@@ -108,34 +111,23 @@ async def wrapper(wrapped, instance, args, kwargs):
108111
result = await wrapped(*args, **kwargs)
109112
finally:
110113
created_txn.__exit__(None, None, None)
111-
114+
112115
return result
113116

114117
return wrapper
115118

119+
116120
# Instrument JobExecutor.execute_one_job to create a background transaction per job (invoked from @router.task or @worker.task annotations)
117121
def instrument_pyzeebe_worker_job_executor(module):
118122
if hasattr(module, "JobExecutor"):
119-
wrap_function_wrapper(
120-
module,
121-
"JobExecutor.execute_one_job",
122-
_nr_wrapper_execute_one_job
123-
)
123+
wrap_function_wrapper(module, "JobExecutor.execute_one_job", _nr_wrapper_execute_one_job)
124+
124125

125126
# Instrument ZeebeClient methods to trace client calls.
126127
def instrument_pyzeebe_client_client(module):
127-
target_methods = (
128-
"run_process",
129-
"run_process_with_result",
130-
"deploy_resource",
131-
"publish_message",
132-
)
128+
target_methods = ("run_process", "run_process_with_result", "deploy_resource", "publish_message")
133129

134130
for method_name in target_methods:
135131
if hasattr(module, "ZeebeClient"):
136132
if hasattr(module.ZeebeClient, method_name):
137-
wrap_function_wrapper(
138-
module,
139-
f"ZeebeClient.{method_name}",
140-
_nr_client_wrapper(method_name)
141-
)
133+
wrap_function_wrapper(module, f"ZeebeClient.{method_name}", _nr_client_wrapper(method_name))

tests/external_pyzeebe/_mocks.py

Lines changed: 44 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,74 +2,86 @@
22
from pyzeebe.grpc_internals.zeebe_adapter import ZeebeAdapter
33

44
# Dummy response objects with only required fields
5-
DummyCreateProcessInstanceResponse = SimpleNamespace(
6-
process_instance_key=12345
7-
)
5+
DummyCreateProcessInstanceResponse = SimpleNamespace(process_instance_key=12345)
86

97
DummyCreateProcessInstanceWithResultResponse = SimpleNamespace(
10-
process_instance_key=45678,
11-
variables={"result": "success"}
8+
process_instance_key=45678, variables={"result": "success"}
129
)
1310

14-
DummyDeployResourceResponse = SimpleNamespace(
15-
key=67890,
16-
deployments=[],
17-
tenant_id=None
18-
)
11+
DummyDeployResourceResponse = SimpleNamespace(key=67890, deployments=[], tenant_id=None)
12+
13+
DummyPublishMessageResponse = SimpleNamespace(key=99999, tenant_id=None)
1914

20-
DummyPublishMessageResponse = SimpleNamespace(
21-
key=99999,
22-
tenant_id=None
23-
)
2415

2516
# Dummy RPC stub coroutines
26-
async def dummy_create_process_instance(self, bpmn_process_id: str, variables: dict = None, version: int = -1, tenant_id: str = None):
17+
async def dummy_create_process_instance(
18+
self, bpmn_process_id: str, variables: dict = None, version: int = -1, tenant_id: str = None
19+
):
2720
"""Simulate ZeebeAdapter.create_process_instance"""
2821
return DummyCreateProcessInstanceResponse
2922

30-
async def dummy_create_process_instance_with_result(self, bpmn_process_id: str, variables: dict = None, version: int = -1, timeout: int = 0, variables_to_fetch=None, tenant_id: str = None):
23+
24+
async def dummy_create_process_instance_with_result(
25+
self,
26+
bpmn_process_id: str,
27+
variables: dict = None,
28+
version: int = -1,
29+
timeout: int = 0,
30+
variables_to_fetch=None,
31+
tenant_id: str = None,
32+
):
3133
"""Simulate ZeebeAdapter.create_process_instance_with_result"""
3234
return DummyCreateProcessInstanceWithResultResponse
3335

36+
3437
async def dummy_deploy_resource(*resource_file_path: str, tenant_id: str = None):
3538
"""Simulate ZeebeAdapter.deploy_resource"""
3639
# Create dummy deployment metadata for each provided resource path
3740
deployments = []
3841
for path in resource_file_path:
39-
deployments.append(SimpleNamespace(
40-
resource_name=str(path),
41-
bpmn_process_id="dummy_process",
42-
process_definition_key=123,
43-
version=1,
44-
tenant_id=tenant_id if tenant_id is not None else None
45-
))
42+
deployments.append(
43+
SimpleNamespace(
44+
resource_name=str(path),
45+
bpmn_process_id="dummy_process",
46+
process_definition_key=123,
47+
version=1,
48+
tenant_id=tenant_id if tenant_id is not None else None,
49+
)
50+
)
4651
# Create a dummy response with a list of deployments
4752
return SimpleNamespace(
48-
deployment_key=333333,
49-
deployments=deployments,
50-
tenant_id=tenant_id if tenant_id is not None else None
53+
deployment_key=333333, deployments=deployments, tenant_id=tenant_id if tenant_id is not None else None
5154
)
5255

53-
async def dummy_publish_message(self, name: str, correlation_key: str, variables: dict = None, time_to_live_in_milliseconds: int = 60000, message_id: str = None, tenant_id: str = None):
56+
57+
async def dummy_publish_message(
58+
self,
59+
name: str,
60+
correlation_key: str,
61+
variables: dict = None,
62+
time_to_live_in_milliseconds: int = 60000,
63+
message_id: str = None,
64+
tenant_id: str = None,
65+
):
5466
"""Simulate ZeebeAdapter.publish_message"""
5567
# Return the dummy response (contains message key)
56-
return SimpleNamespace(
57-
key=999999,
58-
tenant_id=tenant_id if tenant_id is not None else None
59-
)
68+
return SimpleNamespace(key=999999, tenant_id=tenant_id if tenant_id is not None else None)
69+
6070

6171
async def dummy_complete_job(self, job_key: int, variables: dict):
6272
"""Simulate JobExecutor.complete_job"""
6373
setattr(self, "_last_complete", {"job_key": job_key, "variables": variables})
6474
return None
6575

76+
6677
class DummyZeebeAdapter(ZeebeAdapter):
6778
"""Simulate a ZeebeAdapter so JobExecutor can be instatiated w/o gRPC channel"""
79+
6880
def __init__(self):
6981
self.completed_job_key = None
7082
self.completed_job_vars = None
83+
7184
async def complete_job(self, job_key: int, variables: dict):
7285
self.completed_job_key = job_key
7386
self.completed_job_vars = variables
7487
return None
75-

tests/external_pyzeebe/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@
2828

2929
collector_agent_registration = collector_agent_registration_fixture(
3030
app_name="Python Agent Test (external_pyzeebe)", default_settings=_default_settings
31-
)
31+
)

tests/external_pyzeebe/test_client.py

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,12 @@
1616
import asyncio
1717
from pyzeebe import ZeebeClient, create_insecure_channel
1818
from pyzeebe.grpc_internals.zeebe_adapter import ZeebeAdapter
19-
from _mocks import dummy_create_process_instance, dummy_create_process_instance_with_result, dummy_deploy_resource, dummy_publish_message
19+
from _mocks import (
20+
dummy_create_process_instance,
21+
dummy_create_process_instance_with_result,
22+
dummy_deploy_resource,
23+
dummy_publish_message,
24+
)
2025

2126
from newrelic.api.background_task import background_task
2227
from testing_support.validators.validate_transaction_metrics import validate_transaction_metrics
@@ -25,12 +30,9 @@
2530

2631
client = ZeebeClient(create_insecure_channel())
2732

33+
2834
@validate_transaction_metrics(
29-
"test_zeebe_client:run_process",
30-
rollup_metrics=[
31-
("ZeebeClient/run_process", 1)
32-
],
33-
background_task=True
35+
"test_zeebe_client:run_process", rollup_metrics=[("ZeebeClient/run_process", 1)], background_task=True
3436
)
3537
@validate_attributes("agent", ["zeebe.client.bpmnProcessId"])
3638
def test_run_process(monkeypatch):
@@ -40,15 +42,14 @@ def test_run_process(monkeypatch):
4042
def _test():
4143
response = asyncio.run(client.run_process("test_process"))
4244
assert response.process_instance_key == 12345
45+
4346
_test()
4447

4548

4649
@validate_transaction_metrics(
4750
"test_zeebe_client:run_process_with_result",
48-
rollup_metrics=[
49-
("ZeebeClient/run_process_with_result", 1)
50-
],
51-
background_task=True
51+
rollup_metrics=[("ZeebeClient/run_process_with_result", 1)],
52+
background_task=True,
5253
)
5354
@validate_attributes("agent", ["zeebe.client.bpmnProcessId"])
5455
def test_run_process_with_result(monkeypatch):
@@ -59,15 +60,12 @@ def _test():
5960
result = asyncio.run(client.run_process_with_result("test_process"))
6061
assert result.process_instance_key == 45678
6162
assert result.variables == {"result": "success"}
63+
6264
_test()
6365

6466

6567
@validate_transaction_metrics(
66-
"test_zeebe_client:deploy_resource",
67-
rollup_metrics=[
68-
("ZeebeClient/deploy_resource", 1)
69-
],
70-
background_task=True
68+
"test_zeebe_client:deploy_resource", rollup_metrics=[("ZeebeClient/deploy_resource", 1)], background_task=True
7169
)
7270
@validate_attributes("agent", ["zeebe.client.resourceCount", "zeebe.client.resourceFile"])
7371
def test_deploy_resource(monkeypatch):
@@ -77,15 +75,12 @@ def test_deploy_resource(monkeypatch):
7775
def _test():
7876
result = asyncio.run(client.deploy_resource("test.bpmn"))
7977
assert result.deployment_key == 333333
78+
8079
_test()
8180

8281

8382
@validate_transaction_metrics(
84-
"test_zeebe_client:publish_message",
85-
rollup_metrics=[
86-
("ZeebeClient/publish_message", 1)
87-
],
88-
background_task=True
83+
"test_zeebe_client:publish_message", rollup_metrics=[("ZeebeClient/publish_message", 1)], background_task=True
8984
)
9085
@validate_attributes("agent", ["zeebe.client.messageName", "zeebe.client.correlationKey", "zeebe.client.messageId"])
9186
def test_publish_message(monkeypatch):
@@ -95,4 +90,5 @@ def test_publish_message(monkeypatch):
9590
def _test():
9691
result = asyncio.run(client.publish_message(name="test_message", correlation_key="999999", message_id="abc123"))
9792
assert result.key == 999999
98-
_test()
93+
94+
_test()

tests/external_pyzeebe/test_job_executor.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@
1212
# Set up a router with a dummy async task
1313
router = ZeebeTaskRouter()
1414

15+
1516
@router.task(task_type="testTask")
1617
async def dummy_task(x: int) -> dict:
1718
"""
18-
Simulate a task function that reads input variable 'x'
19-
and adds 1.
19+
Simulate a task function that reads input variable x
2020
"""
21-
return {"result": x }
21+
return {"result": x}
22+
2223

2324
# @validate_transaction_metrics(
2425
# "ZeebeTask/test_process/testTask",
@@ -27,20 +28,22 @@ async def dummy_task(x: int) -> dict:
2728
# ],
2829
# background_task=True
2930
# )
30-
@validate_custom_parameters(required_params=[
31-
("zeebe.job.key", 123),
32-
("zeebe.job.type", "testTask"),
33-
("zeebe.job.bpmnProcessId", "test_process"),
34-
("zeebe.job.processInstanceKey", 456),
35-
("zeebe.job.elementId", "service_task_123")
36-
])
31+
@validate_custom_parameters(
32+
required_params=[
33+
("zeebe.job.key", 123),
34+
("zeebe.job.type", "testTask"),
35+
("zeebe.job.bpmnProcessId", "test_process"),
36+
("zeebe.job.processInstanceKey", 456),
37+
("zeebe.job.elementId", "service_task_123"),
38+
]
39+
)
3740
def test_execute_one_job():
3841
dummy_adapter = DummyZeebeAdapter()
3942

4043
# Build a Job with fixed values
4144
job = Job(
4245
key=123,
43-
type="testTask", # must match router.task(task_type="testTask")
46+
type="testTask", # must match router.task(task_type="testTask")
4447
bpmn_process_id="test_process",
4548
process_instance_key=456,
4649
process_definition_version=1,
@@ -52,7 +55,7 @@ def test_execute_one_job():
5255
retries=3,
5356
deadline=0,
5457
variables={"x": 33},
55-
status=JobStatus.Running
58+
status=JobStatus.Running,
5659
)
5760

5861
# JobExecutor constructor params init
@@ -67,4 +70,4 @@ def test_execute_one_job():
6770
job_controller = JobController(job, dummy_adapter)
6871

6972
asyncio.run(job_executor.execute_one_job(job, job_controller))
70-
assert job.variables["x"] == 33
73+
assert job.variables["x"] == 33

0 commit comments

Comments
 (0)