| 1 |
import asyncio |
| 2 |
import json |
| 3 |
from typing import Any, Dict, Iterable, Optional, Tuple |
| 4 |
|
| 5 |
from cockpit.jsonutil import JsonObject, JsonValue |
| 6 |
from cockpit.router import Router |
| 7 |
|
| 8 |
MOCK_HOSTNAME = 'mockbox' |
| 9 |
|
| 10 |
|
| 11 |
class MockTransport(asyncio.Transport): |
| 12 |
queue: 'asyncio.Queue[Tuple[str, bytes]]' |
| 13 |
next_id: int = 0 |
| 14 |
close_future: Optional[asyncio.Future] = None |
| 15 |
|
| 16 |
async def assert_empty(self): |
| 17 |
await asyncio.sleep(0.1) |
| 18 |
assert self.queue.qsize() == 0 |
| 19 |
|
| 20 |
def send_json(self, channel_: str, **kwargs: JsonValue) -> None: |
| 21 |
# max_read_size is one of our special keys which uses underscores |
| 22 |
msg = {k.replace('_', '-') if k != "max_read_size" else k: v for k, v in kwargs.items()} |
| 23 |
self.send_data(channel_, json.dumps(msg).encode('ascii')) |
| 24 |
|
| 25 |
def send_data(self, channel: str, data: bytes) -> None: |
| 26 |
msg = channel.encode('ascii') + b'\n' + data |
| 27 |
msg = str(len(msg)).encode('ascii') + b'\n' + msg |
| 28 |
self.protocol.data_received(msg) |
| 29 |
|
| 30 |
def send_init(self, version: int = 1, host: str = MOCK_HOSTNAME, **kwargs: JsonValue) -> None: |
| 31 |
self.send_json('', command='init', version=version, host=host, **kwargs) |
| 32 |
|
| 33 |
def init(self, **kwargs: Any) -> Dict[str, object]: |
| 34 |
channel, data = self.queue.get_nowait() |
| 35 |
assert channel == '' |
| 36 |
msg = json.loads(data) |
| 37 |
assert msg['command'] == 'init' |
| 38 |
self.send_init(**kwargs) |
| 39 |
return msg |
| 40 |
|
| 41 |
def get_id(self, prefix: str) -> str: |
| 42 |
self.next_id += 1 |
| 43 |
return f'{prefix}.{self.next_id}' |
| 44 |
|
| 45 |
def send_open(self, payload: str, channel: 'str | None' = None, **kwargs: JsonValue) -> str: |
| 46 |
if channel is None: |
| 47 |
channel = self.get_id('channel') |
| 48 |
self.send_json('', command='open', channel=channel, payload=payload, **kwargs) |
| 49 |
return channel |
| 50 |
|
| 51 |
async def check_open( |
| 52 |
self, |
| 53 |
payload: str, |
| 54 |
channel: 'str | None' = None, |
| 55 |
problem: 'str | None' = None, |
| 56 |
reply_keys: Optional[JsonObject] = None, |
| 57 |
absent_keys: 'Iterable[str]' = (), |
| 58 |
**kwargs: JsonValue, |
| 59 |
) -> str: |
| 60 |
assert isinstance(self.protocol, Router) |
| 61 |
ch = self.send_open(payload, channel, **kwargs) |
| 62 |
if problem is None: |
| 63 |
await self.assert_msg('', command='ready', channel=ch, absent_keys=absent_keys, **(reply_keys or {})) |
| 64 |
# it's possible that the channel already closed |
| 65 |
else: |
| 66 |
await self.assert_msg('', command='close', channel=ch, problem=problem, absent_keys=absent_keys, |
| 67 |
**(reply_keys or {})) |
| 68 |
assert ch not in self.protocol.open_channels |
| 69 |
return ch |
| 70 |
|
| 71 |
def send_done(self, channel: str, **kwargs: JsonValue) -> None: |
| 72 |
self.send_json('', command='done', channel=channel, **kwargs) |
| 73 |
|
| 74 |
def send_close(self, channel: str, **kwargs: JsonValue): |
| 75 |
self.send_json('', command='close', channel=channel, **kwargs) |
| 76 |
|
| 77 |
async def check_close(self, channel: str, **kwargs: JsonValue): |
| 78 |
self.send_close(channel, **kwargs) |
| 79 |
await self.assert_msg('', command='close', channel=channel) |
| 80 |
|
| 81 |
def send_ping(self, **kwargs: JsonValue): |
| 82 |
self.send_json('', command='ping', **kwargs) |
| 83 |
|
| 84 |
def __init__(self, protocol: asyncio.Protocol): |
| 85 |
self.queue = asyncio.Queue() |
| 86 |
self.protocol = protocol |
| 87 |
protocol.connection_made(self) |
| 88 |
|
| 89 |
def write(self, data: bytes) -> None: |
| 90 |
# We know that the bridge only ever writes full frames at once, so we |
| 91 |
# can disassemble them immediately. |
| 92 |
_, channel, data = data.split(b'\n', 2) |
| 93 |
self.queue.put_nowait((channel.decode('ascii'), data)) |
| 94 |
|
| 95 |
async def stop(self) -> None: |
| 96 |
keep_open = self.protocol.eof_received() |
| 97 |
if keep_open: |
| 98 |
self.close_future = asyncio.get_running_loop().create_future() |
| 99 |
try: |
| 100 |
await self.close_future |
| 101 |
finally: |
| 102 |
self.close_future = None |
| 103 |
|
| 104 |
def close(self) -> None: |
| 105 |
if self.close_future is not None: |
| 106 |
self.close_future.set_result(None) |
| 107 |
|
| 108 |
if self.protocol is not None: |
| 109 |
self.protocol.connection_lost(None) |
| 110 |
|
| 111 |
async def next_frame(self) -> Tuple[str, bytes]: |
| 112 |
return await self.queue.get() |
| 113 |
|
| 114 |
async def next_msg(self, expected_channel) -> Dict[str, Any]: |
| 115 |
channel, data = await self.next_frame() |
| 116 |
assert channel == expected_channel, data |
| 117 |
return json.loads(data) |
| 118 |
|
| 119 |
async def assert_data(self, expected_channel: str, expected_data: bytes) -> None: |
| 120 |
channel, data = await self.next_frame() |
| 121 |
assert channel == expected_channel |
| 122 |
assert data == expected_data |
| 123 |
|
| 124 |
async def assert_msg(self, expected_channel: str, absent_keys: 'Iterable[str]' = (), |
| 125 |
**kwargs: JsonValue) -> JsonObject: |
| 126 |
msg = await self.next_msg(expected_channel) |
| 127 |
assert msg == dict(msg, **{k.replace('_', '-'): v for k, v in kwargs.items()}), msg |
| 128 |
for absent_key in absent_keys: |
| 129 |
assert absent_key not in msg |
| 130 |
return msg |
| 131 |
|
| 132 |
# D-Bus helpers |
| 133 |
internal_bus: str = '' |
| 134 |
|
| 135 |
async def ensure_internal_bus(self): |
| 136 |
if not self.internal_bus: |
| 137 |
self.internal_bus = await self.check_open('dbus-json3', bus='internal') |
| 138 |
assert self.protocol.open_channels[self.internal_bus].bus == self.protocol.internal_bus.client |
| 139 |
return self.internal_bus |
| 140 |
|
| 141 |
def send_bus_call(self, bus: str, path: str, iface: str, name: str, args: list) -> str: |
| 142 |
tag = self.get_id('call') |
| 143 |
self.send_json(bus, call=[path, iface, name, args], id=tag) |
| 144 |
return tag |
| 145 |
|
| 146 |
async def assert_bus_reply( |
| 147 |
self, |
| 148 |
tag: str, |
| 149 |
expected_reply: Optional[list] = None, |
| 150 |
bus: Optional[str] = None, |
| 151 |
) -> list: |
| 152 |
if bus is None: |
| 153 |
bus = await self.ensure_internal_bus() |
| 154 |
reply = await self.next_msg(bus) |
| 155 |
assert 'id' in reply, reply |
| 156 |
assert reply['id'] == tag, reply |
| 157 |
assert 'reply' in reply, reply |
| 158 |
if expected_reply is not None: |
| 159 |
assert reply['reply'] == [expected_reply] |
| 160 |
return reply['reply'][0] |
| 161 |
|
| 162 |
async def assert_bus_error(self, tag: str, code: str, message: str, bus: Optional[str] = None) -> None: |
| 163 |
if bus is None: |
| 164 |
bus = await self.ensure_internal_bus() |
| 165 |
reply = await self.next_msg(bus) |
| 166 |
assert 'id' in reply, reply |
| 167 |
assert reply['id'] == tag, reply |
| 168 |
assert 'error' in reply, reply |
| 169 |
assert reply['error'] == [code, [message]], reply['error'] |
| 170 |
|
| 171 |
async def check_bus_call( |
| 172 |
self, |
| 173 |
path: str, |
| 174 |
iface: str, |
| 175 |
name: str, |
| 176 |
args: list, |
| 177 |
expected_reply: Optional[list] = None, |
| 178 |
bus: Optional[str] = None, |
| 179 |
) -> list: |
| 180 |
if bus is None: |
| 181 |
bus = await self.ensure_internal_bus() |
| 182 |
tag = self.send_bus_call(bus, path, iface, name, args) |
| 183 |
return await self.assert_bus_reply(tag, expected_reply, bus=bus) |
| 184 |
|
| 185 |
async def assert_bus_props( |
| 186 |
self, path: str, iface: str, expected_values: JsonObject, bus: Optional[str] = None |
| 187 |
) -> None: |
| 188 |
(values,) = await self.check_bus_call(path, 'org.freedesktop.DBus.Properties', 'GetAll', [iface], bus=bus) |
| 189 |
for key, value in expected_values.items(): |
| 190 |
assert values[key]['v'] == value |
| 191 |
|
| 192 |
async def assert_bus_meta( |
| 193 |
self, |
| 194 |
path: str, |
| 195 |
iface: str, |
| 196 |
expected: Iterable[str], |
| 197 |
bus: Optional[str] = None, |
| 198 |
) -> None: |
| 199 |
if bus is None: |
| 200 |
bus = await self.ensure_internal_bus() |
| 201 |
meta = await self.next_msg(bus) |
| 202 |
assert 'meta' in meta, meta |
| 203 |
assert set(meta['meta'][iface]['properties']) == set(expected) |
| 204 |
|
| 205 |
async def assert_bus_notify( |
| 206 |
self, |
| 207 |
path: str, |
| 208 |
iface: str, |
| 209 |
expected: JsonObject, |
| 210 |
bus: Optional[str] = None, |
| 211 |
) -> None: |
| 212 |
if bus is None: |
| 213 |
bus = await self.ensure_internal_bus() |
| 214 |
notify = await self.next_msg(bus) |
| 215 |
assert 'notify' in notify |
| 216 |
assert notify['notify'][path][iface] == expected |
| 217 |
|
| 218 |
async def watch_bus(self, path: str, iface: str, expected: JsonObject, bus: Optional[str] = None) -> None: |
| 219 |
if bus is None: |
| 220 |
bus = await self.ensure_internal_bus() |
| 221 |
tag = self.get_id('watch') |
| 222 |
self.send_json(bus, watch={'path': path, 'interface': iface}, id=tag) |
| 223 |
await self.assert_bus_meta(path, iface, expected, bus) |
| 224 |
await self.assert_bus_notify(path, iface, expected, bus) |
| 225 |
await self.assert_msg(bus, id=tag, reply=[]) |
| 226 |
|
| 227 |
async def assert_bus_signal( |
| 228 |
self, |
| 229 |
path: str, |
| 230 |
iface: str, |
| 231 |
name: str, |
| 232 |
args: list, |
| 233 |
bus: Optional[str] = None, |
| 234 |
) -> None: |
| 235 |
if bus is None: |
| 236 |
bus = await self.ensure_internal_bus() |
| 237 |
signal = await self.next_msg(bus) |
| 238 |
assert 'signal' in signal, signal |
| 239 |
assert signal['signal'] == [path, iface, name, args] |
| 240 |
|
| 241 |
async def add_bus_match(self, path: str, iface: str, bus: Optional[str] = None) -> None: |
| 242 |
if bus is None: |
| 243 |
bus = await self.ensure_internal_bus() |
| 244 |
self.send_json(bus, add_match={'path': path, 'interface': iface}) |