docges-api-py 0.1.1__tar.gz → 0.1.2__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.
Files changed (31) hide show
  1. {docges_api_py-0.1.1/src/docges_api_py.egg-info → docges_api_py-0.1.2}/PKG-INFO +1 -1
  2. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/pyproject.toml +1 -1
  3. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/client.py +19 -12
  4. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/models/responses.py +2 -4
  5. {docges_api_py-0.1.1 → docges_api_py-0.1.2/src/docges_api_py.egg-info}/PKG-INFO +1 -1
  6. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_client_auth.py +56 -0
  7. docges_api_py-0.1.2/tests/test_get_document.py +117 -0
  8. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_models_responses.py +47 -0
  9. docges_api_py-0.1.2/tests/test_retry.py +125 -0
  10. docges_api_py-0.1.1/tests/test_get_document.py +0 -62
  11. docges_api_py-0.1.1/tests/test_retry.py +0 -63
  12. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/LICENSE +0 -0
  13. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/README.md +0 -0
  14. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/setup.cfg +0 -0
  15. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/__init__.py +0 -0
  16. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/models/__init__.py +0 -0
  17. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/models/auth.py +0 -0
  18. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/models/document.py +0 -0
  19. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py/models/requests.py +0 -0
  20. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py.egg-info/SOURCES.txt +0 -0
  21. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py.egg-info/dependency_links.txt +0 -0
  22. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py.egg-info/requires.txt +0 -0
  23. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/src/docges_api_py.egg-info/top_level.txt +0 -0
  24. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_content_methods.py +0 -0
  25. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_endpoints.py +0 -0
  26. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_initial_cats.py +0 -0
  27. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_models_auth.py +0 -0
  28. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_models_init.py +0 -0
  29. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_models_requests.py +0 -0
  30. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_remaining_methods.py +0 -0
  31. {docges_api_py-0.1.1 → docges_api_py-0.1.2}/tests/test_token_refresh.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: docges-api-py
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Async, typed Python client for DocGes REST API
5
5
  Author-email: "ct.galega" <soporte@ctgalega.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "docges-api-py"
7
- version = "0.1.1"
7
+ version = "0.1.2"
8
8
  description = "Async, typed Python client for DocGes REST API"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -140,7 +140,13 @@ class AsyncDocGes:
140
140
  except Exception as e:
141
141
  raise AuthenticationError(f"Invalid auth response: {e}") from e
142
142
 
143
- # Store the raw dict for injection into every subsequent /Content/* request
143
+ # Normalize: copy SIDraiz to SID in wareHouseInfo for bridge compatibility
144
+ # The bridge C# code expects wareHouseInfo.SID, but the API returns SIDraiz
145
+ if "wareHouseInfo" in resp and "SIDraiz" in resp["wareHouseInfo"]:
146
+ if "SID" not in resp["wareHouseInfo"]:
147
+ resp["wareHouseInfo"]["SID"] = resp["wareHouseInfo"]["SIDraiz"]
148
+
149
+ # Store the normalized dict for injection into every subsequent /Content/* request
144
150
  self._login_response = resp
145
151
  return auth_resp
146
152
 
@@ -178,22 +184,22 @@ class AsyncDocGes:
178
184
  # Content endpoints: wrap in requestModel + inject loginResponse
179
185
  if "/Auth/" in url:
180
186
  # Auth endpoints expect fields directly in the body
181
- payload = {}
187
+ payload: dict[str, Any] = {}
182
188
  if data is not None:
183
189
  payload.update(data.model_dump(exclude_none=True))
184
190
  else:
185
191
  # Content endpoints use requestModel wrapper
186
192
  request_model: dict[str, Any] = {}
187
-
193
+
188
194
  # Inject session for all Content endpoints
189
195
  if self._login_response is not None and "/Content/" in url:
190
196
  request_model["loginResponse"] = self._login_response
191
-
197
+
192
198
  # Merge endpoint-specific data
193
199
  if data is not None:
194
200
  request_model.update(data.model_dump(exclude_none=True))
195
-
196
- payload: dict[str, Any] = {"requestModel": request_model}
201
+
202
+ payload = {"requestModel": request_model}
197
203
 
198
204
  last_exc: Exception | None = None
199
205
 
@@ -201,21 +207,22 @@ class AsyncDocGes:
201
207
  try:
202
208
  resp = await client.post(url, json=payload)
203
209
  resp.raise_for_status()
204
- # Debug: log response for troubleshooting
205
- text = resp.text
206
- if not text:
207
- raise RequestError("Server returned empty response")
210
+ # Handle non-JSON responses (e.g., HTML 500 error pages)
208
211
  try:
209
212
  result = resp.json()
210
213
  except Exception as json_err:
211
- raise RequestError(f"Failed to parse JSON: {json_err}. Response text: {text[:200]}")
214
+ # Server returned non-JSON (e.g., HTML 500 error page)
215
+ raise RequestError(
216
+ f"Server returned non-JSON response (status {resp.status_code}): {resp.text[:200]}"
217
+ ) from json_err
212
218
  if result is None:
213
219
  raise RequestError("Server returned null JSON")
214
220
  return result # type: ignore[no-any-return]
215
221
  except (httpx.HTTPStatusError, httpx.RequestError, RequestError) as exc:
216
222
  last_exc = exc
217
223
  if attempt < self.intents:
218
- await asyncio.sleep(self.timeout * attempt)
224
+ # Exponential backoff: 2s, 4s, 8s (capped at 10s)
225
+ await asyncio.sleep(min(2 ** attempt, 10))
219
226
 
220
227
  raise RequestError(
221
228
  f"Request to {url} failed after {self.intents} attempts"
@@ -5,8 +5,8 @@ from pydantic import BaseModel, ConfigDict
5
5
 
6
6
 
7
7
  class DocGesResponseModel(BaseModel):
8
- """Base model for DocGes responses. Allows underscore-prefixed fields (e.g., _Nombre)."""
9
- model_config = ConfigDict(underscore_attrs_are_private=False)
8
+ """Base model for DocGes responses. Ignores unknown fields from API responses."""
9
+ model_config = ConfigDict(extra='ignore')
10
10
 
11
11
 
12
12
  # --- Category & Tree Responses ---
@@ -17,8 +17,6 @@ class ResCatItem(DocGesResponseModel):
17
17
  SID: str
18
18
  CategoriasHijas: list[dict] | None = None
19
19
  Documentos: list[dict] | None = None
20
- CategoriasHijas: list[dict] | None = None
21
- Documentos: list[dict] | None = None
22
20
 
23
21
 
24
22
  class ResCat(DocGesResponseModel):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: docges-api-py
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Async, typed Python client for DocGes REST API
5
5
  Author-email: "ct.galega" <soporte@ctgalega.com>
6
6
  License: MIT
@@ -184,3 +184,59 @@ async def test_ensure_session_network_failure_before_content_request():
184
184
  await client.get_initial_cats()
185
185
 
186
186
  await client.close()
187
+
188
+
189
+ # --- Task 2.4 / 3.1: SIDraiz → SID normalization ---
190
+
191
+ LOGIN_WITH_SIDRAIZ = {
192
+ "userInfo": {"SID": "user-sid", "Nombre": "Admin", "Id": 1},
193
+ "wareHouseInfo": {"SIDraiz": "root-sid-value", "Nombre": "devbg"},
194
+ }
195
+
196
+ LOGIN_WITHOUT_SIDRAIZ = {
197
+ "userInfo": {"SID": "user-sid", "Nombre": "Admin", "Id": 1},
198
+ "wareHouseInfo": {"SID": "already-has-sid", "Nombre": "devbg"},
199
+ }
200
+
201
+
202
+ @pytest.mark.asyncio
203
+ async def test_auth_normalizes_sidraiz_into_sid() -> None:
204
+ """Task 2.4/3.1: auth() must copy SIDraiz to SID in wareHouseInfo when SID is absent."""
205
+ base_url = "https://fake-docges.example.com"
206
+
207
+ with respx.mock(using="httpx") as router:
208
+ router.post(f"{base_url}/Auth/Login").mock(
209
+ return_value=httpx.Response(200, json=LOGIN_WITH_SIDRAIZ)
210
+ )
211
+
212
+ client = AsyncDocGes(base_url, "user", "pass", "app")
213
+ await client.auth()
214
+
215
+ # SIDraiz must have been copied to SID in wareHouseInfo
216
+ assert client._login_response is not None
217
+ wh = client._login_response["wareHouseInfo"]
218
+ assert wh["SID"] == "root-sid-value", (
219
+ f"Expected SID='root-sid-value' (from SIDraiz), got {wh}"
220
+ )
221
+
222
+ await client.close()
223
+
224
+
225
+ @pytest.mark.asyncio
226
+ async def test_auth_skips_normalization_when_sid_already_present() -> None:
227
+ """Task 3.1 triangulation: auth() must NOT overwrite existing SID when SIDraiz is absent."""
228
+ base_url = "https://fake-docges.example.com"
229
+
230
+ with respx.mock(using="httpx") as router:
231
+ router.post(f"{base_url}/Auth/Login").mock(
232
+ return_value=httpx.Response(200, json=LOGIN_WITHOUT_SIDRAIZ)
233
+ )
234
+
235
+ client = AsyncDocGes(base_url, "user", "pass", "app")
236
+ await client.auth()
237
+
238
+ assert client._login_response is not None
239
+ wh = client._login_response["wareHouseInfo"]
240
+ assert wh["SID"] == "already-has-sid"
241
+
242
+ await client.close()
@@ -0,0 +1,117 @@
1
+ """Tests for AsyncDocGes.get_document()."""
2
+
3
+ import httpx
4
+ import pytest
5
+ import respx
6
+
7
+ from docges_api_py import AsyncDocGes, RequestError
8
+ from docges_api_py.models.document import Document
9
+
10
+ REAL_LOGIN_PAYLOAD = {
11
+ "userInfo": {"SID": "a6e65fd7-1234-5678-abcd-ef0123456789", "Nombre": "Administrador", "Id": 5},
12
+ "wareHouseInfo": {"SID": "16cf3ed3-aaaa-bbbb-cccc-ddddeeee0001", "Nombre": "devbg"},
13
+ }
14
+
15
+
16
+ @pytest.mark.asyncio
17
+ async def test_get_document_success():
18
+ """Test that get_document returns a Document on success."""
19
+ base_url = "https://fake-docges.example.com"
20
+
21
+ with respx.mock(using="httpx") as router:
22
+ router.post(f"{base_url}/Content/Download").mock(
23
+ return_value=httpx.Response(
24
+ 200,
25
+ json={
26
+ "result": {"name": "test.pdf", "data": "base64content", "type": "application/pdf"},
27
+ "message": "OK",
28
+ },
29
+ )
30
+ )
31
+
32
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
33
+ client._login_response = REAL_LOGIN_PAYLOAD # inject session, skip auth
34
+
35
+ doc = await client.get_document("doc-123")
36
+
37
+ assert isinstance(doc, Document)
38
+ assert doc.id == "doc-123"
39
+ assert doc.name == "test.pdf"
40
+
41
+ await client.close()
42
+
43
+
44
+ @pytest.mark.asyncio
45
+ async def test_get_document_failure():
46
+ """Test that get_document raises RequestError on persistent 500s."""
47
+ base_url = "https://fake-docges.example.com"
48
+
49
+ with respx.mock(using="httpx", assert_all_called=False) as router:
50
+ router.post(f"{base_url}/Content/Download").mock(
51
+ return_value=httpx.Response(500, json={"error": "Internal Server Error"})
52
+ )
53
+
54
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
55
+ client._login_response = REAL_LOGIN_PAYLOAD
56
+ client.timeout = 0.01 # fast backoff
57
+ client.intents = 1 # only 1 attempt
58
+
59
+ with pytest.raises(RequestError):
60
+ await client.get_document("doc-123")
61
+
62
+ await client.close()
63
+
64
+
65
+ @pytest.mark.asyncio
66
+ async def test_http_500_html_body_raises_structured_request_error():
67
+ """Task 3.3: HTTP 500 with HTML body must raise RequestError, not JSONDecodeError."""
68
+ base_url = "https://fake-docges.example.com"
69
+ html_body = "<html><body><h1>500 Internal Server Error</h1></body></html>"
70
+
71
+ with respx.mock(using="httpx") as router:
72
+ router.post(f"{base_url}/Content/Download").mock(
73
+ return_value=httpx.Response(
74
+ 500,
75
+ content=html_body.encode(),
76
+ headers={"Content-Type": "text/html"},
77
+ )
78
+ )
79
+
80
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
81
+ client._login_response = REAL_LOGIN_PAYLOAD
82
+ client.intents = 1
83
+
84
+ with pytest.raises(RequestError) as exc_info:
85
+ await client.do_request("/Content/Download")
86
+
87
+ # Must be a structured RequestError, NOT a JSONDecodeError crash
88
+ assert "RequestError" in type(exc_info.value).__name__ or isinstance(exc_info.value, RequestError)
89
+ # The error message should NOT be a raw JSONDecodeError
90
+ assert "JSONDecodeError" not in type(exc_info.value).__name__
91
+
92
+ await client.close()
93
+
94
+
95
+ @pytest.mark.asyncio
96
+ async def test_http_200_json_parse_error_raises_structured_request_error():
97
+ """Task 3.3 triangulation: 200 response with non-JSON body raises RequestError, not crash."""
98
+ base_url = "https://fake-docges.example.com"
99
+ broken_body = "this is not json at all"
100
+
101
+ with respx.mock(using="httpx") as router:
102
+ router.post(f"{base_url}/Content/Download").mock(
103
+ return_value=httpx.Response(
104
+ 200,
105
+ content=broken_body.encode(),
106
+ headers={"Content-Type": "text/plain"},
107
+ )
108
+ )
109
+
110
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
111
+ client._login_response = REAL_LOGIN_PAYLOAD
112
+ client.intents = 1
113
+
114
+ with pytest.raises(RequestError):
115
+ await client.do_request("/Content/Download")
116
+
117
+ await client.close()
@@ -83,3 +83,50 @@ def test_res_search_empty():
83
83
  """Triangulation: ResSearch with no results."""
84
84
  res = ResSearch(results=[], message="OK")
85
85
  assert len(res.results) == 0
86
+
87
+
88
+ # --- Task 1.3: No Pydantic deprecation warning on import ---
89
+
90
+ def test_no_pydantic_deprecation_warning_on_import():
91
+ """Task 1.3: Importing response models must produce no Pydantic deprecation warning."""
92
+ import importlib
93
+ import warnings
94
+
95
+ import docges_api_py.models.responses as resp_mod
96
+ with warnings.catch_warnings(record=True) as caught:
97
+ warnings.simplefilter("always")
98
+ importlib.reload(resp_mod)
99
+ pydantic_warnings = [
100
+ w for w in caught
101
+ if issubclass(w.category, UserWarning) and "underscore_attrs_are_private" in str(w.message)
102
+ ]
103
+ assert len(pydantic_warnings) == 0, (
104
+ f"Expected no Pydantic deprecation warnings but got: {[str(w.message) for w in pydantic_warnings]}"
105
+ )
106
+
107
+
108
+ # --- Task 1.4: ResCatItem validates without duplicate fields ---
109
+
110
+ def test_res_cat_item_validates_without_duplicates():
111
+ """Task 1.4: ResCatItem must validate a full payload with single CategoriasHijas and Documentos."""
112
+ from docges_api_py.models.responses import ResCatItem
113
+ item = ResCatItem(
114
+ Nombre="Root",
115
+ SID="16cf3ed3-b8a2-4a08-8a0f-8c07948b3fad",
116
+ CategoriasHijas=[{"Nombre": "Child", "SID": "child-sid"}],
117
+ Documentos=[{"Nombre": "Doc1", "SID": "doc-sid"}],
118
+ )
119
+ assert item.Nombre == "Root"
120
+ assert item.SID == "16cf3ed3-b8a2-4a08-8a0f-8c07948b3fad"
121
+ assert len(item.CategoriasHijas) == 1
122
+ assert item.CategoriasHijas[0]["Nombre"] == "Child"
123
+ assert len(item.Documentos) == 1
124
+ assert item.Documentos[0]["Nombre"] == "Doc1"
125
+
126
+
127
+ def test_res_cat_item_with_none_fields():
128
+ """Task 1.4 triangulation: ResCatItem must accept None for optional fields."""
129
+ from docges_api_py.models.responses import ResCatItem
130
+ item = ResCatItem(Nombre="Empty", SID="some-sid")
131
+ assert item.CategoriasHijas is None
132
+ assert item.Documentos is None
@@ -0,0 +1,125 @@
1
+ """Tests for retry behavior in AsyncDocGes.do_request()."""
2
+
3
+ from unittest.mock import AsyncMock, patch
4
+
5
+ import httpx
6
+ import pytest
7
+ import respx
8
+
9
+ from docges_api_py import AsyncDocGes, RequestError
10
+
11
+ REAL_LOGIN_PAYLOAD = {
12
+ "userInfo": {"SID": "a6e65fd7-1234-5678-abcd-ef0123456789", "Nombre": "Administrador", "Id": 5},
13
+ "wareHouseInfo": {"SID": "16cf3ed3-aaaa-bbbb-cccc-ddddeeee0001", "Nombre": "devbg"},
14
+ }
15
+
16
+
17
+ @pytest.mark.asyncio
18
+ async def test_do_request_retries_on_server_error():
19
+ """Test that do_request retries on 5xx errors and eventually succeeds."""
20
+ base_url = "https://fake-docges.example.com"
21
+
22
+ with respx.mock(using="httpx") as router:
23
+ route = router.post(f"{base_url}/Content/Download").mock(
24
+ side_effect=[
25
+ httpx.Response(500, json={"error": "Internal Server Error"}),
26
+ httpx.Response(500, json={"error": "Internal Server Error"}),
27
+ httpx.Response(200, json={"result": {"name": "test.pdf", "id": "doc-123"}}),
28
+ ]
29
+ )
30
+
31
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
32
+ client._login_response = REAL_LOGIN_PAYLOAD # inject session
33
+ client.timeout = 0.1 # small timeout to reduce backoff sleep
34
+ client.intents = 3
35
+
36
+ with patch("asyncio.sleep", new_callable=AsyncMock):
37
+ result = await client.do_request("/Content/Download")
38
+
39
+ assert route.called
40
+ assert len(route.calls) == 3
41
+ assert result == {"result": {"name": "test.pdf", "id": "doc-123"}}
42
+
43
+ await client.close()
44
+
45
+
46
+ @pytest.mark.asyncio
47
+ async def test_do_request_fails_after_max_retries():
48
+ """Test that do_request raises RequestError after all intents are exhausted."""
49
+ base_url = "https://fake-docges.example.com"
50
+
51
+ with respx.mock(using="httpx") as router:
52
+ route = router.post(f"{base_url}/Content/Download").mock(
53
+ return_value=httpx.Response(500, json={"error": "Internal Server Error"})
54
+ )
55
+
56
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
57
+ client._login_response = REAL_LOGIN_PAYLOAD
58
+ client.timeout = 0.1
59
+ client.intents = 2 # only 2 attempts
60
+
61
+ with patch("asyncio.sleep", new_callable=AsyncMock), pytest.raises(RequestError):
62
+ await client.do_request("/Content/Download")
63
+
64
+ assert len(route.calls) == 2
65
+
66
+ await client.close()
67
+
68
+
69
+ @pytest.mark.asyncio
70
+ async def test_do_request_uses_exponential_backoff():
71
+ """Task 3.2: retry delays must be min(2**attempt, 10), not timeout*attempt."""
72
+ base_url = "https://fake-docges.example.com"
73
+
74
+ with respx.mock(using="httpx") as router:
75
+ router.post(f"{base_url}/Content/Download").mock(
76
+ side_effect=[
77
+ httpx.Response(500, json={"error": "err"}),
78
+ httpx.Response(500, json={"error": "err"}),
79
+ httpx.Response(500, json={"error": "err"}),
80
+ ]
81
+ )
82
+
83
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
84
+ client._login_response = REAL_LOGIN_PAYLOAD
85
+ client.timeout = 30.0 # large timeout — must NOT be used for backoff
86
+ client.intents = 3
87
+
88
+ with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep, pytest.raises(RequestError):
89
+ await client.do_request("/Content/Download")
90
+
91
+ # attempt=1 → sleep(min(2**1, 10)) = sleep(2)
92
+ # attempt=2 → sleep(min(2**2, 10)) = sleep(4)
93
+ sleep_calls = [call.args[0] for call in mock_sleep.call_args_list]
94
+ assert sleep_calls == [2, 4], (
95
+ f"Expected exponential backoff [2, 4] but got {sleep_calls}"
96
+ )
97
+
98
+ await client.close()
99
+
100
+
101
+ @pytest.mark.asyncio
102
+ async def test_do_request_exponential_backoff_capped_at_10():
103
+ """Task 3.2 triangulation: backoff must cap at 10 seconds regardless of attempt number."""
104
+ base_url = "https://fake-docges.example.com"
105
+
106
+ with respx.mock(using="httpx") as router:
107
+ router.post(f"{base_url}/Content/Download").mock(
108
+ return_value=httpx.Response(500, json={"error": "err"})
109
+ )
110
+
111
+ client = AsyncDocGes(base_url, "user", "pass", "appid")
112
+ client._login_response = REAL_LOGIN_PAYLOAD
113
+ client.timeout = 30.0
114
+ client.intents = 5 # attempt 4 → 2**4=16 → cap to 10
115
+
116
+ with patch("asyncio.sleep", new_callable=AsyncMock) as mock_sleep, pytest.raises(RequestError):
117
+ await client.do_request("/Content/Download")
118
+
119
+ sleep_calls = [call.args[0] for call in mock_sleep.call_args_list]
120
+ # attempts 1,2,3,4 → min(2,10), min(4,10), min(8,10), min(16,10)
121
+ assert sleep_calls == [2, 4, 8, 10], (
122
+ f"Expected capped backoff [2, 4, 8, 10] but got {sleep_calls}"
123
+ )
124
+
125
+ await client.close()
@@ -1,62 +0,0 @@
1
- """Tests for AsyncDocGes.get_document()."""
2
-
3
- import httpx
4
- import pytest
5
- import respx
6
-
7
- from docges_api_py import AsyncDocGes, RequestError
8
- from docges_api_py.models.document import Document
9
-
10
- REAL_LOGIN_PAYLOAD = {
11
- "userInfo": {"SID": "a6e65fd7-1234-5678-abcd-ef0123456789", "Nombre": "Administrador", "Id": 5},
12
- "wareHouseInfo": {"SID": "16cf3ed3-aaaa-bbbb-cccc-ddddeeee0001", "Nombre": "devbg"},
13
- }
14
-
15
-
16
- @pytest.mark.asyncio
17
- async def test_get_document_success():
18
- """Test that get_document returns a Document on success."""
19
- base_url = "https://fake-docges.example.com"
20
-
21
- with respx.mock(using="httpx") as router:
22
- router.post(f"{base_url}/Content/Download").mock(
23
- return_value=httpx.Response(
24
- 200,
25
- json={
26
- "result": {"name": "test.pdf", "data": "base64content", "type": "application/pdf"},
27
- "message": "OK",
28
- },
29
- )
30
- )
31
-
32
- client = AsyncDocGes(base_url, "user", "pass", "appid")
33
- client._login_response = REAL_LOGIN_PAYLOAD # inject session, skip auth
34
-
35
- doc = await client.get_document("doc-123")
36
-
37
- assert isinstance(doc, Document)
38
- assert doc.id == "doc-123"
39
- assert doc.name == "test.pdf"
40
-
41
- await client.close()
42
-
43
-
44
- @pytest.mark.asyncio
45
- async def test_get_document_failure():
46
- """Test that get_document raises RequestError on persistent 500s."""
47
- base_url = "https://fake-docges.example.com"
48
-
49
- with respx.mock(using="httpx", assert_all_called=False) as router:
50
- router.post(f"{base_url}/Content/Download").mock(
51
- return_value=httpx.Response(500, json={"error": "Internal Server Error"})
52
- )
53
-
54
- client = AsyncDocGes(base_url, "user", "pass", "appid")
55
- client._login_response = REAL_LOGIN_PAYLOAD
56
- client.timeout = 0.01 # fast backoff
57
- client.intents = 1 # only 1 attempt
58
-
59
- with pytest.raises(RequestError):
60
- await client.get_document("doc-123")
61
-
62
- await client.close()
@@ -1,63 +0,0 @@
1
- """Tests for retry behavior in AsyncDocGes.do_request()."""
2
-
3
- import httpx
4
- import pytest
5
- import respx
6
-
7
- from docges_api_py import AsyncDocGes, RequestError
8
-
9
- REAL_LOGIN_PAYLOAD = {
10
- "userInfo": {"SID": "a6e65fd7-1234-5678-abcd-ef0123456789", "Nombre": "Administrador", "Id": 5},
11
- "wareHouseInfo": {"SID": "16cf3ed3-aaaa-bbbb-cccc-ddddeeee0001", "Nombre": "devbg"},
12
- }
13
-
14
-
15
- @pytest.mark.asyncio
16
- async def test_do_request_retries_on_server_error():
17
- """Test that do_request retries on 5xx errors and eventually succeeds."""
18
- base_url = "https://fake-docges.example.com"
19
-
20
- with respx.mock(using="httpx") as router:
21
- route = router.post(f"{base_url}/Content/Download").mock(
22
- side_effect=[
23
- httpx.Response(500, json={"error": "Internal Server Error"}),
24
- httpx.Response(500, json={"error": "Internal Server Error"}),
25
- httpx.Response(200, json={"result": {"name": "test.pdf", "id": "doc-123"}}),
26
- ]
27
- )
28
-
29
- client = AsyncDocGes(base_url, "user", "pass", "appid")
30
- client._login_response = REAL_LOGIN_PAYLOAD # inject session
31
- client.timeout = 0.1 # small timeout to reduce backoff sleep
32
- client.intents = 3
33
-
34
- result = await client.do_request("/Content/Download")
35
-
36
- assert route.called
37
- assert len(route.calls) == 3
38
- assert result == {"result": {"name": "test.pdf", "id": "doc-123"}}
39
-
40
- await client.close()
41
-
42
-
43
- @pytest.mark.asyncio
44
- async def test_do_request_fails_after_max_retries():
45
- """Test that do_request raises RequestError after all intents are exhausted."""
46
- base_url = "https://fake-docges.example.com"
47
-
48
- with respx.mock(using="httpx") as router:
49
- route = router.post(f"{base_url}/Content/Download").mock(
50
- return_value=httpx.Response(500, json={"error": "Internal Server Error"})
51
- )
52
-
53
- client = AsyncDocGes(base_url, "user", "pass", "appid")
54
- client._login_response = REAL_LOGIN_PAYLOAD
55
- client.timeout = 0.1
56
- client.intents = 2 # only 2 attempts
57
-
58
- with pytest.raises(RequestError):
59
- await client.do_request("/Content/Download")
60
-
61
- assert len(route.calls) == 2
62
-
63
- await client.close()
File without changes
File without changes
File without changes