Debian Codegraph @

tests/test_payments_api.py

raw
1 """Test the payments connection details API."""
2
3 from __future__ import annotations
4
5 import logging
6 import re
7 from typing import TYPE_CHECKING, Any
8 from unittest.mock import AsyncMock, patch
9
10 from aiohttp import ClientError
11 import pytest
12 from syrupy import SnapshotAssertion
13
14 from hass_nabucasa.payments_api import (
15 MigratePaypalAgreementInfo,
16 PaymentsApiError,
17 SubscriptionInfo,
18 )
19 from tests.common import extract_log_messages
20
21 if TYPE_CHECKING:
22 from hass_nabucasa import Cloud
23 from tests.utils.aiohttp import AiohttpClientMocker
24
25
26 @pytest.mark.parametrize(
27 "exception,getmockargs,exception_msg",
28 [
29 [
30 PaymentsApiError,
31 {"status": 500, "text": "Internal Server Error"},
32 "Failed to parse API response",
33 ],
34 [
35 PaymentsApiError,
36 {"status": 429, "text": "Too fast"},
37 "Failed to parse API response",
38 ],
39 [
40 PaymentsApiError,
41 {"exc": TimeoutError()},
42 "Timeout reached while calling API",
43 ],
44 [
45 PaymentsApiError,
46 {"exc": ClientError("boom!")},
47 "Failed to fetch: boom!",
48 ],
49 [
50 PaymentsApiError,
51 {"exc": Exception("boom!")},
52 "Unexpected error while calling API: boom!",
53 ],
54 ],
55 )
56 async def test_problems_getting_connection_details(
57 aioclient_mock: AiohttpClientMocker,
58 exception: Exception,
59 getmockargs,
60 exception_msg,
61 cloud: Cloud,
62 caplog: pytest.LogCaptureFixture,
63 snapshot: SnapshotAssertion,
64 ):
65 """Test problems getting connection details."""
66 aioclient_mock.get(
67 f"https://{cloud.api_server}/account/payments/subscription_info",
68 **getmockargs,
69 )
70
71 with pytest.raises(exception, match=exception_msg):
72 await cloud.payments.subscription_info()
73
74 assert extract_log_messages(caplog) == snapshot
75
76
77 @pytest.mark.parametrize(
78 "response",
79 [
80 {
81 "provider": "legacy",
82 }
83 ],
84 )
85 async def test_getting_connection_details(
86 aioclient_mock: AiohttpClientMocker,
87 response: dict[str, Any],
88 cloud: Cloud,
89 caplog: pytest.LogCaptureFixture,
90 snapshot: SnapshotAssertion,
91 ):
92 """Test getting connection details."""
93 aioclient_mock.get(
94 f"https://{cloud.api_server}/account/payments/subscription_info",
95 json=response,
96 )
97
98 details = await cloud.payments.subscription_info()
99
100 assert details == SubscriptionInfo(**response)
101 assert extract_log_messages(caplog) == snapshot
102
103
104 async def test_trigger_async_renew_access_token(
105 aioclient_mock: AiohttpClientMocker,
106 cloud: Cloud,
107 caplog: pytest.LogCaptureFixture,
108 snapshot: SnapshotAssertion,
109 ):
110 """Test getting connection details."""
111 aioclient_mock.get(
112 f"https://{cloud.api_server}/account/payments/subscription_info",
113 json={"provider": "legacy"},
114 )
115
116 cloud.started = False
117 with patch(
118 "hass_nabucasa.auth.CognitoAuth.async_renew_access_token",
119 new_callable=AsyncMock,
120 ) as renew_access_token_mock:
121 await cloud.payments.subscription_info()
122 assert renew_access_token_mock.call_count == 1
123
124 assert extract_log_messages(caplog) == snapshot
125
126
127 @pytest.mark.parametrize(
128 "exception,postmockargs,exception_msg",
129 [
130 [
131 PaymentsApiError,
132 {"status": 500, "text": "Internal Server Error"},
133 "Failed to fetch: (500)",
134 ],
135 [
136 PaymentsApiError,
137 {"status": 429, "text": "Too fast"},
138 "Failed to fetch: (429)",
139 ],
140 [
141 PaymentsApiError,
142 {"exc": TimeoutError()},
143 "Timeout reached while calling API",
144 ],
145 [
146 PaymentsApiError,
147 {"exc": ClientError("boom!")},
148 "Failed to fetch: boom!",
149 ],
150 [
151 PaymentsApiError,
152 {"exc": Exception("boom!")},
153 "Unexpected error while calling API: boom!",
154 ],
155 ],
156 )
157 async def test_problems_migrating_paypal_agreement(
158 aioclient_mock: AiohttpClientMocker,
159 exception: Exception,
160 postmockargs,
161 exception_msg,
162 cloud: Cloud,
163 caplog: pytest.LogCaptureFixture,
164 snapshot: SnapshotAssertion,
165 ):
166 """Test problems migrating PayPal agreement."""
167 aioclient_mock.post(
168 f"https://{cloud.api_server}/account/payments/migrate_paypal_agreement",
169 **postmockargs,
170 )
171
172 with pytest.raises(exception, match=re.escape(exception_msg)):
173 await cloud.payments.migrate_paypal_agreement()
174
175 assert extract_log_messages(caplog) == snapshot
176
177
178 @pytest.mark.parametrize(
179 "response",
180 [
181 {
182 "url": "https://www.paypal.com/agreement/migrate?token=EC-123456789",
183 },
184 {
185 "url": "https://www.sandbox.paypal.com/agreement/migrate?token=EC-987654321",
186 },
187 ],
188 )
189 async def test_migrate_paypal_agreement_success(
190 aioclient_mock: AiohttpClientMocker,
191 response: dict[str, Any],
192 cloud: Cloud,
193 caplog: pytest.LogCaptureFixture,
194 snapshot: SnapshotAssertion,
195 ):
196 """Test successful PayPal agreement migration."""
197 aioclient_mock.post(
198 f"https://{cloud.api_server}/account/payments/migrate_paypal_agreement",
199 json=response,
200 )
201
202 result = await cloud.payments.migrate_paypal_agreement()
203
204 assert result == MigratePaypalAgreementInfo(**response)
205 assert extract_log_messages(caplog) == snapshot
206
207
208 async def test_no_token_refresh_when_cloud_started(
209 aioclient_mock: AiohttpClientMocker,
210 cloud: Cloud,
211 caplog: pytest.LogCaptureFixture,
212 snapshot: SnapshotAssertion,
213 ):
214 """Test that token refresh is not triggered when cloud is already started."""
215 aioclient_mock.get(
216 f"https://{cloud.api_server}/account/payments/subscription_info",
217 json={"provider": "legacy"},
218 )
219
220 cloud.started = True
221
222 with patch(
223 "hass_nabucasa.auth.CognitoAuth.async_renew_access_token",
224 new_callable=AsyncMock,
225 ) as renew_access_token_mock:
226 await cloud.payments.subscription_info()
227 assert renew_access_token_mock.call_count == 0
228
229
230 async def test_no_token_refresh_when_no_provider(
231 aioclient_mock: AiohttpClientMocker,
232 cloud: Cloud,
233 caplog: pytest.LogCaptureFixture,
234 snapshot: SnapshotAssertion,
235 ):
236 """Test that token refresh is not triggered when no provider is present."""
237 aioclient_mock.get(
238 f"https://{cloud.api_server}/account/payments/subscription_info",
239 json={"provider": None},
240 )
241 cloud.started = False
242 with patch(
243 "hass_nabucasa.auth.CognitoAuth.async_renew_access_token",
244 new_callable=AsyncMock,
245 ) as renew_access_token_mock:
246 await cloud.payments.subscription_info()
247 assert renew_access_token_mock.call_count == 0
248
249
250 async def test_no_token_refresh_when_skip_renew(
251 aioclient_mock: AiohttpClientMocker,
252 cloud: Cloud,
253 caplog: pytest.LogCaptureFixture,
254 snapshot: SnapshotAssertion,
255 ):
256 """Test that token refresh is not triggered when skip_renew is True."""
257 aioclient_mock.get(
258 f"https://{cloud.api_server}/account/payments/subscription_info",
259 json={"provider": "legacy"},
260 )
261
262 cloud.started = False
263 with patch(
264 "hass_nabucasa.auth.CognitoAuth.async_renew_access_token",
265 new_callable=AsyncMock,
266 ) as renew_access_token_mock:
267 await cloud.payments.subscription_info(skip_renew=True)
268 assert renew_access_token_mock.call_count == 0
269
270
271 async def test_token_refresh_debug_log(
272 aioclient_mock: AiohttpClientMocker,
273 cloud: Cloud,
274 caplog: pytest.LogCaptureFixture,
275 snapshot: SnapshotAssertion,
276 ):
277 """Test that debug log is written when token refresh is triggered."""
278 aioclient_mock.get(
279 f"https://{cloud.api_server}/account/payments/subscription_info",
280 json={"provider": "legacy"},
281 )
282
283 cloud.started = False
284 with patch(
285 "hass_nabucasa.auth.CognitoAuth.async_renew_access_token",
286 new_callable=AsyncMock,
287 ) as renew_access_token_mock:
288 with caplog.at_level(logging.DEBUG):
289 await cloud.payments.subscription_info()
290
291 assert renew_access_token_mock.call_count == 1
292 assert extract_log_messages(caplog) == snapshot