feat(serverlibrary): add unit tests for serverlibrary
This commit is contained in:
1 parent
4df676835f
commit
905fa8aa8b
3 files changed
+262
No files matched your search
Vendored
+14
@@ -0,0 +1,14 @@
|
|||||||
|
{
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Python: Run serverlibrary tests",
|
||||||
|
"type": "debugpy",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "${workspaceFolder}/run_tests.py",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"cwd": "${workspaceFolder}",
|
||||||
|
"justMyCode": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent
|
||||||
|
SRC = ROOT / "src"
|
||||||
|
if str(SRC) not in sys.path:
|
||||||
|
sys.path.insert(0, str(SRC))
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(pytest.main(["-q", "tests"]))
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import argparse
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from serverlibrary import core
|
||||||
|
|
||||||
|
|
||||||
|
def test_tag_and_color_helpers():
|
||||||
|
assert core.tag("info") == "INFO"
|
||||||
|
assert core.red_tag("warn") == f"{core.red}[WARN]{core.reset}"
|
||||||
|
assert core.green_tag("ok") == f"{core.green}[OK]{core.reset}"
|
||||||
|
assert core.yellow_tag("warning") == f"{core.yellow}[WARNING]{core.reset}"
|
||||||
|
assert core.blue_tag("info") == f"{core.blue}[INFO]{core.reset}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_parser_add_loglevel():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
core.parser_add_loglevel(parser)
|
||||||
|
args = parser.parse_args(["--log-level", "debug"])
|
||||||
|
assert args.log_level == "DEBUG"
|
||||||
|
|
||||||
|
|
||||||
|
def test_setup_logging_creates_handlers_and_logfile(tmp_path):
|
||||||
|
root_logger = logging.getLogger()
|
||||||
|
original_handlers = root_logger.handlers[:]
|
||||||
|
root_logger.handlers.clear()
|
||||||
|
|
||||||
|
try:
|
||||||
|
logfile = tmp_path / "serverlibrary_test"
|
||||||
|
core.setup_logging(log_level="DEBUG", logfile=str(logfile), no_date=True)
|
||||||
|
|
||||||
|
assert root_logger.level == core.TRACE
|
||||||
|
assert any(isinstance(handler, logging.FileHandler) for handler in root_logger.handlers)
|
||||||
|
assert any(isinstance(handler, logging.StreamHandler) for handler in root_logger.handlers)
|
||||||
|
|
||||||
|
log_dir = Path.home() / "logs"
|
||||||
|
created_logs = list(log_dir.glob("serverlibrary_test*.log"))
|
||||||
|
assert created_logs
|
||||||
|
finally:
|
||||||
|
root_logger.handlers = original_handlers
|
||||||
|
|
||||||
|
|
||||||
|
def test_custom_logger_trace_emits_when_level_enabled():
|
||||||
|
stream = io.StringIO()
|
||||||
|
handler = logging.StreamHandler(stream)
|
||||||
|
handler.setLevel(core.TRACE)
|
||||||
|
|
||||||
|
logger = core.CustomLogger("trace.test")
|
||||||
|
logger.handlers = [handler]
|
||||||
|
logger.propagate = False
|
||||||
|
logger.setLevel(core.TRACE)
|
||||||
|
|
||||||
|
logger.trace("hello trace")
|
||||||
|
|
||||||
|
assert "hello trace" in stream.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_safe_delete_removes_file_and_directory(tmp_path):
|
||||||
|
file_path = tmp_path / "remove_me.txt"
|
||||||
|
file_path.write_text("demo")
|
||||||
|
core.safe_delete(file_path)
|
||||||
|
assert not file_path.exists()
|
||||||
|
|
||||||
|
directory = tmp_path / "remove_me_dir"
|
||||||
|
directory.mkdir()
|
||||||
|
nested = directory / "nested.txt"
|
||||||
|
nested.write_text("demo")
|
||||||
|
core.safe_delete(directory)
|
||||||
|
assert not directory.exists()
|
||||||
|
|
||||||
|
missing = tmp_path / "missing.txt"
|
||||||
|
core.safe_delete(missing)
|
||||||
|
assert not missing.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_safe_rename_success_and_failures(tmp_path):
|
||||||
|
source = tmp_path / "source.txt"
|
||||||
|
source.write_text("hello")
|
||||||
|
|
||||||
|
dry_run_target = tmp_path / "dry_run" / "renamed.txt"
|
||||||
|
result, ok = core.safe_rename(source, dry_run_target, dry_run=True)
|
||||||
|
assert ok is True
|
||||||
|
assert source.exists()
|
||||||
|
assert not dry_run_target.exists()
|
||||||
|
assert "source.txt" in result
|
||||||
|
|
||||||
|
target = tmp_path / "target" / "renamed.txt"
|
||||||
|
result, ok = core.safe_rename(source, target)
|
||||||
|
assert ok is True
|
||||||
|
assert target.exists()
|
||||||
|
assert not source.exists()
|
||||||
|
assert "source.txt" in result
|
||||||
|
|
||||||
|
same, ok = core.safe_rename(target, target)
|
||||||
|
assert same == ""
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
second_source = tmp_path / "second_source.txt"
|
||||||
|
second_source.write_text("hello")
|
||||||
|
existing = tmp_path / "target" / "already_here.txt"
|
||||||
|
existing.write_text("there")
|
||||||
|
result, ok = core.safe_rename(second_source, existing)
|
||||||
|
assert result == ""
|
||||||
|
assert ok is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_subtitle_tracks_handles_real_and_empty_cases(monkeypatch):
|
||||||
|
class DummyResult:
|
||||||
|
stdout = json.dumps(
|
||||||
|
{
|
||||||
|
"streams": [
|
||||||
|
{"codec_type": "video", "index": 0},
|
||||||
|
{
|
||||||
|
"codec_type": "subtitle",
|
||||||
|
"index": 1,
|
||||||
|
"tags": {"title": "English", "language": "eng"},
|
||||||
|
"lang": "eng",
|
||||||
|
"disposition": {"default": 1},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_run(*args, **kwargs):
|
||||||
|
return DummyResult()
|
||||||
|
|
||||||
|
monkeypatch.setattr(core.subprocess, "run", fake_run)
|
||||||
|
tracks = core.get_subtitle_tracks("example.mkv")
|
||||||
|
assert tracks[0]["description"] == "English"
|
||||||
|
assert tracks[0]["language"] == "eng"
|
||||||
|
assert tracks[0]["primary"] is True
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
core.subprocess,
|
||||||
|
"run",
|
||||||
|
lambda *args, **kwargs: type("Result", (), {"stdout": json.dumps({"streams": [{"codec_type": "video", "index": 0}]})})(),
|
||||||
|
)
|
||||||
|
assert core.get_subtitle_tracks("empty.mkv") == [{"number": 0, "description": "", "lang": "", "language": "", "primary": False}]
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_audio_tracks_ffprobe_and_handbrake(monkeypatch):
|
||||||
|
class FfprobeResult:
|
||||||
|
stdout = json.dumps(
|
||||||
|
{
|
||||||
|
"streams": [
|
||||||
|
{"codec_type": "video", "index": 0},
|
||||||
|
{
|
||||||
|
"codec_type": "audio",
|
||||||
|
"index": 1,
|
||||||
|
"tags": {"title": "English", "language": "eng"},
|
||||||
|
"lang": "eng",
|
||||||
|
"disposition": {"default": 1},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def fake_ffprobe(*args, **kwargs):
|
||||||
|
return FfprobeResult()
|
||||||
|
|
||||||
|
monkeypatch.setattr(core.subprocess, "run", fake_ffprobe)
|
||||||
|
tracks = core.get_audio_tracks("movie.mkv")
|
||||||
|
assert tracks[0]["number"] == 1
|
||||||
|
assert tracks[0]["description"] == "English"
|
||||||
|
assert tracks[0]["primary"] is True
|
||||||
|
|
||||||
|
def fake_handbrake(*args, **kwargs):
|
||||||
|
class Result:
|
||||||
|
stdout = " 1, English (AAC)\n 2, Deutsch (AC3)\n"
|
||||||
|
|
||||||
|
return Result()
|
||||||
|
|
||||||
|
monkeypatch.setattr(core.subprocess, "run", fake_handbrake)
|
||||||
|
handbrake_tracks = core.get_audio_tracks("/dev/dvd", title=1, handbrake=True)
|
||||||
|
assert handbrake_tracks[0]["number"] == 1
|
||||||
|
assert handbrake_tracks[0]["description"] == "English"
|
||||||
|
assert handbrake_tracks[1]["number"] == 2
|
||||||
|
assert handbrake_tracks[1]["description"] == "Deutsch"
|
||||||
|
|
||||||
|
|
||||||
|
def test_words_and_similarity_helpers():
|
||||||
|
assert core.words("Hello, world! 123") == {"hello", "world", "123"}
|
||||||
|
assert core.word_similarity("abc", "abc") == 1.0
|
||||||
|
assert core.words("foo_bar") == {"foo", "bar"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_score_match_helpers():
|
||||||
|
search = {"apple", "banana"}
|
||||||
|
candidate = {"apple", "cherry"}
|
||||||
|
assert core.score_match_recall_jaccard(search, candidate) == 0.5
|
||||||
|
assert core.score_match_jaccard(search, candidate) == pytest.approx(1 / 3)
|
||||||
|
|
||||||
|
same_words = {"cat", "dog"}
|
||||||
|
assert core.score_match_fuzzy(same_words, same_words) == 1.0
|
||||||
|
assert core.combined_score(0.5, 0.25, 2.0, 3.0) == 1.75
|
||||||
|
|
||||||
|
|
||||||
|
def test_tmdb_get_and_tvdb_get(monkeypatch):
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, payload):
|
||||||
|
self.payload = payload
|
||||||
|
|
||||||
|
def raise_for_status(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self.payload
|
||||||
|
|
||||||
|
def fake_get(url, headers=None, params=None, timeout=None):
|
||||||
|
captured["url"] = url
|
||||||
|
captured["headers"] = headers
|
||||||
|
captured["params"] = params
|
||||||
|
captured["timeout"] = timeout
|
||||||
|
return FakeResponse({"ok": True})
|
||||||
|
|
||||||
|
monkeypatch.setattr(core.requests, "get", fake_get)
|
||||||
|
assert core.tmdb_get("/movie/123", params={"language": "en"}) == {"ok": True}
|
||||||
|
assert captured["url"].startswith("https://api.themoviedb.org/3")
|
||||||
|
assert captured["headers"]["Authorization"].startswith("Bearer ")
|
||||||
|
assert captured["params"] == {"language": "en"}
|
||||||
|
|
||||||
|
captured.clear()
|
||||||
|
assert core.tvdb_get("/series/123", params={"meta": "episodes"}) == {"ok": True}
|
||||||
|
assert captured["url"].startswith("https://api4.thetvdb.com/v4")
|
||||||
|
assert captured["headers"]["Authorization"].startswith("Bearer ")
|
||||||
|
assert captured["params"] == {"meta": "episodes"}
|
||||||
Reference in new issue
Block a user