| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270 |
- """Python UI tests: no hardware, no X display. Run with `make pytest`.
- The MPD tests talk to tests/fake_mpd.py, never to a real player.
- """
- import os
- import socket
- import subprocess
- import sys
- import tempfile
- import time
- import unittest
- from unittest import mock
- HERE = os.path.dirname(os.path.abspath(__file__))
- sys.path.insert(0, os.path.join(HERE, ".."))
- from gi.repository import GLib # noqa: E402
- from radio import mpd, platform # noqa: E402
- from radio import state as st # noqa: E402
- from radio.__main__ import make_pattern, parse_args # noqa: E402
- from radio.app import App # noqa: E402
- from radio.panel import Panel, PanelError, load_library # noqa: E402
- def have_panel_lib():
- try:
- load_library()
- return True
- except PanelError:
- return False
- def free_port():
- s = socket.socket()
- s.bind(("127.0.0.1", 0))
- port = s.getsockname()[1]
- s.close()
- return port
- def run_loop_until(cond, timeout_s=5.0):
- ctx = GLib.MainContext.default()
- end = time.monotonic() + timeout_s
- while not cond() and time.monotonic() < end:
- ctx.iteration(False)
- time.sleep(0.005)
- return cond()
- class FakeMpd(object):
- def __init__(self, idle_event_s=None):
- self.port = free_port()
- fd, self.log_path = tempfile.mkstemp(prefix="fake_mpd_")
- os.close(fd)
- cmd = [sys.executable, os.path.join(HERE, "fake_mpd.py"), str(self.port), self.log_path]
- if idle_event_s is not None:
- cmd.append(str(idle_event_s))
- self.proc = subprocess.Popen(cmd)
- end = time.monotonic() + 5
- while time.monotonic() < end:
- try:
- socket.create_connection(("127.0.0.1", self.port), 0.2).close()
- break
- except OSError:
- time.sleep(0.05)
- # that probe connection is logged as nothing, but start from empty
- open(self.log_path, "w").close()
- def commands(self):
- with open(self.log_path) as f:
- return [line.strip() for line in f if line.strip()]
- def stop(self):
- self.proc.terminate()
- self.proc.wait()
- os.unlink(self.log_path)
- class TestState(unittest.TestCase):
- def test_log_wraps_and_scrolls(self):
- s = st.RadioState()
- s.log_append("a" * (st.LOG_COLS + 3))
- self.assertEqual(s.log[-2], "a" * st.LOG_COLS)
- self.assertEqual(s.log[-1], "aaa")
- for i in range(st.LOG_ROWS + 2):
- s.log_append("line %d" % i)
- self.assertEqual(len(s.log), st.LOG_ROWS)
- self.assertEqual(s.log[-1], "line %d" % (st.LOG_ROWS + 1))
- def test_log_counts_characters_not_bytes(self):
- s = st.RadioState()
- s.log_append("ż" * st.LOG_COLS)
- self.assertEqual(s.log[-1], "ż" * st.LOG_COLS)
- self.assertEqual(s.log[-2], "")
- def test_elapsed_held_when_not_playing(self):
- s = st.RadioState()
- s.connected, s.state = True, st.PLAY_PAUSED
- s.elapsed_ms, s.elapsed_stamp_ms = 5000, st.monotonic_ms() - 3000
- self.assertEqual(s.current_elapsed_ms(), 5000)
- s.state = st.PLAY_PLAYING
- self.assertGreaterEqual(s.current_elapsed_ms(), 8000)
- s.total_ms = 6000
- self.assertEqual(s.current_elapsed_ms(), 6000)
- class TestTitle(unittest.TestCase):
- def test_variants(self):
- self.assertEqual(mpd.format_title({"artist": "A", "title": "T", "file": "x"}), "A - T")
- self.assertEqual(mpd.format_title({"name": "Radio", "title": "T"}), "Radio: T")
- self.assertEqual(mpd.format_title({"name": "Radio"}), "Radio")
- self.assertEqual(mpd.format_title({"file": "dir/song.flac"}), "song.flac")
- self.assertEqual(mpd.format_title({"file": "http://host/stream"}), "http://host/stream")
- self.assertEqual(mpd.format_title({"file": "dir/"}), "dir/")
- class TestMpdClient(unittest.TestCase):
- def setUp(self):
- self.server = FakeMpd()
- self.state = st.RadioState("localhost")
- self.log = []
- self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
- lambda: None, self.log.append)
- self.assertTrue(run_loop_until(lambda: self.state.connected))
- def tearDown(self):
- self.client.close()
- self.server.stop()
- def test_status_parsed(self):
- s = self.state
- self.assertEqual(s.state, st.PLAY_PLAYING)
- self.assertEqual((s.song_pos, s.queue_len), (2, 10))
- self.assertEqual((s.elapsed_ms, s.total_ms), (83100, 296000))
- self.assertEqual(s.volume, 50)
- self.assertTrue(s.repeat and s.random)
- self.assertTrue(s.title.startswith("Zażółć Gęślą - Jaźń"))
- self.assertIn("Połączono z MPD: 127.0.0.1", self.log)
- def test_commands(self):
- for cmd in (mpd.NEXT, mpd.VOLUME_UP, mpd.VOLUME_DOWN, mpd.TOGGLE, mpd.PREV,
- mpd.STOP, mpd.PLAY, mpd.REFRESH):
- self.client.command(cmd)
- sent = [c for c in self.server.commands()
- if c not in ("status", "currentsong", "noidle")]
- self.assertEqual(sent, ["next", "volume +1", "volume -1", "pause", "previous",
- "stop", "play"])
- self.assertTrue(self.state.connected)
- def test_stopped_has_no_title(self):
- self.client.command(mpd.STOP)
- self.assertEqual(self.state.state, st.PLAY_STOPPED)
- self.assertEqual(self.state.title, "")
- def test_reconnects_after_loss(self):
- self.server.stop()
- self.server = FakeMpd.__new__(FakeMpd) # tearDown stops it again
- self.assertTrue(run_loop_until(lambda: not self.state.connected))
- self.assertTrue(any(line.startswith("MPD: ") for line in self.log))
- port = self.client.port
- restarted = FakeMpd()
- try:
- self.client.port = restarted.port
- self.assertTrue(run_loop_until(lambda: self.state.connected,
- mpd.RECONNECT_S + 3))
- finally:
- self.client.port = port
- self.server = restarted
- def test_idle_event_refreshes(self):
- self.tearDown()
- self.server = FakeMpd(idle_event_s=0.2)
- self.state = st.RadioState()
- self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
- lambda: None, self.log.append)
- self.assertTrue(run_loop_until(lambda: self.server.commands().count("status") >= 2))
- @unittest.skipUnless(have_panel_lib(), "panel library not built (make lib)")
- class TestPanel(unittest.TestCase):
- def test_app_renders_to_simulator_without_faults(self):
- panel = Panel()
- panel.init()
- frames = []
- def present(data, stride, x, y, w, h):
- frames.append((y, h))
- panel.update(data, stride, x, y, w, h)
- app = App("127.0.0.1", free_port(), 240, 160, present, None)
- try:
- self.assertTrue(run_loop_until(lambda: frames))
- app.log("Zażółć gęślą jaźń")
- self.assertTrue(run_loop_until(lambda: len(frames) >= 2, 3))
- finally:
- app.close()
- self.assertEqual(frames[0], (0, 160))
- self.assertLess(frames[1][1], 160) # only the changed rows
- self.assertEqual(panel.sim_faults(), 0)
- shown, levels = panel.sim_render()
- self.assertTrue(shown)
- self.assertIn(3, set(levels)) # some black: the link warning
- def test_key_lockout(self):
- sent = []
- app = App("127.0.0.1", free_port(), 240, 160, lambda *a: None)
- app.mpd.command = sent.append
- try:
- app.key("next")
- app.key("next")
- app.key("menu")
- app.key("bogus")
- finally:
- app.close()
- self.assertEqual(sent, [mpd.NEXT])
- def test_patterns(self):
- for name in ("geometry", "gray"):
- fb = make_pattern(name, 240, 160)
- self.assertEqual(len(fb), 240 * 160 * 4)
- panel = Panel()
- panel.init()
- panel.update(fb, 240 * 4, 0, 0, 240, 160)
- self.assertEqual(panel.sim_faults(), 0)
- levels = panel.sim_render()[1]
- if name == "gray":
- self.assertEqual([levels[x] for x in (0, 60, 120, 180)], [0, 1, 2, 3])
- else:
- self.assertEqual(levels[0], 3)
- self.assertEqual(levels[241], 3) # diagonal
- def test_bad_config(self):
- with self.assertRaises(PanelError):
- Panel(width=241)
- class TestPlatform(unittest.TestCase):
- def test_denied_bus_never_opened(self):
- with mock.patch("builtins.open", mock.mock_open(read_data="SMBus PIIX4 adapter port 0\n")), \
- mock.patch("os.open") as os_open:
- with self.assertRaises(platform.BusRefused):
- platform.open_i2c_bus(6)
- os_open.assert_not_called()
- def test_unknown_bus_needs_allow(self):
- with mock.patch("builtins.open", mock.mock_open(read_data="Some adapter\n")), \
- mock.patch("os.open") as os_open:
- with self.assertRaises(platform.BusRefused) as cm:
- platform.open_i2c_bus(3)
- self.assertIn('--allow-adapter="Some adapter"', str(cm.exception))
- os_open.assert_not_called()
- def test_evdev_keys_match_overlay(self):
- with open(os.path.join(HERE, "..", "dts", "radio-panel.dts")) as f:
- dts = f.read()
- import re
- found = dict((label, int(code)) for label, code in re.findall(
- r'label = "(\w+)";.*?linux,code = <(\d+)>', dts))
- self.assertEqual(found, dict((v, k) for k, v in platform.EVDEV_KEYS.items()))
- self.assertEqual(sorted(found), sorted(st.KEYS))
- def test_args(self):
- a = parse_args(["i2c", "--bus", "11", "--addr", "0x75", "--window-keys"])
- self.assertEqual((a.bus, a.addr, a.window_keys, a.host), (11, 0x75, True, "localhost"))
- self.assertEqual(parse_args(["sim"]).host, "radio.lo")
- if __name__ == "__main__":
- unittest.main()
|