Files
lintunes/tests/test_round134.py
T

418 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Round 134: Connections › Connect to Mumble… — LinTunes as a bot in a
Mumble room, following trav between rooms."""
import asyncio
import sqlite3
import ssl
import subprocess
from unittest.mock import MagicMock
import numpy as np
import pytest
from lintunes.mumble import certs, opus, proto, servers
from lintunes.mumble.client import Connection, MumbleError, ServerState
from lintunes.mumble.sink import (
FRAME_MS, MumbleSink, SAMPLES, apply_gain, bitrate_for)
@pytest.fixture
def xdg(tmp_path, monkeypatch):
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config"))
monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path / "data"))
return tmp_path
# ---- wire format ----
def test_protobuf_round_trip():
data = proto.encode([(1, 7), (3, "Rüm"), (5, True), (6, None),
(9, 300), (14, b"\x00\xff")])
fields = proto.decode(data)
assert fields[1] == [7] and fields[5] == [1] and fields[9] == [300]
assert proto.text(fields, 3) == "Rüm"
assert fields[14] == [b"\x00\xff"]
assert 6 not in fields
@pytest.mark.parametrize("value", [0, 1, 0x7F, 0x80, 0x3FFF, 0x4000,
0x1FFFFF, 0x200000, 0xFFFFFFF,
0x10000000, 0xFFFFFFFF])
def test_mumble_varint_round_trip(value):
data = proto.mumble_varint(value)
assert proto.read_mumble_varint(data) == (value, len(data))
def test_voice_packet_layout():
packet = proto.voice_packet(4, b"abc", terminator=True)
assert packet[0] == 4 << 5 # Opus, normal talking
seq, i = proto.read_mumble_varint(packet, 1)
length, i = proto.read_mumble_varint(packet, i)
assert seq == 4 and length == 3 | proto.TERMINATOR
assert packet[i:] == b"abc"
with pytest.raises(ValueError):
proto.voice_packet(0, bytes(proto.TERMINATOR))
def test_frame_reader_reassembles_split_frames():
stream = proto.frame(proto.PING, b"x" * 10) + proto.frame(9, b"")
reader = proto.FrameReader()
got = []
for i in range(len(stream)):
got += reader.feed(stream[i:i + 1])
assert got == [(proto.PING, b"x" * 10), (9, b"")]
def test_bandwidth_caps_the_bitrate():
assert bitrate_for(128, 0) == 128000 # no limit given
assert bitrate_for(128, 558000) == 128000
capped = bitrate_for(128, 72000)
assert capped < 72000 and capped > 50000
def test_gain_scales_samples():
pcm = np.array([1000, -1000, 32767], dtype="<i2").tobytes()
assert apply_gain(pcm, 1.0) == pcm
half = np.frombuffer(apply_gain(pcm, 0.5), dtype="<i2")
assert list(half) == [500, -500, 16383]
@pytest.mark.skipif(not opus.available(), reason="no libopus")
def test_opus_encodes_music_at_the_bitrate():
encoder = opus.Encoder(2, 96000)
tone = (np.sin(np.arange(SAMPLES * 2) / 7) * 9000).astype("<i2")
sizes = [len(encoder.encode(tone.tobytes(), SAMPLES)) for _ in range(25)]
kbps = sum(sizes) * 8 / (25 * FRAME_MS / 1000) / 1000
assert 70 < kbps < 110
encoder.close()
# ---- where to connect ----
def test_parse_mumble_url():
s = servers.parse_url(
"mumble://trav@chat.example.org:64740/Work/Music%20Room?version=1.2.0")
assert (s.host, s.port, s.username) == ("chat.example.org", 64740, "trav")
assert s.channel_path == ["Work", "Music Room"]
assert servers.parse_url("mumble://h").port == servers.DEFAULT_PORT
assert servers.parse_url("https://h") is None
assert servers.parse_url("") is None
def _mumble_db(path):
with sqlite3.connect(path) as db:
db.execute("CREATE TABLE `servers` (`id` INTEGER PRIMARY KEY, "
"`name` TEXT, `hostname` TEXT, `port` INTEGER DEFAULT "
"64738, `username` TEXT, `password` TEXT, `url` TEXT)")
db.execute("CREATE TABLE `cert` (`id` INTEGER PRIMARY KEY, "
"`hostname` TEXT, `port` INTEGER, `digest` TEXT)")
db.executemany(
"INSERT INTO servers (name, hostname, port, username, password)"
" VALUES (?, ?, ?, ?, ?)",
[("Work", "chat.example.org", 64738, "me", "pw"),
("Home", "home.example", 1234, "me2", "")])
db.execute("INSERT INTO cert (hostname, port, digest) VALUES "
"('Chat.Example.org', 64738, 'ABCDEF')")
return path
def test_saved_servers_and_digest(tmp_path):
db = _mumble_db(tmp_path / "mumble.sqlite")
saved = servers.saved_servers(db)
assert [s.name for s in saved] == ["Home", "Work"]
assert saved[1].password == "pw"
assert servers.accepted_digest("chat.example.org", 64738, db) == "abcdef"
assert servers.accepted_digest("home.example", 1234, db) is None
assert servers.saved_servers(tmp_path / "missing.sqlite") == []
def test_choices_put_the_current_server_first_with_its_password(tmp_path):
saved = servers.saved_servers(_mumble_db(tmp_path / "m.sqlite"))
current = servers.parse_url("mumble://me@chat.example.org/Room")
current.current = True
got = servers.choices(current, saved)
assert got[0] is current and current.password == "pw"
assert current.name == "Work"
assert [s.name for s in got[1:]] == ["Home"]
assert servers.choices(None, saved) == saved
def test_database_paths_cover_flatpak_and_native(tmp_path):
paths = servers.database_paths(tmp_path)
assert any(".var/app/info.mumble.Mumble" in str(p) for p in paths)
assert any(".local/share/Mumble" in str(p) for p in paths)
# ---- trust ----
def test_self_signed_trust_rules(xdg):
der = b"certificate"
good = certs.digest(der)
assert certs.check_self_signed("h", 1, der, good) == "mumble"
with pytest.raises(certs.CertificateError):
certs.check_self_signed("h", 1, der, "0" * 40)
assert certs.check_self_signed("h", 2, der, None) == "first use"
assert certs.check_self_signed("H", 2, der, None) == "pinned"
with pytest.raises(certs.CertificateError):
certs.check_self_signed("h", 2, b"another", None)
@pytest.mark.skipif(subprocess.run(["which", "openssl"],
capture_output=True).returncode != 0,
reason="no openssl")
def test_identity_is_made_once(xdg):
cert, key = certs.ensure_identity()
assert cert.is_file() and key.stat().st_mode & 0o077 == 0
first = cert.read_bytes()
assert certs.ensure_identity() == (cert, key)
assert cert.read_bytes() == first
# ---- channel tree and following ----
def _state_with_rooms():
state = ServerState(session=10)
from lintunes.mumble.client import Channel, User
state.channels = {0: Channel(0, "Root", None),
1: Channel(1, "Work", 0, 1),
2: Channel(2, "Music", 0, 0),
3: Channel(3, "Quiet", 1)}
state.users = {10: User(10, "LinTunes", 0), 11: User(11, "Trav", 1)}
return state
def test_tree_and_paths():
state = _state_with_rooms()
assert state.tree() == [(0, 0, "Root"), (2, 1, "Music"), (1, 1, "Work"),
(3, 2, "Quiet")]
assert state.path_of(3) == ["Work", "Quiet"]
assert state.channel_by_path(["Work", "Quiet"]) == 3
assert state.channel_by_path(["Nope"]) is None
assert state.find_user("trav").session == 11
assert state.find_user("LinTunes", besides=10) is None
def _user_state(**fields):
numbers = {"session": 1, "name": 3, "channel_id": 5, "suppress": 8,
"self_mute": 9}
return proto.encode([(numbers[k], v) for k, v in fields.items()])
def test_follows_the_named_user_unless_pinned():
c = Connection()
c.state = _state_with_rooms()
sent = []
c.send = sent.append
c.follow_name = "trav"
c._handle(proto.USER_STATE, _user_state(session=11, channel_id=3))
assert sent == [proto.move_message(10, 3)]
sent.clear()
c.state.users[10].channel_id = 3
c.set_follow("trav", 2) # pinned to Music
assert sent == [proto.move_message(10, 2)]
sent.clear()
c._handle(proto.USER_STATE, _user_state(session=11, channel_id=1))
assert sent == []
c.set_follow("trav", None) # follow again: go to him now
assert sent == [proto.move_message(10, 1)]
def test_reports_its_own_moves_and_being_silenced():
events = []
c = Connection(on_event=lambda k, d: events.append((k, d)))
c.state = _state_with_rooms()
c._handle(proto.USER_STATE, _user_state(session=10, channel_id=2,
suppress=True))
assert ("moved", 2) in events and ("suppressed", True) in events
# ---- a whole handshake against a fake server ----
def _server_cert(tmp_path):
cert, key = tmp_path / "s.pem", tmp_path / "s.key"
subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048",
"-nodes", "-keyout", str(key), "-out", str(cert),
"-days", "2", "-subj", "/CN=fake"],
check=True, capture_output=True)
return cert, key
async def _fake_server(tmp_path, script):
"""A TLS server that answers the client's first bytes with `script`
(a list of frames) and records everything the client sends after."""
cert, key = _server_cert(tmp_path)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
received = []
async def handle(reader, writer):
frames = proto.FrameReader()
greeted = False
while True:
data = await reader.read(65536)
if not data:
break
for kind, payload in frames.feed(data):
received.append((kind, payload))
if kind == proto.AUTHENTICATE and not greeted:
greeted = True
for chunk in script:
writer.write(chunk)
await writer.drain()
server = await asyncio.start_server(handle, "127.0.0.1", 0, ssl=context)
return server, server.sockets[0].getsockname()[1], received
def _channel(cid, name, parent=None):
return proto.frame(proto.CHANNEL_STATE, proto.encode(
[(1, cid), (2, parent), (3, name)]))
def _user(session, name, channel):
return proto.frame(proto.USER_STATE, proto.encode(
[(1, session), (3, name), (5, channel)]))
needs_openssl = pytest.mark.skipif(
subprocess.run(["which", "openssl"], capture_output=True).returncode != 0,
reason="no openssl")
@needs_openssl
def test_handshake_joins_the_followed_users_room(xdg):
async def run():
script = [_channel(0, "Root"), _channel(1, "Work", 0),
_channel(2, "Music", 0), _user(5, "Trav", 2),
_user(9, "LinTunes", 0),
proto.frame(proto.SERVER_SYNC, proto.encode(
[(1, 9), (2, 72000)]))]
server, port, received = await _fake_server(xdg, script)
c = Connection()
c.follow_name = "trav"
await c.connect("127.0.0.1", port, "LinTunes", "")
await asyncio.sleep(0.2)
assert c.state.max_bandwidth == 72000 and c.trust == "first use"
kinds = [k for k, _ in received]
assert kinds[:2] == [proto.VERSION, proto.AUTHENTICATE]
auth = proto.decode(received[1][1])
assert proto.text(auth, 1) == "LinTunes"
assert proto.first(auth, 6) == proto.CLIENT_TYPE_BOT
moves = [proto.decode(p) for k, p in received
if k == proto.USER_STATE]
assert moves and proto.first(moves[-1], 5) == 2
await c.close()
server.close()
asyncio.run(run())
@needs_openssl
def test_reject_is_reported(xdg):
async def run():
script = [proto.frame(proto.REJECT, proto.encode([(1, 5)]))]
server, port, _ = await _fake_server(xdg, script)
with pytest.raises(MumbleError, match="already in use"):
await Connection().connect("127.0.0.1", port, "LinTunes", "")
server.close()
asyncio.run(run())
# ---- the sink ----
class _Loop:
def __init__(self):
self.submitted = []
def submit(self, coro):
self.submitted.append(coro)
coro.close()
def run(self, coro, timeout):
coro.close()
def _track(location="/music/a.mp3", kind="MPEG audio file"):
t = MagicMock()
t.location, t.kind, t.name, t.total_time = location, kind, "A", 60000
return t
def test_sink_generations_and_failure(qapp):
connection = MagicMock()
connection.state.max_bandwidth = 0
sink = MumbleSink(connection, _Loop(), "Work (Mumble)", {"kbps": 96})
ended, gone = [], []
sink.ended.connect(lambda: ended.append(1))
sink.unavailable.connect(gone.append)
sink.load(_track(), True, 5000)
assert sink.is_playing() and sink.position_ms() == 5000
stale = sink._generation
sink.seek(9000)
sink._on_stream_ended(stale, "finished", "") # the replaced stream
assert ended == [] and sink.is_playing()
sink._on_stream_ended(sink._generation, "finished", "")
assert ended == [1] and not sink.is_playing()
sink.load(_track(), True, 0)
sink.fail("gone")
assert gone == ["gone"] and not sink.is_playing()
assert not sink.can_play(_track("/x.m4p", "Protected AAC audio file"))
assert sink.bitrate() == 96000
def test_heard_position_trails_what_was_sent(qapp):
from lintunes.mumble.sink import Stream
sink = MumbleSink(MagicMock(), _Loop(), "x", {"latency_ms": 200})
stream = Stream("/a", 1000)
assert sink._heard(stream) == 1000
stream.frames_sent = 50
assert sink._heard(stream) == 1000 + 50 * FRAME_MS - 200
# ---- settings ----
def test_mumble_prefs_have_defaults(tmp_path):
from lintunes.preferences import Preferences
from lintunes.mumble.controller import bot_name, settings_from
prefs = Preferences(tmp_path)
assert bot_name(prefs) == "LinTunes"
assert settings_from(prefs)["kbps"] == 128
prefs.set("mumble_name", " ")
assert bot_name(prefs) == "LinTunes"
def test_dialog_takes_a_typed_address(qapp):
from lintunes.gui.mumble_dialog import MumbleServerDialog, parse_address
assert parse_address("example.org:1234").port == 1234
assert parse_address("") is None
dialog = MumbleServerDialog([servers.Server("saved.example")], "Bot")
dialog._address.setText("other.example")
dialog._accept()
assert dialog.selected_server.host == "other.example"
# ---- the window ----
@pytest.fixture
def window(qapp, tmp_path):
from lintunes.gui.main_window import MainWindow
from lintunes.library_manager import LibraryManager
from lintunes.models.library import Library
from lintunes.preferences import Preferences
win = MainWindow(LibraryManager(Library(), tmp_path), Preferences(tmp_path))
win.show()
qapp.processEvents()
yield win
win.close()
def test_menu_has_mumble_and_joins_the_current_server(window, monkeypatch):
assert window._mumble_action.text() == "Connect to Mumble…"
current = servers.parse_url("mumble://me@work.example/Room")
current.current = True
monkeypatch.setattr(window._mumble, "choices", lambda: [current])
monkeypatch.setattr(window._mumble, "is_available", lambda: (True, ""))
joined = []
monkeypatch.setattr(window._mumble, "connect_to", joined.append)
window._toggle_mumble()
assert joined == [current] # no dialog: Mumble said where