Debian Codegraph @

src/tests/test_auth.py

raw symbols SCIP
1 """Tests for VeSyncAuth authentication module.
2
3 Tests cover:
4 - Initialization and properties (region mapping, credentials state)
5 - Credential management (set, clear, output)
6 - File-based credential persistence (save, load)
7 - Login flow (get_authorization_code -> exchange for token)
8 - Re-authentication
9 - Error handling (bad responses, missing fields, cross-region)
10 """
11
12 import logging
13 from pathlib import Path
14
15 import orjson
16 import pytest
17
18 from pyvesync import VeSync
19 from pyvesync.utils.errors import (
20 VeSyncAPIResponseError,
21 VeSyncLoginError,
22 VeSyncServerError,
23 )
24
25 from base_test_cases import TestBase
26 from defaults import TestDefaults
27 import call_json
28
29 logger = logging.getLogger(__name__)
30
31 LOGIN_RESPONSES = call_json.LoginResponses
32
33
34 # ---------------------------------------------------------------------------
35 # Initialization & Properties
36 # ---------------------------------------------------------------------------
37
38
39 class TestAuthInit(TestBase):
40 """Test VeSyncAuth initialization and property accessors."""
41
42 def test_default_region_us(self):
43 """US country code maps to US region."""
44 assert self.manager.auth._country_code == 'US'
45 assert self.manager.auth.current_region == 'US'
46
47 def test_region_eu(self):
48 """Non-US/CA/MX/JP country codes map to EU region."""
49 manager = VeSync('user', 'pass', country_code='DE')
50 assert manager.auth.current_region == 'EU'
51
52 def test_region_jp(self):
53 """JP country code maps to US region."""
54 manager = VeSync('user', 'pass', country_code='JP')
55 assert manager.auth.current_region == 'US'
56
57 def test_country_code_uppercased(self):
58 """Country code is stored uppercased."""
59 manager = VeSync('user', 'pass', country_code='ca')
60 assert manager.auth.country_code == 'CA'
61
62 def test_country_code_setter_uppercases(self):
63 """Country code setter uppercases value."""
64 self.manager.auth.country_code = 'mx'
65 assert self.manager.auth.country_code == 'MX'
66
67 def test_not_authenticated_initially(self):
68 """Auth is not authenticated before login."""
69 manager = VeSync('user', 'pass')
70 assert manager.auth.is_authenticated is False
71
72 def test_token_raises_before_login(self):
73 """Accessing token before login raises AttributeError."""
74 manager = VeSync('user', 'pass')
75 with pytest.raises(AttributeError, match='Token not set'):
76 _ = manager.auth.token
77
78 def test_account_id_raises_before_login(self):
79 """Accessing account_id before login raises AttributeError."""
80 manager = VeSync('user', 'pass')
81 with pytest.raises(AttributeError, match='Account ID not set'):
82 _ = manager.auth.account_id
83
84 def test_repr(self):
85 """Test __repr__ output."""
86 manager = VeSync('[email protected]', 'pass')
87 r = repr(manager.auth)
88 assert '[email protected]' in r
89 assert 'authenticated=False' in r
90
91
92 # ---------------------------------------------------------------------------
93 # Credential Management
94 # ---------------------------------------------------------------------------
95
96
97 class TestCredentialManagement(TestBase):
98 """Test set_credentials, clear_credentials, and output methods."""
99
100 def test_set_credentials(self):
101 """set_credentials sets all fields and marks authenticated."""
102 auth = self.manager.auth
103 auth.set_credentials(
104 token='tk_123',
105 account_id='acct_456',
106 country_code='de',
107 region='EU',
108 )
109 assert auth.is_authenticated is True
110 assert auth.token == 'tk_123'
111 assert auth.account_id == 'acct_456'
112 assert auth.country_code == 'DE'
113 assert auth.current_region == 'EU'
114
115 def test_clear_credentials(self):
116 """clear_credentials resets token and account_id."""
117 auth = self.manager.auth
118 auth.set_credentials('tk', 'acct', 'US', 'US')
119 assert auth.is_authenticated is True
120 auth.clear_credentials()
121 assert auth.is_authenticated is False
122
123 def test_output_credentials_dict_authenticated(self):
124 """output_credentials_dict returns dict when authenticated."""
125 auth = self.manager.auth
126 auth.set_credentials('tk_abc', 'acct_xyz', 'US', 'US')
127 result = auth.output_credentials_dict()
128 assert result == {
129 'token': 'tk_abc',
130 'account_id': 'acct_xyz',
131 'country_code': 'US',
132 'current_region': 'US',
133 }
134
135 def test_output_credentials_dict_not_authenticated(self):
136 """output_credentials_dict returns None when not authenticated."""
137 manager = VeSync('user', 'pass')
138 assert manager.auth.output_credentials_dict() is None
139
140 def test_output_credentials_json_authenticated(self):
141 """output_credentials_json returns JSON string when authenticated."""
142 auth = self.manager.auth
143 auth.set_credentials('tk', 'acct', 'US', 'US')
144 json_str = auth.output_credentials_json()
145 assert json_str is not None
146 parsed = orjson.loads(json_str)
147 assert parsed['token'] == 'tk'
148 assert parsed['account_id'] == 'acct'
149
150 def test_output_credentials_json_not_authenticated(self):
151 """output_credentials_json returns None when not authenticated."""
152 manager = VeSync('user', 'pass')
153 assert manager.auth.output_credentials_json() is None
154
155
156 # ---------------------------------------------------------------------------
157 # File-based Credential Persistence
158 # ---------------------------------------------------------------------------
159
160
161 class TestCredentialFile(TestBase):
162 """Test save/load credentials to/from file."""
163
164 def test_save_and_load_credentials(self, tmp_path):
165 """Save credentials to file and load them back."""
166 auth = self.manager.auth
167 auth.set_credentials('tk_save', 'acct_save', 'US', 'US')
168
169 file_path = tmp_path / '.vesync_auth'
170 self.run_in_loop(auth.save_credentials_to_file, file_path)
171 assert file_path.exists()
172
173 # Load into a fresh manager
174 manager2 = VeSync('user', 'pass')
175 success = self.loop.run_until_complete(
176 manager2.auth.load_credentials_from_file(file_path)
177 )
178 assert success is True
179 assert manager2.auth.token == 'tk_save'
180 assert manager2.auth.account_id == 'acct_save'
181 assert manager2.auth.country_code == 'US'
182 assert manager2.enabled is True
183
184 def test_load_nonexistent_file(self, tmp_path):
185 """Loading from a nonexistent file returns False."""
186 auth = self.manager.auth
187 result = self.loop.run_until_complete(
188 auth.load_credentials_from_file(tmp_path / 'missing_file')
189 )
190 assert result is False
191
192 def test_load_invalid_json(self, tmp_path):
193 """Loading a file with invalid JSON returns False."""
194 file_path = tmp_path / '.vesync_auth'
195 file_path.write_text('not json', encoding='utf-8')
196
197 auth = self.manager.auth
198 result = self.loop.run_until_complete(
199 auth.load_credentials_from_file(file_path)
200 )
201 assert result is False
202
203 def test_load_missing_keys(self, tmp_path):
204 """Loading a file with missing keys returns False."""
205 file_path = tmp_path / '.vesync_auth'
206 file_path.write_text(
207 orjson.dumps({'token': 'tk'}).decode('utf-8'),
208 encoding='utf-8',
209 )
210 auth = self.manager.auth
211 result = self.loop.run_until_complete(
212 auth.load_credentials_from_file(file_path)
213 )
214 assert result is False
215
216 def test_save_not_authenticated(self, tmp_path):
217 """Saving credentials when not authenticated does nothing."""
218 manager = VeSync('user', 'pass')
219 file_path = tmp_path / '.vesync_auth'
220 self.loop.run_until_complete(
221 manager.auth.save_credentials_to_file(file_path)
222 )
223 assert not file_path.exists()
224
225 def test_clear_credentials_deletes_file(self, tmp_path):
226 """clear_credentials deletes the token file."""
227 auth = self.manager.auth
228 auth.set_credentials('tk', 'acct', 'US', 'US')
229
230 file_path = tmp_path / '.vesync_auth'
231 self.loop.run_until_complete(auth.save_credentials_to_file(file_path))
232 assert file_path.exists()
233
234 # Set the token file path (load sets this, but we saved directly)
235 auth._token_file_path = file_path
236 auth.clear_credentials()
237 assert not file_path.exists()
238
239 def test_credentials_saved_property(self, tmp_path):
240 """credentials_saved reflects whether a token file exists."""
241 auth = self.manager.auth
242 assert auth.credentials_saved is False
243
244 auth.set_credentials('tk', 'acct', 'US', 'US')
245 file_path = tmp_path / '.vesync_auth'
246 self.loop.run_until_complete(auth.save_credentials_to_file(file_path))
247 auth._token_file_path = file_path
248 assert auth.credentials_saved is True
249
250 def test_load_with_path_object(self, tmp_path):
251 """Loading credentials accepts a Path object."""
252 auth = self.manager.auth
253 auth.set_credentials('tk_path', 'acct_path', 'CA', 'US')
254
255 file_path = tmp_path / '.vesync_auth'
256 self.loop.run_until_complete(auth.save_credentials_to_file(file_path))
257
258 manager2 = VeSync('user', 'pass')
259 success = self.loop.run_until_complete(
260 manager2.auth.load_credentials_from_file(Path(file_path))
261 )
262 assert success is True
263 assert manager2.auth.token == 'tk_path'
264
265
266 # ---------------------------------------------------------------------------
267 # Login Flow
268 # ---------------------------------------------------------------------------
269
270
271 class TestLoginFlow(TestBase):
272 """Test login flow with mocked async_call_api."""
273
274 def test_login_success(self):
275 """Successful two-step login sets token and account_id."""
276 self.mock_api.side_effect = [
277 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
278 (LOGIN_RESPONSES.LOGIN_RESPONSE_SUCCESS, 200),
279 ]
280 result = self.run_in_loop(self.manager.auth.login)
281 assert result is True
282 assert self.manager.auth.is_authenticated is True
283 assert self.manager.auth.token == TestDefaults.token
284 assert self.manager.auth.account_id == TestDefaults.account_id
285
286 def test_login_no_credentials(self):
287 """Login without username/password raises VeSyncLoginError."""
288 manager = VeSync('', '')
289 manager.auth._token = None
290 manager.auth._account_id = None
291 with pytest.raises(VeSyncLoginError, match='No valid authentication'):
292 self.loop.run_until_complete(manager.auth.login())
293
294 def test_login_auth_error_code(self):
295 """Non-zero code in auth response raises VeSyncLoginError."""
296 error_resp = {
297 'traceId': TestDefaults.trace_id,
298 'code': -11201000,
299 'msg': 'Invalid password',
300 'result': None,
301 }
302 self.mock_api.return_value = (error_resp, 200)
303 with pytest.raises(VeSyncLoginError, match='Authentication failed'):
304 self.run_in_loop(self.manager.auth.login)
305
306 def test_login_none_response(self):
307 """None API response raises VeSyncAPIResponseError."""
308 self.mock_api.return_value = (None, 200)
309 with pytest.raises(
310 VeSyncAPIResponseError, match='Error receiving response'
311 ):
312 self.run_in_loop(self.manager.auth.login)
313
314 def test_login_exchange_error_code(self):
315 """Non-zero code in exchange response raises VeSyncLoginError."""
316 login_error_resp = {
317 'traceId': TestDefaults.trace_id,
318 'code': -11201000,
319 'msg': 'Login failed',
320 'result': {
321 'accountID': TestDefaults.account_id,
322 'acceptLanguage': 'en',
323 'countryCode': 'US',
324 'token': '',
325 },
326 }
327 self.mock_api.side_effect = [
328 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
329 (login_error_resp, 200),
330 ]
331 with pytest.raises(VeSyncLoginError, match='Login failed'):
332 self.run_in_loop(self.manager.auth.login)
333
334 def test_login_exchange_none_response(self):
335 """None response in exchange step raises VeSyncAPIResponseError."""
336 self.mock_api.side_effect = [
337 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
338 (None, 200),
339 ]
340 with pytest.raises(
341 VeSyncAPIResponseError, match='Error receiving response'
342 ):
343 self.run_in_loop(self.manager.auth.login)
344
345 def test_login_cross_region(self):
346 """Cross-region error triggers retry with new region."""
347 cross_region_resp = LOGIN_RESPONSES.LOGIN_RESPONSE_CROSS_REGION
348 success_resp = LOGIN_RESPONSES.LOGIN_RESPONSE_SUCCESS
349 self.mock_api.side_effect = [
350 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
351 (cross_region_resp, 200),
352 (success_resp, 200),
353 ]
354 result = self.run_in_loop(self.manager.auth.login)
355 assert result is True
356 assert self.mock_api.call_count == 3
357
358 def test_login_server_error_in_exchange(self):
359 """Server error code in exchange raises VeSyncServerError."""
360 server_error_resp = {
361 'traceId': TestDefaults.trace_id,
362 'code': -11102000,
363 'msg': 'Server error',
364 'result': {
365 'accountID': TestDefaults.account_id,
366 'acceptLanguage': 'en',
367 'countryCode': 'US',
368 'token': '',
369 },
370 }
371 self.mock_api.side_effect = [
372 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
373 (server_error_resp, 200),
374 ]
375 with pytest.raises(VeSyncServerError):
376 self.run_in_loop(self.manager.auth.login)
377
378
379 # ---------------------------------------------------------------------------
380 # Re-authentication
381 # ---------------------------------------------------------------------------
382
383
384 class TestReauthentication(TestBase):
385 """Test reauthenticate method."""
386
387 def test_reauthenticate_success(self):
388 """Reauthenticate clears and re-establishes credentials."""
389 auth = self.manager.auth
390 auth.set_credentials('old_tk', 'old_acct', 'US', 'US')
391 assert auth.is_authenticated is True
392
393 self.mock_api.side_effect = [
394 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
395 (LOGIN_RESPONSES.LOGIN_RESPONSE_SUCCESS, 200),
396 ]
397 result = self.run_in_loop(auth.reauthenticate)
398 assert result is True
399 assert auth.token == TestDefaults.token
400
401 def test_reauthenticate_saves_to_file(self, tmp_path):
402 """Reauthenticate re-saves credentials when file existed."""
403 auth = self.manager.auth
404 auth.set_credentials('tk', 'acct', 'US', 'US')
405 file_path = tmp_path / '.vesync_auth'
406 self.loop.run_until_complete(auth.save_credentials_to_file(file_path))
407 auth._token_file_path = file_path
408
409 self.mock_api.side_effect = [
410 (LOGIN_RESPONSES.GET_TOKEN_RESPONSE_SUCCESS, 200),
411 (LOGIN_RESPONSES.LOGIN_RESPONSE_SUCCESS, 200),
412 ]
413 self.run_in_loop(auth.reauthenticate)
414
415 # File should be re-created with new credentials
416 assert file_path.exists()
417 data = orjson.loads(file_path.read_text(encoding='utf-8'))
418 assert data['token'] == TestDefaults.token
419
420 def test_reauthenticate_login_failure_raises(self):
421 """Reauthenticate propagates login errors."""
422 auth = self.manager.auth
423 auth.set_credentials('tk', 'acct', 'US', 'US')
424
425 self.mock_api.return_value = (None, 200)
426 with pytest.raises(VeSyncAPIResponseError):
427 self.run_in_loop(auth.reauthenticate)
428 assert auth.is_authenticated is False