Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathtest_server.py
More file actions
Latest commit
576 lines (489 loc) · 20.2 KB
/
Copy pathtest_server.py
File metadata and controls
576 lines (489 loc) · 20.2 KB
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
importre
importtime
fromurllib.parseimportquote_plus
importpytest
fromdatetimeimportdatetime
fromPILimportImage
fromplexapi.exceptionsimportBadRequest, NotFound
fromplexapi.serverimportPlexServer
fromplexapi.utilsimportdownload
fromrequestsimportSession
from . importconftestasutils
from .payloadsimportSERVER_RESOURCES, SERVER_TRANSCODE_SESSIONS
deftest_server_attr(plex, account):
assertplex._baseurl==utils.SERVER_BASEURL
assertlen(plex.friendlyName) >=1
assertlen(plex.machineIdentifier) ==40
assertplex.myPlexisTrue
# if you run the tests very shortly after server creation the state in rare cases may be `unknown`
assertplex.myPlexMappingStatein ("mapped", "unknown")
assertplex.myPlexSigninState=="ok"
assertutils.is_int(plex.myPlexSubscription, gte=0)
assertre.match(utils.REGEX_EMAIL, plex.myPlexUsername)
assertplex.platformin ("Linux", "Windows")
assertlen(plex.platformVersion) >=5
assertplex._token==account.authenticationToken
assertutils.is_int(plex.transcoderActiveVideoSessions, gte=0)
assertutils.is_datetime(plex.updatedAt)
assertlen(plex.version) >=5
deftest_server_alert_listener(plex, movies):
try:
messages= []
listener=plex.startAlertListener(messages.append)
movies.refresh()
utils.wait_until(lambda: len(messages) >=3, delay=1, timeout=30)
assertlen(messages) >=3
finally:
listener.stop()
@pytest.mark.req_client
deftest_server_session():
# TODO: Implement test_server_session
pass
deftest_server_library(plex):
# TODO: Implement test_server_library
assertplex.library
deftest_server_url(plex):
assert"ohno"inplex.url("ohno")
deftest_server_transcodeImage(tmpdir, plex, movie):
width, height=500, 100
background="000000"
blend="FFFFFF"
original_url=movie.thumbUrl
resize_jpeg_url=plex.transcodeImage(original_url, height, width)
no_minSize_png_url=plex.transcodeImage(original_url, height, width, minSize=False, imageFormat="png")
grayscale_url=plex.transcodeImage(original_url, height, width, saturation=0)
opacity_background_url=plex.transcodeImage(original_url, height, width, opacity=0, background=background, blur=100)
blend_url=plex.transcodeImage(original_url, height, width, blendColor=blend, blur=1000)
online_no_upscale_url=plex.transcodeImage(
"https://raw.githubusercontent.com/pushingkarmaorg/python-plexapi/master/tests/data/cute_cat.jpg",
1000,
1000,
upscale=False
)
original_img=download(
original_url, plex._token, savepath=str(tmpdir), filename="original_img",
)
resized_jpeg_img=download(
resize_jpeg_url, plex._token, savepath=str(tmpdir), filename="resized_jpeg_img"
)
no_minSize_png_img=download(
no_minSize_png_url, plex._token, savepath=str(tmpdir), filename="no_minSize_png_img"
)
grayscale_img=download(
grayscale_url, plex._token, savepath=str(tmpdir), filename="grayscale_img"
)
opacity_background_img=download(
opacity_background_url, plex._token, savepath=str(tmpdir), filename="opacity_background_img"
)
blend_img=download(
blend_url, plex._token, savepath=str(tmpdir), filename="blend_img"
)
online_no_upscale_img=download(
online_no_upscale_url, plex._token, savepath=str(tmpdir), filename="online_no_upscale_img"
)
withImage.open(original_img) asimage:
assertimage.size[0] !=width
assertimage.size[1] !=height
withImage.open(resized_jpeg_img) asimage:
assertimage.size[0] ==width
assertimage.size[1] !=height
assertimage.format=="JPEG"
withImage.open(no_minSize_png_img) asimage:
assertimage.size[0] !=width
assertimage.size[1] ==height
assertimage.format=="PNG"
assertutils.detect_color_image(grayscale_img) =="grayscale"
assertutils.detect_dominant_hexcolor(opacity_background_img) ==background
assertutils.detect_color_distance(utils.detect_dominant_hexcolor(blend_img), blend)
withImage.open(online_no_upscale_img) asimage1:
withImage.open(utils.STUB_IMAGE_PATH) asimage2:
assertimage1.size==image2.size
deftest_server_fetchitem_notfound(plex):
withpytest.raises(NotFound):
plex.fetchItem(123456789)
deftest_server_search(plex, movie):
title=movie.title
# this search seem to fail on my computer but not at travis, wtf.
assertplex.search(title)
results=plex.search(title, mediatype="movie")
assertresults[0] ==movie
# Test genre search
genre=movie.genres[0]
results=plex.search(genre.tag, mediatype="genre")
hub_tag=results[0]
assertutils.is_int(hub_tag.count)
asserthub_tag.filter==f"genre={hub_tag.id}"
assertutils.is_int(hub_tag.id)
assertutils.is_metadata(
hub_tag.key,
prefix=hub_tag.librarySectionKey,
contains=f"{hub_tag.librarySectionID}/all",
suffix=hub_tag.filter)
assertutils.is_int(hub_tag.librarySectionID)
assertutils.is_metadata(hub_tag.librarySectionKey, prefix="/library/sections")
asserthub_tag.librarySectionTitle=="Movies"
asserthub_tag.librarySectionType==1
asserthub_tag.reason=="section"
asserthub_tag.reasonID==hub_tag.librarySectionID
asserthub_tag.reasonTitle==hub_tag.librarySectionTitle
assertutils.is_float(hub_tag.score, gte=0.0)
asserthub_tag.type=="tag"
asserthub_tag.tag==genre.tag
asserthub_tag.tagType==1
asserthub_tag.tagValueisNone
asserthub_tag.thumbisNone
assertmovieinhub_tag.items()
# Test director search
director=movie.directors[0]
assertplex.search(director.tag, mediatype="director")
# Test actor search
role=movie.roles[0]
results=plex.search(role.tag, mediatype="actor")
assertresults
hub_tag=results[0]
asserthub_tag.tagKey
deftest_server_playlist(plex, show):
episodes=show.episodes()
playlist=plex.createPlaylist("test_playlist", items=episodes[:3])
try:
assertplaylist.title=="test_playlist"
withpytest.raises(NotFound):
plex.playlist("<playlist-not-found>")
finally:
playlist.delete()
deftest_server_playlists(plex, show):
playlists=plex.playlists()
count=len(playlists)
episodes=show.episodes()
playlist=plex.createPlaylist("test_playlist", items=episodes[:3])
try:
playlists=plex.playlists()
assertlen(playlists) ==count+1
assertplaylistinplex.playlists(playlistType='video')
assertplaylistnotinplex.playlists(playlistType='audio')
finally:
playlist.delete()
deftest_server_Server_query(plex):
assertplex.query("/")
withpytest.raises(NotFound):
assertplex.query("/asdf/1234/asdf", headers={"random_headers": "1234"})
deftest_server_Server_session(account):
# Mock Session
classMySession(Session):
def__init__(self):
super(self.__class__, self).__init__()
self.plexapi_session_test=True
# Test Code
plex=PlexServer(
utils.SERVER_BASEURL, account.authenticationToken, session=MySession()
)
asserthasattr(plex._session, "plexapi_session_test")
@pytest.mark.authenticated
deftest_server_token_in_headers(plex):
headers=plex._headers()
assert"X-Plex-Token"inheaders
assertlen(headers["X-Plex-Token"]) >=1
deftest_server_createPlayQueue(plex, movie):
playqueue=plex.createPlayQueue(movie, shuffle=1, repeat=1)
assert"shuffle=1"inplayqueue._initpath
assert"repeat=1"inplayqueue._initpath
assertplayqueue.playQueueShuffledisTrue
deftest_server_client_not_found(plex):
withpytest.raises(NotFound):
plex.client("<This-client-should-not-be-found>")
deftest_server_sessions(plex):
assertlen(plex.sessions()) >=0
deftest_server_butlerTasks(plex):
assertlen(plex.butlerTasks())
deftest_server_runButlerTask(plex):
assertplex.runButlerTask("CleanOldBundles")
withpytest.raises(BadRequest):
plex.runButlerTask("<This-task-should-not-exist>")
deftest_server_isLatest(plex, mocker):
fromosimportenviron
is_latest=plex.isLatest()
ifenviron.get("PLEX_CONTAINER_TAG") andenviron["PLEX_CONTAINER_TAG"] notin ("latest", "plexpass", "public"):
assertnotis_latest
else:
returnpytest.skip(
"Run with PLEX_CONTAINER_TAG != latest, plexpass, or public to ensure that update is available"
)
deftest_server_installUpdate(plex, mocker):
m=mocker.MagicMock(release="aa")
withutils.patch('plexapi.server.PlexServer.checkForUpdate', return_value=m):
withutils.callable_http_patch():
plex.installUpdate()
deftest_server_checkForUpdate(plex, mocker):
classR:
def__init__(self, **kwargs):
self.download_key="plex.tv/release/1337"
self.version="1337"
self.added="gpu transcode"
self.fixed="fixed rare bug"
self.downloadURL="http://path-to-update"
self.state="downloaded"
withutils.patch('plexapi.server.PlexServer.checkForUpdate', return_value=R()):
rel=plex.checkForUpdate(force=False, download=True)
assertrel.download_key=="plex.tv/release/1337"
assertrel.version=="1337"
assertrel.added=="gpu transcode"
assertrel.fixed=="fixed rare bug"
assertrel.downloadURL=="http://path-to-update"
assertrel.state=="downloaded"
@pytest.mark.client
deftest_server_clients(plex):
assertlen(plex.clients())
client=plex.clients()[0]
assertclient._baseurl==utils.CLIENT_BASEURL
assertclient._server._baseurl==utils.SERVER_BASEURL
assertclient.protocol=='plex'
assertint(client.protocolVersion) inrange(4)
assertisinstance(client.machineIdentifier, str)
assertclient.deviceClassin ['phone', 'tablet', 'stb', 'tv', 'pc']
assertset(client.protocolCapabilities).issubset({'timeline', 'playback', 'navigation', 'mirror', 'playqueues'})
@pytest.mark.authenticated
@pytest.mark.xfail(strict=False)
deftest_server_account(plex):
account=plex.account()
assertaccount.authToken
# TODO: Figure out why this is missing from time to time.
# assert account.mappingError == 'publisherror'
assertaccount.mappingErrorMessageisNone
assertaccount.mappingState=="mapped"
ifaccount.mappingError!="unreachable":
ifaccount.privateAddressisnotNone:
# This seems to fail way to often..
iflen(account.privateAddress):
assertre.match(utils.REGEX_IPADDR, account.privateAddress)
else:
assertaccount.privateAddress==""
assertint(account.privatePort) >=1000
assertre.match(utils.REGEX_IPADDR, account.publicAddress)
assertint(account.publicPort) >=1000
else:
assertaccount.privateAddress==""
assertint(account.privatePort) ==0
assertaccount.publicAddress==""
assertint(account.publicPort) ==0
assertaccount.signInState=="ok"
assertisinstance(account.subscriptionActive, bool)
ifaccount.subscriptionActive:
assertlen(account.subscriptionFeatures)
# Below check keeps failing.. it should go away.
# else: assert sorted(account.subscriptionFeatures) == ['adaptive_bitrate',
# 'download_certificates', 'federated-auth', 'news']
assert (
account.subscriptionState=="Active"
ifaccount.subscriptionActive
else"Unknown"
)
assertre.match(utils.REGEX_EMAIL, account.username)
@pytest.mark.authenticated
deftest_server_claim_unclaim(plex, account):
server_account=plex.account()
assertserver_account.signInState=='ok'
result=plex.unclaim()
assertresult.signInState=='none'
result=plex.claim(account)
assertresult.signInState=='ok'
deftest_server_downloadLogs(tmpdir, plex):
plex.downloadLogs(savepath=str(tmpdir), unpack=True)
assertlen(tmpdir.listdir()) >1
deftest_server_downloadDatabases(tmpdir, plex):
plex.downloadDatabases(savepath=str(tmpdir), unpack=True)
assertlen(tmpdir.listdir()) >1
deftest_server_browse(plex, movies):
movies_path=movies.locations[0]
# browse root
paths=plex.browse()
assertlen(paths)
# browse the path of the movie library
paths=plex.browse(movies_path)
assertlen(paths)
# browse the path of the movie library without files
paths=plex.browse(movies_path, includeFiles=False)
assertnotlen([fforfinpathsiff.TAG=='File'])
# walk the path of the movie library
forpath, paths, filesinplex.walk(movies_path):
assertpath.startswith(movies_path)
assertlen(paths) orlen(files)
deftest_server_allowMediaDeletion(account):
plex=PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
# Check server current allowMediaDeletion setting
ifplex.allowMediaDeletion:
# If allowed then test disallowed
plex._allowMediaDeletion(False)
time.sleep(1)
plex=PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
assertplex.allowMediaDeletionisNone
# Test redundant toggle
withpytest.raises(BadRequest):
plex._allowMediaDeletion(False)
plex._allowMediaDeletion(True)
time.sleep(1)
plex=PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
assertplex.allowMediaDeletionisTrue
# Test redundant toggle
withpytest.raises(BadRequest):
plex._allowMediaDeletion(True)
else:
# If disallowed then test allowed
plex._allowMediaDeletion(True)
time.sleep(1)
plex=PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
assertplex.allowMediaDeletionisTrue
# Test redundant toggle
withpytest.raises(BadRequest):
plex._allowMediaDeletion(True)
plex._allowMediaDeletion(False)
time.sleep(1)
plex=PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
assertplex.allowMediaDeletionisNone
# Test redundant toggle
withpytest.raises(BadRequest):
plex._allowMediaDeletion(False)
deftest_server_system_accounts(plex):
accounts=plex.systemAccounts()
assertlen(accounts)
account=accounts[0]
assertutils.is_bool(account.autoSelectAudio)
assertaccount.defaultAudioLanguage=="en"
assertaccount.defaultSubtitleLanguage=="en"
assertutils.is_int(account.id, gte=0)
assertlen(account.key)
assert (account.name=="") ifaccount.id==0elselen(account.name)
assertaccount.subtitleMode==0
assertaccount.thumb==""
assertaccount.accountID==account.id
assertaccount.accountKey==account.key
assertplex.systemAccount(account.id) ==account
deftest_server_system_devices(plex):
devices=plex.systemDevices()
assertlen(devices)
device=devices[-1]
assertdevice.clientIdentifierordevice.clientIdentifier==""
assertutils.is_datetime(device.createdAt)
assertutils.is_int(device.id)
assertlen(device.key)
assertlen(device.name) ordevice.name==""
assertlen(device.platform) ordevice.platform==""
assertplex.systemDevice(device.id) ==device
@pytest.mark.authenticated
deftest_server_dashboard_bandwidth(account_plexpass, plex):
bandwidthData=plex.bandwidth()
assertlen(bandwidthData)
bandwidth=bandwidthData[0]
assertutils.is_int(bandwidth.accountID, gte=0)
assertutils.is_datetime(bandwidth.at)
assertutils.is_int(bandwidth.bytes)
assertutils.is_int(bandwidth.deviceID)
assertutils.is_bool(bandwidth.lan)
assertbandwidth.timespan==6# Default seconds timespan
account=bandwidth.account()
assertutils.is_int(account.id, gte=0)
device=bandwidth.device()
assertutils.is_int(device.id)
@pytest.mark.authenticated
deftest_server_dashboard_bandwidth_filters(account_plexpass, plex):
at=datetime(2021, 1, 1)
filters= {
'at>': at,
'bytes>': 1,
'lan': True,
'accountID': 1
}
bandwidthData=plex.bandwidth(timespan='hours', **filters)
assertlen(bandwidthData)
bandwidth=bandwidthData[0]
assertbandwidth.accountID==1
assertbandwidth.at>=at
assertbandwidth.bytes>=1
assertbandwidth.lanisTrue
assertbandwidth.timespan==4
withpytest.raises(BadRequest):
plex.bandwidth(timespan='n/a')
withpytest.raises(BadRequest):
filters= {'n/a': None}
plex.bandwidth(**filters)
withpytest.raises(BadRequest):
filters= {'at': 123456}
plex.bandwidth(**filters)
@pytest.mark.authenticated
deftest_server_dashboard_resources(plex, requests_mock):
url=plex.url("/statistics/resources")
requests_mock.get(url, text=SERVER_RESOURCES)
resourceData=plex.resources()
assertlen(resourceData)
resource=resourceData[0]
assertutils.is_datetime(resource.at)
assertutils.is_float(resource.hostCpuUtilization, gte=0.0)
assertutils.is_float(resource.hostMemoryUtilization, gte=0.0)
assertutils.is_float(resource.processCpuUtilization, gte=0.0)
assertutils.is_float(resource.processMemoryUtilization, gte=0.0)
assertresource.timespan==6# Default seconds timespan
deftest_server_transcode_sessions(plex, requests_mock):
url=plex.url("/transcode/sessions")
requests_mock.get(url, text=SERVER_TRANSCODE_SESSIONS)
transcode_sessions=plex.transcodeSessions()
assertlen(transcode_sessions)
session=transcode_sessions[0]
assertsession.audioChannels==2
assertsession.audioCodecinutils.CODECS
assertsession.audioDecision=="transcode"
assertsession.completeisFalse
assertsession.containerinutils.CONTAINERS
assertsession.context=="streaming"
assertutils.is_int(session.duration, gte=100000)
assertutils.is_int(session.height, gte=480)
assertlen(session.key)
assertutils.is_float(session.maxOffsetAvailable, gte=0.0)
assertutils.is_float(session.minOffsetAvailable, gte=0.0)
assertutils.is_float(session.progress)
assertsession.protocol=="dash"
assertutils.is_int(session.remaining)
assertutils.is_int(session.size)
assertsession.sourceAudioCodecinutils.CODECS
assertsession.sourceVideoCodecinutils.CODECS
assertutils.is_float(session.speed)
assertsession.subtitleDecisionisNone
assertsession.throttledisFalse
assertutils.is_float(session.timestamp, gte=1600000000)
assertsession.transcodeHwDecodinginutils.HW_DECODERS
assertsession.transcodeHwDecodingTitle=="Windows (DXVA2)"
assertsession.transcodeHwEncodinginutils.HW_ENCODERS
assertsession.transcodeHwEncodingTitle=="Intel (QuickSync)"
assertsession.transcodeHwFullPipelineisFalse
assertsession.transcodeHwRequestedisTrue
assertsession.videoCodecinutils.CODECS
assertsession.videoDecision=="transcode"
assertutils.is_int(session.width, gte=852)
deftest_server_PlexWebURL(plex):
url=plex.getWebURL()
asserturl.startswith('https://app.plex.tv/desktop')
assertplex.machineIdentifierinurl
assertquote_plus('/hubs') inurl
assert'pageType=hub'inurl
# Test a different base
base='https://doesnotexist.com/plex'
url=plex.getWebURL(base=base)
asserturl.startswith(base)
deftest_server_PlexWebURL_playlists(plex):
tab='audio'
url=plex.getWebURL(playlistTab=tab)
asserturl.startswith('https://app.plex.tv/desktop')
assertplex.machineIdentifierinurl
assert'source=playlists'inurl
assertf'pivot=playlists.{tab}'inurl
deftest_server_agents(plex):
agents=plex.agents()
assertagents
agent=next((aforainagentsifa.identifier=='com.plexapp.agents.imdb'), None)
assertagent
settings=agent.settings()
assertsettings
setting=next((sforsinsettingsifs.id=='country'), None)
assertsetting
assertsetting.enumValuesisnotNone
deftest_server_identity(plex):
identity=plex.identity()
assertidentity.machineIdentifier==plex.machineIdentifier