Files
retroLabs/tests/test_bridge.py

127 lines
6.1 KiB
Python

import tempfile
import unittest
from datetime import datetime, timedelta
from pathlib import Path
import httpx
from fastapi.testclient import TestClient
from bridge.app import create_app, program_title
CHANNEL = "4592af97-494e-42d4-9758-10bb26b05343"
class Body(httpx.AsyncByteStream):
def __init__(self, content):
self.content = content
async def __aiter__(self):
yield self.content
class BridgeTest(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.app = create_app(
tunarr_url="http://tunarr:8000", transport=httpx.MockTransport(self.upstream),
discover=False, id_file=Path(temporary.name) / "server-id",
iptv_file=Path(temporary.name) / "channels.json",
)
self.client = self.enterContext(TestClient(self.app))
async def upstream(self, request):
path = request.url.path
if path == "/api/channels":
return httpx.Response(200, json=[
{"id": CHANNEL, "number": 99, "name": "Test TV"},
{"id": "hidden", "number": 100, "name": "Hidden", "stealth": True},
])
if path == "/api/guide/channels":
start = datetime.fromisoformat(request.url.params["dateFrom"])
intervals = [
("Current show", start - timedelta(minutes=20), start + timedelta(minutes=10)),
("Next show", start + timedelta(minutes=10), start + timedelta(minutes=40)),
]
return httpx.Response(200, json={CHANNEL: {"programs": [
{"type": "content", "title": title, "start": int(first.timestamp() * 1000),
"stop": int(last.timestamp() * 1000)}
for title, first, last in reversed(intervals)
]}})
if path == f"/stream/channels/{CHANNEL}.m3u8":
return httpx.Response(200, text=(
'#EXTM3U\n#EXT-X-MEDIA:TYPE=SUBTITLES,URI="subs.m3u8"\n'
f'http://tunarr:8000/stream/channels/{CHANNEL}/hls/live.m3u8?a=1\n'
))
if path.endswith("/hls/live.m3u8"):
self.assertEqual(request.url.params["a"], "1")
return httpx.Response(200, text="#EXTM3U\nsegment.ts\n")
if path.endswith("/hls/segment.ts"):
self.assertEqual(request.headers["range"], "bytes=0-6")
return httpx.Response(206, stream=Body(b"segment"), headers={"Content-Range": "bytes 0-6/7"})
if path == "/api/test-write":
self.assertEqual(request.url.params["limit"], "2")
return httpx.Response(201, stream=Body(await request.aread()))
return httpx.Response(404)
def test_lineup_and_guide(self):
lineup = self.client.get("/api/v1/channels").json()["channels"]
self.assertEqual([channel["id"] for channel in lineup], [CHANNEL, "weather"])
self.assertEqual(lineup[1]["number"], 100)
guide = self.client.get("/api/v1/guide?hours=3").json()
self.assertEqual(guide["channels"][0]["programs"][0]["title"], "Current show")
current = self.client.get(f"/api/v1/channels/{CHANNEL}/now").json()
self.assertEqual(current["now"]["title"], "Current show")
self.assertEqual(current["next"]["title"], "Next show")
self.assertEqual(self.client.get("/api/v1/channels/hidden/now").status_code, 404)
def test_stream_proxy_resolves_from_upstream_path(self):
result = self.client.get(f"/stream/{CHANNEL}/master.m3u8")
self.assertEqual(result.headers["content-type"], "application/vnd.apple.mpegurl")
self.assertIn('URI="/stream/channels/subs.m3u8"', result.text)
variant_path = result.text.splitlines()[-1]
self.assertEqual(variant_path, f"/stream/channels/{CHANNEL}/hls/live.m3u8?a=1")
segment_path = self.client.get(variant_path).text.splitlines()[-1]
result = self.client.get(segment_path, headers={"Range": "bytes=0-6"})
self.assertEqual(result.status_code, 206)
self.assertEqual(result.headers["content-range"], "bytes 0-6/7")
self.assertEqual(result.content, b"segment")
def test_admin_proxies_writes(self):
self.assertEqual(self.client.get("/admin/", follow_redirects=False).status_code, 307)
response = self.client.post("/api/test-write?limit=2", content="test body")
self.assertEqual(response.status_code, 201)
self.assertEqual(response.text, "test body")
def test_server_id_is_persisted(self):
server_id = self.client.get("/api/v1/server").json()["id"]
self.assertIn(server_id, self.client.get("/api/v1/device.xml").text)
with TestClient(self.app) as restarted:
self.assertEqual(restarted.get("/api/v1/server").json()["id"], server_id)
def test_episode_labels_remove_release_metadata(self):
episode = {"type": "content", "program": {
"type": "episode", "title": "The.Rookie.S01E01.720p.AMZN.WEBRip.x264",
}}
self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01")
episode["program"]["title"] = "The Rookie S01E01 Pilot"
self.assertEqual(program_title(episode, "The Rookie"), "The Rookie S01E01 · Pilot")
def test_iptv_joins_lineup_without_tunarr_programming(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "channels.json"
path.write_text(
'[{"id":"sports","name":"Sports","number":12,'
'"url":"https://example.com/live.m3u8"}]'
)
app = create_app(
transport=httpx.MockTransport(self.upstream), discover=False,
id_file=path.with_name("server-id"), iptv_file=path,
)
with TestClient(app) as client:
channels = client.get("/api/v1/channels").json()["channels"]
self.assertEqual(channels[0]["streamUrl"], "/iptv/iptv-sports/master.m3u8")
self.assertEqual(channels[0]["type"], "iptv")
self.assertEqual(client.get("/api/v1/guide").json()["channels"][0]["programs"], [])
self.assertIsNone(client.get("/api/v1/channels/iptv-sports/now").json()["now"])