Debian Codegraph @

tests/test_init.py

raw
1 """Tests for aiodukeenergy library."""
2
3 import re
4 from datetime import datetime, timedelta, timezone
5 from typing import Any
6
7 import aiohttp
8 import pytest
9 from aioresponses import aioresponses
10
11 from aiodukeenergy import (
12 AbstractDukeEnergyAuth,
13 Auth0Client,
14 DukeEnergy,
15 DukeEnergyAuth,
16 )
17
18
19 # Create a valid-looking JWT for testing (not cryptographically valid, but parseable)
20 def _create_test_jwt(exp_offset_seconds: int = 3600, **extra_claims: str) -> str:
21 """Create a test JWT token with configurable expiration."""
22 import base64
23 import json
24
25 header = (
26 base64.urlsafe_b64encode(json.dumps({"alg": "RS256", "typ": "JWT"}).encode())
27 .rstrip(b"=")
28 .decode()
29 )
30 exp = int(
31 (datetime.now(timezone.utc) + timedelta(seconds=exp_offset_seconds)).timestamp()
32 )
33 payload_data = {
34 "sub": "auth0|TEST",
35 "email": "[email protected]",
36 "internal_identifier": "DUKE_TEST_USER",
37 "exp": exp,
38 **extra_claims,
39 }
40 payload = (
41 base64.urlsafe_b64encode(json.dumps(payload_data).encode())
42 .rstrip(b"=")
43 .decode()
44 )
45 signature = base64.urlsafe_b64encode(b"fake_signature").rstrip(b"=").decode()
46 return f"{header}.{payload}.{signature}"
47
48
49 @pytest.fixture
50 def mock_auth0_token_response():
51 """Create a mock Auth0 token response."""
52 return {
53 "access_token": _create_test_jwt(),
54 "refresh_token": "refresh_token_value",
55 "id_token": _create_test_jwt(de_auth="encrypted_auth_data"),
56 "token_type": "Bearer",
57 "expires_in": 86400,
58 }
59
60
61 @pytest.fixture
62 def mock_duke_token_response():
63 """Create a mock Duke Energy API token response."""
64 return {
65 "access_token": _create_test_jwt(),
66 "internalUserID": "DUKE_TEST_USER",
67 "email": "[email protected]",
68 }
69
70
71 @pytest.fixture
72 def mock_account_list_response():
73 """Create a mock account list response."""
74 return {
75 "accounts": [
76 {
77 "accountNumber": "accountNumber",
78 "primaryBpNumber": "primaryBpNumber",
79 "serviceAddressParsed": {
80 "zipCode": "zipCode",
81 "addressLine1": "123 Test St",
82 "city": "Test City",
83 "state": "NC",
84 },
85 "srcSysCd": "srcSysCd",
86 "srcAcctId": "srcAcctId",
87 "srcAcctId2": "srcAcctId2",
88 }
89 ],
90 "relatedBpNumber": "relatedBpNumber",
91 }
92
93
94 @pytest.fixture
95 def mock_account_details_response():
96 """Create a mock account details response."""
97 return {
98 "meterInfo": [
99 {
100 "serviceType": "ELECTRIC",
101 "serialNum": "serialNum",
102 "agreementActiveDate": "2000-01-01",
103 "agreementEndDate": "2999-01-01",
104 "meterCertificationDate": "2020-01-01",
105 }
106 ],
107 }
108
109
110 @pytest.fixture
111 def mock_usage_data():
112 """Create mock usage data for hourly interval."""
113 hour_formats = [
114 "12 AM",
115 "01 AM",
116 "02 AM",
117 "03 AM",
118 "04 AM",
119 "05 AM",
120 "06 AM",
121 "07 AM",
122 "08 AM",
123 "09 AM",
124 "10 AM",
125 "11 AM",
126 "12 PM",
127 "01 PM",
128 "02 PM",
129 "03 PM",
130 "04 PM",
131 "05 PM",
132 "06 PM",
133 "07 PM",
134 "08 PM",
135 "09 PM",
136 "10 PM",
137 "11 PM",
138 ]
139
140 hourly_data = []
141 for day in range(31):
142 for hour in range(24):
143 idx = day * 24 + hour
144 # Skip 02 AM on first day to simulate missing data
145 if day == 0 and hour == 2:
146 continue
147 hourly_data.append(
148 {
149 "date": hour_formats[hour],
150 "usage": str(idx),
151 "temperatureAvg": 30,
152 }
153 )
154 return hourly_data
155
156
157 @pytest.fixture
158 def mock_daily_usage_data():
159 """Create mock usage data for daily interval."""
160 daily_data = []
161 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
162
163 for day in range(31):
164 current_date = start + timedelta(days=day)
165 date_str = f"{current_date.month}/{current_date.strftime('%d/%Y')}"
166 # Day 3 (index 2) will have 0 usage (detected as missing)
167 usage_value = "0" if day == 2 else str(day * 10)
168 daily_data.append(
169 {
170 "date": date_str,
171 "usage": usage_value,
172 "temperatureAvg": 30,
173 }
174 )
175
176 return daily_data
177
178
179 @pytest.fixture
180 def mock_duplicate_hours_data():
181 """Create mock usage data with duplicate hours (simulating DST fall back)."""
182 hour_formats = [
183 "12 AM",
184 "01 AM",
185 "02 AM",
186 "03 AM",
187 "04 AM",
188 "05 AM",
189 "06 AM",
190 "07 AM",
191 "08 AM",
192 "09 AM",
193 "10 AM",
194 "11 AM",
195 "12 PM",
196 "01 PM",
197 "02 PM",
198 "03 PM",
199 "04 PM",
200 "05 PM",
201 "06 PM",
202 "07 PM",
203 "08 PM",
204 "09 PM",
205 "10 PM",
206 "11 PM",
207 ]
208
209 hourly_data = []
210 for day in range(2): # Just use 2 days for this test
211 for hour in range(24):
212 idx = day * 24 + hour
213
214 # Add the regular entry
215 hourly_data.append(
216 {"date": hour_formats[hour], "usage": str(idx), "temperatureAvg": 30}
217 )
218
219 # For day 1, duplicate the 1 AM hour to simulate DST fall back
220 if day == 1 and hour == 1:
221 hourly_data.append(
222 {
223 "date": hour_formats[hour],
224 "usage": str(900), # Special value for the duplicate hour
225 "temperatureAvg": 25,
226 }
227 )
228
229 return hourly_data
230
231
232 def setup_api_mocks(mocked, account_list, account_details, usage_data=None):
233 """Set up the mocked responses for Duke Energy API."""
234 # Mock account list
235 pattern = re.compile(r"^https://api-v2\.cma\.duke-energy\.app/account-list")
236 mocked.get(pattern, payload=account_list, repeat=True)
237
238 # Mock account details
239 pattern = re.compile(r"^https://api-v2\.cma\.duke-energy\.app/account-details-v2")
240 mocked.get(pattern, payload=account_details, repeat=True)
241
242 # Mock usage graph
243 if usage_data is not None:
244 pattern = re.compile(
245 r"^https://api-v2\.cma\.duke-energy\.app/account/usage/graph"
246 )
247 mocked.post(pattern, payload={"usageArray": usage_data}, repeat=True)
248
249
250 def setup_auth_mocks(mocked, mock_duke_token_response, mock_auth0_token_response=None):
251 """Set up authentication mocks."""
252 # Mock Duke Energy API token exchange
253 mocked.post(
254 "https://api-v2.cma.duke-energy.app/login/auth-token",
255 payload=mock_duke_token_response,
256 repeat=True,
257 )
258
259 # Mock Auth0 token endpoint
260 if mock_auth0_token_response:
261 mocked.post(
262 "https://login.duke-energy.com/oauth/token",
263 payload=mock_auth0_token_response,
264 repeat=True,
265 )
266
267
268 @pytest.fixture
269 def mock_session():
270 """Create a mock aiohttp session."""
271 return aiohttp.ClientSession()
272
273
274 class MockAuth(AbstractDukeEnergyAuth):
275 """Mock auth implementation for testing DukeEnergy client."""
276
277 def __init__(self, session, email="[email protected]", user_id="DUKE_TEST_USER"):
278 super().__init__(session)
279 self._email = email
280 self._internal_user_id = user_id
281 self._mock_responses = {}
282
283 async def async_get_id_token(self) -> str:
284 return _create_test_jwt()
285
286 def set_mock_response(self, url_pattern: str, response: dict[str, Any]) -> None:
287 """Set a mock response for a URL pattern."""
288 self._mock_responses[url_pattern] = response
289
290
291 class TestClientCreation:
292 """Tests for DukeEnergy client creation."""
293
294 @pytest.mark.asyncio
295 async def test_create_client_with_mock_auth(self):
296 """Creating a client with mock auth works as expected."""
297 async with aiohttp.ClientSession() as session:
298 auth = MockAuth(session)
299 client = DukeEnergy(auth)
300 assert client.email == "[email protected]"
301 assert client.internal_user_id == "DUKE_TEST_USER"
302
303 @pytest.mark.asyncio
304 async def test_create_duke_energy_auth_with_tokens(self):
305 """Creating DukeEnergyAuth with pre-provided tokens works."""
306 test_token = _create_test_jwt(exp_offset_seconds=3600)
307 test_refresh = "refresh_token_value"
308 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
309
310 async with aiohttp.ClientSession() as session:
311 auth0_client = Auth0Client(session)
312 auth = DukeEnergyAuth(
313 session,
314 auth0_client,
315 access_token=test_token,
316 refresh_token=test_refresh,
317 id_token=test_id_token,
318 )
319 # Email should be populated from id_token
320 assert auth.email == "[email protected]"
321 assert auth.internal_user_id == "DUKE_TEST_USER"
322
323 @pytest.mark.asyncio
324 async def test_duke_energy_auth_token_property(self):
325 """Test that token property returns serializable dict."""
326 test_token = _create_test_jwt(exp_offset_seconds=3600)
327 test_refresh = "refresh_token_value"
328 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
329
330 async with aiohttp.ClientSession() as session:
331 auth0_client = Auth0Client(session)
332 auth = DukeEnergyAuth(
333 session,
334 auth0_client,
335 access_token=test_token,
336 refresh_token=test_refresh,
337 id_token=test_id_token,
338 )
339 token_dict = auth.token
340 assert token_dict is not None
341 assert token_dict["access_token"] == test_token
342 assert token_dict["refresh_token"] == test_refresh
343 assert token_dict["id_token"] == test_id_token
344
345
346 class TestAuthorizationURL:
347 """Tests for authorization URL generation."""
348
349 @pytest.mark.asyncio
350 async def test_get_authorization_url(self):
351 """Test generating authorization URL."""
352 async with aiohttp.ClientSession() as session:
353 auth0_client = Auth0Client(session)
354
355 auth_url, state, code_verifier = auth0_client.get_authorization_url()
356
357 # Check URL structure
358 assert auth_url.startswith("https://login.duke-energy.com/authorize")
359 assert "client_id=" in auth_url
360 assert "redirect_uri=" in auth_url
361 assert "response_type=code" in auth_url
362 assert "code_challenge=" in auth_url
363 assert "code_challenge_method=S256" in auth_url
364 assert "state=" in auth_url
365
366 # State and code_verifier should be non-empty
367 assert len(state) > 0
368 assert len(code_verifier) > 0
369
370
371 class TestCodeExchange:
372 """Tests for authorization code exchange."""
373
374 @pytest.mark.asyncio
375 async def test_authenticate_with_code(
376 self,
377 mock_auth0_token_response,
378 mock_duke_token_response,
379 ):
380 """Test exchanging authorization code for tokens."""
381 async with aiohttp.ClientSession() as session:
382 auth0_client = Auth0Client(session)
383
384 # Generate auth URL first (to get code_verifier)
385 auth_url, state, code_verifier = auth0_client.get_authorization_url()
386
387 auth = DukeEnergyAuth(session, auth0_client)
388
389 with aioresponses() as mocked:
390 # Mock Auth0 token endpoint
391 mocked.post(
392 "https://login.duke-energy.com/oauth/token",
393 payload=mock_auth0_token_response,
394 )
395
396 # Mock Duke Energy API token exchange
397 mocked.post(
398 "https://api-v2.cma.duke-energy.app/login/auth-token",
399 payload=mock_duke_token_response,
400 )
401
402 # Exchange code
403 result = await auth.authenticate_with_code(
404 "test_auth_code", code_verifier
405 )
406
407 assert "access_token" in result
408 assert auth.token is not None
409 assert auth.internal_user_id == "DUKE_TEST_USER"
410
411 @pytest.mark.asyncio
412 async def test_get_id_token_without_authentication(self):
413 """Test that async_get_id_token fails without authentication."""
414 from aiodukeenergy import DukeEnergyAuthError
415
416 async with aiohttp.ClientSession() as session:
417 auth0_client = Auth0Client(session)
418 auth = DukeEnergyAuth(session, auth0_client)
419
420 with pytest.raises(DukeEnergyAuthError, match="Not authenticated"):
421 await auth.async_get_id_token()
422
423
424 class TestTokenRefresh:
425 """Tests for token refresh functionality."""
426
427 @pytest.mark.asyncio
428 async def test_refresh_expired_token(
429 self,
430 mock_auth0_token_response,
431 mock_duke_token_response,
432 mock_account_list_response,
433 ):
434 """Test that expired tokens are automatically refreshed."""
435 # Create an expired token
436 expired_token = _create_test_jwt(exp_offset_seconds=-3600)
437 expired_id_token = _create_test_jwt(exp_offset_seconds=-3600)
438 fresh_token = _create_test_jwt(exp_offset_seconds=3600)
439 fresh_id_token = _create_test_jwt(exp_offset_seconds=3600)
440
441 async with aiohttp.ClientSession() as session:
442 auth0_client = Auth0Client(session)
443 auth = DukeEnergyAuth(
444 session,
445 auth0_client,
446 access_token=expired_token,
447 refresh_token="refresh_token", # noqa: S106
448 id_token=expired_id_token,
449 )
450
451 with aioresponses() as mocked:
452 # Mock token refresh
453 mocked.post(
454 "https://login.duke-energy.com/oauth/token",
455 payload={
456 **mock_auth0_token_response,
457 "access_token": fresh_token,
458 "id_token": fresh_id_token,
459 },
460 )
461
462 # Mock Duke Energy API token exchange (for the refreshed token)
463 setup_auth_mocks(mocked, mock_duke_token_response)
464
465 # Mock account list endpoint
466 setup_api_mocks(mocked, mock_account_list_response, {"meterInfo": []})
467
468 # Create client and trigger API call (which triggers token refresh)
469 client = DukeEnergy(auth)
470 await client.get_accounts()
471
472 # Token should now be refreshed
473 token = auth.token
474 assert token is not None
475 assert token["access_token"] == fresh_token
476
477
478 class TestAccountAPI:
479 """Tests for account-related API calls."""
480
481 @pytest.mark.asyncio
482 async def test_get_accounts(
483 self,
484 mock_duke_token_response,
485 mock_account_list_response,
486 mock_account_details_response,
487 ):
488 """Test getting account information."""
489 test_token = _create_test_jwt(exp_offset_seconds=3600)
490 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
491
492 async with aiohttp.ClientSession() as session:
493 auth0_client = Auth0Client(session)
494 auth = DukeEnergyAuth(
495 session,
496 auth0_client,
497 access_token=test_token,
498 refresh_token="refresh", # noqa: S106
499 id_token=test_id_token,
500 )
501
502 with aioresponses() as mocked:
503 setup_auth_mocks(mocked, mock_duke_token_response)
504 setup_api_mocks(
505 mocked,
506 mock_account_list_response,
507 mock_account_details_response,
508 )
509
510 client = DukeEnergy(auth)
511 accounts = await client.get_accounts()
512
513 assert len(accounts) == 1
514 assert "accountNumber" in accounts
515 assert accounts["accountNumber"]["srcSysCd"] == "srcSysCd"
516
517 @pytest.mark.asyncio
518 async def test_get_meters(
519 self,
520 mock_duke_token_response,
521 mock_account_list_response,
522 mock_account_details_response,
523 ):
524 """Test getting meter information."""
525 test_token = _create_test_jwt(exp_offset_seconds=3600)
526 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
527
528 async with aiohttp.ClientSession() as session:
529 auth0_client = Auth0Client(session)
530 auth = DukeEnergyAuth(
531 session,
532 auth0_client,
533 access_token=test_token,
534 refresh_token="refresh", # noqa: S106
535 id_token=test_id_token,
536 )
537
538 with aioresponses() as mocked:
539 setup_auth_mocks(mocked, mock_duke_token_response)
540 setup_api_mocks(
541 mocked,
542 mock_account_list_response,
543 mock_account_details_response,
544 )
545
546 client = DukeEnergy(auth)
547 meters = await client.get_meters()
548
549 assert len(meters) == 1
550 assert "serialNum" in meters
551 assert meters["serialNum"]["serviceType"] == "ELECTRIC"
552
553
554 class TestUsageAPI:
555 """Tests for energy usage API calls."""
556
557 @pytest.mark.asyncio
558 async def test_hourly_energy_usage(
559 self,
560 mock_duke_token_response,
561 mock_account_list_response,
562 mock_account_details_response,
563 mock_usage_data,
564 ):
565 """Test getting hourly energy usage."""
566 test_token = _create_test_jwt(exp_offset_seconds=3600)
567 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
568
569 async with aiohttp.ClientSession() as session:
570 auth0_client = Auth0Client(session)
571 auth = DukeEnergyAuth(
572 session,
573 auth0_client,
574 access_token=test_token,
575 refresh_token="refresh", # noqa: S106
576 id_token=test_id_token,
577 )
578
579 with aioresponses() as mocked:
580 setup_auth_mocks(mocked, mock_duke_token_response)
581 setup_api_mocks(
582 mocked,
583 mock_account_list_response,
584 mock_account_details_response,
585 mock_usage_data,
586 )
587
588 client = DukeEnergy(auth)
589
590 # Get meters first
591 meters = await client.get_meters()
592 serial_number = next(iter(meters.keys()))
593
594 # Query for energy usage
595 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
596 end = datetime.strptime("2024-01-31", "%Y-%m-%d")
597 result = await client.get_energy_usage(
598 serial_number,
599 "HOURLY",
600 "DAY",
601 start,
602 end,
603 )
604
605 # Check results
606 assert len(result["data"]) == (31 * 24) - 2
607 assert len(result["missing"]) == 2
608 assert result["missing"][0] == start # First hour on first day
609 assert result["missing"][1] == start + timedelta(hours=2) # 02 AM
610 assert list(result["data"].values())[-1].get("temperature") == 30
611
612 @pytest.mark.asyncio
613 async def test_daily_energy_usage(
614 self,
615 mock_duke_token_response,
616 mock_account_list_response,
617 mock_account_details_response,
618 mock_daily_usage_data,
619 ):
620 """Test getting daily energy usage."""
621 test_token = _create_test_jwt(exp_offset_seconds=3600)
622 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
623
624 async with aiohttp.ClientSession() as session:
625 auth0_client = Auth0Client(session)
626 auth = DukeEnergyAuth(
627 session,
628 auth0_client,
629 access_token=test_token,
630 refresh_token="refresh", # noqa: S106
631 id_token=test_id_token,
632 )
633
634 with aioresponses() as mocked:
635 setup_auth_mocks(mocked, mock_duke_token_response)
636 setup_api_mocks(
637 mocked,
638 mock_account_list_response,
639 mock_account_details_response,
640 mock_daily_usage_data,
641 )
642
643 client = DukeEnergy(auth)
644
645 # Get meters first
646 meters = await client.get_meters()
647 serial_number = next(iter(meters.keys()))
648
649 # Query for energy usage
650 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
651 end = datetime.strptime("2024-01-31", "%Y-%m-%d")
652 result = await client.get_energy_usage(
653 serial_number,
654 "DAILY",
655 "BILLINGCYCLE",
656 start,
657 end,
658 )
659
660 # Check results
661 assert len(result["data"]) > 0, "No data was processed"
662 assert len(result["missing"]) > 0, "No missing days detected"
663
664 # Day 3 should be missing (0 usage)
665 missing_day = start + timedelta(days=2)
666 assert missing_day in result["missing"]
667
668 @pytest.mark.asyncio
669 async def test_energy_usage_duplicate_hours(
670 self,
671 mock_duke_token_response,
672 mock_account_list_response,
673 mock_account_details_response,
674 mock_duplicate_hours_data,
675 ):
676 """Test energy usage handling duplicate hours (like during DST changes)."""
677 test_token = _create_test_jwt(exp_offset_seconds=3600)
678 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
679
680 async with aiohttp.ClientSession() as session:
681 auth0_client = Auth0Client(session)
682 auth = DukeEnergyAuth(
683 session,
684 auth0_client,
685 access_token=test_token,
686 refresh_token="refresh", # noqa: S106
687 id_token=test_id_token,
688 )
689
690 with aioresponses() as mocked:
691 setup_auth_mocks(mocked, mock_duke_token_response)
692 setup_api_mocks(
693 mocked,
694 mock_account_list_response,
695 mock_account_details_response,
696 mock_duplicate_hours_data,
697 )
698
699 client = DukeEnergy(auth)
700
701 # Get meters first
702 meters = await client.get_meters()
703 serial_number = next(iter(meters.keys()))
704
705 # Query for energy usage - use a 2-day period
706 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
707 end = datetime.strptime("2024-01-02", "%Y-%m-%d")
708 result = await client.get_energy_usage(
709 serial_number,
710 "HOURLY",
711 "DAY",
712 start,
713 end,
714 )
715
716 # We should have 48 hours of data (2 days), minus 1 for the duplicate
717 expected_data_count = (2 * 24) - 1
718 assert len(result["data"]) == expected_data_count, (
719 f"Expected {expected_data_count} data points, "
720 f"got {len(result['data'])}"
721 )
722
723 # Verify all timestamps are sequential (no duplicates)
724 timestamps = sorted(result["data"].keys())
725 for i in range(1, len(timestamps)):
726 time_diff = timestamps[i] - timestamps[i - 1]
727 assert time_diff == timedelta(
728 hours=1
729 ), f"Expected 1 hour difference, got {time_diff}"
730
731 # The 1 AM on day 2 should have the first value, not the duplicate
732 day2_1am = start + timedelta(days=1, hours=1)
733 if day2_1am in result["data"]:
734 energy_value = result["data"][day2_1am]["energy"]
735 assert (
736 energy_value != 900.0
737 ), "Should not have the duplicate hour value (900.0)"
738
739
740 class TestErrorHandling:
741 """Tests for error handling."""
742
743 @pytest.mark.asyncio
744 async def test_get_id_token_without_authentication(self):
745 """Test that async_get_id_token fails without authentication."""
746 from aiodukeenergy import DukeEnergyAuthError
747
748 async with aiohttp.ClientSession() as session:
749 auth0_client = Auth0Client(session)
750 auth = DukeEnergyAuth(session, auth0_client)
751
752 with pytest.raises(DukeEnergyAuthError, match="Not authenticated"):
753 await auth.async_get_id_token()
754
755 @pytest.mark.asyncio
756 async def test_token_refresh_with_expired_token_no_refresh(self):
757 """Test token refresh with expired token and no refresh token."""
758 from aiodukeenergy import DukeEnergyTokenExpiredError
759
760 expired_token = _create_test_jwt(exp_offset_seconds=-3600)
761 expired_id_token = _create_test_jwt(exp_offset_seconds=-3600)
762
763 async with aiohttp.ClientSession() as session:
764 auth0_client = Auth0Client(session)
765 auth = DukeEnergyAuth(
766 session,
767 auth0_client,
768 access_token=expired_token,
769 id_token=expired_id_token,
770 # No refresh token provided
771 )
772
773 with pytest.raises(DukeEnergyTokenExpiredError):
774 await auth.async_get_id_token()
775
776 @pytest.mark.asyncio
777 async def test_auth0_token_exchange_failure(self):
778 """Test Auth0 token exchange returns error on failure."""
779 from aiodukeenergy import DukeEnergyAuthError
780
781 async with aiohttp.ClientSession() as session:
782 auth0_client = Auth0Client(session)
783 auth = DukeEnergyAuth(session, auth0_client)
784
785 with aioresponses() as mocked:
786 # Mock Auth0 token endpoint with error
787 mocked.post(
788 "https://login.duke-energy.com/oauth/token",
789 status=400,
790 payload={"error": "invalid_grant"},
791 )
792
793 with pytest.raises(DukeEnergyAuthError, match="Token exchange failed"):
794 await auth.authenticate_with_code("bad_code", "verifier")
795
796 @pytest.mark.asyncio
797 async def test_duke_energy_token_exchange_failure(self, mock_auth0_token_response):
798 """Test Duke Energy token exchange returns error on failure."""
799 from aiodukeenergy import DukeEnergyAuthError
800
801 async with aiohttp.ClientSession() as session:
802 auth0_client = Auth0Client(session)
803 auth = DukeEnergyAuth(session, auth0_client)
804
805 with aioresponses() as mocked:
806 # Mock Auth0 token endpoint success
807 mocked.post(
808 "https://login.duke-energy.com/oauth/token",
809 payload=mock_auth0_token_response,
810 )
811 # Mock Duke Energy API token exchange with error
812 mocked.post(
813 "https://api-v2.cma.duke-energy.app/login/auth-token",
814 status=401,
815 payload={"error": "unauthorized"},
816 )
817
818 with pytest.raises(
819 DukeEnergyAuthError, match="Duke Energy token exchange failed"
820 ):
821 await auth.authenticate_with_code("test_code", "verifier")
822
823 @pytest.mark.asyncio
824 async def test_auth0_token_refresh_failure(self):
825 """Test Auth0 token refresh returns error on failure."""
826 from aiodukeenergy import DukeEnergyTokenExpiredError
827
828 expired_token = _create_test_jwt(exp_offset_seconds=-3600)
829 expired_id_token = _create_test_jwt(exp_offset_seconds=-3600)
830
831 async with aiohttp.ClientSession() as session:
832 auth0_client = Auth0Client(session)
833 auth = DukeEnergyAuth(
834 session,
835 auth0_client,
836 access_token=expired_token,
837 id_token=expired_id_token,
838 refresh_token="refresh_token", # noqa: S106
839 )
840
841 with aioresponses() as mocked:
842 # Mock Auth0 refresh endpoint with error
843 mocked.post(
844 "https://login.duke-energy.com/oauth/token",
845 status=400,
846 payload={"error": "invalid_grant"},
847 )
848
849 with pytest.raises(DukeEnergyTokenExpiredError, match="Token refresh"):
850 await auth.async_get_id_token()
851
852 @pytest.mark.asyncio
853 async def test_get_energy_usage_invalid_serial_number(
854 self,
855 mock_duke_token_response,
856 mock_account_list_response,
857 mock_account_details_response,
858 ):
859 """Test that get_energy_usage raises ValueError for unknown serial number."""
860 test_token = _create_test_jwt(exp_offset_seconds=3600)
861 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
862
863 async with aiohttp.ClientSession() as session:
864 auth0_client = Auth0Client(session)
865 auth = DukeEnergyAuth(
866 session,
867 auth0_client,
868 access_token=test_token,
869 refresh_token="refresh", # noqa: S106
870 id_token=test_id_token,
871 )
872
873 with aioresponses() as mocked:
874 setup_auth_mocks(mocked, mock_duke_token_response)
875 setup_api_mocks(
876 mocked,
877 mock_account_list_response,
878 mock_account_details_response,
879 )
880
881 client = DukeEnergy(auth)
882 await client.get_meters()
883
884 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
885 end = datetime.strptime("2024-01-31", "%Y-%m-%d")
886 with pytest.raises(ValueError, match="Meter invalid_serial not found"):
887 await client.get_energy_usage(
888 "invalid_serial", "DAILY", "WEEK", start, end
889 )
890
891 @pytest.mark.asyncio
892 async def test_get_json_logs_error_body_on_failure(
893 self,
894 mock_duke_token_response,
895 mock_account_list_response,
896 ):
897 """Test that _get_json logs error body and raises on non-OK response."""
898 test_token = _create_test_jwt(exp_offset_seconds=3600)
899 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
900
901 async with aiohttp.ClientSession() as session:
902 auth0_client = Auth0Client(session)
903 auth = DukeEnergyAuth(
904 session,
905 auth0_client,
906 access_token=test_token,
907 refresh_token="refresh", # noqa: S106
908 id_token=test_id_token,
909 )
910
911 with aioresponses() as mocked:
912 setup_auth_mocks(mocked, mock_duke_token_response)
913 pattern = re.compile(
914 r"^https://api-v2\.cma\.duke-energy\.app/account-list"
915 )
916 mocked.get(pattern, status=500, body=b"Internal Server Error")
917
918 client = DukeEnergy(auth)
919 with pytest.raises(aiohttp.ClientResponseError):
920 await client.get_accounts()
921
922 @pytest.mark.asyncio
923 async def test_post_json_logs_error_body_on_failure(
924 self,
925 mock_duke_token_response,
926 mock_account_list_response,
927 mock_account_details_response,
928 ):
929 """Test that _post_json logs error body and raises on non-OK response."""
930 test_token = _create_test_jwt(exp_offset_seconds=3600)
931 test_id_token = _create_test_jwt(exp_offset_seconds=3600)
932
933 async with aiohttp.ClientSession() as session:
934 auth0_client = Auth0Client(session)
935 auth = DukeEnergyAuth(
936 session,
937 auth0_client,
938 access_token=test_token,
939 refresh_token="refresh", # noqa: S106
940 id_token=test_id_token,
941 )
942
943 with aioresponses() as mocked:
944 setup_auth_mocks(mocked, mock_duke_token_response)
945 setup_api_mocks(
946 mocked,
947 mock_account_list_response,
948 mock_account_details_response,
949 )
950 pattern = re.compile(
951 r"^https://api-v2\.cma\.duke-energy\.app/account/usage/graph"
952 )
953 mocked.post(pattern, status=400, body=b"Bad Request")
954
955 client = DukeEnergy(auth)
956 meters = await client.get_meters()
957 serial_number = next(iter(meters.keys()))
958
959 start = datetime.strptime("2024-01-01", "%Y-%m-%d")
960 end = datetime.strptime("2024-01-31", "%Y-%m-%d")
961 with pytest.raises(aiohttp.ClientResponseError):
962 await client.get_energy_usage(
963 serial_number, "DAILY", "WEEK", start, end
964 )
965
966
967 class TestUtilityFunctions:
968 """Tests for utility functions."""
969
970 def test_extract_code_from_url_valid(self):
971 """Test extracting authorization code from valid redirect URL."""
972 from aiodukeenergy.auth0 import extract_code_from_url
973
974 url = "https://login.duke-energy.com/ios/com.duke-energy.app/callback?code=abc123&state=xyz"
975 code = extract_code_from_url(url)
976 assert code == "abc123"
977
978 def test_extract_code_from_url_no_code(self):
979 """Test extracting authorization code when not present."""
980 from aiodukeenergy.auth0 import extract_code_from_url
981
982 url = "https://login.duke-energy.com/ios/com.duke-energy.app/callback?state=xyz"
983 code = extract_code_from_url(url)
984 assert code is None
985
986 def test_extract_code_from_url_with_ampersand(self):
987 """Test extracting authorization code with trailing parameters."""
988 from aiodukeenergy.auth0 import extract_code_from_url
989
990 url = "https://login.duke-energy.com/ios/com.duke-energy.app/callback?code=test_code_123&state=abc&other=param"
991 code = extract_code_from_url(url)
992 assert code == "test_code_123"
993
994 def test_is_token_expired_valid_token(self):
995 """Test is_token_expired with a valid non-expired token."""
996 from aiodukeenergy.auth0 import is_token_expired
997
998 token = _create_test_jwt(exp_offset_seconds=3600) # 1 hour in future
999 assert is_token_expired(token) is False
1000
1001 def test_is_token_expired_expired_token(self):
1002 """Test is_token_expired with an expired token."""
1003 from aiodukeenergy.auth0 import is_token_expired
1004
1005 token = _create_test_jwt(exp_offset_seconds=-3600) # 1 hour ago
1006 assert is_token_expired(token) is True
1007
1008 def test_is_token_expired_invalid_token(self):
1009 """Test is_token_expired with an invalid token."""
1010 from aiodukeenergy.auth0 import is_token_expired
1011
1012 assert is_token_expired("invalid.token") is True
1013 assert is_token_expired("") is True
1014
1015 def test_is_token_expired_no_exp_claim(self):
1016 """Test is_token_expired with token missing exp claim."""
1017 import jwt as pyjwt
1018
1019 from aiodukeenergy.auth0 import is_token_expired
1020
1021 # Create token without exp claim
1022 payload = {"email": "[email protected]"}
1023 token = pyjwt.encode(payload, "secret", algorithm="HS256")
1024 assert is_token_expired(token) is True
1025
1026 def test_decode_token(self):
1027 """Test decode_token returns payload."""
1028 from aiodukeenergy.auth0 import decode_token
1029
1030 token = _create_test_jwt()
1031 payload = decode_token(token)
1032 assert payload["email"] == "[email protected]"
1033 assert payload["internal_identifier"] == "DUKE_TEST_USER"
1034
1035
1036 class TestAuth0Client:
1037 """Tests for Auth0Client class."""
1038
1039 @pytest.mark.asyncio
1040 async def test_exchange_code_without_verifier(self):
1041 """Test exchange_code raises error when verifier not set."""
1042 from aiodukeenergy import Auth0Client, DukeEnergyAuthError
1043
1044 async with aiohttp.ClientSession() as session:
1045 auth0 = Auth0Client(session)
1046 # Don't call get_authorization_url first, so no verifier is set
1047 with pytest.raises(DukeEnergyAuthError, match="Code verifier not set"):
1048 await auth0.exchange_code("test_code")
1049
1050 @pytest.mark.asyncio
1051 async def test_get_user_info(self):
1052 """Test getting user info from Auth0."""
1053 from aiodukeenergy import Auth0Client
1054
1055 async with aiohttp.ClientSession() as session:
1056 auth0 = Auth0Client(session)
1057
1058 with aioresponses() as mocked:
1059 mocked.get(
1060 "https://login.duke-energy.com/userinfo",
1061 payload={"email": "[email protected]", "sub": "user123"},
1062 )
1063
1064 user_info = await auth0.get_user_info("test_access_token")
1065 assert user_info["email"] == "[email protected]"
1066 assert user_info["sub"] == "user123"
1067
1068
1069 class TestDukeEnergyAuthTokenManagement:
1070 """Tests for DukeEnergyAuth token management."""
1071
1072 @pytest.mark.asyncio
1073 async def test_token_property_returns_none_when_not_authenticated(self):
1074 """Test token property returns None when not authenticated."""
1075 from aiodukeenergy import Auth0Client, DukeEnergyAuth
1076
1077 async with aiohttp.ClientSession() as session:
1078 auth0 = Auth0Client(session)
1079 auth = DukeEnergyAuth(session, auth0)
1080 assert auth.token is None
1081
1082 @pytest.mark.asyncio
1083 async def test_restore_token(self):
1084 """Test restore_token restores tokens and user info."""
1085 from aiodukeenergy import Auth0Client, DukeEnergyAuth
1086
1087 async with aiohttp.ClientSession() as session:
1088 auth0 = Auth0Client(session)
1089 auth = DukeEnergyAuth(session, auth0)
1090
1091 # Create token data with valid JWT for user info extraction
1092 id_token = _create_test_jwt()
1093 token_data = {
1094 "access_token": "restored_access",
1095 "refresh_token": "restored_refresh",
1096 "id_token": id_token,
1097 }
1098
1099 auth.restore_token(token_data)
1100
1101 assert auth.token is not None
1102 assert auth.token["access_token"] == "restored_access" # noqa: S105
1103 assert auth.token["refresh_token"] == "restored_refresh" # noqa: S105
1104 assert auth.email == "[email protected]"
1105 assert auth.internal_user_id == "DUKE_TEST_USER"
1106
1107 @pytest.mark.asyncio
1108 async def test_restore_token_with_invalid_id_token(self):
1109 """Test restore_token handles invalid id_token gracefully."""
1110 from aiodukeenergy import Auth0Client, DukeEnergyAuth
1111
1112 async with aiohttp.ClientSession() as session:
1113 auth0 = Auth0Client(session)
1114 auth = DukeEnergyAuth(session, auth0)
1115
1116 # Restore with invalid id_token - should not raise
1117 token_data = {
1118 "access_token": "restored_access",
1119 "refresh_token": "restored_refresh",
1120 "id_token": "invalid.jwt.token",
1121 }
1122
1123 # Should not raise, just log debug message
1124 auth.restore_token(token_data)
1125 assert auth.token is not None
1126
1127 @pytest.mark.asyncio
1128 async def test_duke_token_expired_without_expiry_info(self):
1129 """Test DE token is considered expired when no expiry info."""
1130 from aiodukeenergy import Auth0Client, DukeEnergyAuth
1131
1132 async with aiohttp.ClientSession() as session:
1133 auth0 = Auth0Client(session)
1134 auth = DukeEnergyAuth(session, auth0)
1135
1136 # Set only the DE access token without issued_at/expires_in
1137 auth._de_access_token = "some_token" # noqa: S105
1138 auth._de_token_issued_at = None
1139 auth._de_token_expires_in = None
1140
1141 # Token should be considered expired
1142 assert auth._is_de_token_expired() is True
1143
1144 @pytest.mark.asyncio
1145 async def test_duke_token_with_server_issued_at(self, mock_auth0_token_response):
1146 """Test Duke token exchange uses server's issued_at timestamp."""
1147 from aiodukeenergy import Auth0Client, DukeEnergyAuth
1148
1149 async with aiohttp.ClientSession() as session:
1150 auth0 = Auth0Client(session)
1151 auth = DukeEnergyAuth(session, auth0)
1152
1153 server_issued_at = 1700000000 # Fixed timestamp
1154
1155 with aioresponses() as mocked:
1156 # Mock Auth0 token endpoint
1157 mocked.post(
1158 "https://login.duke-energy.com/oauth/token",
1159 payload=mock_auth0_token_response,
1160 )
1161 # Mock Duke Energy API token exchange with server-provided issued_at
1162 mocked.post(
1163 "https://api-v2.cma.duke-energy.app/login/auth-token",
1164 payload={
1165 "access_token": "de_token",
1166 "expires_in": 1800,
1167 "issued_at": server_issued_at,
1168 },
1169 )
1170
1171 await auth.authenticate_with_code("test_code", "verifier")
1172
1173 # Verify server timestamp was used
1174 assert auth._de_token_issued_at is not None
1175 assert auth._de_token_issued_at.timestamp() == server_issued_at
1176
1177
1178 class TestImports:
1179 """Tests for module imports and exports."""
1180
1181 def test_package_exports(self):
1182 """Test that the package exports the expected symbols."""
1183 from aiodukeenergy import (
1184 AbstractDukeEnergyAuth,
1185 Auth0Client,
1186 DukeEnergy,
1187 DukeEnergyAuth,
1188 DukeEnergyAuthError,
1189 DukeEnergyError,
1190 DukeEnergyTokenExpiredError,
1191 )
1192
1193 assert AbstractDukeEnergyAuth is not None
1194 assert Auth0Client is not None
1195 assert DukeEnergy is not None
1196 assert DukeEnergyAuth is not None
1197 assert DukeEnergyError is not None
1198 assert DukeEnergyAuthError is not None
1199 assert DukeEnergyTokenExpiredError is not None
1200
1201 def test_duke_energy_auth_is_subclass_of_abstract(self):
1202 """Test that DukeEnergyAuth is a subclass of AbstractDukeEnergyAuth."""
1203 from aiodukeenergy import AbstractDukeEnergyAuth, DukeEnergyAuth
1204
1205 assert issubclass(DukeEnergyAuth, AbstractDukeEnergyAuth)
1206
1207 def test_version_available(self):
1208 """Test that version is available."""
1209 from aiodukeenergy import __version__
1210
1211 assert __version__ is not None
1212 assert isinstance(__version__, str)