File: test_synology_dsm.py

package info (click to toggle)
python-synologydsm-api 2.7.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,364 kB
  • sloc: python: 27,201; sh: 25; makefile: 2
file content (665 lines) | stat: -rw-r--r-- 22,015 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
"""Synology DSM tests."""

# pylint: disable=protected-access
import pytest
from aiohttp import ClientTimeout

from synology_dsm.api.core.external_usb import SynoCoreExternalUSB
from synology_dsm.api.core.security import SynoCoreSecurity
from synology_dsm.api.core.share import SynoCoreShare
from synology_dsm.api.core.system import SynoCoreSystem
from synology_dsm.api.core.upgrade import SynoCoreUpgrade
from synology_dsm.api.core.utilization import SynoCoreUtilization
from synology_dsm.api.download_station import SynoDownloadStation
from synology_dsm.api.dsm.information import SynoDSMInformation
from synology_dsm.api.photos import SynoPhotos
from synology_dsm.api.storage.storage import SynoStorage
from synology_dsm.api.surveillance_station import SynoSurveillanceStation
from synology_dsm.const import API_AUTH, API_INFO
from synology_dsm.exceptions import (
    SynologyDSMAPIErrorException,
    SynologyDSMAPINotExistsException,
    SynologyDSMLogin2SAFailedException,
    SynologyDSMLogin2SARequiredException,
    SynologyDSMLoginFailedException,
    SynologyDSMLoginInvalidException,
    SynologyDSMNotLoggedInException,
    SynologyDSMRequestException,
)

from . import (
    USER_MAX_TRY,
    VALID_HOST,
    VALID_HTTPS,
    VALID_PASSWORD,
    VALID_PORT,
    VALID_USER,
    VALID_USER_2SA,
    SynologyDSMMock,
)


class TestSynologyDSM:
    """Common SynologyDSM 5 and 6 test cases."""

    def test_init(self, dsm):
        """Test init."""
        assert dsm.username == VALID_USER
        assert str(dsm._base_url) == f"https://{VALID_HOST}:{VALID_PORT}"
        assert dsm._aiohttp_timeout.total == 10
        assert not dsm.apis.get(API_AUTH)
        assert not dsm._session_id

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.asyncio
    async def test_login_neccessary(self, version):
        """Test login is neccessary."""
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            USER_MAX_TRY,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version

        with pytest.raises(SynologyDSMNotLoggedInException) as error:
            await dsm.utilisation.update()
        error_value = error.value.args[0]
        assert error_value["api"] is None
        assert error_value["code"] == -1
        assert error_value["reason"] == "Unknown"
        assert error_value["details"] == "Not logged in. You have to do login() first."

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.asyncio
    async def test_login_basic_failed(self, version):
        """Test basic failed login."""
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            USER_MAX_TRY,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version

        with pytest.raises(SynologyDSMLoginFailedException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.API.Auth"
        assert error_value["code"] == 407
        assert error_value["reason"] == "Max Tries (if auto blocking is set to true)"
        assert error_value["details"] == USER_MAX_TRY

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.asyncio
    async def test_login_2sa_failed(self, version):
        """Test failed login with 2SA."""
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            VALID_USER_2SA,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version

        with pytest.raises(SynologyDSMLogin2SARequiredException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.API.Auth"
        assert error_value["code"] == 403
        assert error_value["reason"] == "One time password not specified"
        assert (
            error_value["details"]
            == "Two-step authentication required for account: valid_user_2sa"
        )

        with pytest.raises(SynologyDSMLogin2SAFailedException) as error:
            await dsm.login(888888)
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.API.Auth"
        assert error_value["code"] == 404
        assert error_value["reason"] == "One time password authenticate failed"
        assert (
            error_value["details"]
            == "Two-step authentication failed, retry with a new pass code"
        )

        assert dsm._session_id is None
        assert dsm._syno_token is None
        assert dsm._device_token is None

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.asyncio
    async def test_connection_failed(self, version):
        """Test failed connection."""
        # No internet
        dsm = SynologyDSMMock(
            None,
            "no_internet",
            VALID_PORT,
            VALID_USER,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMRequestException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert not error_value["api"]
        assert error_value["code"] == -1
        assert error_value["reason"] == "Unknown"
        assert (
            "ClientError = <urllib3.connection.VerifiedHTTPSConnection "
            in error_value["details"]
        )

        assert not dsm.apis.get(API_AUTH)
        assert not dsm._session_id

        # Wrong host
        dsm = SynologyDSMMock(
            None,
            "host",
            VALID_PORT,
            VALID_USER,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMRequestException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert not error_value["api"]
        assert error_value["code"] == -1
        assert error_value["reason"] == "Unknown"
        assert (
            "ClientError = <urllib3.connection.HTTPConnection "
            in error_value["details"]
        )

        assert not dsm.apis.get(API_AUTH)
        assert not dsm._session_id

        # Wrong port
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            0,
            VALID_USER,
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMRequestException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert not error_value["api"]
        assert error_value["code"] == -1
        assert error_value["reason"] == "Unknown"
        assert error_value["details"] == (
            "ClientError = [SSL: WRONG_VERSION_NUMBER] "
            "wrong version number (_ssl.c:1076)"
        )

        assert not dsm.apis.get(API_AUTH)
        assert not dsm._session_id

        # Wrong HTTPS
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            VALID_USER,
            VALID_PASSWORD,
            False,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMRequestException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert not error_value["api"]
        assert error_value["code"] == -1
        assert error_value["reason"] == "Unknown"
        assert error_value["details"] == "ClientError = Bad request"

        assert not dsm.apis.get(API_AUTH)
        assert not dsm._session_id

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.asyncio
    async def test_login_failed(self, version):
        """Test failed login."""
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            "user",
            VALID_PASSWORD,
            VALID_HTTPS,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMLoginInvalidException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.API.Auth"
        assert error_value["code"] == 400
        assert error_value["reason"] == "Invalid credentials"
        assert error_value["details"] == "Invalid password or not admin account: user"

        assert dsm.apis.get(API_AUTH)
        assert not dsm._session_id

        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            VALID_USER,
            "pass",
            VALID_HTTPS,
        )
        dsm.dsm_version = version
        with pytest.raises(SynologyDSMLoginInvalidException) as error:
            await dsm.login()
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.API.Auth"
        assert error_value["code"] == 400
        assert error_value["reason"] == "Invalid credentials"
        assert (
            error_value["details"]
            == "Invalid password or not admin account: valid_user"
        )

        assert dsm.apis.get(API_AUTH)
        assert not dsm._session_id

    @pytest.mark.parametrize("version", [5, 6, 7])
    @pytest.mark.parametrize(
        "timeout,expected_result",
        [
            (2, (2, None)),
            (15, (15, None)),
            (ClientTimeout(total=5), (5, None)),
            (ClientTimeout(total=60, connect=15), (60, 15)),
        ],
    )
    def test_request_timeout(self, version, timeout, expected_result):
        """Test request timeout."""
        dsm = SynologyDSMMock(
            None,
            VALID_HOST,
            VALID_PORT,
            VALID_USER,
            VALID_PASSWORD,
            VALID_HTTPS,
            timeout=timeout,
        )
        dsm.dsm_version = version
        assert dsm._aiohttp_timeout.total == expected_result[0]
        assert dsm._aiohttp_timeout.connect == expected_result[1]

    @pytest.mark.asyncio
    async def test_request_get(self, dsm):
        """Test get request."""
        await dsm.login()
        assert await dsm.get(API_INFO, "query")
        assert await dsm.get(API_AUTH, "login")
        assert await dsm.get("SYNO.DownloadStation2.Task", "list")
        assert await dsm.get(API_AUTH, "logout")

    @pytest.mark.asyncio
    async def test_request_get_failed(self, dsm):
        """Test failed get request."""
        await dsm.login()
        with pytest.raises(SynologyDSMAPINotExistsException) as error:
            await dsm.get("SYNO.Virtualization.API.Task.Info", "list")
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.Virtualization.API.Task.Info"
        assert error_value["code"] == -2
        assert error_value["reason"] == "Unknown"
        assert (
            error_value["details"]
            == "API SYNO.Virtualization.API.Task.Info does not exists"
        )

    @pytest.mark.asyncio
    async def test_request_post(self, dsm):
        """Test post request."""
        await dsm.login()
        assert await dsm.post(
            "SYNO.FileStation.Upload",
            "upload",
            params={"dest_folder_path": "/upload/test", "create_parents": True},
            files={"file": "open('file.txt','rb')"},
        )

        assert await dsm.post(
            "SYNO.DownloadStation2.Task",
            "create",
            params={
                "uri": "ftps://192.0.0.1:21/test/test.zip",
                "username": "admin",
                "password": "1234",
            },
        )

    @pytest.mark.asyncio
    async def test_request_post_failed(self, dsm):
        """Test failed post request."""
        await dsm.login()
        with pytest.raises(SynologyDSMAPIErrorException) as error:
            await dsm.post(
                "SYNO.FileStation.Upload",
                "upload",
                params={"dest_folder_path": "/upload/test", "create_parents": True},
                files={"file": "open('file_already_exists.txt','rb')"},
            )
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.FileStation.Upload"
        assert error_value["code"] == 1805
        assert error_value["reason"] == (
            "Can’t overwrite or skip the existed file, if no overwrite"
            " parameter is given"
        )
        assert not error_value["details"]

        with pytest.raises(SynologyDSMAPIErrorException) as error:
            await dsm.post(
                "SYNO.DownloadStation2.Task",
                "create",
                params={
                    "uri": "ftps://192.0.0.1:21/test/test_not_exists.zip",
                    "username": "admin",
                    "password": "1234",
                },
            )
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.DownloadStation2.Task"
        assert error_value["code"] == 408
        assert error_value["reason"] == "File does not exist"
        assert not error_value["details"]

    def test_reset_str_attr(self, dsm):
        """Test reset with string attr."""
        assert not dsm._external_usb
        assert dsm.external_usb
        assert dsm._external_usb
        assert dsm.reset("external_usb")
        assert not dsm._external_usb

        assert not dsm._security
        assert dsm.security
        assert dsm._security
        assert dsm.reset("security")
        assert not dsm._security

        assert not dsm._share
        assert dsm.share
        assert dsm._share
        assert dsm.reset("share")
        assert not dsm._share

        assert not dsm._system
        assert dsm.system
        assert dsm._system
        assert dsm.reset("system")
        assert not dsm._system

        assert not dsm._upgrade
        assert dsm.upgrade
        assert dsm._upgrade
        assert dsm.reset("upgrade")
        assert not dsm._upgrade

        assert not dsm._utilisation
        assert dsm.utilisation
        assert dsm._utilisation
        assert dsm.reset("utilisation")
        assert not dsm._utilisation

        assert not dsm._download
        assert dsm.download_station
        assert dsm._download
        assert dsm.reset("download")
        assert not dsm._download

        assert not dsm._photos
        assert dsm.photos
        assert dsm._photos
        assert dsm.reset("photos")
        assert not dsm._photos

        assert not dsm._storage
        assert dsm.storage
        assert dsm._storage
        assert dsm.reset("storage")
        assert not dsm._storage

        assert not dsm._surveillance
        assert dsm.surveillance_station
        assert dsm._surveillance
        assert dsm.reset("surveillance")
        assert not dsm._surveillance

    def test_reset_str_key(self, dsm):
        """Test reset with string API key."""
        assert not dsm._external_usb
        assert dsm.external_usb
        assert dsm._external_usb
        assert dsm.reset(SynoCoreExternalUSB.API_KEY)
        assert not dsm._external_usb

        assert not dsm._security
        assert dsm.security
        assert dsm._security
        assert dsm.reset(SynoCoreSecurity.API_KEY)
        assert not dsm._security

        assert not dsm._share
        assert dsm.share
        assert dsm._share
        assert dsm.reset(SynoCoreShare.API_KEY)
        assert not dsm._share

        assert not dsm._system
        assert dsm.system
        assert dsm._system
        assert dsm.reset(SynoCoreSystem.API_KEY)
        assert not dsm._system

        assert not dsm._upgrade
        assert dsm.upgrade
        assert dsm._upgrade
        assert dsm.reset(SynoCoreUpgrade.API_KEY)
        assert not dsm._upgrade

        assert not dsm._utilisation
        assert dsm.utilisation
        assert dsm._utilisation
        assert dsm.reset(SynoCoreUtilization.API_KEY)
        assert not dsm._utilisation

        assert not dsm._download
        assert dsm.download_station
        assert dsm._download
        assert dsm.reset(SynoDownloadStation.API_KEY)
        assert not dsm._download

        assert not dsm._photos
        assert dsm.photos
        assert dsm._photos
        assert dsm.reset(SynoPhotos.API_KEY)
        assert not dsm._photos

        assert not dsm._storage
        assert dsm.storage
        assert dsm._storage
        assert dsm.reset(SynoStorage.API_KEY)
        assert not dsm._storage

        assert not dsm._surveillance
        assert dsm.surveillance_station
        assert dsm._surveillance
        assert dsm.reset(SynoSurveillanceStation.API_KEY)
        assert not dsm._surveillance

    def test_reset_object(self, dsm):
        """Test reset with object."""
        assert not dsm._external_usb
        assert dsm.external_usb
        assert dsm._external_usb
        assert dsm.reset(dsm.external_usb)
        assert not dsm._external_usb

        assert not dsm._security
        assert dsm.security
        assert dsm._security
        assert dsm.reset(dsm.security)
        assert not dsm._security

        assert not dsm._share
        assert dsm.share
        assert dsm._share
        assert dsm.reset(dsm.share)
        assert not dsm._share

        assert not dsm._system
        assert dsm.system
        assert dsm._system
        assert dsm.reset(dsm.system)
        assert not dsm._system

        assert not dsm._upgrade
        assert dsm.upgrade
        assert dsm._upgrade
        assert dsm.reset(dsm.upgrade)
        assert not dsm._upgrade

        assert not dsm._utilisation
        assert dsm.utilisation
        assert dsm._utilisation
        assert dsm.reset(dsm.utilisation)
        assert not dsm._utilisation

        assert not dsm._download
        assert dsm.download_station
        assert dsm._download
        assert dsm.reset(dsm.download_station)
        assert not dsm._download

        assert not dsm._photos
        assert dsm.photos
        assert dsm._photos
        assert dsm.reset(dsm.photos)
        assert not dsm._photos

        assert not dsm._storage
        assert dsm.storage
        assert dsm._storage
        assert dsm.reset(dsm.storage)
        assert not dsm._storage

        assert not dsm._surveillance
        assert dsm.surveillance_station
        assert dsm._surveillance
        assert dsm.reset(dsm.surveillance_station)
        assert not dsm._surveillance

    def test_reset_str_attr_information(self, dsm):
        """Test reset with string information attr (should not be reset)."""
        assert not dsm._information
        assert dsm.information
        assert dsm._information
        assert not dsm.reset("information")
        assert dsm._information

    def test_reset_str_key_information(self, dsm):
        """Test reset with string information API key (should not be reset)."""
        assert not dsm._information
        assert dsm.information
        assert dsm._information
        assert not dsm.reset(SynoDSMInformation.API_KEY)
        assert dsm._information

    def test_reset_object_information(self, dsm):
        """Test reset with information object (should not be reset)."""
        assert not dsm._information
        assert dsm.information
        assert dsm._information
        assert not dsm.reset(dsm.information)
        assert dsm._information

    @pytest.mark.asyncio
    async def test_utilisation(self, dsm):
        """Test utilisation."""
        await dsm.login()
        assert dsm.utilisation
        await dsm.utilisation.update()

    @pytest.mark.asyncio
    async def test_utilisation_cpu(self, dsm):
        """Test utilisation CPU."""
        await dsm.login()
        await dsm.utilisation.update()
        assert dsm.utilisation.cpu
        assert dsm.utilisation.cpu_other_load
        assert dsm.utilisation.cpu_user_load
        assert dsm.utilisation.cpu_system_load
        assert dsm.utilisation.cpu_total_load
        assert dsm.utilisation.cpu_1min_load
        assert dsm.utilisation.cpu_5min_load
        assert dsm.utilisation.cpu_15min_load

    @pytest.mark.asyncio
    async def test_utilisation_error(self, dsm):
        """Test utilisation error."""
        dsm.error = True
        await dsm.login()
        with pytest.raises(SynologyDSMAPIErrorException) as error:
            await dsm.utilisation.update()
        error_value = error.value.args[0]
        assert error_value["api"] == "SYNO.Core.System.Utilization"
        assert error_value["code"] == 1055
        assert error_value["reason"] == "Unknown"
        assert error_value["details"] == {
            "err_key": "",
            "err_line": 883,
            "err_msg": "Transmition failed.",
            "err_session": "",
        }

    @pytest.mark.asyncio
    async def test_utilisation_memory(self, dsm):
        """Test utilisation memory."""
        await dsm.login()
        await dsm.utilisation.update()
        assert dsm.utilisation.memory
        assert dsm.utilisation.memory_real_usage
        assert dsm.utilisation.memory_size()
        assert dsm.utilisation.memory_size(True)
        assert dsm.utilisation.memory_available_swap()
        assert dsm.utilisation.memory_available_swap(True)
        assert dsm.utilisation.memory_cached()
        assert dsm.utilisation.memory_cached(True)
        assert dsm.utilisation.memory_available_real()
        assert dsm.utilisation.memory_available_real(True)
        assert dsm.utilisation.memory_total_real()
        assert dsm.utilisation.memory_total_real(True)
        assert dsm.utilisation.memory_total_swap()
        assert dsm.utilisation.memory_total_swap(True)

    @pytest.mark.asyncio
    async def test_utilisation_network(self, dsm):
        """Test utilisation network."""
        await dsm.login()
        await dsm.utilisation.update()
        assert dsm.utilisation.network
        assert dsm.utilisation.network_up()
        assert dsm.utilisation.network_up(True)
        assert dsm.utilisation.network_down()
        assert dsm.utilisation.network_down(True)