Files
mi8-platina-linux/tests/test_cellular_rpmsg.py
T
2026-11-12 17:44:36 +09:00

253 lines
11 KiB
Python

"""Exercise AT framing, endpoint cleanup, and the experimental PPP boundary."""
import importlib.util
import os
from pathlib import Path
import select
import socket
import subprocess
import tempfile
import threading
import unittest
from unittest.mock import MagicMock, patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('cellular_rpmsg', ROOT / 'scripts/phone-cellular-rpmsg.py')
rpmsg = importlib.util.module_from_spec(spec)
spec.loader.exec_module(rpmsg)
class ATTests(unittest.TestCase):
def exchange(self, chunks, command='AT', timeout=1):
host, modem = socket.socketpair(type=socket.SOCK_DGRAM)
self.addCleanup(host.close)
self.addCleanup(modem.close)
observed = []
def respond():
observed.append(modem.recv(65536))
for data in chunks:
modem.send(data)
thread = threading.Thread(target=respond, daemon=True)
thread.start()
result = rpmsg.at_command(host.fileno(), command, timeout)
thread.join(timeout=1)
self.assertFalse(thread.is_alive())
self.assertEqual(observed, [command.encode() + b'\r'])
return result
def test_split_response(self):
result = self.exchange([b'AT\r\r\nO', b'K\r\n'])
self.assertEqual(result['result'], 'OK')
def test_connect_preserves_binary_ppp_bytes_in_same_message(self):
payload = b'\x7e\xff\x03\xc0\x21\x00\xff\x7d\x5e\x7e'
result = self.exchange([b'\r\nCONNECT\r\n' + payload], 'ATD*99#')
self.assertEqual(result['result'], 'CONNECT')
self.assertEqual(result['trailing'], b'\n' + payload)
def test_extended_error_is_not_success(self):
result = self.exchange([b'\r\n+CME ERROR: operation not supported\r\n'])
self.assertEqual(result['result'], '+CME ERROR: operation not supported')
def test_no_carrier(self):
result = self.exchange([b'\r\nNO CARRIER\r\n'])
self.assertEqual(result['result'], 'NO CARRIER')
def test_ok_inside_information_line_does_not_end_response(self):
result = self.exchange([b'\r\n+INFO: OK\r\n', b'\r\nERROR\r\n'])
self.assertEqual(result['result'], 'ERROR')
def test_timeout_is_not_success(self):
result = self.exchange([b'\r\n+CEREG: 0,2\r\n'], timeout=0.02)
self.assertEqual(result['result'], 'TIMEOUT')
def test_reject_command_injection(self):
with self.assertRaises(ValueError):
rpmsg.at_command(-1, 'AT\rATD*99#')
class EndpointTests(unittest.TestCase):
def test_exclusive_session_rejects_a_second_owner(self):
with tempfile.TemporaryDirectory() as tmp:
lock = str(Path(tmp) / 'session.lock')
with rpmsg.exclusive_session(lock):
with self.assertRaisesRegex(RuntimeError, 'Another'):
with rpmsg.exclusive_session(lock):
self.fail('must not acquire an owned lock')
with rpmsg.exclusive_session(lock):
pass
def test_existing_binding_is_preserved(self):
with tempfile.TemporaryDirectory() as tmp:
device = Path(tmp) / 'bus/rpmsg/devices/4080000.remoteproc:glink-edge.DS.-1.-1'
(device / 'driver').mkdir(parents=True)
(device / 'driver_override').write_text('existing\n')
with self.assertRaisesRegex(RuntimeError, 'already bound'):
with rpmsg.open_channel(sys_path=tmp):
self.fail('must not yield a busy endpoint')
self.assertEqual((device / 'driver_override').read_text(), 'existing\n')
def test_endpoint_timeout_restores_override(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
device = root / 'bus/rpmsg/devices/4080000.remoteproc:glink-edge.DS.-1.-1'
driver = root / 'bus/rpmsg/drivers/rpmsg_chrdev'
device.mkdir(parents=True)
driver.mkdir(parents=True)
(device / 'driver_override').write_text('(null)\n')
with self.assertRaises(TimeoutError):
with rpmsg.open_channel(sys_path=tmp, timeout=0):
self.fail('must not yield a missing endpoint')
self.assertEqual((device / 'driver_override').read_text(), '\n')
def test_does_not_take_over_control_channel(self):
with self.assertRaises(ValueError):
with rpmsg.open_channel('IPCRTR'):
self.fail('must not open a control channel')
class PPPTests(unittest.TestCase):
def test_manager_is_restored_when_modem_preparation_fails(self):
calls = []
def run(command, **kwargs):
calls.append(command)
if command[0] == 'qmicli':
raise subprocess.CalledProcessError(1, command)
return subprocess.CompletedProcess(command, 0)
with patch.object(rpmsg.subprocess, 'run', side_effect=run):
with self.assertRaises(subprocess.CalledProcessError):
with rpmsg.data_session():
self.fail('must not enter a failed data session')
self.assertIn(['rc-service', 'modemmanager', 'stop'], calls)
self.assertEqual(calls[-1], ['rc-service', 'modemmanager', 'start'])
def test_initially_stopped_manager_stays_stopped(self):
calls = []
def run(command, **kwargs):
calls.append(command)
status = 3 if command == ['rc-service', 'modemmanager', 'status'] else 0
return subprocess.CompletedProcess(command, status)
with patch.object(rpmsg.subprocess, 'run', side_effect=run):
with rpmsg.data_session():
pass
self.assertNotIn(['rc-service', 'modemmanager', 'stop'], calls)
self.assertNotIn(['rc-service', 'modemmanager', 'start'], calls)
def test_dns_requires_a_matching_reply_and_binds_the_interface(self):
fake = MagicMock()
fake.__enter__.return_value = fake
fake.recv.side_effect = [b'bad', b'\x12\x34\x81\x80\x00\x01\x00\x01' + b'\x00' * 4]
with patch.object(rpmsg.socket, 'SO_BINDTODEVICE', 25, create=True), \
patch.object(rpmsg.socket, 'socket', return_value=fake), \
patch.object(rpmsg.os, 'urandom', return_value=b'\x12\x34'):
result = rpmsg.probe_dns('ppp0', '223.5.5.5')
fake.setsockopt.assert_called_once_with(socket.SOL_SOCKET, 25, b'ppp0\0')
fake.connect.assert_called_once_with(('223.5.5.5', 53))
self.assertEqual(result['exit_code'], 0)
self.assertEqual(result['answers'], 1)
def test_dns_timeouts_do_not_report_connectivity(self):
fake = MagicMock()
fake.__enter__.return_value = fake
fake.recv.side_effect = TimeoutError('timed out')
with patch.object(rpmsg.socket, 'SO_BINDTODEVICE', 25, create=True), \
patch.object(rpmsg.socket, 'socket', return_value=fake):
result = rpmsg.probe_dns('ppp0', '223.5.5.5')
self.assertEqual(result['exit_code'], 1)
self.assertEqual(len(result['errors']), 3)
def test_bridge_preserves_binary_data_in_both_directions(self):
host, modem = socket.socketpair(type=socket.SOCK_DGRAM)
self.addCleanup(host.close)
self.addCleanup(modem.close)
outgoing = b'\x7e\x00\xff\x7d\x5e\x01\x7e'
incoming = b'\x7e\x03\x00\xff\x7d\x5d\x7e'
received = []
observed = []
def modem_peer():
observed.append(modem.recv(65536))
modem.send(incoming)
class PPPPeer:
def __init__(self, command):
self.returncode = None
self.fd = os.open(command[1], os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY)
self.thread = threading.Thread(target=self.run, daemon=True)
self.thread.start()
def run(self):
try:
os.write(self.fd, outgoing)
while self.returncode is None:
if select.select([self.fd], [], [], 0.1)[0]:
received.append(os.read(self.fd, 65536))
if b''.join(received) == incoming:
self.returncode = 0
finally:
os.close(self.fd)
def poll(self):
return self.returncode
def terminate(self):
self.returncode = -15
def wait(self, timeout=None):
self.thread.join(timeout)
thread = threading.Thread(target=modem_peer, daemon=True)
thread.start()
replies = [{'result': 'OK', 'response': 'OK', 'trailing': b''} for _ in range(4)]
replies.append({'result': 'CONNECT', 'response': 'CONNECT', 'trailing': b''})
with patch.object(rpmsg, 'at_command', side_effect=replies), \
patch.object(rpmsg, 'wait_registration'), \
patch.object(rpmsg.shutil, 'which', return_value='/usr/sbin/pppd'), \
patch.object(rpmsg.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)), \
patch.object(rpmsg.subprocess, 'Popen', side_effect=PPPPeer), \
patch.object(rpmsg, 'interface_ipv4', return_value='10.0.0.2'), \
patch('builtins.print'):
result = rpmsg.connect(host.fileno(), '3gnet', duration=2)
thread.join(timeout=1)
self.assertFalse(thread.is_alive())
self.assertEqual(observed, [outgoing])
self.assertEqual(b''.join(received), incoming)
self.assertEqual(result['bridge_tx_bytes'], len(outgoing))
self.assertEqual(result['bridge_rx_bytes'], len(incoming))
self.assertFalse(result['ip_connectivity'])
def test_registration_waits_for_home_or_roaming(self):
results = [{'result': 'OK', 'response': '+CEREG: 0,2\r\n', 'trailing': b''},
{'result': 'OK', 'response': '+CEREG: 0,5\r\n', 'trailing': b''}]
with patch.object(rpmsg, 'at_command', side_effect=results), \
patch.object(rpmsg.time, 'sleep'), patch('builtins.print'):
rpmsg.wait_registration(-1, 1)
def test_command_does_not_install_default_route_or_dns(self):
command = rpmsg.ppp_command('/dev/pts/5')
self.assertIn('nodefaultroute', command)
self.assertNotIn('usepeerdns', command)
self.assertNotIn('persist', command)
self.assertIn('noauth', command)
def test_invalid_interface_rejected(self):
with self.assertRaises(ValueError):
rpmsg.ppp_command('/dev/pts/5', 'wlan0')
def test_invalid_apn_rejected_before_any_call(self):
with self.assertRaises(ValueError):
rpmsg.connect(-1, '3gnet"\rAT+CFUN=0')
def test_local_verification_target_is_not_an_internet_test(self):
with self.assertRaisesRegex(ValueError, 'public IPv4'):
rpmsg.connect(-1, '3gnet', verify_target='172.16.42.1')
if __name__ == '__main__':
unittest.main()