Skip to content

Commit 348b145

Browse files
committed
style: fix issues reported by ruff check
Signed-off-by: Kiki L Hakiem <[email protected]>
1 parent 286765f commit 348b145

File tree

8 files changed

+34
-44
lines changed

8 files changed

+34
-44
lines changed

providers/openfeature-provider-unleash/src/openfeature/contrib/provider/unleash/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
from typing import Any, Callable, List, Mapping, Optional, Sequence, Union
1+
from collections.abc import Mapping, Sequence
2+
from typing import Any, Callable, Optional, Union
23

34
from UnleashClient import UnleashClient
45
from UnleashClient.events import BaseEvent, UnleashReadyEvent
6+
57
from openfeature.evaluation_context import EvaluationContext
68
from openfeature.event import ProviderEvent
79
from openfeature.exception import ErrorCode, GeneralError
@@ -39,7 +41,7 @@ def __init__(
3941
self.client: Optional[UnleashClient] = None
4042
self._status = ProviderStatus.NOT_READY
4143
self._last_context: Optional[EvaluationContext] = None
42-
self._event_handlers: dict[ProviderEvent, List[Callable]] = {
44+
self._event_handlers: dict[ProviderEvent, list[Callable]] = {
4345
ProviderEvent.PROVIDER_READY: [],
4446
ProviderEvent.PROVIDER_ERROR: [],
4547
ProviderEvent.PROVIDER_CONFIGURATION_CHANGED: [],
@@ -85,7 +87,7 @@ def get_metadata(self) -> Metadata:
8587
"""Get provider metadata."""
8688
return Metadata(name="Unleash Provider")
8789

88-
def get_provider_hooks(self) -> List[Hook]:
90+
def get_provider_hooks(self) -> list[Hook]:
8991
"""Get provider hooks."""
9092
return []
9193

providers/openfeature-provider-unleash/src/openfeature/contrib/provider/unleash/events.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
"""Events functionality for Unleash provider."""
22

3-
from typing import Any, Callable, List, Protocol
3+
from contextlib import suppress
4+
from typing import Any, Callable, Protocol
45

56
from UnleashClient.events import BaseEvent, UnleashFetchedEvent, UnleashReadyEvent
7+
68
from openfeature.event import ProviderEvent
79
from openfeature.provider import Metadata
810

@@ -11,7 +13,7 @@ class UnleashProvider(Protocol):
1113
"""Protocol defining the interface expected from UnleashProvider for events."""
1214

1315
@property
14-
def _event_handlers(self) -> dict[ProviderEvent, List[Callable]]:
16+
def _event_handlers(self) -> dict[ProviderEvent, list[Callable]]:
1517
"""Event handlers dictionary."""
1618
...
1719

@@ -67,11 +69,8 @@ def emit_event(self, event_type: ProviderEvent, **kwargs: Any) -> None:
6769
**kwargs,
6870
}
6971
for handler in self._provider._event_handlers[event_type]:
70-
try:
72+
with suppress(Exception):
7173
handler(event_details)
72-
except Exception:
73-
# Ignore handler errors to prevent breaking other handlers
74-
pass
7574

7675
def handle_unleash_event(self, event: BaseEvent) -> None:
7776
"""Handle UnleashClient events and translate them to OpenFeature events.

providers/openfeature-provider-unleash/src/openfeature/contrib/provider/unleash/flag_evaluation.py

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"""Flag evaluation functionality for Unleash provider."""
22

3+
import json
34
from typing import Any, Callable, Optional, Protocol
45

6+
import requests
57
from UnleashClient import UnleashClient
8+
69
from openfeature.evaluation_context import EvaluationContext
710
from openfeature.exception import (
811
FlagNotFoundError,
@@ -11,7 +14,6 @@
1114
TypeMismatchError,
1215
)
1316
from openfeature.flag_evaluation import FlagResolutionDetails, Reason
14-
import requests
1517

1618

1719
class UnleashProvider(Protocol):
@@ -76,13 +78,12 @@ def resolve_boolean_details(
7678
)
7779
except requests.exceptions.HTTPError as e:
7880
if e.response and e.response.status_code == 404:
79-
raise FlagNotFoundError(f"Flag not found: {flag_key}")
80-
raise GeneralError(f"HTTP error: {e}")
81+
raise FlagNotFoundError(f"Flag not found: {flag_key}") from e
82+
raise GeneralError(f"HTTP error: {e}") from e
8183
except (FlagNotFoundError, TypeMismatchError, ParseError, GeneralError):
82-
# Re-raise specific OpenFeature exceptions
8384
raise
8485
except Exception as e:
85-
raise GeneralError(f"Unexpected error: {e}")
86+
raise GeneralError(f"Unexpected error: {e}") from e
8687

8788
def resolve_string_details(
8889
self,
@@ -186,11 +187,9 @@ def _resolve_variant_flag(
186187
raise GeneralError("Provider not initialized. Call initialize() first.")
187188

188189
try:
189-
# Use get_variant to get the variant payload
190190
context = self._provider._build_unleash_context(evaluation_context)
191191
variant = self._provider.client.get_variant(flag_key, context=context)
192192

193-
# Check if the feature is enabled and has a payload
194193
if variant.get("enabled", False) and "payload" in variant:
195194
try:
196195
payload_value = variant["payload"].get("value", default_value)
@@ -209,10 +208,8 @@ def _resolve_variant_flag(
209208
},
210209
)
211210
except (ValueError, TypeError) as e:
212-
# If payload value can't be converted, raise TypeMismatchError
213-
raise TypeMismatchError(str(e))
211+
raise TypeMismatchError(str(e)) from e
214212
except ParseError:
215-
# Re-raise ParseError directly
216213
raise
217214
else:
218215
return FlagResolutionDetails(
@@ -229,13 +226,12 @@ def _resolve_variant_flag(
229226
)
230227
except requests.exceptions.HTTPError as e:
231228
if e.response and e.response.status_code == 404:
232-
raise FlagNotFoundError(f"Flag not found: {flag_key}")
233-
raise GeneralError(f"HTTP error: {e}")
229+
raise FlagNotFoundError(f"Flag not found: {flag_key}") from e
230+
raise GeneralError(f"HTTP error: {e}") from e
234231
except (FlagNotFoundError, TypeMismatchError, ParseError, GeneralError):
235-
# Re-raise specific OpenFeature exceptions
236232
raise
237233
except Exception as e:
238-
raise GeneralError(f"Unexpected error: {e}")
234+
raise GeneralError(f"Unexpected error: {e}") from e
239235

240236
def _parse_json(self, value: Any) -> Any:
241237
"""Parse JSON value for object flags.
@@ -249,11 +245,9 @@ def _parse_json(self, value: Any) -> Any:
249245
Raises:
250246
ParseError: If JSON parsing fails
251247
"""
252-
import json
253-
254248
if isinstance(value, str):
255249
try:
256250
return json.loads(value)
257251
except json.JSONDecodeError as e:
258-
raise ParseError(f"Invalid JSON: {e}")
252+
raise ParseError(f"Invalid JSON: {e}") from e
259253
return value

providers/openfeature-provider-unleash/src/openfeature/contrib/provider/unleash/tracking.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
"""Tracking functionality for Unleash provider."""
22

3-
from typing import Any, Optional, Protocol
43
import uuid
4+
from typing import Any, Optional, Protocol
55

66
from UnleashClient import UnleashClient
77
from UnleashClient.events import UnleashEvent, UnleashEventType
8+
89
from openfeature.evaluation_context import EvaluationContext
910

1011

providers/openfeature-provider-unleash/tests/test_events.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
11
"""Tests for events functionality."""
22

3-
from unittest.mock import Mock, patch
43
import uuid
4+
from unittest.mock import Mock, patch
55

6+
import pytest
67
from UnleashClient.events import (
78
UnleashEventType,
89
UnleashFetchedEvent,
910
UnleashReadyEvent,
1011
)
12+
1113
from openfeature.contrib.provider.unleash import UnleashProvider
1214
from openfeature.event import ProviderEvent
1315
from openfeature.exception import GeneralError
1416
from openfeature.provider import ProviderStatus
15-
import pytest
1617

1718

1819
def test_events():
@@ -71,8 +72,6 @@ def on_config_changed(event_details):
7172
provider.remove_handler(ProviderEvent.PROVIDER_READY, on_ready)
7273
provider.shutdown() # Should not trigger ready event again
7374

74-
provider.shutdown()
75-
7675

7776
def test_unleash_event_callback():
7877
"""Test that UnleashProvider handles UnleashClient events correctly."""

providers/openfeature-provider-unleash/tests/test_flag_evaluation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from unittest.mock import Mock, patch
44

5+
import pytest
6+
import requests
7+
58
from openfeature.contrib.provider.unleash import UnleashProvider
69
from openfeature.evaluation_context import EvaluationContext
710
from openfeature.exception import (
@@ -11,8 +14,6 @@
1114
TypeMismatchError,
1215
)
1316
from openfeature.flag_evaluation import Reason
14-
import pytest
15-
import requests
1617

1718

1819
def test_resolve_boolean_details():
@@ -128,7 +129,6 @@ def test_with_evaluation_context():
128129
flag = provider.resolve_boolean_details("test_flag", False, context)
129130
assert flag.value is True
130131

131-
# Verify that context was passed to UnleashClient
132132
mock_client.is_enabled.assert_called_with(
133133
"test_flag",
134134
context={"userId": "user123", "email": "[email protected]", "country": "US"},

providers/openfeature-provider-unleash/tests/test_integration.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
11
"""Integration tests for Unleash provider using testcontainers."""
22

3-
from datetime import datetime, timezone
43
import time
4+
from datetime import datetime, timezone
55

6-
from openfeature import api
7-
from openfeature.contrib.provider.unleash import UnleashProvider
8-
from openfeature.evaluation_context import EvaluationContext
96
import psycopg2
107
import pytest
118
import requests
129
from testcontainers.core.container import DockerContainer
1310
from testcontainers.postgres import PostgresContainer
1411

12+
from openfeature import api
13+
from openfeature.contrib.provider.unleash import UnleashProvider
14+
from openfeature.evaluation_context import EvaluationContext
15+
1516
# Configuration for the running Unleash instance (will be set by fixtures)
1617
UNLEASH_URL = None
1718
API_TOKEN = "default:development.unleash-insecure-api-token"
@@ -288,7 +289,6 @@ def unleash_container(postgres_container):
288289

289290
while time.time() - start_time < max_wait_time:
290291
try:
291-
# Get the exposed port
292292
try:
293293
exposed_port = container.get_exposed_port(4242)
294294
unleash_url = f"http://localhost:{exposed_port}"
@@ -298,7 +298,6 @@ def unleash_container(postgres_container):
298298
time.sleep(2)
299299
continue
300300

301-
# Try to connect to health endpoint
302301
response = requests.get(f"{unleash_url}/health", timeout=5)
303302
if response.status_code == 200:
304303
print("Unleash container is healthy!")
@@ -341,14 +340,12 @@ def unleash_provider(setup_test_flags):
341340
)
342341
provider.initialize()
343342
yield provider
344-
# Clean up the provider to avoid multiple UnleashClient instances
345343
provider.shutdown()
346344

347345

348346
@pytest.fixture(scope="session")
349347
def client(unleash_provider):
350348
"""Create an OpenFeature client with the Unleash provider."""
351-
# Set the provider globally
352349
api.set_provider(unleash_provider)
353350
return api.get_client()
354351

providers/openfeature-provider-unleash/tests/test_tracking.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,11 @@ def test_track_basic():
2222
)
2323
provider.initialize()
2424

25-
# Set the event callback
2625
provider._unleash_event_callback = mock_event_callback
2726

2827
# Track a basic event
2928
provider.track("user_action")
3029

31-
# Verify the tracking event was created and passed to callback
3230
assert mock_event_callback.call_count == 1
3331
tracking_event = mock_event_callback.call_args[0][0]
3432
assert tracking_event.feature_name == "user_action"

0 commit comments

Comments
 (0)