forked from jvdillon/netv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.py
More file actions
712 lines (549 loc) · 23.5 KB
/
main_test.py
File metadata and controls
712 lines (549 loc) · 23.5 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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
"""Tests for main.py - FastAPI routes."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import MagicMock, patch
import json
import pytest
import cache as cache_module
import m3u as m3u_module
@pytest.fixture
def mock_deps():
"""Mock all external dependencies before importing main."""
with (
patch.dict(
"sys.modules", {"defusedxml": MagicMock(), "defusedxml.ElementTree": MagicMock()}
),
patch("cache.CACHE_DIR", Path("/tmp/test_cache")),
patch("cache.SERVER_SETTINGS_FILE", Path("/tmp/test_cache/server_settings.json")),
patch("cache.USERS_DIR", Path("/tmp/test_cache/users")),
):
yield
@pytest.fixture
def client(tmp_path: Path, mock_deps):
"""Create test client with mocked dependencies."""
from fastapi.testclient import TestClient
# Patch paths before importing main
with (
patch("cache.CACHE_DIR", tmp_path),
patch("cache.SERVER_SETTINGS_FILE", tmp_path / "server_settings.json"),
patch("cache.USERS_DIR", tmp_path / "users"),
patch("auth.CACHE_DIR", tmp_path),
patch("auth.SERVER_SETTINGS_FILE", tmp_path / "server_settings.json"),
patch("auth.USERS_DIR", tmp_path / "users"),
patch("epg.init"),
patch("ffmpeg_command.init"),
patch("ffmpeg_session.cleanup_and_recover_sessions"),
):
(tmp_path / "users").mkdir(exist_ok=True)
import main
# Disable background loading
cache_module.get_cache().clear()
yield TestClient(main.app)
@pytest.fixture
def auth_client(tmp_path: Path, mock_deps):
"""Create test client with a logged-in user."""
from fastapi.testclient import TestClient
with (
patch("cache.CACHE_DIR", tmp_path),
patch("cache.SERVER_SETTINGS_FILE", tmp_path / "server_settings.json"),
patch("cache.USERS_DIR", tmp_path / "users"),
patch("auth.CACHE_DIR", tmp_path),
patch("auth.SERVER_SETTINGS_FILE", tmp_path / "server_settings.json"),
patch("auth.USERS_DIR", tmp_path / "users"),
patch("epg.init"),
patch("ffmpeg_command.init"),
patch("ffmpeg_session.cleanup_and_recover_sessions"),
):
(tmp_path / "users").mkdir(exist_ok=True)
import auth
import main
cache_module.get_cache().clear()
client = TestClient(main.app)
# Create user and get token
auth.create_user("testuser", "testpass123")
token = auth.create_token({"sub": "testuser"})
client.cookies.set("token", token)
yield client
class TestSetup:
"""Tests for initial setup flow."""
def test_setup_page_shown_when_no_users(self, client):
resp = client.get("/setup", follow_redirects=False)
assert resp.status_code == 200
assert b"setup" in resp.content.lower() or b"Create" in resp.content
def test_setup_redirects_when_users_exist(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/setup", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
def test_setup_creates_user(self, client):
resp = client.post(
"/setup",
data={"username": "admin", "password": "password123", "confirm": "password123"},
follow_redirects=False,
)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
import auth
assert auth.verify_password("admin", "password123")
def test_setup_validates_username_length(self, client):
resp = client.post(
"/setup",
data={"username": "ab", "password": "password123", "confirm": "password123"},
)
assert resp.status_code == 200
assert b"at least 3" in resp.content
def test_setup_validates_password_length(self, client):
resp = client.post(
"/setup",
data={"username": "admin", "password": "short", "confirm": "short"},
)
assert resp.status_code == 200
assert b"at least 8" in resp.content
def test_setup_validates_password_match(self, client):
resp = client.post(
"/setup",
data={"username": "admin", "password": "password123", "confirm": "different"},
)
assert resp.status_code == 200
assert b"do not match" in resp.content
class TestLogin:
"""Tests for login flow."""
def test_login_page_redirects_to_setup_when_no_users(self, client):
resp = client.get("/login", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/setup"
def test_login_page_shown_when_users_exist(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/login")
assert resp.status_code == 200
def test_login_success_sets_cookie(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.post(
"/login",
data={"username": "admin", "password": "password123"},
follow_redirects=False,
)
assert resp.status_code == 303
assert "token" in resp.cookies
def test_login_failure_returns_401(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.post(
"/login",
data={"username": "admin", "password": "wrongpassword"},
follow_redirects=False,
)
assert resp.status_code == 303
assert "error=invalid" in resp.headers["location"]
class TestLogout:
"""Tests for logout."""
def test_logout_clears_cookie(self, auth_client):
resp = auth_client.get("/logout", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
class TestAuthRequired:
"""Tests for auth-protected routes."""
def test_index_redirects_to_login(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
def test_guide_redirects_to_login(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/guide", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
def test_vod_redirects_to_login(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/vod", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
def test_series_redirects_to_login(self, client, tmp_path):
import auth
auth.create_user("admin", "password123")
resp = client.get("/series", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/login"
class TestIndex:
"""Tests for index route."""
def test_index_redirects_to_guide(self, auth_client):
resp = auth_client.get("/", follow_redirects=False)
assert resp.status_code == 303
assert resp.headers["location"] == "/guide"
class TestFavicon:
"""Tests for favicon."""
def test_favicon_returns_204(self, client):
resp = client.get("/favicon.ico")
assert resp.status_code == 204
class TestGuide:
"""Tests for guide page."""
def test_guide_shows_loading_when_no_cache(self, auth_client):
with patch("main.load_file_cache", return_value=None):
resp = auth_client.get("/guide")
assert resp.status_code == 200
# Should show loading state
assert b"loading" in resp.content.lower() or b"Loading" in resp.content
def test_guide_shows_channels_from_cache(self, auth_client):
cache_module.get_cache()["live_categories"] = [
{"category_id": "1", "category_name": "News"}
]
cache_module.get_cache()["live_streams"] = [
{"stream_id": 1, "name": "CNN", "category_ids": ["1"], "epg_channel_id": ""}
]
with patch("main.epg.has_programs", return_value=True):
resp = auth_client.get("/guide?cats=1")
assert resp.status_code == 200
def test_guide_uses_saved_filter(self, auth_client, tmp_path):
user_dir = tmp_path / "users" / "testuser"
user_dir.mkdir(parents=True, exist_ok=True)
(user_dir / "settings.json").write_text(json.dumps({"guide_filter": ["1", "2"]}))
cache_module.get_cache()["live_categories"] = []
cache_module.get_cache()["live_streams"] = []
# Guide now renders directly using saved filter (no redirect)
with patch("main.epg.has_programs", return_value=True):
resp = auth_client.get("/guide")
assert resp.status_code == 200
class TestVod:
"""Tests for VOD page."""
def test_vod_shows_loading_when_no_cache(self, auth_client):
with patch("main.load_file_cache", return_value=None):
resp = auth_client.get("/vod")
assert resp.status_code == 200
def test_vod_shows_movies_from_cache(self, auth_client):
cache_module.get_cache()["vod_categories"] = [
{"category_id": "10", "category_name": "Movies", "source_id": "src1"}
]
cache_module.get_cache()["vod_streams"] = [
{"stream_id": 100, "name": "Movie 1", "category_id": "10", "source_id": "src1"}
]
resp = auth_client.get("/vod")
assert resp.status_code == 200
def test_vod_filters_by_category(self, auth_client):
cache_module.get_cache()["vod_categories"] = [
{"category_id": "10", "category_name": "Action", "source_id": "src1"},
{"category_id": "20", "category_name": "Comedy", "source_id": "src1"},
]
cache_module.get_cache()["vod_streams"] = [
{"stream_id": 100, "name": "Action Movie", "category_id": "10", "source_id": "src1"},
{"stream_id": 101, "name": "Comedy Movie", "category_id": "20", "source_id": "src1"},
]
resp = auth_client.get("/vod?category=10")
assert resp.status_code == 200
def test_vod_sorts_by_alpha(self, auth_client):
cache_module.get_cache()["vod_categories"] = []
cache_module.get_cache()["vod_streams"] = [
{"stream_id": 1, "name": "Zebra", "source_id": "src1"},
{"stream_id": 2, "name": "Apple", "source_id": "src1"},
]
resp = auth_client.get("/vod?sort=alpha")
assert resp.status_code == 200
class TestSeries:
"""Tests for series page."""
def test_series_shows_loading_when_no_cache(self, auth_client):
with patch("main.load_file_cache", return_value=None):
resp = auth_client.get("/series")
assert resp.status_code == 200
def test_series_shows_list_from_cache(self, auth_client):
cache_module.get_cache()["series_categories"] = [
{"category_id": "30", "category_name": "Drama", "source_id": "src1"}
]
cache_module.get_cache()["series"] = [
{"series_id": 200, "name": "Show 1", "category_id": "30", "source_id": "src1"}
]
resp = auth_client.get("/series")
assert resp.status_code == 200
class TestSearch:
"""Tests for search page."""
def test_search_page_renders(self, auth_client):
cache_module.get_cache()["live_streams"] = []
cache_module.get_cache()["vod_streams"] = []
cache_module.get_cache()["series"] = []
resp = auth_client.get("/search")
assert resp.status_code == 200
def test_search_finds_live_streams(self, auth_client):
cache_module.get_cache()["live_streams"] = [
{"stream_id": 1, "name": "CNN News"},
{"stream_id": 2, "name": "BBC World"},
]
cache_module.get_cache()["live_categories"] = []
cache_module.get_cache()["epg_urls"] = []
cache_module.get_cache()["vod_streams"] = []
cache_module.get_cache()["series"] = []
resp = auth_client.get("/search?q=CNN&live=true")
assert resp.status_code == 200
def test_search_regex_mode(self, auth_client):
cache_module.get_cache()["live_streams"] = [
{"stream_id": 1, "name": "CNN News"},
{"stream_id": 2, "name": "CNBC Finance"},
]
cache_module.get_cache()["live_categories"] = []
cache_module.get_cache()["epg_urls"] = []
cache_module.get_cache()["vod_streams"] = []
cache_module.get_cache()["series"] = []
resp = auth_client.get("/search?q=CN.*®ex=true&live=true")
assert resp.status_code == 200
def test_search_rejects_long_regex(self, auth_client):
cache_module.get_cache()["live_streams"] = []
resp = auth_client.get(f"/search?q={'a' * 101}®ex=true&live=true")
assert resp.status_code == 400
class TestSettings:
"""Tests for settings page."""
def test_settings_page_renders(self, auth_client):
cache_module.get_cache()["live_categories"] = []
with patch("main.load_file_cache", return_value=None):
resp = auth_client.get("/settings")
assert resp.status_code == 200
def test_settings_guide_filter(self, auth_client):
resp = auth_client.post(
"/settings/guide-filter",
json={"cats": ["1", "2", "3"]},
)
assert resp.status_code == 200
assert resp.json()["status"] == "ok"
def test_settings_captions(self, auth_client):
resp = auth_client.post(
"/settings/captions",
data={"enabled": "on"},
)
assert resp.status_code == 200
assert resp.json()["ok"] is True
def test_settings_transcode(self, auth_client):
resp = auth_client.post(
"/settings/transcode",
data={
"transcode_mode": "auto",
"transcode_hw": "nvidia",
"vod_transcode_cache_mins": 60,
},
)
assert resp.status_code == 200
assert resp.json()["ok"] is True
class TestAddSource:
"""Tests for adding sources."""
def test_add_xtream_source(self, auth_client):
with patch("main.clear_all_caches"):
resp = auth_client.post(
"/settings/add",
data={
"name": "Test Provider",
"source_type": "xtream",
"url": "http://example.com",
"username": "user",
"password": "pass",
"epg_timeout": 120,
},
follow_redirects=False,
)
assert resp.status_code == 303
def test_add_m3u_source(self, auth_client):
with patch("main.clear_all_caches"):
resp = auth_client.post(
"/settings/add",
data={
"name": "M3U Playlist",
"source_type": "m3u",
"url": "http://example.com/playlist.m3u",
"epg_timeout": 120,
},
follow_redirects=False,
)
assert resp.status_code == 303
def test_add_source_validates_type(self, auth_client):
resp = auth_client.post(
"/settings/add",
data={
"name": "Bad Source",
"source_type": "invalid",
"url": "http://example.com",
},
)
assert resp.status_code == 400
def test_add_source_validates_url_scheme(self, auth_client):
resp = auth_client.post(
"/settings/add",
data={
"name": "Bad Source",
"source_type": "xtream",
"url": "ftp://example.com",
},
)
assert resp.status_code == 400
def test_add_source_validates_name_length(self, auth_client):
resp = auth_client.post(
"/settings/add",
data={
"name": "x" * 201,
"source_type": "xtream",
"url": "http://example.com",
},
)
assert resp.status_code == 400
class TestDeleteSource:
"""Tests for deleting sources."""
def test_delete_source(self, auth_client, tmp_path):
settings_file = tmp_path / "server_settings.json"
settings_file.write_text(
json.dumps(
{
"sources": [
{
"id": "src_123",
"name": "Test",
"type": "xtream",
"url": "http://example.com",
}
]
}
)
)
with patch("main.clear_all_caches"):
resp = auth_client.post("/settings/delete/src_123", follow_redirects=False)
assert resp.status_code == 303
class TestUserPrefs:
"""Tests for user preferences API."""
def test_get_user_prefs(self, auth_client):
resp = auth_client.get("/api/user-prefs")
assert resp.status_code == 200
data = resp.json()
assert "favorites" in data
assert "cc_lang" in data
def test_save_user_prefs(self, auth_client):
resp = auth_client.post(
"/api/user-prefs",
json={"cc_lang": "eng", "cast_host": "192.168.1.100"},
)
assert resp.status_code == 200
assert resp.json()["ok"] is True
class TestWatchPosition:
"""Tests for watch position API."""
def test_save_watch_position(self, auth_client):
resp = auth_client.post(
"/api/watch-position",
json={"url": "http://example.com/movie.mkv", "position": 1234.5, "duration": 7200},
)
assert resp.status_code == 200
def test_get_watch_position(self, auth_client):
# Save first
auth_client.post(
"/api/watch-position",
json={"url": "http://example.com/movie.mkv", "position": 1234.5, "duration": 7200},
)
resp = auth_client.get("/api/watch-position?url=http://example.com/movie.mkv")
assert resp.status_code == 200
data = resp.json()
assert data["position"] == 1234.5
assert data["duration"] == 7200
def test_get_watch_position_not_found(self, auth_client):
resp = auth_client.get("/api/watch-position?url=http://example.com/unknown.mkv")
assert resp.status_code == 200
data = resp.json()
assert data["position"] == 0
class TestUserManagement:
"""Tests for user management endpoints."""
def test_delete_user(self, auth_client, tmp_path):
import auth
auth.create_user("otheruser", "password123")
resp = auth_client.post("/settings/users/delete/otheruser", follow_redirects=False)
assert resp.status_code == 303
def test_cannot_delete_self(self, auth_client):
resp = auth_client.post("/settings/users/delete/testuser")
assert resp.status_code == 400
def test_change_password(self, auth_client):
resp = auth_client.post(
"/settings/users/password",
data={"current_password": "testpass123", "new_password": "newpass456"},
)
assert resp.status_code == 200
def test_change_password_wrong_current(self, auth_client):
resp = auth_client.post(
"/settings/users/password",
data={"current_password": "wrongpass", "new_password": "newpass456"},
)
assert resp.status_code == 400
class TestPlaylistXspf:
"""Tests for XSPF playlist generation."""
def test_playlist_xspf(self, auth_client):
resp = auth_client.get("/playlist.xspf?url=http://example.com/stream.m3u8")
assert resp.status_code == 200
assert b"<?xml" in resp.content
assert b"http://example.com/stream.m3u8" in resp.content
assert resp.headers["content-type"] == "application/xspf+xml"
class TestApiSettings:
"""Tests for settings API."""
def test_get_settings(self, auth_client):
resp = auth_client.get("/api/settings")
assert resp.status_code == 200
data = resp.json()
assert "transcode_mode" in data
def test_update_settings(self, auth_client):
resp = auth_client.post(
"/api/settings",
json={"transcode_mode": "always"},
)
assert resp.status_code == 200
class TestTranscodeRoutes:
"""Tests for transcode routes (with mocked transcoding module)."""
def test_transcode_file_not_found(self, auth_client):
with patch("main.ffmpeg_session.get_session", return_value=None):
resp = auth_client.get("/transcode/invalid-session/stream.m3u8")
assert resp.status_code == 404
def test_transcode_stop(self, auth_client):
with patch("main.ffmpeg_session.stop_session"):
resp = auth_client.delete("/transcode/test-session")
assert resp.status_code == 200
assert resp.json()["status"] == "stopped"
def test_transcode_stop_post(self, auth_client):
with patch("main.ffmpeg_session.stop_session"):
resp = auth_client.post("/transcode/test-session/stop")
assert resp.status_code == 200
def test_transcode_progress_not_found(self, auth_client):
with patch("main.ffmpeg_session.get_session_progress", return_value=None):
resp = auth_client.get("/transcode/progress/invalid-session")
assert resp.status_code == 404
class TestSubtitleRoutes:
"""Tests for subtitle routes."""
def test_subtitle_invalid_filename(self, auth_client):
resp = auth_client.get("/subs/session/notavtt.txt")
assert resp.status_code == 400
def test_subtitle_session_not_found(self, auth_client):
with patch("main.ffmpeg_session.get_session", return_value=None):
resp = auth_client.get("/subs/invalid-session/sub0.vtt")
assert resp.status_code == 404
class TestProbeCache:
"""Tests for probe cache endpoints."""
def test_get_probe_cache(self, auth_client):
with patch("main.ffmpeg_command.get_series_probe_cache_stats", return_value=[]):
resp = auth_client.get("/settings/probe-cache")
assert resp.status_code == 200
assert "series" in resp.json()
def test_clear_probe_cache(self, auth_client):
with patch("main.ffmpeg_command.clear_all_probe_cache", return_value=5):
resp = auth_client.post("/settings/probe-cache/clear")
assert resp.status_code == 200
assert resp.json()["cleared"] == 5
def test_clear_series_probe_cache(self, auth_client):
with patch("main.ffmpeg_command.invalidate_series_probe_cache"):
resp = auth_client.post("/settings/probe-cache/clear/123")
assert resp.status_code == 200
class TestRefreshStatus:
"""Tests for refresh status endpoints."""
def test_guide_refresh_status(self, auth_client):
m3u_module.get_refresh_in_progress().clear()
resp = auth_client.get("/guide/refresh-status")
assert resp.status_code == 200
data = resp.json()
assert data["live"] is False
assert data["epg"] is False
def test_settings_refresh_status(self, auth_client):
m3u_module.get_refresh_in_progress().clear()
resp = auth_client.get("/settings/refresh-status")
assert resp.status_code == 200
if __name__ == "__main__":
from testing import run_tests
run_tests(__file__)