tests: fix test code coverage

- properly rewrite TestPluginAPIHTTPSession.test_read_timeout
- remove Python 2 compat code from TestBuffer.test_reuse_input
- add category variable to simple player --title tests and merge them
- ignore ImportError exceptions from code coverage
- remove unnecessary branch in unsupported_versions_1979
- annotate dead branches in tests/resources and remove unused mock_http
This commit is contained in:
bastimeyer 2021-02-07 19:57:07 +01:00 committed by Forrest
parent da0bfe9353
commit 1b178b3ee2
6 changed files with 31 additions and 52 deletions

View File

@ -4,7 +4,6 @@ import xml.etree.ElementTree as ET
from contextlib import contextmanager
from io import BytesIO
import requests_mock
__here__ = os.path.abspath(os.path.dirname(__file__))
@ -14,11 +13,11 @@ def _parse_xml(data, strip_ns=False):
try:
it = ET.iterparse(BytesIO(data))
for _, el in it:
if '}' in el.tag and strip_ns:
if '}' in el.tag and strip_ns: # pragma: no branch
# strip all namespaces
el.tag = el.tag.split('}', 1)[1]
return it.root
except Exception as err:
except Exception as err: # pragma: no cover
snippet = repr(data)
if len(snippet) > 35:
snippet = snippet[:35] + " ..."
@ -36,11 +35,3 @@ def text(path, encoding="utf8"):
def xml(path, encoding="utf8"):
with codecs.open(os.path.join(__here__, path), 'r', encoding=encoding) as resource_fh:
yield _parse_xml(resource_fh.read(), strip_ns=True)
@contextmanager
def mock_http(path, url, encoding="utf8"):
with text(path, encoding) as resource:
with requests_mock.Mocker() as mock:
mock.get(url, text=resource.read())
yield mock

View File

@ -1,5 +1,5 @@
import unittest
from unittest.mock import PropertyMock, patch
from unittest.mock import PropertyMock, call, patch
import requests
@ -8,17 +8,26 @@ from streamlink.plugin.api.http_session import HTTPSession
class TestPluginAPIHTTPSession(unittest.TestCase):
@patch('requests.sessions.Session.send')
def test_read_timeout(self, mock_send):
mock_send.side_effect = IOError
@patch("streamlink.plugin.api.http_session.time.sleep")
@patch("streamlink.plugin.api.http_session.Session.request")
def test_read_timeout(self, mock_request, mock_sleep):
mock_request.side_effect = requests.Timeout
session = HTTPSession()
def stream_data():
res = session.get("http://httpbin.org/delay/6",
timeout=3, stream=True)
next(res.iter_content(8192))
self.assertRaises(PluginError, stream_data)
with self.assertRaises(PluginError) as cm:
session.get("http://localhost/", timeout=123, retries=3, retry_backoff=2, retry_max_backoff=5)
self.assertTrue(str(cm.exception).startswith("Unable to open URL: http://localhost/"))
self.assertEqual(mock_request.mock_calls, [
call(session, "GET", "http://localhost/", headers={}, params={}, timeout=123, proxies={}, allow_redirects=True),
call(session, "GET", "http://localhost/", headers={}, params={}, timeout=123, proxies={}, allow_redirects=True),
call(session, "GET", "http://localhost/", headers={}, params={}, timeout=123, proxies={}, allow_redirects=True),
call(session, "GET", "http://localhost/", headers={}, params={}, timeout=123, proxies={}, allow_redirects=True),
])
self.assertEqual(mock_sleep.mock_calls, [
call(2),
call(4),
call(5)
])
def test_json_encoding(self):
json_str = "{\"test\": \"Α and Ω\"}"

View File

@ -52,15 +52,7 @@ class TestBuffer(unittest.TestCase):
"""Objects should be reusable after write()"""
original = b"original"
tests = [bytearray(original)]
try:
m = memoryview(bytearray(original))
except NameError: # Python 2.6 does not have "memoryview"
pass
else:
# Python 2.7 doesn't do bytes(memoryview) properly
if bytes(m) == original:
tests.append(m)
tests = [bytearray(original), memoryview(bytearray(original))]
for data in tests:
self.buffer.write(data)

View File

@ -7,12 +7,9 @@ from tests.test_cmdline import CommandLineTestCase
@unittest.skipIf(is_win32, "test only applicable in a POSIX OS")
class TestCommandLineWithTitlePOSIX(CommandLineTestCase):
def test_open_player_with_title_vlc(self):
self._test_args(["streamlink", "-p", "/usr/bin/vlc", "--title", "{title}", "http://test.se", "test"],
["/usr/bin/vlc", "--input-title-format", 'Test Title', "-"])
def test_open_player_with_unicode_author_vlc(self):
self._test_args(["streamlink", "-p", "/usr/bin/vlc", "--title", "{author}", "http://test.se", "test"],
["/usr/bin/vlc", "--input-title-format", "Tѥst Āuƭhǿr", "-"])
self._test_args(["streamlink", "-p", "/usr/bin/vlc",
"--title", "{title} - {author} - {category}", "http://test.se", "test"],
["/usr/bin/vlc", "--input-title-format", "Test Title - Tѥst Āuƭhǿr - No Category", "-"])
def test_open_player_with_default_title_vlc(self):
self._test_args(["streamlink", "-p", "/usr/bin/vlc", "http://test.se", "test"],
@ -36,15 +33,8 @@ class TestCommandLineWithTitleWindows(CommandLineTestCase):
def test_open_player_with_title_vlc(self):
self._test_args(
["streamlink", "-p", "c:\\Program Files\\VideoLAN\\vlc.exe",
"--title", "{title}", "http://test.se", "test"],
"c:\\Program Files\\VideoLAN\\vlc.exe --input-title-format \"Test Title\" -"
)
def test_open_player_with_unicode_author_vlc_py3(self):
self._test_args(
["streamlink", "-p", "c:\\Program Files\\VideoLAN\\vlc.exe",
"--title", "{author}", "http://test.se", "test"],
"c:\\Program Files\\VideoLAN\\vlc.exe --input-title-format \"Tѥst Āuƭhǿr\" -"
"--title", "{title} - {author} - {category}", "http://test.se", "test"],
"c:\\Program Files\\VideoLAN\\vlc.exe --input-title-format \"Test Title - Tѥst Āuƭhǿr - No Category\" -"
)
def test_open_player_with_default_title_vlc(self):

View File

@ -8,14 +8,14 @@ try:
import iso3166 # noqa: F401
ISO639 = True
except ImportError:
except ImportError: # pragma: no cover
ISO639 = False
try:
import pycountry # noqa: F401
PYCOUNTRY = True
except ImportError:
except ImportError: # pragma: no cover
PYCOUNTRY = False

View File

@ -11,15 +11,12 @@ def unsupported_versions_1979():
- https://bugs.python.org/issue34294
"""
v = sys.version_info
if (v.major == 3) and (
return (v.major == 3) and (
# 3.7.0 - 3.7.2
(v.minor == 7 and v.micro <= 2)
# 3.8.0a1
or (v.minor == 8 and v.micro == 0 and v.releaselevel == 'alpha' and v.serial <= 1)
):
return True
else:
return False
)
class TestPluginUtil(unittest.TestCase):