docges-api-py 0.1.1__tar.gz → 0.1.3__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 (32) hide show
  1. {docges_api_py-0.1.1/src/docges_api_py.egg-info → docges_api_py-0.1.3}/PKG-INFO +5 -2
  2. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/README.md +4 -1
  3. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/pyproject.toml +1 -1
  4. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/client.py +29 -14
  5. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/models/responses.py +2 -4
  6. {docges_api_py-0.1.1 → docges_api_py-0.1.3/src/docges_api_py.egg-info}/PKG-INFO +5 -2
  7. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py.egg-info/SOURCES.txt +1 -0
  8. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_client_auth.py +56 -0
  9. docges_api_py-0.1.3/tests/test_examples.py +121 -0
  10. docges_api_py-0.1.3/tests/test_get_document.py +117 -0
  11. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_models_responses.py +47 -0
  12. docges_api_py-0.1.3/tests/test_retry.py +125 -0
  13. docges_api_py-0.1.1/tests/test_get_document.py +0 -62
  14. docges_api_py-0.1.1/tests/test_retry.py +0 -63
  15. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/LICENSE +0 -0
  16. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/setup.cfg +0 -0
  17. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/__init__.py +0 -0
  18. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/models/__init__.py +0 -0
  19. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/models/auth.py +0 -0
  20. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/models/document.py +0 -0
  21. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py/models/requests.py +0 -0
  22. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py.egg-info/dependency_links.txt +0 -0
  23. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py.egg-info/requires.txt +0 -0
  24. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/src/docges_api_py.egg-info/top_level.txt +0 -0
  25. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_content_methods.py +0 -0
  26. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_endpoints.py +0 -0
  27. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_initial_cats.py +0 -0
  28. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_models_auth.py +0 -0
  29. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_models_init.py +0 -0
  30. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_models_requests.py +0 -0
  31. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/tests/test_remaining_methods.py +0 -0
  32. {docges_api_py-0.1.1 → docges_api_py-0.1.3}/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.3
4
4
  Summary: Async, typed Python client for DocGes REST API
5
5
  Author-email: "ct.galega" <soporte@ctgalega.com>
6
6
  License: MIT
@@ -83,7 +83,8 @@ async def main():
83
83
  print(f"User: {auth_resp.user_info.get('Nombre')}")
84
84
  print(f"Warehouse: {auth_resp.ware_house_info.get('Nombre')}")
85
85
 
86
- # Load initial categories (the client injects loginResponse automatically)
86
+ # Load initial categories (the client injects loginDocGesData + loginResponse automatically)
87
+ # Some DocGes bridge servers expect both fields in requestModel for Content endpoints.
87
88
  cats = await client.get_initial_cats()
88
89
  print(f"Initial categories: {len(cats.CategoriasHijas)}")
89
90
 
@@ -99,6 +100,8 @@ asyncio.run(main())
99
100
 
100
101
  See `docs/quickstart.md` or `examples/quickstart.py` for a more complete example.
101
102
 
103
+ For a working end-to-end demo (login + fetch root categories), see [`examples/initial_categories.py`](examples/initial_categories.py).
104
+
102
105
  ## Development
103
106
 
104
107
  ```bash
@@ -63,7 +63,8 @@ async def main():
63
63
  print(f"User: {auth_resp.user_info.get('Nombre')}")
64
64
  print(f"Warehouse: {auth_resp.ware_house_info.get('Nombre')}")
65
65
 
66
- # Load initial categories (the client injects loginResponse automatically)
66
+ # Load initial categories (the client injects loginDocGesData + loginResponse automatically)
67
+ # Some DocGes bridge servers expect both fields in requestModel for Content endpoints.
67
68
  cats = await client.get_initial_cats()
68
69
  print(f"Initial categories: {len(cats.CategoriasHijas)}")
69
70
 
@@ -79,6 +80,8 @@ asyncio.run(main())
79
80
 
80
81
  See `docs/quickstart.md` or `examples/quickstart.py` for a more complete example.
81
82
 
83
+ For a working end-to-end demo (login + fetch root categories), see [`examples/initial_categories.py`](examples/initial_categories.py).
84
+
82
85
  ## Development
83
86
 
84
87
  ```bash
@@ -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.3"
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,30 @@ 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
- if self._login_response is not None and "/Content/" in url:
190
- request_model["loginResponse"] = self._login_response
191
-
195
+ if "/Content/" in url:
196
+ # Include original login request data (loginDocGesData) so bridge can reconstruct
197
+ # the DocGesLoginModel (some bridges expect this field).
198
+ request_model["loginDocGesData"] = {
199
+ "username": self.user,
200
+ "password": self.pwd,
201
+ "appID": self.appid,
202
+ }
203
+ if self._login_response is not None:
204
+ request_model["loginResponse"] = self._login_response
205
+
192
206
  # Merge endpoint-specific data
193
207
  if data is not None:
194
208
  request_model.update(data.model_dump(exclude_none=True))
195
-
196
- payload: dict[str, Any] = {"requestModel": request_model}
209
+
210
+ payload = {"requestModel": request_model}
197
211
 
198
212
  last_exc: Exception | None = None
199
213
 
@@ -201,21 +215,22 @@ class AsyncDocGes:
201
215
  try:
202
216
  resp = await client.post(url, json=payload)
203
217
  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")
218
+ # Handle non-JSON responses (e.g., HTML 500 error pages)
208
219
  try:
209
220
  result = resp.json()
210
221
  except Exception as json_err:
211
- raise RequestError(f"Failed to parse JSON: {json_err}. Response text: {text[:200]}")
222
+ # Server returned non-JSON (e.g., HTML 500 error page)
223
+ raise RequestError(
224
+ f"Server returned non-JSON response (status {resp.status_code}): {resp.text[:200]}"
225
+ ) from json_err
212
226
  if result is None:
213
227
  raise RequestError("Server returned null JSON")
214
228
  return result # type: ignore[no-any-return]
215
229
  except (httpx.HTTPStatusError, httpx.RequestError, RequestError) as exc:
216
230
  last_exc = exc
217
231
  if attempt < self.intents:
218
- await asyncio.sleep(self.timeout * attempt)
232
+ # Exponential backoff: 2s, 4s, 8s (capped at 10s)
233
+ await asyncio.sleep(min(2 ** attempt, 10))
219
234
 
220
235
  raise RequestError(
221
236
  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.3
4
4
  Summary: Async, typed Python client for DocGes REST API
5
5
  Author-email: "ct.galega" <soporte@ctgalega.com>
6
6
  License: MIT
@@ -83,7 +83,8 @@ async def main():
83
83
  print(f"User: {auth_resp.user_info.get('Nombre')}")
84
84
  print(f"Warehouse: {auth_resp.ware_house_info.get('Nombre')}")
85
85
 
86
- # Load initial categories (the client injects loginResponse automatically)
86
+ # Load initial categories (the client injects loginDocGesData + loginResponse automatically)
87
+ # Some DocGes bridge servers expect both fields in requestModel for Content endpoints.
87
88
  cats = await client.get_initial_cats()
88
89
  print(f"Initial categories: {len(cats.CategoriasHijas)}")
89
90
 
@@ -99,6 +100,8 @@ asyncio.run(main())
99
100
 
100
101
  See `docs/quickstart.md` or `examples/quickstart.py` for a more complete example.
101
102
 
103
+ For a working end-to-end demo (login + fetch root categories), see [`examples/initial_categories.py`](examples/initial_categories.py).
104
+
102
105
  ## Development
103
106
 
104
107
  ```bash
@@ -16,6 +16,7 @@ src/docges_api_py/models/responses.py
16
16
  tests/test_client_auth.py
17
17
  tests/test_content_methods.py
18
18
  tests/test_endpoints.py
19
+ tests/test_examples.py
19
20
  tests/test_get_document.py
20
21
  tests/test_initial_cats.py
21
22
  tests/test_models_auth.py
@@ -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,121 @@
1
+ """Tests for examples/initial_categories.py — TDD RED → GREEN."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import runpy
6
+ import sys
7
+
8
+ import pytest
9
+ import respx
10
+ import httpx
11
+ import json
12
+
13
+ # Shared fixtures -----------------------------------------------------------------
14
+
15
+ LOGIN_RESPONSE = {
16
+ "userInfo": {"SID": "a6e65fd7-0000-0000-0000-000000000001", "Nombre": "TestUser", "Id": 1},
17
+ "wareHouseInfo": {"SID": "16cf3ed3-0000-0000-0000-000000000002", "Nombre": "devbg"},
18
+ }
19
+
20
+ CATS_RESPONSE = {
21
+ "result": {
22
+ "CategoriasHijas": [
23
+ {"_Nombre": "CatA", "_SID": "cat-a"},
24
+ {"_Nombre": "CatB", "_SID": "cat-b"},
25
+ ],
26
+ "Documentos": [],
27
+ },
28
+ "message": "OK",
29
+ }
30
+
31
+ CATS_EMPTY_RESPONSE = {
32
+ "result": {
33
+ "CategoriasHijas": [],
34
+ "Documentos": [],
35
+ },
36
+ "message": "OK",
37
+ }
38
+
39
+ ENV_VARS = {
40
+ "DOCGES_API_BASE_URL": "http://testserver.local",
41
+ "DOCGES_USER": "testuser",
42
+ "DOCGES_PASSWORD": "testpass",
43
+ "DOCGES_APP_ID": "testapp",
44
+ }
45
+
46
+
47
+ def _run_example(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture) -> str:
48
+ """Run examples/initial_categories.py in-process via runpy and return captured stdout."""
49
+ for k, v in ENV_VARS.items():
50
+ monkeypatch.setenv(k, v)
51
+
52
+ example_path = os.path.join(os.path.dirname(__file__), "..", "examples", "initial_categories.py")
53
+ example_path = os.path.normpath(example_path)
54
+
55
+ # Remove cached module state so re-runs are isolated
56
+ for mod in list(sys.modules.keys()):
57
+ if "initial_categories" in mod:
58
+ del sys.modules[mod]
59
+
60
+ runpy.run_path(example_path, run_name="__main__")
61
+ captured = capsys.readouterr()
62
+ return captured.out
63
+
64
+
65
+ # Tests ---------------------------------------------------------------------------
66
+
67
+
68
+ def test_example_prints_logged_in_user(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture) -> None:
69
+ """Script prints the logged-in user name from auth response."""
70
+ with respx.mock:
71
+ respx.post("http://testserver.local/Auth/Login").respond(json=LOGIN_RESPONSE)
72
+ # Expect the example to send loginDocGesData + loginResponse in requestModel
73
+ def load_ini_cats_handler(request):
74
+ # request.content is bytes
75
+ body = json.loads(request.content.decode())
76
+ rm = body.get("requestModel", {})
77
+ assert "loginDocGesData" in rm
78
+ assert "loginResponse" in rm
79
+ return httpx.Response(200, json=CATS_RESPONSE)
80
+
81
+ respx.post("http://testserver.local/Content/LoadIniCats").mock(side_effect=load_ini_cats_handler)
82
+
83
+ output = _run_example(monkeypatch, capsys)
84
+
85
+ assert "TestUser" in output
86
+
87
+
88
+ def test_example_prints_root_category_count(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture) -> None:
89
+ """Script prints 'Root categories: 2' when 2 categories are returned."""
90
+ with respx.mock:
91
+ respx.post("http://testserver.local/Auth/Login").respond(json=LOGIN_RESPONSE)
92
+ respx.post("http://testserver.local/Content/LoadIniCats").mock(side_effect=lambda req: httpx.Response(200, json=CATS_RESPONSE))
93
+
94
+ output = _run_example(monkeypatch, capsys)
95
+
96
+ assert "Root categories: 2" in output
97
+
98
+
99
+ def test_example_prints_zero_categories_when_empty(
100
+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
101
+ ) -> None:
102
+ """Script prints 'Root categories: 0' when no categories are returned."""
103
+ with respx.mock:
104
+ respx.post("http://testserver.local/Auth/Login").respond(json=LOGIN_RESPONSE)
105
+ respx.post("http://testserver.local/Content/LoadIniCats").mock(side_effect=lambda req: httpx.Response(200, json=CATS_EMPTY_RESPONSE))
106
+
107
+ output = _run_example(monkeypatch, capsys)
108
+
109
+ assert "Root categories: 0" in output
110
+
111
+
112
+ def test_example_exits_when_env_vars_missing(monkeypatch: pytest.MonkeyPatch) -> None:
113
+ """Script raises SystemExit when required environment variables are absent."""
114
+ for k in ENV_VARS:
115
+ monkeypatch.delenv(k, raising=False)
116
+
117
+ example_path = os.path.join(os.path.dirname(__file__), "..", "examples", "initial_categories.py")
118
+ example_path = os.path.normpath(example_path)
119
+
120
+ with pytest.raises(SystemExit):
121
+ runpy.run_path(example_path, run_name="__main__")
@@ -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