switch2 0.1.0__tar.gz → 0.1.1__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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: switch2
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Async client library for the Switch2 energy portal
5
5
  Author-email: Jelmer Vernooij <jelmer@jelmer.uk>
6
6
  License-Expression: Apache-2.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "switch2"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "Async client library for the Switch2 energy portal"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -2,6 +2,8 @@
2
2
 
3
3
  from .api import (
4
4
  Bill,
5
+ BillCharge,
6
+ BillDetail,
5
7
  CustomerInfo,
6
8
  MeterReading,
7
9
  Switch2ApiClient,
@@ -12,6 +14,8 @@ from .api import (
12
14
 
13
15
  __all__ = [
14
16
  "Bill",
17
+ "BillCharge",
18
+ "BillDetail",
15
19
  "CustomerInfo",
16
20
  "MeterReading",
17
21
  "Switch2ApiClient",
@@ -53,6 +53,34 @@ class Bill:
53
53
  detail_url: str
54
54
 
55
55
 
56
+ @dataclass
57
+ class BillCharge:
58
+ """A single line item on a bill."""
59
+
60
+ description: str
61
+ units: str
62
+ charge: float
63
+
64
+
65
+ @dataclass
66
+ class BillDetail:
67
+ """Detailed breakdown of a bill."""
68
+
69
+ invoice_number: str
70
+ date_of_issue: datetime
71
+ period_from: datetime
72
+ period_to: datetime
73
+ consumption_charges: list[BillCharge]
74
+ other_charges: list[BillCharge]
75
+ total_excl_vat: float
76
+ vat: float
77
+ total: float
78
+ previous_balance: float
79
+ payments_received: float
80
+ balance: float
81
+ download_url: str
82
+
83
+
56
84
  @dataclass
57
85
  class Switch2Data:
58
86
  """All data fetched from the Switch2 portal."""
@@ -67,8 +95,8 @@ def _get_attr(tag: Tag, attr: str, default: str = "") -> str:
67
95
  """Get a string attribute from a BeautifulSoup tag, handling list values."""
68
96
  value = tag.get(attr, default)
69
97
  if isinstance(value, list):
70
- return value[0] if value else default
71
- return value
98
+ return str(value[0]) if value else default
99
+ return str(value) if value is not None else default
72
100
 
73
101
 
74
102
  class Switch2ApiClient:
@@ -135,6 +163,27 @@ class Switch2ApiClient:
135
163
  f"Connection error during login: {err}"
136
164
  ) from err
137
165
 
166
+ async def fetch_bill_detail(self, bill: Bill) -> BillDetail:
167
+ """Fetch and parse the detail page for a bill.
168
+
169
+ The caller must be authenticated before calling this method.
170
+ """
171
+ if not bill.detail_url:
172
+ raise ValueError("Bill has no detail URL")
173
+ session = await self._ensure_session()
174
+ try:
175
+ async with session.get(bill.detail_url) as resp:
176
+ if resp.status != 200:
177
+ raise Switch2ConnectionError(
178
+ f"Failed to load bill detail: HTTP {resp.status}"
179
+ )
180
+ html = await resp.text()
181
+ except aiohttp.ClientError as err:
182
+ raise Switch2ConnectionError(
183
+ f"Connection error fetching bill detail: {err}"
184
+ ) from err
185
+ return _parse_bill_detail(BeautifulSoup(html, "html.parser"))
186
+
138
187
  async def fetch_data(self) -> Switch2Data:
139
188
  """Authenticate and fetch all meter data."""
140
189
  customer = await self.authenticate()
@@ -287,3 +336,203 @@ def _parse_bills(soup: BeautifulSoup) -> list[Bill]:
287
336
  _LOGGER.debug("Failed to parse bill row: %s", err)
288
337
 
289
338
  return bills
339
+
340
+
341
+ def _parse_currency(text: str) -> float:
342
+ """Parse a currency string like '£172.26' or '-£205.13'."""
343
+ text = text.strip()
344
+ negative = text.startswith("-")
345
+ text = text.lstrip("-").lstrip("£").lstrip("\xa3").replace(",", "")
346
+ value = float(text)
347
+ return -value if negative else value
348
+
349
+
350
+ def _parse_bill_charges(
351
+ soup: BeautifulSoup, container_selector: str
352
+ ) -> list[BillCharge]:
353
+ """Extract charge line items from desktop-layout rows."""
354
+ charges: list[BillCharge] = []
355
+ rows = soup.select(f"{container_selector} .bill-table-row-desktop .bill-table-row")
356
+ for row in rows:
357
+ desc_el = row.select_one(".bill-table-row-item-left")
358
+ units_el = row.select_one(".bill-table-row-item")
359
+ charge_el = row.select_one(".bill-table-row-item-right")
360
+ if desc_el and charge_el:
361
+ charges.append(
362
+ BillCharge(
363
+ description=desc_el.text.strip(),
364
+ units=units_el.text.strip() if units_el else "",
365
+ charge=_parse_currency(charge_el.text),
366
+ )
367
+ )
368
+ return charges
369
+
370
+
371
+ def _parse_bill_detail(soup: BeautifulSoup) -> BillDetail:
372
+ """Extract bill detail from the bill detail page."""
373
+ # Header: invoice number and date of issue
374
+ header_rows = soup.select(".bill-header-row")
375
+ invoice_number = ""
376
+ date_of_issue_text = ""
377
+ for row in header_rows:
378
+ label_el = row.select_one(".bill-header-row-item")
379
+ value_el = row.select_one(".bill-header-row-item-right")
380
+ if label_el and value_el:
381
+ label = label_el.text.strip().rstrip(":")
382
+ if label == "Invoice Number":
383
+ invoice_number = value_el.text.strip()
384
+ elif label == "Date of issue":
385
+ date_of_issue_text = value_el.text.strip()
386
+
387
+ date_of_issue = _parse_date(date_of_issue_text)
388
+
389
+ # Period: from/to dates
390
+ from_el = soup.select_one(".bill-table-row-item-left")
391
+ to_el = soup.select_one(".bill-table-row-item-dateto")
392
+ period_from_text = ""
393
+ period_to_text = ""
394
+ if from_el:
395
+ # Text is like "From: 27th January 2026"
396
+ period_from_text = from_el.text.strip()
397
+ if period_from_text.lower().startswith("from:"):
398
+ period_from_text = period_from_text[5:].strip()
399
+ if to_el:
400
+ period_to_text = to_el.text.strip()
401
+ if period_to_text.lower().startswith("to:"):
402
+ period_to_text = period_to_text[3:].strip()
403
+
404
+ period_from = _parse_date(period_from_text)
405
+ period_to = _parse_date(period_to_text)
406
+
407
+ # Consumption charges (desktop layout rows within BillItemsContainer)
408
+ consumption_charges = _parse_bill_charges(
409
+ soup, "#BillItemsContainer > .bill-table-row:first-of-type"
410
+ )
411
+ # If the CSS child selector doesn't match, fall back to looking at
412
+ # desktop rows that come before .other-charges-table-row
413
+ if not consumption_charges:
414
+ items_container = soup.select_one("#BillItemsContainer")
415
+ if items_container:
416
+ consumption_rows: list[Tag] = []
417
+ for child in items_container.children:
418
+ if not isinstance(child, Tag):
419
+ continue
420
+ if "other-charges-table-row" in child.get("class", []):
421
+ break
422
+ desktop = child.select_one(".bill-table-row-desktop .bill-table-row")
423
+ if desktop:
424
+ consumption_rows.append(desktop)
425
+ elif "bill-table-row-desktop" in child.get("class", []):
426
+ inner = child.select_one(".bill-table-row")
427
+ if inner:
428
+ consumption_rows.append(inner)
429
+ for row in consumption_rows:
430
+ desc_el = row.select_one(".bill-table-row-item-left")
431
+ units_el = row.select_one(".bill-table-row-item")
432
+ charge_el = row.select_one(".bill-table-row-item-right")
433
+ if desc_el and charge_el:
434
+ consumption_charges.append(
435
+ BillCharge(
436
+ description=desc_el.text.strip(),
437
+ units=(units_el.text.strip() if units_el else ""),
438
+ charge=_parse_currency(charge_el.text),
439
+ )
440
+ )
441
+
442
+ # Other charges
443
+ other_charges: list[BillCharge] = []
444
+ other_header = soup.select_one(".other-charges-table-row")
445
+ if other_header:
446
+ sibling = other_header.next_sibling
447
+ while sibling:
448
+ if isinstance(sibling, Tag):
449
+ if "bill-table-row-desktop" in sibling.get("class", []):
450
+ charge_row = sibling.select_one(".bill-table-row")
451
+ if charge_row:
452
+ desc_el = charge_row.select_one(".bill-table-row-item-left")
453
+ units_el = charge_row.select_one(".bill-table-row-item")
454
+ charge_el = charge_row.select_one(".bill-table-row-item-right")
455
+ if desc_el and charge_el:
456
+ other_charges.append(
457
+ BillCharge(
458
+ description=desc_el.text.strip(),
459
+ units=(units_el.text.strip() if units_el else ""),
460
+ charge=_parse_currency(charge_el.text),
461
+ )
462
+ )
463
+ elif "bill-table-row-narrow" not in sibling.get("class", []):
464
+ break
465
+ sibling = sibling.next_sibling
466
+
467
+ # Totals
468
+ totals_container = soup.select_one("#BillTotalsCollapsibleContent")
469
+ total_excl_vat = 0.0
470
+ vat = 0.0
471
+ total_rows = (
472
+ totals_container.select(".bill-total-table-row") if totals_container else []
473
+ )
474
+ for row in total_rows:
475
+ label_el = row.select_one(".bill-total-table-row-item-left")
476
+ value_el = row.select_one(".bill-total-table-row-item-right")
477
+ if label_el and value_el:
478
+ label = label_el.text.strip()
479
+ if label.startswith("Total charges excluding VAT"):
480
+ total_excl_vat = _parse_currency(value_el.text)
481
+ elif label.startswith("VAT"):
482
+ vat = _parse_currency(value_el.text)
483
+
484
+ # Bill total from the collapsible header
485
+ total = 0.0
486
+ total_header = soup.select_one(
487
+ "#BillTotalsContainer > .collapsible-header .bill-total-table-row-item-right"
488
+ )
489
+ if total_header:
490
+ total = _parse_currency(total_header.text)
491
+
492
+ # Account balance
493
+ balance_container = soup.select_one("#AccountBalanceCollapsibleContent")
494
+ previous_balance = 0.0
495
+ payments_received = 0.0
496
+ balance_rows = (
497
+ balance_container.select(".bill-total-table-row") if balance_container else []
498
+ )
499
+ for row in balance_rows:
500
+ label_el = row.select_one(".bill-total-table-row-item-left")
501
+ value_el = row.select_one(".bill-total-table-row-item-right")
502
+ if label_el and value_el:
503
+ label = label_el.text.strip()
504
+ if label == "Previous account balance":
505
+ previous_balance = _parse_currency(value_el.text)
506
+ elif label == "Payments received":
507
+ payments_received = _parse_currency(value_el.text)
508
+
509
+ balance = 0.0
510
+ balance_header = soup.select_one(
511
+ "#AccountBalanceContainer > .collapsible-header"
512
+ " .bill-total-table-row-item-right"
513
+ )
514
+ if balance_header:
515
+ balance = _parse_currency(balance_header.text)
516
+
517
+ # Download URL
518
+ download_url = ""
519
+ download_el = soup.select_one("#DownloadBillButton")
520
+ if download_el:
521
+ href = _get_attr(download_el, "href")
522
+ download_url = f"{BASE_URL}{href}" if href else ""
523
+
524
+ return BillDetail(
525
+ invoice_number=invoice_number,
526
+ date_of_issue=date_of_issue,
527
+ period_from=period_from,
528
+ period_to=period_to,
529
+ consumption_charges=consumption_charges,
530
+ other_charges=other_charges,
531
+ total_excl_vat=total_excl_vat,
532
+ vat=vat,
533
+ total=total,
534
+ previous_balance=previous_balance,
535
+ payments_received=payments_received,
536
+ balance=balance,
537
+ download_url=download_url,
538
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: switch2
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Async client library for the Switch2 energy portal
5
5
  Author-email: Jelmer Vernooij <jelmer@jelmer.uk>
6
6
  License-Expression: Apache-2.0
@@ -0,0 +1,352 @@
1
+ """Tests for the Switch2 API client."""
2
+
3
+ import unittest
4
+ from datetime import datetime
5
+
6
+ from bs4 import BeautifulSoup
7
+
8
+ from switch2.api import (
9
+ _parse_bill_detail,
10
+ _parse_bills,
11
+ _parse_currency,
12
+ _parse_customer_info,
13
+ _parse_date,
14
+ _parse_readings,
15
+ )
16
+
17
+
18
+ class ParseDateTests(unittest.TestCase):
19
+ def test_ordinal_th(self) -> None:
20
+ self.assertEqual(_parse_date("27th February 2026"), datetime(2026, 2, 27))
21
+
22
+ def test_ordinal_st(self) -> None:
23
+ self.assertEqual(_parse_date("1st January 2025"), datetime(2025, 1, 1))
24
+
25
+ def test_ordinal_nd(self) -> None:
26
+ self.assertEqual(_parse_date("2nd March 2025"), datetime(2025, 3, 2))
27
+
28
+ def test_ordinal_rd(self) -> None:
29
+ self.assertEqual(_parse_date("3rd April 2025"), datetime(2025, 4, 3))
30
+
31
+ def test_abbreviated_month(self) -> None:
32
+ self.assertEqual(_parse_date("15th Jan 2025"), datetime(2025, 1, 15))
33
+
34
+ def test_invalid_date(self) -> None:
35
+ with self.assertRaises(ValueError):
36
+ _parse_date("not a date")
37
+
38
+
39
+ class ParseCustomerInfoTests(unittest.TestCase):
40
+ def test_full_info(self) -> None:
41
+ html = """
42
+ <div>
43
+ <span class="customer-info-name">John Doe</span>
44
+ <span class="customer-info-account-number">ACC-123</span>
45
+ <span class="customer-info-address">42 Test Lane</span>
46
+ </div>
47
+ """
48
+ soup = BeautifulSoup(html, "html.parser")
49
+ info = _parse_customer_info(soup)
50
+ self.assertEqual(info.name, "John Doe")
51
+ self.assertEqual(info.account_number, "ACC-123")
52
+ self.assertEqual(info.address, "42 Test Lane")
53
+
54
+ def test_missing_elements(self) -> None:
55
+ soup = BeautifulSoup("<div></div>", "html.parser")
56
+ info = _parse_customer_info(soup)
57
+ self.assertEqual(info.name, "")
58
+ self.assertEqual(info.account_number, "")
59
+ self.assertEqual(info.address, "")
60
+
61
+
62
+ class ParseReadingsTests(unittest.TestCase):
63
+ def test_single_reading(self) -> None:
64
+ html = """
65
+ <div class="meter-reading-history-table-data-row desktop-layout">
66
+ <div class="meter-reading-history-table-data-date-row-item">
67
+ 27th February 2026
68
+ </div>
69
+ <div class="meter-reading-history-table-data-amount-row-item">
70
+ 8551 kWh
71
+ </div>
72
+ <div class="meter-reading-history-table-data-type-row-item">
73
+ Actual
74
+ </div>
75
+ </div>
76
+ """
77
+ soup = BeautifulSoup(html, "html.parser")
78
+ readings = _parse_readings(soup)
79
+ self.assertEqual(len(readings), 1)
80
+ self.assertEqual(readings[0].date, datetime(2026, 2, 27))
81
+ self.assertEqual(readings[0].amount, 8551.0)
82
+ self.assertEqual(readings[0].unit, "kWh")
83
+ self.assertEqual(readings[0].reading_type, "Actual")
84
+
85
+ def test_no_readings(self) -> None:
86
+ soup = BeautifulSoup("<div></div>", "html.parser")
87
+ self.assertEqual(_parse_readings(soup), [])
88
+
89
+ def test_amount_without_unit(self) -> None:
90
+ html = """
91
+ <div class="meter-reading-history-table-data-row desktop-layout">
92
+ <div class="meter-reading-history-table-data-date-row-item">
93
+ 1st January 2025
94
+ </div>
95
+ <div class="meter-reading-history-table-data-amount-row-item">
96
+ 1234
97
+ </div>
98
+ </div>
99
+ """
100
+ soup = BeautifulSoup(html, "html.parser")
101
+ readings = _parse_readings(soup)
102
+ self.assertEqual(len(readings), 1)
103
+ self.assertEqual(readings[0].unit, "")
104
+ self.assertEqual(readings[0].reading_type, "")
105
+
106
+
107
+ class ParseBillsTests(unittest.TestCase):
108
+ def test_single_bill(self) -> None:
109
+ bill_amount_cls = (
110
+ "bill-history-table-data-row-item-right"
111
+ " bill-history-table-data-row-text-item"
112
+ )
113
+ html = f"""
114
+ <div class="bill-history-table-data-row">
115
+ <div class="bill-history-table-data-row-text-item">
116
+ 15th March 2025
117
+ </div>
118
+ <div class="{bill_amount_cls}">£172.26</div>
119
+ <a class="bill-history-view-bill-button"
120
+ href="/Credit/Bill/42">View</a>
121
+ </div>
122
+ """
123
+ soup = BeautifulSoup(html, "html.parser")
124
+ bills = _parse_bills(soup)
125
+ self.assertEqual(len(bills), 1)
126
+ self.assertEqual(bills[0].date, datetime(2025, 3, 15))
127
+ self.assertEqual(bills[0].amount, 172.26)
128
+ self.assertEqual(bills[0].detail_url, "https://my.switch2.co.uk/Credit/Bill/42")
129
+
130
+ def test_no_bills(self) -> None:
131
+ soup = BeautifulSoup("<div></div>", "html.parser")
132
+ self.assertEqual(_parse_bills(soup), [])
133
+
134
+ def test_bill_without_link(self) -> None:
135
+ bill_amount_cls = (
136
+ "bill-history-table-data-row-item-right"
137
+ " bill-history-table-data-row-text-item"
138
+ )
139
+ html = f"""
140
+ <div class="bill-history-table-data-row">
141
+ <div class="bill-history-table-data-row-text-item">
142
+ 1st January 2025
143
+ </div>
144
+ <div class="{bill_amount_cls}">£50.00</div>
145
+ </div>
146
+ """
147
+ soup = BeautifulSoup(html, "html.parser")
148
+ bills = _parse_bills(soup)
149
+ self.assertEqual(len(bills), 1)
150
+ self.assertEqual(bills[0].detail_url, "")
151
+
152
+
153
+ class ParseCurrencyTests(unittest.TestCase):
154
+ def test_pounds(self) -> None:
155
+ self.assertEqual(_parse_currency("£172.26"), 172.26)
156
+
157
+ def test_negative(self) -> None:
158
+ self.assertEqual(_parse_currency("-£205.13"), -205.13)
159
+
160
+ def test_with_comma(self) -> None:
161
+ self.assertEqual(_parse_currency("£1,234.56"), 1234.56)
162
+
163
+ def test_html_entity(self) -> None:
164
+ self.assertEqual(_parse_currency("\xa3105.97"), 105.97)
165
+
166
+
167
+ class ParseBillDetailTests(unittest.TestCase):
168
+ BILL_DETAIL_HTML = """\
169
+ <div class="bill-container border-color-2">
170
+ <div class="bill-header-container border-color-2 font-large">
171
+ <div class="bill-header-row fg-color-2">
172
+ <div class="bill-header-row-item">Invoice Number:</div>
173
+ <div class="bill-header-row-item-right fg-color-4">
174
+ 0642001470
175
+ </div>
176
+ <div class="clear-fix"></div>
177
+ </div>
178
+ <div class="bill-header-row fg-color-2">
179
+ <div class="bill-header-row-item">Date of issue:</div>
180
+ <div class="bill-header-row-item-right fg-color-4">
181
+ 27th February 2026
182
+ </div>
183
+ <div class="clear-fix"></div>
184
+ </div>
185
+ </div>
186
+
187
+ <div class="bill-table-row bg-color-1 fg-color-1">
188
+ <div class="bill-table-row-item-left">
189
+ From:&nbsp;27th January 2026
190
+ </div>
191
+ <div class="bill-table-row-item bill-table-row-item-dateto">
192
+ To: 26th February 2026
193
+ </div>
194
+ <div class="clear-fix"></div>
195
+ </div>
196
+
197
+ <div id="BillItemsContainer">
198
+ <div class="bill-table-row fg-color-2 font-bold">
199
+ <div class="bill-table-row-item-left">Consumption charges</div>
200
+ </div>
201
+ <div class="bill-table-row-desktop">
202
+ <div class="bill-table-row bg-color-6 fg-color-4 font-bold">
203
+ <div class="bill-table-row-item-left">Heat</div>
204
+ <div class="bill-table-row-item">623 kWh</div>
205
+ <div class="bill-table-row-item-right">&#163;105.97</div>
206
+ <div class="clear-fix"></div>
207
+ </div>
208
+ </div>
209
+ <div class="bill-table-row-narrow"></div>
210
+
211
+ <div class="other-charges-table-row fg-color-2 font-bold">
212
+ <div class="other-charges-row-item">Other charges</div>
213
+ </div>
214
+ <div class="bill-table-row-desktop">
215
+ <div class="bill-table-row bg-color-6 fg-color-4 font-bold">
216
+ <div class="bill-table-row-item-left">Heat Standing Charge</div>
217
+ <div class="bill-table-row-item">31.00 days</div>
218
+ <div class="bill-table-row-item-right">&#163;23.21</div>
219
+ <div class="clear-fix"></div>
220
+ </div>
221
+ </div>
222
+ <div class="bill-table-row-narrow"></div>
223
+ <div class="bill-table-row-desktop">
224
+ <div class="bill-table-row bg-color-6 fg-color-4 font-bold">
225
+ <div class="bill-table-row-item-left">
226
+ Admin Standing Charge
227
+ </div>
228
+ <div class="bill-table-row-item">31.00 days</div>
229
+ <div class="bill-table-row-item-right">&#163;34.88</div>
230
+ <div class="clear-fix"></div>
231
+ </div>
232
+ </div>
233
+ <div class="bill-table-row-narrow"></div>
234
+ </div>
235
+
236
+ <div id="BillTotalsContainer" class="collapsible-container">
237
+ <div class="collapsible-header bill-total-table-row bg-color-4">
238
+ <div class="bill-total-table-row-item-left">Bill total</div>
239
+ <div class="bill-total-table-row-item-right">
240
+ &#163;172.26
241
+ </div>
242
+ </div>
243
+ <div id="BillTotalsCollapsibleContent" class="collapsible">
244
+ <div class="bill-total-table-row bg-color-3 fg-color-4">
245
+ <div class="bill-total-table-row-item-left">
246
+ VAT @ 5% on &#163;164.06
247
+ </div>
248
+ <div class="bill-total-table-row-item-right">£8.20</div>
249
+ </div>
250
+ <div class="bill-total-table-row bg-color-3 fg-color-4">
251
+ <div class="bill-total-table-row-item-left">
252
+ Total charges excluding VAT
253
+ </div>
254
+ <div class="bill-total-table-row-item-right">£164.06</div>
255
+ </div>
256
+ </div>
257
+ </div>
258
+
259
+ <div id="AccountBalanceContainer" class="collapsible-container">
260
+ <div class="collapsible-header bill-total-table-row bg-color-5">
261
+ <div class="bill-total-table-row-item-left">
262
+ Balance as of 27th February 2026
263
+ </div>
264
+ <div class="bill-total-table-row-item-right">
265
+ &#163;172.26
266
+ </div>
267
+ </div>
268
+ <div id="AccountBalanceCollapsibleContent" class="collapsible">
269
+ <div class="bill-total-table-row bg-color-6 fg-color-4">
270
+ <div class="bill-total-table-row-item-left">
271
+ Previous account balance
272
+ </div>
273
+ <div class="bill-total-table-row-item-right">£205.13</div>
274
+ </div>
275
+ <div class="bill-total-table-row bg-color-6 fg-color-4">
276
+ <div class="bill-total-table-row-item-left">
277
+ Payments received
278
+ </div>
279
+ <div class="bill-total-table-row-item-right">-£205.13</div>
280
+ </div>
281
+ </div>
282
+ </div>
283
+
284
+ <a id="DownloadBillButton"
285
+ href="/Credit/Bill/Download/2289896"
286
+ class="wizard-button">
287
+ <span>Download this bill</span>
288
+ </a>
289
+ </div>
290
+ """
291
+
292
+ def test_invoice_number(self) -> None:
293
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
294
+ detail = _parse_bill_detail(soup)
295
+ self.assertEqual(detail.invoice_number, "0642001470")
296
+
297
+ def test_date_of_issue(self) -> None:
298
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
299
+ detail = _parse_bill_detail(soup)
300
+ self.assertEqual(detail.date_of_issue, datetime(2026, 2, 27))
301
+
302
+ def test_period(self) -> None:
303
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
304
+ detail = _parse_bill_detail(soup)
305
+ self.assertEqual(detail.period_from, datetime(2026, 1, 27))
306
+ self.assertEqual(detail.period_to, datetime(2026, 2, 26))
307
+
308
+ def test_consumption_charges(self) -> None:
309
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
310
+ detail = _parse_bill_detail(soup)
311
+ self.assertEqual(len(detail.consumption_charges), 1)
312
+ self.assertEqual(detail.consumption_charges[0].description, "Heat")
313
+ self.assertEqual(detail.consumption_charges[0].units, "623 kWh")
314
+ self.assertEqual(detail.consumption_charges[0].charge, 105.97)
315
+
316
+ def test_other_charges(self) -> None:
317
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
318
+ detail = _parse_bill_detail(soup)
319
+ self.assertEqual(len(detail.other_charges), 2)
320
+ self.assertEqual(
321
+ detail.other_charges[0].description,
322
+ "Heat Standing Charge",
323
+ )
324
+ self.assertEqual(detail.other_charges[0].units, "31.00 days")
325
+ self.assertEqual(detail.other_charges[0].charge, 23.21)
326
+ self.assertEqual(
327
+ detail.other_charges[1].description,
328
+ "Admin Standing Charge",
329
+ )
330
+ self.assertEqual(detail.other_charges[1].charge, 34.88)
331
+
332
+ def test_totals(self) -> None:
333
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
334
+ detail = _parse_bill_detail(soup)
335
+ self.assertEqual(detail.total_excl_vat, 164.06)
336
+ self.assertEqual(detail.vat, 8.20)
337
+ self.assertEqual(detail.total, 172.26)
338
+
339
+ def test_account_balance(self) -> None:
340
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
341
+ detail = _parse_bill_detail(soup)
342
+ self.assertEqual(detail.previous_balance, 205.13)
343
+ self.assertEqual(detail.payments_received, -205.13)
344
+ self.assertEqual(detail.balance, 172.26)
345
+
346
+ def test_download_url(self) -> None:
347
+ soup = BeautifulSoup(self.BILL_DETAIL_HTML, "html.parser")
348
+ detail = _parse_bill_detail(soup)
349
+ self.assertEqual(
350
+ detail.download_url,
351
+ "https://my.switch2.co.uk/Credit/Bill/Download/2289896",
352
+ )
@@ -1,148 +0,0 @@
1
- """Tests for the Switch2 API client."""
2
-
3
- import unittest
4
- from datetime import datetime
5
-
6
- from bs4 import BeautifulSoup
7
-
8
- from switch2.api import (
9
- _parse_bills,
10
- _parse_customer_info,
11
- _parse_date,
12
- _parse_readings,
13
- )
14
-
15
-
16
- class ParseDateTests(unittest.TestCase):
17
- def test_ordinal_th(self) -> None:
18
- self.assertEqual(_parse_date("27th February 2026"), datetime(2026, 2, 27))
19
-
20
- def test_ordinal_st(self) -> None:
21
- self.assertEqual(_parse_date("1st January 2025"), datetime(2025, 1, 1))
22
-
23
- def test_ordinal_nd(self) -> None:
24
- self.assertEqual(_parse_date("2nd March 2025"), datetime(2025, 3, 2))
25
-
26
- def test_ordinal_rd(self) -> None:
27
- self.assertEqual(_parse_date("3rd April 2025"), datetime(2025, 4, 3))
28
-
29
- def test_abbreviated_month(self) -> None:
30
- self.assertEqual(_parse_date("15th Jan 2025"), datetime(2025, 1, 15))
31
-
32
- def test_invalid_date(self) -> None:
33
- with self.assertRaises(ValueError):
34
- _parse_date("not a date")
35
-
36
-
37
- class ParseCustomerInfoTests(unittest.TestCase):
38
- def test_full_info(self) -> None:
39
- html = """
40
- <div>
41
- <span class="customer-info-name">John Doe</span>
42
- <span class="customer-info-account-number">ACC-123</span>
43
- <span class="customer-info-address">42 Test Lane</span>
44
- </div>
45
- """
46
- soup = BeautifulSoup(html, "html.parser")
47
- info = _parse_customer_info(soup)
48
- self.assertEqual(info.name, "John Doe")
49
- self.assertEqual(info.account_number, "ACC-123")
50
- self.assertEqual(info.address, "42 Test Lane")
51
-
52
- def test_missing_elements(self) -> None:
53
- soup = BeautifulSoup("<div></div>", "html.parser")
54
- info = _parse_customer_info(soup)
55
- self.assertEqual(info.name, "")
56
- self.assertEqual(info.account_number, "")
57
- self.assertEqual(info.address, "")
58
-
59
-
60
- class ParseReadingsTests(unittest.TestCase):
61
- def test_single_reading(self) -> None:
62
- html = """
63
- <div class="meter-reading-history-table-data-row desktop-layout">
64
- <div class="meter-reading-history-table-data-date-row-item">
65
- 27th February 2026
66
- </div>
67
- <div class="meter-reading-history-table-data-amount-row-item">
68
- 8551 kWh
69
- </div>
70
- <div class="meter-reading-history-table-data-type-row-item">
71
- Actual
72
- </div>
73
- </div>
74
- """
75
- soup = BeautifulSoup(html, "html.parser")
76
- readings = _parse_readings(soup)
77
- self.assertEqual(len(readings), 1)
78
- self.assertEqual(readings[0].date, datetime(2026, 2, 27))
79
- self.assertEqual(readings[0].amount, 8551.0)
80
- self.assertEqual(readings[0].unit, "kWh")
81
- self.assertEqual(readings[0].reading_type, "Actual")
82
-
83
- def test_no_readings(self) -> None:
84
- soup = BeautifulSoup("<div></div>", "html.parser")
85
- self.assertEqual(_parse_readings(soup), [])
86
-
87
- def test_amount_without_unit(self) -> None:
88
- html = """
89
- <div class="meter-reading-history-table-data-row desktop-layout">
90
- <div class="meter-reading-history-table-data-date-row-item">
91
- 1st January 2025
92
- </div>
93
- <div class="meter-reading-history-table-data-amount-row-item">
94
- 1234
95
- </div>
96
- </div>
97
- """
98
- soup = BeautifulSoup(html, "html.parser")
99
- readings = _parse_readings(soup)
100
- self.assertEqual(len(readings), 1)
101
- self.assertEqual(readings[0].unit, "")
102
- self.assertEqual(readings[0].reading_type, "")
103
-
104
-
105
- class ParseBillsTests(unittest.TestCase):
106
- def test_single_bill(self) -> None:
107
- bill_amount_cls = (
108
- "bill-history-table-data-row-item-right"
109
- " bill-history-table-data-row-text-item"
110
- )
111
- html = f"""
112
- <div class="bill-history-table-data-row">
113
- <div class="bill-history-table-data-row-text-item">
114
- 15th March 2025
115
- </div>
116
- <div class="{bill_amount_cls}">£172.26</div>
117
- <a class="bill-history-view-bill-button"
118
- href="/Credit/Bill/42">View</a>
119
- </div>
120
- """
121
- soup = BeautifulSoup(html, "html.parser")
122
- bills = _parse_bills(soup)
123
- self.assertEqual(len(bills), 1)
124
- self.assertEqual(bills[0].date, datetime(2025, 3, 15))
125
- self.assertEqual(bills[0].amount, 172.26)
126
- self.assertEqual(bills[0].detail_url, "https://my.switch2.co.uk/Credit/Bill/42")
127
-
128
- def test_no_bills(self) -> None:
129
- soup = BeautifulSoup("<div></div>", "html.parser")
130
- self.assertEqual(_parse_bills(soup), [])
131
-
132
- def test_bill_without_link(self) -> None:
133
- bill_amount_cls = (
134
- "bill-history-table-data-row-item-right"
135
- " bill-history-table-data-row-text-item"
136
- )
137
- html = f"""
138
- <div class="bill-history-table-data-row">
139
- <div class="bill-history-table-data-row-text-item">
140
- 1st January 2025
141
- </div>
142
- <div class="{bill_amount_cls}">£50.00</div>
143
- </div>
144
- """
145
- soup = BeautifulSoup(html, "html.parser")
146
- bills = _parse_bills(soup)
147
- self.assertEqual(len(bills), 1)
148
- self.assertEqual(bills[0].detail_url, "")
File without changes
File without changes