feat: added testing of video id parsing

This commit is contained in:
Hazel 2024-04-24 11:22:51 +02:00
parent 6a7cf23e9d
commit b2c03a3f2d
5 changed files with 69 additions and 4 deletions

View File

@ -1,5 +1,6 @@
{
"cSpell.words": [
"Didnt",
"sponsorblock"
]
}

View File

@ -1,6 +1,9 @@
from python_sponsorblock import SponsorBlock
from python_sponsorblock import SponsorBlock, _get_video_id
if __name__ == "__main__":
sb = SponsorBlock()
print(_get_video_id("dksaödfksöldkföslkafdsölfkas"))

View File

@ -1,7 +1,29 @@
import requests
from urllib.parse import urlparse, urlunparse, parse_qs
import re
class SponsorBlockError(Exception):
pass
from .exceptions import SponsorBlockError, SponsorBlockIdNotFoundError
def _get_video_id(i: str, silent: bool = False) -> None:
# check with regex if i is already an id like r1Fa1iWJVEA
if re.match(r"^[a-zA-Z0-9_-]{11}$", i):
return i.strip()
url = urlparse(url=i)
if url.netloc == "youtu.be":
return url.path[1:]
type_frag_list = url.path.split("/")
query_stuff = parse_qs(url.query)
if "v" not in query_stuff:
if not silent:
raise SponsorBlockIdNotFoundError("No video id found in the url")
return None
else:
return query_stuff["v"][0]
class SponsorBlock:

View File

@ -0,0 +1,6 @@
class SponsorBlockError(Exception):
pass
class SponsorBlockIdNotFoundError(SponsorBlockError):
pass

33
tests/test_video_id.py Normal file
View File

@ -0,0 +1,33 @@
import unittest
from python_sponsorblock import _get_video_id, exceptions
MAGIC_ID = "dQw4w9WgXcQ"
class TestVideoIdParsing(unittest.TestCase):
def test_already_parsed_id(self):
self.assertEqual(_get_video_id(MAGIC_ID), MAGIC_ID)
def test_non_existing_id(self):
with self.assertRaises(exceptions.SponsorBlockIdNotFoundError):
_get_video_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
self.assertEqual(_get_video_id("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", silent=True), None)
def test_youtu_dot_be(self):
self.assertEqual(_get_video_id("https://youtu.be/" + MAGIC_ID), MAGIC_ID)
def test_youtube_dot_com(self):
self.assertEqual(_get_video_id("https://www.youtube.com/watch?v=" + MAGIC_ID), MAGIC_ID)
def test_invidious(self):
self.assertEqual(_get_video_id("https://invidio.us/watch?v=" + MAGIC_ID), MAGIC_ID)
def test_piped(self):
self.assertEqual(_get_video_id("https://piped.video/watch?v=" + MAGIC_ID), MAGIC_ID)
if __name__ == "__main__":
unittest.main()