smoothapi-py 1.1.0__tar.gz → 1.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smoothapi-py
3
- Version: 1.1.0
4
- Summary: API resilience library — exponential backoff and circuit breaker
3
+ Version: 1.2.0
4
+ Summary: API protection library — exponential backoff and circuit breaker
5
5
  License: MIT
6
6
  License-File: LICENSE
7
7
  Keywords: backoff,circuit-breaker,http,resilience,retry
@@ -15,7 +15,7 @@ Description-Content-Type: text/markdown
15
15
 
16
16
  # smoothapi-py
17
17
 
18
- API resilience library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
18
+ API protection library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
19
19
 
20
20
  Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
21
21
 
@@ -29,24 +29,24 @@ pip install smoothapi-py
29
29
 
30
30
  - **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
31
31
  - **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
32
- - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
32
+ - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on retryable codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
33
33
  - **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
34
- - **Request Deduplication:** Automatically coalesce concurrent identical requests into a single network call (async only).
34
+ - **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
35
35
 
36
36
  ## Usage
37
37
 
38
38
  ### Basic Usage (Defaults)
39
39
 
40
- If you don't need custom configurations, you can instantiate the decorator with its defaults by passing an empty config object.
40
+ If you don't need custom configurations, you can use the decorator with its defaults by passing an empty config object.
41
41
 
42
42
  ```python
43
43
  import requests
44
- from smooth_api import resilient_api, ResilientConfig
44
+ from smooth_api import smooth_api, SmoothConfig
45
45
 
46
46
  # Create it with default settings
47
- config = ResilientConfig()
47
+ config = SmoothConfig()
48
48
 
49
- @resilient_api(config)
49
+ @smooth_api(config)
50
50
  def get_user_data(user_id: str):
51
51
  res = requests.get(f"https://api.example.com/users/{user_id}")
52
52
  res.raise_for_status() # Always raise so the decorator knows it failed!
@@ -72,11 +72,11 @@ except Exception as e:
72
72
  You can override any of the defaults to suit your application's needs, such as adding a fallback object.
73
73
 
74
74
  ```python
75
- from smooth_api import resilient_api, ResilientConfig
75
+ from smooth_api import smooth_api, SmoothConfig
76
76
  from smooth_api.config import BackoffConfig, CircuitBreakerConfig
77
77
  import requests
78
78
 
79
- config = ResilientConfig(
79
+ config = SmoothConfig(
80
80
  backoff=BackoffConfig(
81
81
  base_delay=0.1, # seconds to wait before first retry
82
82
  max_delay=30.0, # cap on exponential growth
@@ -92,7 +92,7 @@ config = ResilientConfig(
92
92
  retry_on=[429, 500, 502, 503, 504]
93
93
  )
94
94
 
95
- @resilient_api(config)
95
+ @smooth_api(config)
96
96
  def get_user_data(user_id: str):
97
97
  res = requests.get(f"https://api.example.com/users/{user_id}")
98
98
  res.raise_for_status()
@@ -107,12 +107,12 @@ data = get_user_data("456", fallback={"status": "override"})
107
107
  By default, non-retryable client errors (e.g. `400`, `401`, `403`, `404`, `405`) bubble up and raise exceptions immediately. If you want to intercept these client errors:
108
108
 
109
109
  ```python
110
- from smooth_api import resilient_api, ResilientConfig
110
+ from smooth_api import smooth_api, SmoothConfig
111
111
 
112
112
  def my_callback(status: int, message: str):
113
113
  print(f"Error hook: Received client error {status}")
114
114
 
115
- config = ResilientConfig(
115
+ config = SmoothConfig(
116
116
  fallback_on_non_retryable=True,
117
117
  # Optional: Custom error hook function
118
118
  on_non_retryable_error=my_callback,
@@ -123,7 +123,7 @@ config = ResilientConfig(
123
123
 
124
124
  * **Default Warning**: If `fallback_on_non_retryable` is `True` and no custom `on_non_retryable_error` is defined, it will write a warning message to `sys.stderr`.
125
125
  * **Graceful Return**: If no `fallback` is configured, it returns a mock `Response` wrapper with `status_code`, `.json()` returning `{"error": True, "status": status, "message": "..."}`, and `.ok` returning `False`. Code downstream can check `res.status_code` or call `res.json()` without raising exceptions.
126
- ```
126
+
127
127
 
128
128
  ### Async Support
129
129
 
@@ -132,7 +132,7 @@ The decorator automatically detects if your function is a coroutine and uses `as
132
132
  ```python
133
133
  import httpx
134
134
 
135
- @resilient_api(config)
135
+ @smooth_api(config)
136
136
  async def get_user_data_async(user_id: str):
137
137
  async with httpx.AsyncClient() as client:
138
138
  res = await client.get(f"https://api.example.com/users/{user_id}")
@@ -148,12 +148,12 @@ When multiple identical async requests are made concurrently, SmoothAPI can exec
148
148
 
149
149
  ```python
150
150
  import httpx
151
- from smooth_api import resilient_api, ResilientConfig
151
+ from smooth_api import smooth_api, SmoothConfig
152
152
  from smooth_api.config import DeduplicationConfig
153
153
 
154
- config = ResilientConfig(deduplication=DeduplicationConfig())
154
+ config = SmoothConfig(deduplication=DeduplicationConfig())
155
155
 
156
- @resilient_api(config)
156
+ @smooth_api(config)
157
157
  async def get_user(user_id: int):
158
158
  async with httpx.AsyncClient() as client:
159
159
  res = await client.get(f"https://api.example.com/users/{user_id}")
@@ -178,13 +178,13 @@ def my_key(*args, **kwargs):
178
178
  # Deduplicate by second argument (resource type)
179
179
  return str(args[1]) if len(args) > 1 else str(args[0])
180
180
 
181
- config = ResilientConfig(deduplication=DeduplicationConfig(key_fn=my_key))
181
+ config = SmoothConfig(deduplication=DeduplicationConfig(key_fn=my_key))
182
182
  ```
183
183
 
184
184
  **Opt out of deduplication** for specific calls:
185
185
 
186
186
  ```python
187
- config = ResilientConfig(
187
+ config = SmoothConfig(
188
188
  deduplication=DeduplicationConfig(
189
189
  key_fn=lambda *a, **k: None # Return None to skip dedup
190
190
  )
@@ -1,6 +1,6 @@
1
1
  # smoothapi-py
2
2
 
3
- API resilience library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
3
+ API protection library for Python. It provides a decorator to wrap your HTTP requests with **exponential backoff, full jitter, and a finite-state machine circuit breaker** to protect against cascading failures.
4
4
 
5
5
  Zero dependencies. Fully typed. Supports both sync and async functions out of the box. Automatically integrates with `requests` and `httpx` if installed.
6
6
 
@@ -14,24 +14,24 @@ pip install smoothapi-py
14
14
 
15
15
  - **Exponential Backoff with Full Jitter:** Prevents the "thundering herd" problem by randomizing retry delays.
16
16
  - **Circuit Breaker (FSM):** Isolated state machine (`CLOSED` → `OPEN` → `HALF_OPEN`) per decorated function. Thread-safe execution.
17
- - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on transient codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
17
+ - **Smart Retries:** Automatically detects HTTP status codes from `requests` and `httpx` exceptions. Retries on retryable codes (429, 500, 502, 503, 504) and re-raises client errors immediately.
18
18
  - **Graceful Fallbacks:** Optionally return cached or default data instantly when the circuit is `OPEN`, bypassing network IO entirely.
19
- - **Request Deduplication:** Automatically coalesce concurrent identical requests into a single network call (async only).
19
+ - **Request Deduplication:** Automatically merges concurrent identical requests into a single network call (async only).
20
20
 
21
21
  ## Usage
22
22
 
23
23
  ### Basic Usage (Defaults)
24
24
 
25
- If you don't need custom configurations, you can instantiate the decorator with its defaults by passing an empty config object.
25
+ If you don't need custom configurations, you can use the decorator with its defaults by passing an empty config object.
26
26
 
27
27
  ```python
28
28
  import requests
29
- from smooth_api import resilient_api, ResilientConfig
29
+ from smooth_api import smooth_api, SmoothConfig
30
30
 
31
31
  # Create it with default settings
32
- config = ResilientConfig()
32
+ config = SmoothConfig()
33
33
 
34
- @resilient_api(config)
34
+ @smooth_api(config)
35
35
  def get_user_data(user_id: str):
36
36
  res = requests.get(f"https://api.example.com/users/{user_id}")
37
37
  res.raise_for_status() # Always raise so the decorator knows it failed!
@@ -57,11 +57,11 @@ except Exception as e:
57
57
  You can override any of the defaults to suit your application's needs, such as adding a fallback object.
58
58
 
59
59
  ```python
60
- from smooth_api import resilient_api, ResilientConfig
60
+ from smooth_api import smooth_api, SmoothConfig
61
61
  from smooth_api.config import BackoffConfig, CircuitBreakerConfig
62
62
  import requests
63
63
 
64
- config = ResilientConfig(
64
+ config = SmoothConfig(
65
65
  backoff=BackoffConfig(
66
66
  base_delay=0.1, # seconds to wait before first retry
67
67
  max_delay=30.0, # cap on exponential growth
@@ -77,7 +77,7 @@ config = ResilientConfig(
77
77
  retry_on=[429, 500, 502, 503, 504]
78
78
  )
79
79
 
80
- @resilient_api(config)
80
+ @smooth_api(config)
81
81
  def get_user_data(user_id: str):
82
82
  res = requests.get(f"https://api.example.com/users/{user_id}")
83
83
  res.raise_for_status()
@@ -92,12 +92,12 @@ data = get_user_data("456", fallback={"status": "override"})
92
92
  By default, non-retryable client errors (e.g. `400`, `401`, `403`, `404`, `405`) bubble up and raise exceptions immediately. If you want to intercept these client errors:
93
93
 
94
94
  ```python
95
- from smooth_api import resilient_api, ResilientConfig
95
+ from smooth_api import smooth_api, SmoothConfig
96
96
 
97
97
  def my_callback(status: int, message: str):
98
98
  print(f"Error hook: Received client error {status}")
99
99
 
100
- config = ResilientConfig(
100
+ config = SmoothConfig(
101
101
  fallback_on_non_retryable=True,
102
102
  # Optional: Custom error hook function
103
103
  on_non_retryable_error=my_callback,
@@ -108,7 +108,7 @@ config = ResilientConfig(
108
108
 
109
109
  * **Default Warning**: If `fallback_on_non_retryable` is `True` and no custom `on_non_retryable_error` is defined, it will write a warning message to `sys.stderr`.
110
110
  * **Graceful Return**: If no `fallback` is configured, it returns a mock `Response` wrapper with `status_code`, `.json()` returning `{"error": True, "status": status, "message": "..."}`, and `.ok` returning `False`. Code downstream can check `res.status_code` or call `res.json()` without raising exceptions.
111
- ```
111
+
112
112
 
113
113
  ### Async Support
114
114
 
@@ -117,7 +117,7 @@ The decorator automatically detects if your function is a coroutine and uses `as
117
117
  ```python
118
118
  import httpx
119
119
 
120
- @resilient_api(config)
120
+ @smooth_api(config)
121
121
  async def get_user_data_async(user_id: str):
122
122
  async with httpx.AsyncClient() as client:
123
123
  res = await client.get(f"https://api.example.com/users/{user_id}")
@@ -133,12 +133,12 @@ When multiple identical async requests are made concurrently, SmoothAPI can exec
133
133
 
134
134
  ```python
135
135
  import httpx
136
- from smooth_api import resilient_api, ResilientConfig
136
+ from smooth_api import smooth_api, SmoothConfig
137
137
  from smooth_api.config import DeduplicationConfig
138
138
 
139
- config = ResilientConfig(deduplication=DeduplicationConfig())
139
+ config = SmoothConfig(deduplication=DeduplicationConfig())
140
140
 
141
- @resilient_api(config)
141
+ @smooth_api(config)
142
142
  async def get_user(user_id: int):
143
143
  async with httpx.AsyncClient() as client:
144
144
  res = await client.get(f"https://api.example.com/users/{user_id}")
@@ -163,13 +163,13 @@ def my_key(*args, **kwargs):
163
163
  # Deduplicate by second argument (resource type)
164
164
  return str(args[1]) if len(args) > 1 else str(args[0])
165
165
 
166
- config = ResilientConfig(deduplication=DeduplicationConfig(key_fn=my_key))
166
+ config = SmoothConfig(deduplication=DeduplicationConfig(key_fn=my_key))
167
167
  ```
168
168
 
169
169
  **Opt out of deduplication** for specific calls:
170
170
 
171
171
  ```python
172
- config = ResilientConfig(
172
+ config = SmoothConfig(
173
173
  deduplication=DeduplicationConfig(
174
174
  key_fn=lambda *a, **k: None # Return None to skip dedup
175
175
  )
@@ -1,24 +1,24 @@
1
- [build-system]
2
- requires = ["hatchling"]
3
- build-backend = "hatchling.build"
4
-
5
- [project]
6
- name = "smoothapi-py"
7
- version = "1.1.0"
8
- description = "API resilience library — exponential backoff and circuit breaker"
9
- readme = "README.md"
10
- requires-python = ">=3.10"
11
- license = { text = "MIT" }
12
- keywords = ["resilience", "circuit-breaker", "retry", "backoff", "http"]
13
- dependencies = []
14
-
15
- [project.optional-dependencies]
16
- dev = [
17
- "pytest>=7.0",
18
- "pytest-asyncio>=0.21",
19
- "requests>=2.28",
20
- "httpx>=0.24",
21
- ]
22
-
23
- [tool.hatch.build.targets.wheel]
24
- packages = ["smooth_api"]
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "smoothapi-py"
7
+ version = "1.2.0"
8
+ description = "API protection library — exponential backoff and circuit breaker"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ keywords = ["resilience", "circuit-breaker", "retry", "backoff", "http"]
13
+ dependencies = []
14
+
15
+ [project.optional-dependencies]
16
+ dev = [
17
+ "pytest>=7.0",
18
+ "pytest-asyncio>=0.21",
19
+ "requests>=2.28",
20
+ "httpx>=0.24",
21
+ ]
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["smooth_api"]
@@ -4,7 +4,7 @@ import asyncio
4
4
  import functools
5
5
  from urllib.parse import urlparse
6
6
 
7
- from .config import ResilientConfig
7
+ from .config import SmoothConfig
8
8
  from .dedup import RequestDeduplicator
9
9
  from .state import CircuitBreakerState
10
10
  from .utils import calculate_backoff, sleep_backoff
@@ -51,7 +51,7 @@ class MockResponse:
51
51
  pass
52
52
 
53
53
 
54
- def resilient_api(config: ResilientConfig):
54
+ def smooth_api(config: SmoothConfig):
55
55
  def decorator(fn):
56
56
  # One breaker per decorated function, shared across all calls to fn.
57
57
  breaker = CircuitBreakerState(config.circuit_breaker)
@@ -192,6 +192,17 @@ def resilient_api(config: ResilientConfig):
192
192
  return decorator
193
193
 
194
194
 
195
- __all__ = ['resilient_api', 'ResilientConfig', 'DeduplicationConfig']
195
+ import warnings
196
+
197
+ def resilient_api(*args, **kwargs):
198
+ warnings.warn("'resilient_api' is deprecated, use 'smooth_api' instead", DeprecationWarning, stacklevel=2)
199
+ return smooth_api(*args, **kwargs)
200
+
201
+ class ResilientConfig(SmoothConfig):
202
+ def __init__(self, *args, **kwargs):
203
+ warnings.warn("'ResilientConfig' is deprecated, use 'SmoothConfig' instead", DeprecationWarning, stacklevel=2)
204
+ super().__init__(*args, **kwargs)
205
+
206
+ __all__ = ['smooth_api', 'SmoothConfig', 'DeduplicationConfig', 'resilient_api', 'ResilientConfig']
196
207
 
197
208
  from .config import DeduplicationConfig # re-export for convenience
@@ -27,7 +27,7 @@ class DeduplicationConfig:
27
27
  """
28
28
  Configuration for request deduplication.
29
29
 
30
- When attached to ``ResilientConfig``, in-flight calls that share the same
30
+ When attached to ``SmoothConfig``, in-flight calls that share the same
31
31
  *key* are coalesced: only the first caller actually runs the function; all
32
32
  others await the same coroutine and receive its result (or exception).
33
33
 
@@ -43,7 +43,7 @@ class DeduplicationConfig:
43
43
 
44
44
 
45
45
  @dataclass
46
- class ResilientConfig:
46
+ class SmoothConfig:
47
47
  backoff: BackoffConfig = field(default_factory=BackoffConfig)
48
48
  circuit_breaker: CircuitBreakerConfig = field(default_factory=CircuitBreakerConfig)
49
49
  # Returned immediately on an OPEN circuit, no network IO.
@@ -1 +1 @@
1
- # pytest package marker
1
+ # pytest package marker
@@ -1,37 +1,37 @@
1
- import asyncio
2
- import pytest
3
- import httpx
4
- from smooth_api import resilient_api, ResilientConfig
5
- from smooth_api.config import BackoffConfig, CircuitBreakerConfig
6
-
7
- BASE = "http://localhost:3001"
8
-
9
- @pytest.fixture(autouse=True)
10
- def reset_counter():
11
- import requests
12
- requests.get(f"{BASE}/reset")
13
- yield
14
- requests.get(f"{BASE}/reset")
15
-
16
- @pytest.mark.asyncio
17
- async def test_async_wrapper_concurrency():
18
- config = ResilientConfig(
19
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
20
- circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
21
- retry_on=[500],
22
- fallback={"tripped": True}
23
- )
24
-
25
- @resilient_api(config)
26
- async def get_data():
27
- request = httpx.Request("GET", f"{BASE}/unstable-data")
28
- response = httpx.Response(500, request=request)
29
- raise httpx.HTTPStatusError("error", request=request, response=response)
30
-
31
- # Trip the circuit with 8 concurrent requests
32
- tasks = [get_data() for _ in range(8)]
33
- await asyncio.gather(*tasks, return_exceptions=True)
34
-
35
- # Now the circuit should be open, so the next request should instantly return fallback
36
- fallback = await get_data()
37
- assert fallback == {"tripped": True}, "Circuit should have tripped under load and returned fallback"
1
+ import asyncio
2
+ import pytest
3
+ import httpx
4
+ from smooth_api import smooth_api, SmoothConfig
5
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
6
+
7
+ BASE = "http://localhost:3001"
8
+
9
+ @pytest.fixture(autouse=True)
10
+ def reset_counter():
11
+ import requests
12
+ requests.get(f"{BASE}/reset")
13
+ yield
14
+ requests.get(f"{BASE}/reset")
15
+
16
+ @pytest.mark.asyncio
17
+ async def test_async_wrapper_concurrency():
18
+ config = SmoothConfig(
19
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
20
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
21
+ retry_on=[500],
22
+ fallback={"tripped": True}
23
+ )
24
+
25
+ @smooth_api(config)
26
+ async def get_data():
27
+ request = httpx.Request("GET", f"{BASE}/unstable-data")
28
+ response = httpx.Response(500, request=request)
29
+ raise httpx.HTTPStatusError("error", request=request, response=response)
30
+
31
+ # Trip the circuit with 8 concurrent requests
32
+ tasks = [get_data() for _ in range(8)]
33
+ await asyncio.gather(*tasks, return_exceptions=True)
34
+
35
+ # Now the circuit should be open, so the next request should instantly return fallback
36
+ fallback = await get_data()
37
+ assert fallback == {"tripped": True}, "Circuit should have tripped under load and returned fallback"
@@ -9,7 +9,7 @@ import asyncio
9
9
  import time
10
10
  import pytest
11
11
 
12
- from smooth_api import resilient_api, ResilientConfig, DeduplicationConfig
12
+ from smooth_api import smooth_api, SmoothConfig, DeduplicationConfig
13
13
  from smooth_api.config import BackoffConfig, CircuitBreakerConfig
14
14
 
15
15
 
@@ -17,9 +17,9 @@ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
17
17
  # Helpers
18
18
  # ---------------------------------------------------------------------------
19
19
 
20
- def _fast_config(**extra) -> ResilientConfig:
20
+ def _fast_config(**extra) -> SmoothConfig:
21
21
  """Minimal config: no real delays, no retries."""
22
- return ResilientConfig(
22
+ return SmoothConfig(
23
23
  backoff=BackoffConfig(base_delay=0, max_delay=0, max_retries=0),
24
24
  circuit_breaker=CircuitBreakerConfig(failure_threshold=100, cooldown_ms=60_000),
25
25
  **extra,
@@ -35,7 +35,7 @@ async def test_deduplication_disabled_by_default():
35
35
  """Without deduplication config each call runs the function independently."""
36
36
  counter = {"calls": 0}
37
37
 
38
- @resilient_api(_fast_config())
38
+ @smooth_api(_fast_config())
39
39
  async def fetch_user(user_id: int):
40
40
  counter["calls"] += 1
41
41
  await asyncio.sleep(0.02) # simulate latency
@@ -53,7 +53,7 @@ async def test_concurrent_identical_calls_deduplicated():
53
53
  """3 concurrent calls with the same arg produce exactly 1 execution."""
54
54
  counter = {"calls": 0}
55
55
 
56
- @resilient_api(_fast_config(deduplication=DeduplicationConfig()))
56
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig()))
57
57
  async def fetch_user(user_id: int):
58
58
  counter["calls"] += 1
59
59
  await asyncio.sleep(0.02)
@@ -71,7 +71,7 @@ async def test_different_args_not_deduplicated():
71
71
  """Calls with different arguments must each execute independently."""
72
72
  counter = {"calls": 0}
73
73
 
74
- @resilient_api(_fast_config(deduplication=DeduplicationConfig()))
74
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig()))
75
75
  async def fetch_user(user_id: int):
76
76
  counter["calls"] += 1
77
77
  await asyncio.sleep(0.02)
@@ -89,7 +89,7 @@ async def test_sequential_calls_not_deduplicated():
89
89
  """After a call settles the next sequential call triggers a fresh execution."""
90
90
  counter = {"calls": 0}
91
91
 
92
- @resilient_api(_fast_config(deduplication=DeduplicationConfig()))
92
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig()))
93
93
  async def fetch_user(user_id: int):
94
94
  counter["calls"] += 1
95
95
  return {"id": user_id}
@@ -105,7 +105,7 @@ async def test_error_propagated_to_all_callers():
105
105
  """When the executing coroutine raises, all waiting callers get the same exception."""
106
106
  counter = {"calls": 0}
107
107
 
108
- @resilient_api(_fast_config(deduplication=DeduplicationConfig()))
108
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig()))
109
109
  async def fetch_user(user_id: int):
110
110
  counter["calls"] += 1
111
111
  await asyncio.sleep(0.01)
@@ -131,7 +131,7 @@ async def test_custom_key_fn_coalesces_by_resource_type():
131
131
  def resource_key(*args, **kwargs):
132
132
  return str(args[1]) if len(args) > 1 else str(args[0])
133
133
 
134
- @resilient_api(_fast_config(deduplication=DeduplicationConfig(key_fn=resource_key)))
134
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig(key_fn=resource_key)))
135
135
  async def fetch_resource(resource_id: int, resource_type: str):
136
136
  counter["calls"] += 1
137
137
  await asyncio.sleep(0.02)
@@ -152,7 +152,7 @@ async def test_none_key_fn_opts_out_of_deduplication():
152
152
  counter = {"calls": 0}
153
153
 
154
154
  # Always return None → every call bypasses dedup.
155
- @resilient_api(_fast_config(deduplication=DeduplicationConfig(key_fn=lambda *a, **k: None)))
155
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig(key_fn=lambda *a, **k: None)))
156
156
  async def fetch_user(user_id: int):
157
157
  counter["calls"] += 1
158
158
  await asyncio.sleep(0.02)
@@ -173,11 +173,11 @@ async def test_deduplication_benchmark(capsys):
173
173
  CONCURRENCY = 200
174
174
  RUNS = 5
175
175
 
176
- @resilient_api(_fast_config())
176
+ @smooth_api(_fast_config())
177
177
  async def plain_fn(x: int):
178
178
  return x
179
179
 
180
- @resilient_api(_fast_config(deduplication=DeduplicationConfig()))
180
+ @smooth_api(_fast_config(deduplication=DeduplicationConfig()))
181
181
  async def deduped_fn(x: int):
182
182
  return x
183
183
 
@@ -1,18 +1,18 @@
1
- import pytest
2
- import requests
3
- import httpx
4
- from smooth_api import _get_status_code
5
-
6
- def test_get_status_code_requests():
7
- err = requests.exceptions.HTTPError(response=type('R', (), {'status_code': 502})())
8
- assert _get_status_code(err) == 502
9
-
10
- def test_get_status_code_httpx():
11
- request = httpx.Request("GET", "http://localhost")
12
- response = httpx.Response(503, request=request)
13
- err = httpx.HTTPStatusError("error", request=request, response=response)
14
- assert _get_status_code(err) == 503
15
-
16
- def test_get_status_code_unrelated_exception():
17
- err = ValueError("Something else")
18
- assert _get_status_code(err) is None
1
+ import pytest
2
+ import requests
3
+ import httpx
4
+ from smooth_api import _get_status_code
5
+
6
+ def test_get_status_code_requests():
7
+ err = requests.exceptions.HTTPError(response=type('R', (), {'status_code': 502})())
8
+ assert _get_status_code(err) == 502
9
+
10
+ def test_get_status_code_httpx():
11
+ request = httpx.Request("GET", "http://localhost")
12
+ response = httpx.Response(503, request=request)
13
+ err = httpx.HTTPStatusError("error", request=request, response=response)
14
+ assert _get_status_code(err) == 503
15
+
16
+ def test_get_status_code_unrelated_exception():
17
+ err = ValueError("Something else")
18
+ assert _get_status_code(err) is None
@@ -1,43 +1,43 @@
1
- import pytest
2
- import requests
3
- from smooth_api import resilient_api, ResilientConfig
4
- from smooth_api.config import BackoffConfig, CircuitBreakerConfig
5
-
6
- BASE = "http://localhost:3001"
7
-
8
- @pytest.fixture(autouse=True)
9
- def reset_counter():
10
- requests.get(f"{BASE}/reset")
11
- yield
12
- requests.get(f"{BASE}/reset")
13
-
14
- def test_decorator_isolation_and_runtime_override():
15
- config = ResilientConfig(
16
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
17
- circuit_breaker=CircuitBreakerConfig(failure_threshold=2, cooldown_ms=60_000),
18
- retry_on=[500],
19
- fallback={"default": True}
20
- )
21
-
22
- @resilient_api(config)
23
- def api_one():
24
- raise requests.exceptions.HTTPError(response=type('R', (), {'status_code': 500})())
25
-
26
- @resilient_api(config)
27
- def api_two():
28
- return {"success": True}
29
-
30
- # Trip api_one
31
- for _ in range(5):
32
- try:
33
- api_one()
34
- except requests.exceptions.HTTPError:
35
- pass
36
-
37
- # api_one should return fallback with override precedence
38
- res_one = api_one(fallback={"override": True})
39
- assert res_one == {"override": True}, "Runtime fallback override failed"
40
-
41
- # api_two should not be tripped
42
- res_two = api_two()
43
- assert res_two == {"success": True}, "Decorator state leaked to other decorated functions"
1
+ import pytest
2
+ import requests
3
+ from smooth_api import smooth_api, SmoothConfig
4
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
5
+
6
+ BASE = "http://localhost:3001"
7
+
8
+ @pytest.fixture(autouse=True)
9
+ def reset_counter():
10
+ requests.get(f"{BASE}/reset")
11
+ yield
12
+ requests.get(f"{BASE}/reset")
13
+
14
+ def test_decorator_isolation_and_runtime_override():
15
+ config = SmoothConfig(
16
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
17
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=2, cooldown_ms=60_000),
18
+ retry_on=[500],
19
+ fallback={"default": True}
20
+ )
21
+
22
+ @smooth_api(config)
23
+ def api_one():
24
+ raise requests.exceptions.HTTPError(response=type('R', (), {'status_code': 500})())
25
+
26
+ @smooth_api(config)
27
+ def api_two():
28
+ return {"success": True}
29
+
30
+ # Trip api_one
31
+ for _ in range(5):
32
+ try:
33
+ api_one()
34
+ except requests.exceptions.HTTPError:
35
+ pass
36
+
37
+ # api_one should return fallback with override precedence
38
+ res_one = api_one(fallback={"override": True})
39
+ assert res_one == {"override": True}, "Runtime fallback override failed"
40
+
41
+ # api_two should not be tripped
42
+ res_two = api_two()
43
+ assert res_two == {"success": True}, "Decorator state leaked to other decorated functions"
@@ -1,268 +1,268 @@
1
- """Integration tests for smooth_api against the sandbox server on port 3001."""
2
- from __future__ import annotations
3
-
4
- import time
5
-
6
- import pytest
7
- import requests
8
-
9
- from smooth_api import resilient_api, ResilientConfig
10
- from smooth_api.config import BackoffConfig, CircuitBreakerConfig
11
-
12
- BASE = "http://localhost:3001"
13
-
14
-
15
- def reset():
16
- """Reset sandbox request counter between tests."""
17
- requests.get(f"{BASE}/reset")
18
-
19
-
20
- # ─── Fixtures ─────────────────────────────────────────────────────────────────
21
-
22
- @pytest.fixture(autouse=True)
23
- def reset_counter():
24
- reset()
25
- yield
26
- reset()
27
-
28
-
29
- # ─── Retry logic ──────────────────────────────────────────────────────────────
30
-
31
- def test_retries_on_500_and_eventually_succeeds():
32
- config = ResilientConfig(
33
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=5),
34
- circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
35
- )
36
-
37
- @resilient_api(config)
38
- def get_data():
39
- res = requests.get(f"{BASE}/unstable-data")
40
- res.raise_for_status()
41
- return res.json()
42
-
43
- result = get_data()
44
- assert result == {"success": True, "data": "Solid Data"}
45
-
46
-
47
- def test_retry_respects_retry_on_codes():
48
- """429 and 500 trigger retries; 200 does not."""
49
- config = ResilientConfig(
50
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=3),
51
- circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
52
- retry_on=[429, 500],
53
- )
54
-
55
- call_count = [0]
56
-
57
- @resilient_api(config)
58
- def get_data():
59
- call_count[0] += 1
60
- res = requests.get(f"{BASE}/unstable-data")
61
- res.raise_for_status()
62
- return res.json()
63
-
64
- try:
65
- get_data()
66
- except Exception:
67
- pass
68
-
69
- # At least one retry happened (call_count > 1) or first call succeeded
70
- assert call_count[0] >= 1
71
-
72
-
73
- # ─── Circuit breaker ──────────────────────────────────────────────────────────
74
-
75
- def test_circuit_trips_and_returns_fallback():
76
- fallback = {"data": "cached"}
77
- config = ResilientConfig(
78
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
79
- circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
80
- retry_on=[500, 429],
81
- fallback=fallback,
82
- )
83
-
84
- call_count = [0]
85
-
86
- @resilient_api(config)
87
- def get_data():
88
- call_count[0] += 1
89
- # Always raise so failures accumulate without recordSuccess resetting the count.
90
- raise requests.exceptions.HTTPError(
91
- response=type('R', (), {'status_code': 500})()
92
- )
93
-
94
- results = []
95
- for _ in range(5):
96
- try:
97
- result = get_data(fallback=fallback)
98
- results.append(result)
99
- except requests.exceptions.HTTPError:
100
- results.append("ERROR")
101
-
102
- assert fallback in results, f"circuit should have returned fallback, got: {results}"
103
-
104
-
105
- def test_circuit_open_raises_runtime_error_without_fallback():
106
- config = ResilientConfig(
107
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
108
- circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
109
- retry_on=[500, 429],
110
- )
111
-
112
- @resilient_api(config)
113
- def get_data():
114
- # Always raises a 500 so recordSuccess never fires and count accumulates.
115
- raise requests.exceptions.HTTPError(
116
- response=type('R', (), {'status_code': 500})()
117
- )
118
-
119
- # 3 calls trip the circuit (threshold=3, no successes to reset count)
120
- for _ in range(3):
121
- try:
122
- get_data()
123
- except Exception:
124
- pass
125
-
126
- # Next call should raise RuntimeError (OPEN, no fallback)
127
- with pytest.raises(RuntimeError, match="Circuit breaker is OPEN"):
128
- get_data()
129
-
130
-
131
- # ─── Recovery ─────────────────────────────────────────────────────────────────
132
-
133
- def test_circuit_recovers_after_cooldown():
134
- cooldown_ms = 500
135
- config = ResilientConfig(
136
- backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
137
- circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=cooldown_ms),
138
- retry_on=[500, 429],
139
- fallback={"tripped": True},
140
- )
141
-
142
- @resilient_api(config)
143
- def get_data():
144
- res = requests.get(f"{BASE}/unstable-data")
145
- res.raise_for_status()
146
- return res.json()
147
-
148
- # Trip the circuit
149
- for _ in range(9):
150
- try:
151
- get_data(fallback={"tripped": True})
152
- except requests.exceptions.HTTPError:
153
- pass
154
-
155
- # Wait for cooldown
156
- time.sleep((cooldown_ms / 1000) + 0.2)
157
-
158
- # Reset sandbox so next request gets 200
159
- reset()
160
-
161
- # Probe should succeed and close the circuit
162
- result = get_data()
163
- assert result == {"success": True, "data": "Solid Data"}
164
-
165
-
166
- # ─── Non-retryable error fallback & callbacks ──────────────────────────────────
167
-
168
- def test_python_non_retryable_default_behavior():
169
- config = ResilientConfig(fallback_on_non_retryable=False)
170
-
171
- @resilient_api(config)
172
- def get_data():
173
- raise requests.exceptions.HTTPError(
174
- response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
175
- )
176
-
177
- with pytest.raises(requests.exceptions.HTTPError):
178
- get_data()
179
-
180
-
181
- def test_python_non_retryable_fallback_and_stderr(capsys):
182
- config = ResilientConfig(fallback_on_non_retryable=True)
183
-
184
- @resilient_api(config)
185
- def get_data_sync():
186
- raise requests.exceptions.HTTPError(
187
- response=type('R', (), {'status_code': 405, 'reason': 'Method Not Allowed'})()
188
- )
189
-
190
- res = get_data_sync()
191
-
192
- # Check return type and fields
193
- assert res.status_code == 405
194
- assert res.ok is False
195
- assert res.reason == "Method Not Allowed"
196
-
197
- data = res.json()
198
- assert data["error"] is True
199
- assert data["status"] == 405
200
- assert "405 Method Not Allowed" in data["message"]
201
-
202
- # Check stderr warning
203
- captured = capsys.readouterr()
204
- assert "405 Method Not Allowed" in captured.err
205
-
206
-
207
- @pytest.mark.asyncio
208
- async def test_python_non_retryable_async_fallback_and_stderr(capsys):
209
- config = ResilientConfig(fallback_on_non_retryable=True)
210
-
211
- @resilient_api(config)
212
- async def get_data_async():
213
- raise requests.exceptions.HTTPError(
214
- response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
215
- )
216
-
217
- res = await get_data_async()
218
-
219
- assert res.status_code == 404
220
- assert res.ok is False
221
-
222
- data = res.json()
223
- assert data["error"] is True
224
- assert data["status"] == 404
225
-
226
- captured = capsys.readouterr()
227
- assert "404 Not Found" in captured.err
228
-
229
-
230
- def test_python_non_retryable_custom_fallback():
231
- fallback_val = {"custom": "python_fallback"}
232
- config = ResilientConfig(fallback_on_non_retryable=True, fallback=fallback_val)
233
-
234
- @resilient_api(config)
235
- def get_data():
236
- raise requests.exceptions.HTTPError(
237
- response=type('R', (), {'status_code': 400, 'reason': 'Bad Request'})()
238
- )
239
-
240
- res = get_data()
241
- assert res == fallback_val
242
-
243
-
244
- def test_python_non_retryable_custom_callback(capsys):
245
- called = []
246
- def callback(status, msg):
247
- called.append((status, msg))
248
-
249
- config = ResilientConfig(
250
- fallback_on_non_retryable=True,
251
- on_non_retryable_error=callback
252
- )
253
-
254
- @resilient_api(config)
255
- def get_data():
256
- raise requests.exceptions.HTTPError(
257
- response=type('R', (), {'status_code': 403, 'reason': 'Forbidden'})()
258
- )
259
-
260
- res = get_data()
261
- assert res.status_code == 403
262
- assert len(called) == 1
263
- assert called[0][0] == 403
264
- assert "403 Forbidden" in called[0][1]
265
-
266
- # Stderr should be empty since callback was used
267
- captured = capsys.readouterr()
268
- assert captured.err == ""
1
+ """Integration tests for smooth_api against the sandbox server on port 3001."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+
6
+ import pytest
7
+ import requests
8
+
9
+ from smooth_api import smooth_api, SmoothConfig
10
+ from smooth_api.config import BackoffConfig, CircuitBreakerConfig
11
+
12
+ BASE = "http://localhost:3001"
13
+
14
+
15
+ def reset():
16
+ """Reset sandbox request counter between tests."""
17
+ requests.get(f"{BASE}/reset")
18
+
19
+
20
+ # ─── Fixtures ─────────────────────────────────────────────────────────────────
21
+
22
+ @pytest.fixture(autouse=True)
23
+ def reset_counter():
24
+ reset()
25
+ yield
26
+ reset()
27
+
28
+
29
+ # ─── Retry logic ──────────────────────────────────────────────────────────────
30
+
31
+ def test_retries_on_500_and_eventually_succeeds():
32
+ config = SmoothConfig(
33
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=5),
34
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
35
+ )
36
+
37
+ @smooth_api(config)
38
+ def get_data():
39
+ res = requests.get(f"{BASE}/unstable-data")
40
+ res.raise_for_status()
41
+ return res.json()
42
+
43
+ result = get_data()
44
+ assert result == {"success": True, "data": "Solid Data"}
45
+
46
+
47
+ def test_retry_respects_retry_on_codes():
48
+ """429 and 500 trigger retries; 200 does not."""
49
+ config = SmoothConfig(
50
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.1, max_retries=3),
51
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=10, cooldown_ms=60_000),
52
+ retry_on=[429, 500],
53
+ )
54
+
55
+ call_count = [0]
56
+
57
+ @smooth_api(config)
58
+ def get_data():
59
+ call_count[0] += 1
60
+ res = requests.get(f"{BASE}/unstable-data")
61
+ res.raise_for_status()
62
+ return res.json()
63
+
64
+ try:
65
+ get_data()
66
+ except Exception:
67
+ pass
68
+
69
+ # At least one retry happened (call_count > 1) or first call succeeded
70
+ assert call_count[0] >= 1
71
+
72
+
73
+ # ─── Circuit breaker ──────────────────────────────────────────────────────────
74
+
75
+ def test_circuit_trips_and_returns_fallback():
76
+ fallback = {"data": "cached"}
77
+ config = SmoothConfig(
78
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
79
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
80
+ retry_on=[500, 429],
81
+ fallback=fallback,
82
+ )
83
+
84
+ call_count = [0]
85
+
86
+ @smooth_api(config)
87
+ def get_data():
88
+ call_count[0] += 1
89
+ # Always raise so failures accumulate without recordSuccess resetting the count.
90
+ raise requests.exceptions.HTTPError(
91
+ response=type('R', (), {'status_code': 500})()
92
+ )
93
+
94
+ results = []
95
+ for _ in range(5):
96
+ try:
97
+ result = get_data(fallback=fallback)
98
+ results.append(result)
99
+ except requests.exceptions.HTTPError:
100
+ results.append("ERROR")
101
+
102
+ assert fallback in results, f"circuit should have returned fallback, got: {results}"
103
+
104
+
105
+ def test_circuit_open_raises_runtime_error_without_fallback():
106
+ config = SmoothConfig(
107
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
108
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=60_000),
109
+ retry_on=[500, 429],
110
+ )
111
+
112
+ @smooth_api(config)
113
+ def get_data():
114
+ # Always raises a 500 so recordSuccess never fires and count accumulates.
115
+ raise requests.exceptions.HTTPError(
116
+ response=type('R', (), {'status_code': 500})()
117
+ )
118
+
119
+ # 3 calls trip the circuit (threshold=3, no successes to reset count)
120
+ for _ in range(3):
121
+ try:
122
+ get_data()
123
+ except Exception:
124
+ pass
125
+
126
+ # Next call should raise RuntimeError (OPEN, no fallback)
127
+ with pytest.raises(RuntimeError, match="Circuit breaker is OPEN"):
128
+ get_data()
129
+
130
+
131
+ # ─── Recovery ─────────────────────────────────────────────────────────────────
132
+
133
+ def test_circuit_recovers_after_cooldown():
134
+ cooldown_ms = 500
135
+ config = SmoothConfig(
136
+ backoff=BackoffConfig(base_delay=0.01, max_delay=0.05, max_retries=0),
137
+ circuit_breaker=CircuitBreakerConfig(failure_threshold=3, cooldown_ms=cooldown_ms),
138
+ retry_on=[500, 429],
139
+ fallback={"tripped": True},
140
+ )
141
+
142
+ @smooth_api(config)
143
+ def get_data():
144
+ res = requests.get(f"{BASE}/unstable-data")
145
+ res.raise_for_status()
146
+ return res.json()
147
+
148
+ # Trip the circuit
149
+ for _ in range(9):
150
+ try:
151
+ get_data(fallback={"tripped": True})
152
+ except requests.exceptions.HTTPError:
153
+ pass
154
+
155
+ # Wait for cooldown
156
+ time.sleep((cooldown_ms / 1000) + 0.2)
157
+
158
+ # Reset sandbox so next request gets 200
159
+ reset()
160
+
161
+ # Probe should succeed and close the circuit
162
+ result = get_data()
163
+ assert result == {"success": True, "data": "Solid Data"}
164
+
165
+
166
+ # ─── Non-retryable error fallback & callbacks ──────────────────────────────────
167
+
168
+ def test_python_non_retryable_default_behavior():
169
+ config = SmoothConfig(fallback_on_non_retryable=False)
170
+
171
+ @smooth_api(config)
172
+ def get_data():
173
+ raise requests.exceptions.HTTPError(
174
+ response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
175
+ )
176
+
177
+ with pytest.raises(requests.exceptions.HTTPError):
178
+ get_data()
179
+
180
+
181
+ def test_python_non_retryable_fallback_and_stderr(capsys):
182
+ config = SmoothConfig(fallback_on_non_retryable=True)
183
+
184
+ @smooth_api(config)
185
+ def get_data_sync():
186
+ raise requests.exceptions.HTTPError(
187
+ response=type('R', (), {'status_code': 405, 'reason': 'Method Not Allowed'})()
188
+ )
189
+
190
+ res = get_data_sync()
191
+
192
+ # Check return type and fields
193
+ assert res.status_code == 405
194
+ assert res.ok is False
195
+ assert res.reason == "Method Not Allowed"
196
+
197
+ data = res.json()
198
+ assert data["error"] is True
199
+ assert data["status"] == 405
200
+ assert "405 Method Not Allowed" in data["message"]
201
+
202
+ # Check stderr warning
203
+ captured = capsys.readouterr()
204
+ assert "405 Method Not Allowed" in captured.err
205
+
206
+
207
+ @pytest.mark.asyncio
208
+ async def test_python_non_retryable_async_fallback_and_stderr(capsys):
209
+ config = SmoothConfig(fallback_on_non_retryable=True)
210
+
211
+ @smooth_api(config)
212
+ async def get_data_async():
213
+ raise requests.exceptions.HTTPError(
214
+ response=type('R', (), {'status_code': 404, 'reason': 'Not Found'})()
215
+ )
216
+
217
+ res = await get_data_async()
218
+
219
+ assert res.status_code == 404
220
+ assert res.ok is False
221
+
222
+ data = res.json()
223
+ assert data["error"] is True
224
+ assert data["status"] == 404
225
+
226
+ captured = capsys.readouterr()
227
+ assert "404 Not Found" in captured.err
228
+
229
+
230
+ def test_python_non_retryable_custom_fallback():
231
+ fallback_val = {"custom": "python_fallback"}
232
+ config = SmoothConfig(fallback_on_non_retryable=True, fallback=fallback_val)
233
+
234
+ @smooth_api(config)
235
+ def get_data():
236
+ raise requests.exceptions.HTTPError(
237
+ response=type('R', (), {'status_code': 400, 'reason': 'Bad Request'})()
238
+ )
239
+
240
+ res = get_data()
241
+ assert res == fallback_val
242
+
243
+
244
+ def test_python_non_retryable_custom_callback(capsys):
245
+ called = []
246
+ def callback(status, msg):
247
+ called.append((status, msg))
248
+
249
+ config = SmoothConfig(
250
+ fallback_on_non_retryable=True,
251
+ on_non_retryable_error=callback
252
+ )
253
+
254
+ @smooth_api(config)
255
+ def get_data():
256
+ raise requests.exceptions.HTTPError(
257
+ response=type('R', (), {'status_code': 403, 'reason': 'Forbidden'})()
258
+ )
259
+
260
+ res = get_data()
261
+ assert res.status_code == 403
262
+ assert len(called) == 1
263
+ assert called[0][0] == 403
264
+ assert "403 Forbidden" in called[0][1]
265
+
266
+ # Stderr should be empty since callback was used
267
+ captured = capsys.readouterr()
268
+ assert captured.err == ""
File without changes
File without changes