uw-api 0.2.2__tar.gz → 0.3.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.
Files changed (39) hide show
  1. {uw_api-0.2.2 → uw_api-0.3.0}/.github/workflows/ci.yml +4 -4
  2. {uw_api-0.2.2 → uw_api-0.3.0}/.github/workflows/release-please.yml +5 -5
  3. uw_api-0.3.0/.release-please-manifest.json +3 -0
  4. {uw_api-0.2.2 → uw_api-0.3.0}/CHANGELOG.md +19 -0
  5. {uw_api-0.2.2 → uw_api-0.3.0}/PKG-INFO +9 -9
  6. {uw_api-0.2.2 → uw_api-0.3.0}/pyproject.toml +8 -8
  7. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/__init__.py +3 -2
  8. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/auth.py +64 -12
  9. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/client.py +50 -9
  10. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/graphql/__init__.py +27 -13
  11. uw_api-0.3.0/tests/test_auth.py +108 -0
  12. {uw_api-0.2.2 → uw_api-0.3.0}/tests/test_client.py +19 -0
  13. uw_api-0.3.0/tests/test_energy.py +88 -0
  14. uw_api-0.3.0/tests/test_session.py +71 -0
  15. uw_api-0.2.2/.release-please-manifest.json +0 -3
  16. {uw_api-0.2.2 → uw_api-0.3.0}/.github/CODEOWNERS +0 -0
  17. {uw_api-0.2.2 → uw_api-0.3.0}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  18. {uw_api-0.2.2 → uw_api-0.3.0}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  19. {uw_api-0.2.2 → uw_api-0.3.0}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  20. {uw_api-0.2.2 → uw_api-0.3.0}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  21. {uw_api-0.2.2 → uw_api-0.3.0}/.github/dependabot.yml +0 -0
  22. {uw_api-0.2.2 → uw_api-0.3.0}/.gitignore +0 -0
  23. {uw_api-0.2.2 → uw_api-0.3.0}/LICENSE +0 -0
  24. {uw_api-0.2.2 → uw_api-0.3.0}/README.md +0 -0
  25. {uw_api-0.2.2 → uw_api-0.3.0}/release-please-config.json +0 -0
  26. {uw_api-0.2.2 → uw_api-0.3.0}/scripts/discover_api.py +0 -0
  27. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/exceptions.py +0 -0
  28. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/graphql/queries.py +0 -0
  29. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/models/__init__.py +0 -0
  30. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/models/account.py +0 -0
  31. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/models/bill.py +0 -0
  32. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/models/energy.py +0 -0
  33. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/models/meter.py +0 -0
  34. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/pdf/__init__.py +0 -0
  35. {uw_api-0.2.2 → uw_api-0.3.0}/src/uw_api/pdf/extractor.py +0 -0
  36. {uw_api-0.2.2 → uw_api-0.3.0}/tests/__init__.py +0 -0
  37. {uw_api-0.2.2 → uw_api-0.3.0}/tests/conftest.py +0 -0
  38. {uw_api-0.2.2 → uw_api-0.3.0}/tests/test_bills.py +0 -0
  39. {uw_api-0.2.2 → uw_api-0.3.0}/tests/test_models.py +0 -0
@@ -23,7 +23,7 @@ jobs:
23
23
  - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
24
24
  with:
25
25
  fetch-depth: 0
26
- - uses: dorny/paths-filter@7b450fff21473bca461d4b92ce414b9d0420d706 # v4.0.2
26
+ - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3
27
27
  id: filter
28
28
  with:
29
29
  filters: |
@@ -112,14 +112,14 @@ jobs:
112
112
 
113
113
  - name: Upload coverage report
114
114
  if: always()
115
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
115
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
116
116
  with:
117
117
  name: coverage-report
118
118
  path: coverage.xml
119
119
 
120
120
  - name: Upload coverage to Codecov
121
121
  if: always()
122
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
122
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
123
123
  with:
124
124
  token: ${{ secrets.CODECOV_TOKEN }}
125
125
  files: coverage.xml
@@ -127,7 +127,7 @@ jobs:
127
127
 
128
128
  - name: Upload test results to Codecov
129
129
  if: ${{ !cancelled() }}
130
- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
130
+ uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1
131
131
  with:
132
132
  token: ${{ secrets.CODECOV_TOKEN }}
133
133
  report_type: test_results
@@ -33,8 +33,8 @@ jobs:
33
33
  runs-on: ubuntu-latest
34
34
  timeout-minutes: 10
35
35
  steps:
36
- - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
37
- - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0
36
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
37
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
38
38
  with:
39
39
  python-version: "3.13"
40
40
  - name: Install build tools
@@ -42,7 +42,7 @@ jobs:
42
42
  - name: Build distributions
43
43
  run: python -m build
44
44
  - name: Upload distributions
45
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
45
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
46
46
  with:
47
47
  name: release-dists
48
48
  path: dist/
@@ -59,11 +59,11 @@ jobs:
59
59
  id-token: write
60
60
  steps:
61
61
  - name: Retrieve release distributions
62
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
62
+ uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
63
63
  with:
64
64
  name: release-dists
65
65
  path: dist/
66
66
  - name: Publish release distributions to PyPI
67
- uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # v1.14.0
67
+ uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2
68
68
  with:
69
69
  packages-dir: dist/
@@ -0,0 +1,3 @@
1
+ {
2
+ ".": "0.3.0"
3
+ }
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.0](https://github.com/KRoperUK/uw-py/compare/v0.2.2...v0.3.0) (2026-11-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * support authentication with imported session cookies ([a00e9a1](https://github.com/KRoperUK/uw-py/commit/a00e9a1760487eb0ae2365d8618e9fd0d7ebb529))
9
+ * support authentication with imported session cookies ([71c5034](https://github.com/KRoperUK/uw-py/commit/71c5034aded9765f9102e537ec9a4b4788c99481))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * follow OAuth redirect chain to reach login page ([37a81b5](https://github.com/KRoperUK/uw-py/commit/37a81b5619b7eb7b07505c677e80b4711256cf7b))
15
+ * recognise a completed login and surface portal auth errors ([274c8c1](https://github.com/KRoperUK/uw-py/commit/274c8c1a9977ff2efb3545892d80315a51365011))
16
+ * recognise a completed login and surface portal auth errors ([07f29ba](https://github.com/KRoperUK/uw-py/commit/07f29ba12153af133215a78ede071887e760fa71))
17
+ * send the portal's _csrf cookie as the GraphQL CSRF token ([a8b220f](https://github.com/KRoperUK/uw-py/commit/a8b220fe0cef385695771ebb432ace27b51cc43e))
18
+ * send the portal's _csrf cookie as the GraphQL CSRF token ([12d1af0](https://github.com/KRoperUK/uw-py/commit/12d1af0f5d5d9a1d571a17d2dc5bb8646bb27f2e))
19
+ * sum register readings when the portal returns a list ([df22096](https://github.com/KRoperUK/uw-py/commit/df22096c729da8dfe20436423723132da19d0fcd))
20
+ * wrap the redirect URL line to satisfy the 100-column limit ([#13](https://github.com/KRoperUK/uw-py/issues/13)) ([5a4a739](https://github.com/KRoperUK/uw-py/commit/5a4a7393ac919f6c1054bfc57005fdf97873c5ab))
21
+
3
22
  ## [0.2.2](https://github.com/KRoperUK/uw-py/compare/v0.2.1...v0.2.2) (2026-07-24)
4
23
 
5
24
 
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: uw-api
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: Async Python client for the Utility Warehouse customer portal API
5
5
  Author-email: Kieran <kieran@example.com>
6
6
  License: MIT
@@ -14,17 +14,17 @@ Classifier: Programming Language :: Python :: 3.11
14
14
  Classifier: Programming Language :: Python :: 3.12
15
15
  Classifier: Programming Language :: Python :: 3.13
16
16
  Requires-Python: >=3.11
17
- Requires-Dist: httpx>=0.27.0
18
- Requires-Dist: pydantic>=2.0
17
+ Requires-Dist: httpx>=0.28.1
18
+ Requires-Dist: pydantic>=2.14.2
19
19
  Provides-Extra: dev
20
- Requires-Dist: mypy>=2.3.0; extra == 'dev'
21
- Requires-Dist: pdfplumber>=0.11.0; extra == 'dev'
22
- Requires-Dist: pytest-asyncio>=1.4.0; extra == 'dev'
20
+ Requires-Dist: mypy>=2.4.1; extra == 'dev'
21
+ Requires-Dist: pdfplumber>=0.11.10; extra == 'dev'
22
+ Requires-Dist: pytest-asyncio>=1.4.1.post1; extra == 'dev'
23
23
  Requires-Dist: pytest-cov>=7.1.0; extra == 'dev'
24
24
  Requires-Dist: pytest-httpx>=0.36.2; extra == 'dev'
25
25
  Requires-Dist: pytest-xdist>=3.8.0; extra == 'dev'
26
- Requires-Dist: pytest>=9.1.1; extra == 'dev'
27
- Requires-Dist: ruff>=0.16.0; extra == 'dev'
26
+ Requires-Dist: pytest>=9.2.0; extra == 'dev'
27
+ Requires-Dist: ruff>=0.17.3; extra == 'dev'
28
28
  Description-Content-Type: text/markdown
29
29
 
30
30
  # uw-api
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "uw-api"
7
- version = "0.2.2"
7
+ version = "0.3.0"
8
8
  description = "Async Python client for the Utility Warehouse customer portal API"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -24,20 +24,20 @@ classifiers = [
24
24
  ]
25
25
 
26
26
  dependencies = [
27
- "httpx>=0.27.0",
28
- "pydantic>=2.0",
27
+ "httpx>=0.28.1",
28
+ "pydantic>=2.14.2",
29
29
  ]
30
30
 
31
31
  [project.optional-dependencies]
32
32
  dev = [
33
- "pdfplumber>=0.11.0",
34
- "pytest>=9.1.1",
35
- "pytest-asyncio>=1.4.0",
33
+ "pdfplumber>=0.11.10",
34
+ "pytest>=9.2.0",
35
+ "pytest-asyncio>=1.4.1.post1",
36
36
  "pytest-cov>=7.1.0",
37
37
  "pytest-httpx>=0.36.2",
38
38
  "pytest-xdist>=3.8.0",
39
- "ruff>=0.16.0",
40
- "mypy>=2.3.0",
39
+ "ruff>=0.17.3",
40
+ "mypy>=2.4.1",
41
41
  ]
42
42
 
43
43
  [tool.ruff]
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from uw_api.client import UWClient
3
+ from uw_api.client import UWClient, parse_cookie_string
4
4
  from uw_api.exceptions import (
5
5
  UWApiError,
6
6
  UWAuthError,
@@ -10,7 +10,7 @@ from uw_api.exceptions import (
10
10
  UWSessionExpiredError,
11
11
  )
12
12
 
13
- __version__ = "0.2.2"
13
+ __version__ = "0.3.0"
14
14
  __all__ = [
15
15
  "UWApiError",
16
16
  "UWAuthError",
@@ -20,4 +20,5 @@ __all__ = [
20
20
  "UWRateLimitError",
21
21
  "UWSessionExpiredError",
22
22
  "__version__",
23
+ "parse_cookie_string",
23
24
  ]
@@ -6,11 +6,12 @@ import logging
6
6
  import re
7
7
  import secrets
8
8
  import time
9
- from urllib.parse import urlparse
9
+ from collections.abc import Mapping
10
+ from urllib.parse import urljoin, urlparse
10
11
 
11
12
  import httpx
12
13
 
13
- from uw_api.exceptions import UWAuthError
14
+ from uw_api.exceptions import UWAuthError, UWSessionExpiredError
14
15
 
15
16
  _LOGGER = logging.getLogger(__name__)
16
17
 
@@ -18,6 +19,9 @@ _LOGIN_BASE = "https://account.uw.co.uk"
18
19
  _LOGIN_PAGE = f"{_LOGIN_BASE}/v2/login"
19
20
  _GRAPHQL_URL = "https://myaccount.uw.co.uk/server/graphql"
20
21
  _REDIRECT_HOST = "myaccount.uw.co.uk"
22
+ _CSRF_COOKIE = "_csrf"
23
+ _SESSION_COOKIES = ("uw-user-session", "uw-access-token")
24
+ _COOKIE_DOMAIN = ".uw.co.uk"
21
25
 
22
26
 
23
27
  def _b64url(data: bytes) -> str:
@@ -36,6 +40,7 @@ class UWAuth:
36
40
  graphql_url: str = _GRAPHQL_URL,
37
41
  max_retries: int = 3,
38
42
  backoff_base: float = 1.0,
43
+ session_cookies: Mapping[str, str] | None = None,
39
44
  ) -> None:
40
45
  self._client = client
41
46
  self._email = email
@@ -47,14 +52,31 @@ class UWAuth:
47
52
 
48
53
  self._session_expires_at: float = 0.0
49
54
  self._authenticated = False
55
+ self._session_mode = session_cookies is not None
56
+ if session_cookies is not None:
57
+ self._load_session(session_cookies)
58
+
59
+ def _load_session(self, cookies: Mapping[str, str]) -> None:
60
+ if not cookies.get(_CSRF_COOKIE):
61
+ raise UWAuthError("Session cookies must include the _csrf cookie")
62
+ if not any(cookies.get(name) for name in _SESSION_COOKIES):
63
+ raise UWAuthError("Session cookies must include one of: " + ", ".join(_SESSION_COOKIES))
64
+ for name, value in cookies.items():
65
+ self._client.cookies.set(name, value, domain=_COOKIE_DOMAIN)
66
+ self._authenticated = True
67
+ self._session_expires_at = float("inf")
50
68
 
51
69
  @property
52
70
  def is_authenticated(self) -> bool:
53
71
  return self._authenticated and time.monotonic() < self._session_expires_at
54
72
 
73
+ @property
74
+ def can_reauthenticate(self) -> bool:
75
+ return not self._session_mode
76
+
55
77
  @property
56
78
  def csrf_token(self) -> str | None:
57
- return None
79
+ return self._client.cookies.get(_CSRF_COOKIE)
58
80
 
59
81
  @property
60
82
  def graphql_url(self) -> str:
@@ -89,11 +111,23 @@ class UWAuth:
89
111
  return code_verifier, code_challenge
90
112
 
91
113
  async def _fetch_login_page(self) -> httpx.Response:
92
- response = await self._client.get(self._login_page)
93
- response.raise_for_status()
94
- return response
114
+ url = "https://myaccount.uw.co.uk/"
115
+ for _ in range(5):
116
+ response = await self._client.get(url)
117
+ if response.status_code == 200:
118
+ return response
119
+ location = response.headers.get("Location", "")
120
+ if not location:
121
+ break
122
+ url = location if location.startswith("http") else urljoin(str(response.url), location)
123
+ raise UWAuthError("Could not reach UW login page")
95
124
 
96
125
  async def login(self) -> None:
126
+ if self._session_mode:
127
+ raise UWAuthError(
128
+ "Password login is not available to a session-cookie client; "
129
+ "import fresh cookies instead"
130
+ )
97
131
  code_verifier, code_challenge = self._generate_pkce()
98
132
 
99
133
  for attempt in range(self._max_retries):
@@ -140,16 +174,21 @@ class UWAuth:
140
174
 
141
175
  if response.is_redirect or response.status_code in (302, 303):
142
176
  await self._follow_redirects(response, code_verifier, code_challenge)
143
- self._authenticated = True
144
- self._session_expires_at = time.monotonic() + 3600
177
+ self._mark_authenticated()
145
178
  return
146
179
 
147
180
  if response.status_code >= 500:
148
181
  await asyncio.sleep(self._backoff_base * (2**attempt))
149
182
  continue
150
183
 
151
- page_text = response.text
152
- error = self._extract_error(page_text)
184
+ # An auto-following client (UWClient's own default) has already
185
+ # walked the OAuth redirect chain. A 200 that no longer shows the
186
+ # login form is a completed login; one that does is a rejection.
187
+ if response.status_code == 200 and "login-form" not in response.text:
188
+ self._mark_authenticated()
189
+ return
190
+
191
+ error = self._extract_error(response.text)
153
192
  if error:
154
193
  raise UWAuthError(error)
155
194
  raise UWAuthError(f"Unexpected login response: {response.status_code}")
@@ -195,6 +234,14 @@ class UWAuth:
195
234
  if redirect_response.is_redirect or redirect_response.status_code in (302, 303):
196
235
  await self._follow_redirects(redirect_response, code_verifier, code_challenge)
197
236
 
237
+ def _mark_authenticated(self) -> None:
238
+ if not any(self._client.cookies.get(name) for name in _SESSION_COOKIES):
239
+ raise UWAuthError(
240
+ "Login did not complete — the UW portal did not issue a session cookie"
241
+ )
242
+ self._authenticated = True
243
+ self._session_expires_at = time.monotonic() + 3600
244
+
198
245
  def _extract_error(self, text: str) -> str | None:
199
246
  patterns = [
200
247
  r'class="[^"]*error[^"]*"[^>]*>([^<]+)<',
@@ -208,9 +255,14 @@ class UWAuth:
208
255
  return None
209
256
 
210
257
  async def ensure_authenticated(self) -> None:
211
- if not self.is_authenticated:
212
- await self.login()
258
+ if self.is_authenticated:
259
+ return
260
+ if self._session_mode:
261
+ raise UWSessionExpiredError("UW session cookies have expired; import fresh ones")
262
+ await self.login()
213
263
 
214
264
  async def re_auth(self) -> None:
265
+ if self._session_mode:
266
+ raise UWSessionExpiredError("UW session cookies have expired; import fresh ones")
215
267
  self._authenticated = False
216
268
  await self.login()
@@ -2,32 +2,48 @@ from __future__ import annotations
2
2
 
3
3
  import asyncio
4
4
  import logging
5
+ from collections.abc import Mapping
5
6
  from typing import Any
6
7
 
7
8
  import httpx
8
9
 
9
10
  from uw_api.auth import UWAuth
10
- from uw_api.exceptions import UWApiError, UWRateLimitError
11
+ from uw_api.exceptions import UWApiError, UWRateLimitError, UWSessionExpiredError
11
12
  from uw_api.graphql import UWGraphQL
12
13
 
13
14
  _LOGGER = logging.getLogger(__name__)
14
15
 
15
16
 
17
+ def parse_cookie_string(raw: str) -> dict[str, str]:
18
+ """Split a browser `Cookie:` header into name/value pairs."""
19
+ cookies: dict[str, str] = {}
20
+ for part in raw.split(";"):
21
+ name, separator, value = part.strip().partition("=")
22
+ if name and separator:
23
+ cookies[name.strip()] = value.strip()
24
+ return cookies
25
+
26
+
16
27
  class UWClient:
17
28
  def __init__(
18
29
  self,
19
- email: str,
20
- password: str,
30
+ email: str | None = None,
31
+ password: str | None = None,
21
32
  timeout: float = 30.0,
22
33
  max_retries: int = 3,
23
34
  backoff_base: float = 1.0,
24
35
  http_client: httpx.AsyncClient | None = None,
36
+ session_cookies: Mapping[str, str] | None = None,
25
37
  ) -> None:
26
- self._email = email
27
- self._password = password
38
+ if session_cookies is None and (email is None or password is None):
39
+ raise ValueError("Provide either email/password or session_cookies")
40
+
41
+ self._email = email or ""
42
+ self._password = password or ""
28
43
  self._timeout = timeout
29
44
  self._max_retries = max_retries
30
45
  self._backoff_base = backoff_base
46
+ self._session_cookies = session_cookies
31
47
 
32
48
  self._owns_client = http_client is None
33
49
  self._http_client = http_client
@@ -35,6 +51,25 @@ class UWClient:
35
51
  self._auth_obj: UWAuth | None = None
36
52
  self._gql_obj: UWGraphQL | None = None
37
53
 
54
+ @classmethod
55
+ def from_session(
56
+ cls,
57
+ cookie_string: str,
58
+ *,
59
+ timeout: float = 30.0,
60
+ max_retries: int = 3,
61
+ backoff_base: float = 1.0,
62
+ http_client: httpx.AsyncClient | None = None,
63
+ ) -> UWClient:
64
+ """Build a client from a browser `Cookie:` header instead of a password."""
65
+ return cls(
66
+ timeout=timeout,
67
+ max_retries=max_retries,
68
+ backoff_base=backoff_base,
69
+ http_client=http_client,
70
+ session_cookies=parse_cookie_string(cookie_string),
71
+ )
72
+
38
73
  def _ensure_client(self) -> None:
39
74
  if self._auth_obj is not None:
40
75
  return
@@ -50,6 +85,7 @@ class UWClient:
50
85
  password=self._password,
51
86
  max_retries=self._max_retries,
52
87
  backoff_base=self._backoff_base,
88
+ session_cookies=self._session_cookies,
53
89
  )
54
90
  self._gql_obj = UWGraphQL(self, self._http_client)
55
91
 
@@ -70,6 +106,13 @@ class UWClient:
70
106
  assert self._auth_obj is not None
71
107
  await self._auth_obj.login()
72
108
 
109
+ async def _handle_unauthorized(self) -> None:
110
+ assert self._auth_obj is not None
111
+ if not self._auth_obj.can_reauthenticate:
112
+ raise UWSessionExpiredError("UW session has expired; import fresh browser cookies")
113
+ _LOGGER.warning("Session expired, re-authenticating")
114
+ await self._auth_obj.re_auth()
115
+
73
116
  async def close(self) -> None:
74
117
  if self._owns_client and self._http_client is not None:
75
118
  await self._http_client.aclose()
@@ -110,8 +153,7 @@ class UWClient:
110
153
  )
111
154
 
112
155
  if response.status_code == 401:
113
- _LOGGER.warning("Session expired, re-authenticating")
114
- await self._auth_obj.re_auth()
156
+ await self._handle_unauthorized()
115
157
  continue
116
158
 
117
159
  if response.status_code == 429:
@@ -149,8 +191,7 @@ class UWClient:
149
191
  raise
150
192
  except httpx.HTTPStatusError as exc:
151
193
  if exc.response.status_code == 401:
152
- _LOGGER.warning("Session expired, re-authenticating")
153
- await self._auth_obj.re_auth()
194
+ await self._handle_unauthorized()
154
195
  continue
155
196
  if exc.response.status_code == 429:
156
197
  retry_after = int(
@@ -23,6 +23,22 @@ if TYPE_CHECKING:
23
23
  from uw_api.client import UWClient
24
24
 
25
25
 
26
+ def register_value(register_reading: object) -> float | None:
27
+ """Total kWh across a read's register readings.
28
+
29
+ The portal returns one entry per register (e.g. Day and Night on an
30
+ Economy 7 meter), so a read can carry several values.
31
+ """
32
+ if isinstance(register_reading, dict):
33
+ entries: list[dict[str, Any]] = [register_reading]
34
+ elif isinstance(register_reading, list):
35
+ entries = [entry for entry in register_reading if isinstance(entry, dict)]
36
+ else:
37
+ return None
38
+ values = [float(entry["value"]) for entry in entries if entry.get("value") is not None]
39
+ return sum(values) if values else None
40
+
41
+
26
42
  class UWGraphQL:
27
43
  def __init__(self, client: UWClient, http_client: httpx.AsyncClient) -> None:
28
44
  self._client = client
@@ -56,24 +72,23 @@ class UWGraphQL:
56
72
  total_kwh: float = 0.0
57
73
 
58
74
  if latest:
59
- rr = latest.get("registerReading", {})
60
- if rr:
75
+ value = register_value(latest.get("registerReading"))
76
+ if value is not None:
61
77
  read_date = latest.get("readDate", "")
62
78
  dt = (
63
79
  datetime.fromisoformat(read_date.replace("Z", "+00:00"))
64
80
  if read_date
65
81
  else datetime.now(tz=UTC)
66
82
  )
67
- val = float(rr.get("value", 0))
68
83
  readings.append(
69
84
  UsageReading(
70
85
  date=dt,
71
- value=val,
86
+ value=value,
72
87
  unit="kWh",
73
88
  reading_type=("estimated" if latest.get("isEstimated") else "actual"),
74
89
  )
75
90
  )
76
- total_kwh = val
91
+ total_kwh = value
77
92
 
78
93
  results.append(
79
94
  EnergyUsage(
@@ -95,10 +110,9 @@ class UWGraphQL:
95
110
 
96
111
  for svc in services:
97
112
  fuel = svc.get("fuelType", "").upper()
98
- meter = svc.get("meterpoint", {}).get("installedMeter", {})
99
- latest = meter.get("reads", {}).get("latestRead", {})
100
- rr = latest.get("registerReading", {})
101
- val = float(rr.get("value", 0)) if rr.get("value") else 0.0
113
+ meter = svc.get("meterpoint", {}).get("installedMeter", {}) or {}
114
+ latest = meter.get("reads", {}).get("latestRead") or {}
115
+ val = register_value(latest.get("registerReading")) or 0.0
102
116
 
103
117
  if fuel == "ELECTRICITY":
104
118
  elec_kwh = val
@@ -122,7 +136,7 @@ class UWGraphQL:
122
136
 
123
137
  meter_type = MeterType.ELECTRICITY if fuel == "ELECTRICITY" else MeterType.GAS
124
138
 
125
- latest = meter.get("reads", {}).get("latestRead", {})
139
+ latest = meter.get("reads", {}).get("latestRead") or {}
126
140
  read_date_str = latest.get("readDate")
127
141
  read_date = None
128
142
  if read_date_str:
@@ -151,8 +165,8 @@ class UWGraphQL:
151
165
  for read in [latest, actual_read]:
152
166
  if not read or not read.get("id"):
153
167
  continue
154
- rr = read.get("registerReading", {})
155
- if not rr.get("value"):
168
+ value = register_value(read.get("registerReading"))
169
+ if value is None:
156
170
  continue
157
171
  read_date_str = read.get("readDate", "")
158
172
  read_date = (
@@ -166,7 +180,7 @@ class UWGraphQL:
166
180
  reading_id=read.get("id"),
167
181
  meter_id=meter.get("id", ""),
168
182
  reading_date=read_date,
169
- value=float(rr.get("value", 0)),
183
+ value=value,
170
184
  unit="kWh",
171
185
  reading_type=("estimated" if read.get("isEstimated") else "actual"),
172
186
  source=read.get("source", "customer"),
@@ -0,0 +1,108 @@
1
+ from __future__ import annotations
2
+
3
+ import httpx
4
+ import pytest
5
+
6
+ from uw_api.auth import UWAuth
7
+ from uw_api.exceptions import UWAuthError
8
+
9
+ CHALLENGE = "challenge-abc"
10
+ CSRF = "csrf-xyz"
11
+ LOGIN_PAGE_URL = "https://account.uw.co.uk/v2/login"
12
+ CALLBACK_URL = "https://myaccount.uw.co.uk/login/callback?code=one-time-code"
13
+ INVALID_CREDENTIALS = "Oops, invalid credentials. Please try again."
14
+
15
+
16
+ def _login_html(*, error: str | None = None) -> str:
17
+ error_markup = f'<div class="form__error">{error}</div>' if error else ""
18
+ return (
19
+ "<html><body>"
20
+ '<form id="login-form" name="login-form" method="POST" action="/v2/login">'
21
+ f'<input type="hidden" name="login_challenge" value="{CHALLENGE}" />'
22
+ f'<input type="hidden" name="_csrf" value="{CSRF}" />'
23
+ "</form>"
24
+ f"{error_markup}"
25
+ "</body></html>"
26
+ )
27
+
28
+
29
+ def _register_login_page(httpx_mock, *, login_html: str) -> None:
30
+ httpx_mock.add_response(
31
+ url="https://myaccount.uw.co.uk/",
32
+ status_code=302,
33
+ headers={"Location": "/login"},
34
+ )
35
+ httpx_mock.add_response(
36
+ url="https://myaccount.uw.co.uk/login",
37
+ status_code=302,
38
+ headers={"Location": f"{LOGIN_PAGE_URL}?login_challenge={CHALLENGE}"},
39
+ )
40
+ httpx_mock.add_response(
41
+ url=f"{LOGIN_PAGE_URL}?login_challenge={CHALLENGE}",
42
+ status_code=200,
43
+ text=login_html,
44
+ )
45
+
46
+
47
+ def _register_successful_submit(httpx_mock, *, session_cookie: bool = True) -> None:
48
+ httpx_mock.add_response(
49
+ method="POST",
50
+ url=LOGIN_PAGE_URL,
51
+ status_code=302,
52
+ headers={"Location": CALLBACK_URL},
53
+ )
54
+ headers = {"set-cookie": "uw-access-token=session-token; Path=/"} if session_cookie else {}
55
+ httpx_mock.add_response(
56
+ url=CALLBACK_URL,
57
+ status_code=200,
58
+ text="<html>dashboard</html>",
59
+ headers=headers,
60
+ )
61
+
62
+
63
+ def _auth(client: httpx.AsyncClient) -> UWAuth:
64
+ return UWAuth(client, email="user@example.com", password="secret")
65
+
66
+
67
+ class TestLogin:
68
+ async def test_success_when_client_follows_redirects(self, httpx_mock) -> None:
69
+ _register_login_page(httpx_mock, login_html=_login_html())
70
+ _register_successful_submit(httpx_mock)
71
+ async with httpx.AsyncClient(follow_redirects=True) as http:
72
+ auth = _auth(http)
73
+ await auth.login()
74
+ assert auth.is_authenticated
75
+
76
+ async def test_success_when_client_does_not_follow_redirects(self, httpx_mock) -> None:
77
+ _register_login_page(httpx_mock, login_html=_login_html())
78
+ _register_successful_submit(httpx_mock)
79
+ async with httpx.AsyncClient(follow_redirects=False) as http:
80
+ auth = _auth(http)
81
+ await auth.login()
82
+ assert auth.is_authenticated
83
+
84
+ async def test_rejected_credentials_surface_portal_message(self, httpx_mock) -> None:
85
+ rejected = _login_html(error=INVALID_CREDENTIALS)
86
+ _register_login_page(httpx_mock, login_html=_login_html())
87
+ httpx_mock.add_response(method="POST", url=LOGIN_PAGE_URL, status_code=200, text=rejected)
88
+ async with httpx.AsyncClient(follow_redirects=True) as http:
89
+ auth = _auth(http)
90
+ with pytest.raises(UWAuthError, match="invalid credentials"):
91
+ await auth.login()
92
+
93
+ async def test_missing_session_cookie_is_not_success(self, httpx_mock) -> None:
94
+ _register_login_page(httpx_mock, login_html=_login_html())
95
+ _register_successful_submit(httpx_mock, session_cookie=False)
96
+ async with httpx.AsyncClient(follow_redirects=True) as http:
97
+ auth = _auth(http)
98
+ with pytest.raises(UWAuthError, match="session cookie"):
99
+ await auth.login()
100
+
101
+ async def test_missing_csrf_raises(self, httpx_mock) -> None:
102
+ httpx_mock.add_response(
103
+ url="https://myaccount.uw.co.uk/", status_code=200, text="<html></html>"
104
+ )
105
+ async with httpx.AsyncClient(follow_redirects=True) as http:
106
+ auth = _auth(http)
107
+ with pytest.raises(UWAuthError, match="CSRF"):
108
+ await auth.login()
@@ -74,6 +74,25 @@ class TestGraphQL:
74
74
  assert account.account_id == "acc-uuid-123"
75
75
  assert account.account_number == "12345678"
76
76
 
77
+ async def test_graphql_sends_csrf_cookie(self, httpx_mock, graphql_account: dict) -> None:
78
+ httpx_mock.add_response(
79
+ method="POST",
80
+ url="https://myaccount.uw.co.uk/server/graphql",
81
+ json=graphql_account,
82
+ status_code=200,
83
+ )
84
+
85
+ async with UWClient(email="test@example.com", password="secret") as client:
86
+ _mock_authenticated(client)
87
+ assert client._auth_obj is not None
88
+ client._auth_obj._client.cookies.set(
89
+ "_csrf", "csrf-cookie-value", domain="myaccount.uw.co.uk"
90
+ )
91
+ await client.gql.get_account()
92
+
93
+ request = httpx_mock.get_requests()[0]
94
+ assert request.headers["x-csrf-token"] == "csrf-cookie-value"
95
+
77
96
  async def test_get_bills(self, httpx_mock, graphql_bills: dict) -> None:
78
97
  httpx_mock.add_response(
79
98
  method="POST",
@@ -0,0 +1,88 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from uw_api.graphql import UWGraphQL, register_value
6
+
7
+
8
+ class _StubClient:
9
+ def __init__(self, payload: dict[str, Any]) -> None:
10
+ self._payload = payload
11
+
12
+ async def graphql_request(
13
+ self, operation_name: str, query: str, variables: dict[str, Any] | None = None
14
+ ) -> dict[str, Any]:
15
+ return self._payload
16
+
17
+
18
+ def _service(fuel: str, registers: list[dict[str, Any]]) -> dict[str, Any]:
19
+ return {
20
+ "id": f"{fuel.lower()}-service",
21
+ "fuelType": fuel,
22
+ "isLive": True,
23
+ "meterpoint": {
24
+ "installedMeter": {
25
+ "id": f"{fuel.lower()}-meter",
26
+ "isSmart": True,
27
+ "serialNumber": "E6S123",
28
+ "reads": {
29
+ "latestRead": {
30
+ "id": f"{fuel.lower()}-read",
31
+ "isEstimated": False,
32
+ "readDate": "2026-11-01T00:00:00Z",
33
+ "source": "smart",
34
+ "registerReading": registers,
35
+ }
36
+ },
37
+ }
38
+ },
39
+ }
40
+
41
+
42
+ def test_register_value_sums_a_register_list() -> None:
43
+ registers = [{"value": 2404}, {"value": 23863}]
44
+ assert register_value(registers) == 26267
45
+
46
+
47
+ def test_register_value_accepts_a_single_register() -> None:
48
+ assert register_value({"value": 1750}) == 1750
49
+
50
+
51
+ def test_register_value_ignores_missing_values() -> None:
52
+ assert register_value([]) is None
53
+ assert register_value([{"value": None}, {"value": 10}]) == 10
54
+ assert register_value(None) is None
55
+
56
+
57
+ async def test_get_consumption_sums_register_readings() -> None:
58
+ payload = {
59
+ "account": {
60
+ "energy": {
61
+ "services": [
62
+ _service("ELECTRICITY", [{"value": 2404}, {"value": 23863}]),
63
+ _service("GAS", [{"value": 900}]),
64
+ ]
65
+ }
66
+ }
67
+ }
68
+ gql = UWGraphQL(_StubClient(payload), http_client=None) # type: ignore[arg-type]
69
+
70
+ consumption = await gql.get_consumption()
71
+
72
+ assert consumption is not None
73
+ assert consumption.electricity_kwh == 26267
74
+ assert consumption.gas_kwh == 900
75
+
76
+
77
+ async def test_get_meter_readings_sums_register_readings() -> None:
78
+ payload = {
79
+ "account": {
80
+ "energy": {"services": [_service("ELECTRICITY", [{"value": 10}, {"value": 32}])]}
81
+ }
82
+ }
83
+ gql = UWGraphQL(_StubClient(payload), http_client=None) # type: ignore[arg-type]
84
+
85
+ readings = await gql.get_meter_readings()
86
+
87
+ assert len(readings) == 1
88
+ assert readings[0].value == 42
@@ -0,0 +1,71 @@
1
+ from __future__ import annotations
2
+
3
+ import pytest
4
+
5
+ from uw_api import UWClient, parse_cookie_string
6
+ from uw_api.exceptions import UWAuthError, UWSessionExpiredError
7
+
8
+ GRAPHQL_URL = "https://myaccount.uw.co.uk/server/graphql"
9
+ ACCOUNT_RESPONSE = {
10
+ "data": {
11
+ "account": {
12
+ "id": "acc-uuid-123",
13
+ "number": "12345678",
14
+ "__typename": "Account",
15
+ }
16
+ }
17
+ }
18
+ SESSION = "_csrf=csrf-value; uw-user-session=session-value; uw_exp_uid=abc"
19
+
20
+
21
+ def test_parse_cookie_string() -> None:
22
+ assert parse_cookie_string(SESSION) == {
23
+ "_csrf": "csrf-value",
24
+ "uw-user-session": "session-value",
25
+ "uw_exp_uid": "abc",
26
+ }
27
+
28
+
29
+ def test_password_client_still_requires_credentials() -> None:
30
+ with pytest.raises(ValueError, match="session_cookies"):
31
+ UWClient()
32
+
33
+
34
+ async def test_session_client_sends_csrf_and_skips_login(httpx_mock) -> None:
35
+ httpx_mock.add_response(method="POST", url=GRAPHQL_URL, json=ACCOUNT_RESPONSE)
36
+
37
+ async with UWClient.from_session(SESSION) as client:
38
+ account = await client.gql.get_account()
39
+
40
+ assert account.account_number == "12345678"
41
+ requests = httpx_mock.get_requests()
42
+ assert len(requests) == 1
43
+ assert requests[0].headers["x-csrf-token"] == "csrf-value"
44
+
45
+
46
+ async def test_session_requires_csrf_cookie(httpx_mock) -> None:
47
+ async with UWClient.from_session("uw-user-session=session-value") as client:
48
+ with pytest.raises(UWAuthError, match="_csrf"):
49
+ client._ensure_client()
50
+
51
+
52
+ async def test_session_requires_session_cookie(httpx_mock) -> None:
53
+ async with UWClient.from_session("_csrf=csrf-value") as client:
54
+ with pytest.raises(UWAuthError, match="uw-user-session"):
55
+ client._ensure_client()
56
+
57
+
58
+ async def test_expired_session_does_not_attempt_login(httpx_mock) -> None:
59
+ httpx_mock.add_response(method="POST", url=GRAPHQL_URL, status_code=401, json={})
60
+
61
+ async with UWClient.from_session(SESSION) as client:
62
+ with pytest.raises(UWSessionExpiredError, match="import fresh"):
63
+ await client.gql.get_account()
64
+
65
+ assert len(httpx_mock.get_requests()) == 1
66
+
67
+
68
+ async def test_login_unavailable_in_session_mode(httpx_mock) -> None:
69
+ async with UWClient.from_session(SESSION) as client:
70
+ with pytest.raises(UWAuthError, match="not available"):
71
+ await client.login()
@@ -1,3 +0,0 @@
1
- {
2
- ".": "0.2.2"
3
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes