Coverage for slidge/util/test.py: 83%

237 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-12-01 19:36 +0000

1# type:ignore 

2import os 

3import sys 

4import tempfile 

5import types 

6import typing 

7from pathlib import Path 

8from types import ModuleType, NoneType 

9from typing import Any, ClassVar, ForwardRef, NotRequired, get_args, get_origin 

10 

11from slixmpp import JID, Iq, Message, Presence 

12from slixmpp.stanza.error import Error 

13from slixmpp.test import SlixTest, TestTransport 

14from sqlalchemy import create_engine, delete 

15 

16from slidge import ( 

17 BaseGateway, 

18 BaseSession, 

19 LegacyContact, 

20 LegacyParticipant, 

21 LegacyRoom, 

22) 

23from slidge.command.register import AltRegistrationFlow 

24from slidge.util.types import UserPreferences 

25 

26from ..command import FormField 

27from ..core import config 

28from ..core.session import _sessions 

29from ..db import SlidgeStore 

30from ..db.avatar import avatar_cache 

31from ..db.meta import Base 

32from ..db.models import Contact, GatewayUser 

33 

34 

35class SlixTestPlus(SlixTest): 

36 def setUp(self) -> None: 

37 super().setUp() 

38 Error.namespace = "jabber:component:accept" 

39 

40 def next_sent(self, timeout: float = 0.05) -> Message | Iq | Presence | None: 

41 self.wait_for_send_queue() 

42 sent = self.xmpp.socket.next_sent(timeout=timeout) 

43 if sent is None: 

44 return None 

45 xml = self.parse_xml(sent) 

46 self.fix_namespaces(xml, "jabber:component:accept") 

47 sent = self.xmpp._build_stanza(xml, "jabber:component:accept") 

48 return sent 

49 

50 

51class SlidgeTest(SlixTestPlus): 

52 plugin: types.ModuleType | dict 

53 

54 class Config: 

55 jid = "aim.shakespeare.lit" 

56 secret = "test" 

57 server = "shakespeare.lit" 

58 port = 5222 

59 upload_service = "upload.test" 

60 home_dir = Path(tempfile.mkdtemp()) 

61 user_jid_validator = ".*" 

62 admins: ClassVar[list[str]] = [] 

63 upload_requester = None 

64 ignore_delay_threshold = 300 

65 

66 gateway_cls: type[BaseGateway] 

67 

68 @classmethod 

69 def setUpClass(cls) -> None: 

70 for k, v in vars(cls.Config).items(): 

71 setattr(config, k.upper(), v) 

72 if not hasattr(cls, "plugin"): 

73 raise RuntimeError( 

74 f"{cls.__name__} must set the 'plugin' attribute to the" 

75 " module (or dict) containing the gateway class, e.g." 

76 " 'plugin = globals()' or 'plugin = my_legacy_module'." 

77 ) 

78 cls.gateway_cls = find_subclass(cls.plugin, BaseGateway) 

79 session_cls = cls.gateway_cls._session_cls 

80 wired = [ 

81 cls.gateway_cls, 

82 session_cls, 

83 session_cls._roster_cls, 

84 session_cls._roster_cls._contact_cls, 

85 session_cls._bookmarks_cls, 

86 session_cls._bookmarks_cls._muc_cls, 

87 session_cls._bookmarks_cls._muc_cls._participant_cls, 

88 session_cls._space_nodes_cls, 

89 session_cls._space_nodes_cls._space_cls, 

90 ] 

91 for wired_cls in wired: 

92 wired_cls.__abstractmethods__ = frozenset() 

93 

94 def setUp(self) -> None: 

95 # workaround for duplicate output of sql alchemy's log, cf 

96 # https://stackoverflow.com/a/76498428/5902284 

97 from sqlalchemy import log as sqlalchemy_log 

98 from sqlalchemy.pool import StaticPool 

99 

100 sqlalchemy_log._add_default_handler = lambda x: None 

101 db_url = os.getenv("SLIDGETEST_DB_URL", "sqlite+pysqlite:///:memory:") 

102 engine = self.db_engine = create_engine( 

103 db_url, poolclass=StaticPool if db_url.startswith("postgresql+") else None 

104 ) 

105 Base.metadata.create_all(engine) 

106 BaseGateway.store = SlidgeStore(engine) 

107 BaseGateway._test_mode = True 

108 

109 # Clean up commands potentially left behind by a previous test. 

110 LegacyContact._commands.clear() 

111 LegacyContact._commands_chat.clear() 

112 LegacyRoom._commands.clear() 

113 LegacyRoom._commands_chat.clear() 

114 

115 self.xmpp = self.gateway_cls() 

116 

117 avatar_cache.store = self.xmpp.store.avatars 

118 avatar_cache.set_dir(Path(tempfile.mkdtemp())) 

119 self.xmpp._always_send_everything = True 

120 engine.echo = True 

121 

122 self.xmpp.connection_made(TestTransport(self.xmpp)) 

123 self.xmpp.session_bind_event.set() 

124 # Remove unique ID prefix to make it easier to test 

125 self.xmpp._id_prefix = "" 

126 self.xmpp.default_lang = None 

127 self.xmpp.peer_default_lang = None 

128 

129 def new_id() -> str: 

130 self.xmpp._id += 1 

131 return str(self.xmpp._id) 

132 

133 self.xmpp._id = 0 

134 self.xmpp.new_id = new_id 

135 

136 # Must have the stream header ready for xmpp.process() to work. 

137 header = self.xmpp.stream_header 

138 

139 self.xmpp.data_received(header) 

140 self.wait_for_send_queue() 

141 

142 self.xmpp.socket.next_sent() 

143 self.xmpp.socket.next_sent() 

144 

145 # Some plugins require messages to have ID values. Set 

146 # this to True in tests related to those plugins. 

147 self.xmpp.use_message_ids = False 

148 self.xmpp.use_presence_ids = False 

149 Error.namespace = "jabber:component:accept" 

150 

151 def _add_slidge_user( 

152 self, 

153 jid: str | JID = "romeo@shakespeare.lit", 

154 legacy_module_data: dict | None = None, 

155 preferences: dict | None = None, 

156 ) -> None: 

157 with self.xmpp.store.session() as orm: 

158 user = GatewayUser( 

159 jid=JID(jid), 

160 legacy_module_data=legacy_module_data or {}, 

161 preferences=preferences 

162 or {"sync_avatar": False, "sync_presence": False}, 

163 ) 

164 orm.add(user) 

165 orm.commit() 

166 self.run_coro( 

167 self.xmpp._BaseGateway__dispatcher._on_user_register(Iq(sfrom=JID(jid))) 

168 ) 

169 welcome = self.next_sent() 

170 assert welcome["body"] 

171 stanza = self.next_sent() 

172 assert "logging in" in stanza["status"].lower(), stanza 

173 stanza = self.next_sent() 

174 assert "syncing contacts" in stanza["status"].lower(), stanza 

175 if self.xmpp.ROOMS: 

176 stanza = self.next_sent() 

177 assert "syncing rooms" in stanza["status"].lower(), stanza 

178 probe = self.next_sent() 

179 assert probe.get_type() == "probe" 

180 stanza = self.next_sent() 

181 assert stanza["status"].lower() 

182 

183 def user_session(self, jid: str | JID = "romeo@shakespeare.lit") -> BaseSession: 

184 return self.xmpp._session_cls.from_jid(JID(jid)) 

185 

186 def get_joined_muc( 

187 self, 

188 legacy_id: str | int, 

189 user_jid: str | JID = "romeo@shakespeare.lit", 

190 resource: str = "gajim", 

191 ) -> LegacyRoom: 

192 muc: LegacyRoom = self.run_coro( 

193 self.user_session(user_jid).rooms.get_or_create(legacy_id) 

194 ) 

195 muc.add_user_resource(resource) 

196 muc._update_stored_attribute(participants_filled=True) 

197 return muc 

198 

199 def tearDown(self) -> None: 

200 self.db_engine.echo = False 

201 self.xmpp.plugin["xep_0356"].granted_privileges.clear() 

202 self.xmpp.plugin["xep_0356"].granted_privileges.default_factory.iq.clear() 

203 super().tearDown() 

204 Base.metadata.drop_all(self.xmpp.store._engine) 

205 self.db_engine.dispose() 

206 _sessions.clear() 

207 

208 def setup_logged_session(self, n_contacts: int = 0) -> None: 

209 with self.xmpp.store.session() as orm: 

210 user = GatewayUser( 

211 jid=JID("romeo@montague.lit/gajim").bare, 

212 legacy_module_data={"username": "romeo", "city": ""}, 

213 preferences={"sync_avatar": True, "sync_presence": True}, 

214 ) 

215 orm.add(user) 

216 orm.commit() 

217 

218 with self.xmpp.store.session() as session: 

219 session.execute(delete(Contact)) 

220 session.commit() 

221 

222 self.run_coro( 

223 self.xmpp._BaseGateway__dispatcher._on_user_register( 

224 Iq(sfrom="romeo@montague.lit/gajim") 

225 ) 

226 ) 

227 welcome = self.next_sent() 

228 assert welcome["body"], welcome 

229 stanza = self.next_sent() 

230 assert "logging in" in stanza["status"].lower(), stanza 

231 stanza = self.next_sent() 

232 assert "syncing contacts" in stanza["status"].lower(), stanza 

233 if self.xmpp.ROOMS: 

234 stanza = self.next_sent() 

235 assert "syncing rooms" in stanza["status"].lower(), stanza 

236 probe = self.next_sent() 

237 assert probe.get_type() == "probe" 

238 stanza = self.next_sent() 

239 assert "yup" in stanza["status"].lower(), stanza 

240 self.romeo: BaseSession = self.xmpp._session_cls.from_jid( 

241 JID("romeo@montague.lit") 

242 ) 

243 

244 self.juliet: LegacyContact = self.run_coro( 

245 self.romeo.contacts.get_or_create("juliet") 

246 ) 

247 self.room: LegacyRoom = self.run_coro(self.romeo.rooms.get_or_create("room")) 

248 self.first_witch: LegacyParticipant = self.room.participants.get_or_create( 

249 nick="firstwitch" 

250 ) 

251 

252 self.send( # language=XML 

253 """ 

254 <iq type="get" 

255 to="romeo@montague.lit" 

256 id="1" 

257 from="aim.shakespeare.lit"> 

258 <pubsub xmlns="http://jabber.org/protocol/pubsub"> 

259 <items node="urn:xmpp:avatar:metadata" /> 

260 </pubsub> 

261 </iq> 

262 """ 

263 ) 

264 

265 

266def find_subclass(o, parent, base_ok: bool = False): # noqa 

267 try: 

268 vals = vars(o).values() 

269 except TypeError: 

270 vals = o.values() 

271 for x in vals: 

272 try: 

273 if issubclass(x, parent) and x is not parent: 

274 return x 

275 except TypeError: 

276 pass 

277 if base_ok: 

278 return parent 

279 else: 

280 raise RuntimeError(f"Could not find a subclass of {parent} in {o}") 

281 

282 

283def typed_dict_consistency_tester(module: ModuleType) -> None: 

284 """ 

285 Ensure consistency between the Preferences TypedDict and the fields defined 

286 in Gateway.PREFERENCES. 

287 """ 

288 session_cls = _get_type_arg(module.Gateway, "SessionT") 

289 prefs = _get_type_arg(session_cls, "PrefsT") 

290 if prefs is Any: 

291 prefs = UserPreferences 

292 _test_typed_dict_consistency(prefs, module.Gateway.PREFERENCES) 

293 registration_dict = _get_type_arg(module.Gateway, "RegistrationFormT") 

294 _test_typed_dict_consistency(registration_dict, module.Gateway.REGISTRATION_FIELDS) 

295 for flow in module.Gateway.ALTERNATIVE_REGISTRATION_FLOWS: 

296 assert isinstance(flow, AltRegistrationFlow) 

297 _test_typed_dict_consistency(flow.__orig_class__.__args__[0], flow.fields) 

298 

299 

300def _test_typed_dict_consistency(obj: object, form_fields: list[FormField]) -> None: 

301 annotations = obj.__annotations__ 

302 total = getattr(obj, "__total__", True) 

303 fields_dict = {} 

304 for field in form_fields: 

305 if field.type == "fixed": 

306 continue 

307 assert field.var in annotations, ( 

308 f"{field} is missing in the TypedDict: {annotations}" 

309 ) 

310 fields_dict[field.var] = field 

311 name = f"{obj.__name__}.{field.var}" 

312 if isinstance(annotations[field.var], ForwardRef): 

313 type_ = _evaluate_forward_ref(annotations[field.var]) 

314 else: 

315 type_ = annotations[field.var] 

316 if not field.required and total: 

317 assert get_origin(type_) is NotRequired, ( 

318 f"{name} is not 'required', its type should be `NotRequired`, or the typed dict should not be `total`." 

319 ) 

320 types = set(get_args(type_)) 

321 types.discard(NoneType) 

322 type_ = types.pop() 

323 assert not types 

324 

325 match field.type: 

326 case "boolean": 

327 assert type_ is bool, ( 

328 f"{name} is 'boolean', it should be 'bool', instead it is {type_}" 

329 ) 

330 case "fixed": 

331 assert type_ is str, ( 

332 f"{name} is 'fixed', it should be 'str', instead it is {type_}" 

333 ) 

334 case "text-single": 

335 assert type_ is str, ( 

336 f"{name} is 'text-single', it should be 'str', instead it is {type_}" 

337 ) 

338 case "text-multi": 

339 assert type_ is str, ( 

340 f"{name} is 'text-multi', it should be 'str', instead it is {type_}" 

341 ) 

342 case "jid-single": 

343 assert type_ is JID, ( 

344 f"{name} is 'jid-single', it should be 'JID', instead it is {type_}" 

345 ) 

346 case "jid-multi": 

347 assert type_ is list[JID], ( 

348 f"{name} is 'jid-multi', it should be 'list', instead it is {type_}" 

349 ) 

350 case "list-single": 

351 assert type_ is str, ( 

352 f"{name} is 'list-single', it should be 'str', instead it is {type_}" 

353 ) 

354 case "list-multi": 

355 assert type_ is list[str], ( 

356 f"{name} is 'list-multi', it should be 'list', instead it is {type_}" 

357 ) 

358 case "text-private": 

359 assert type_ is str, ( 

360 f"{name} is 'text-private', it should be 'str', instead it is {type_}" 

361 ) 

362 

363 for attr, typ_ in annotations.items(): 

364 if get_origin(typ_) is NotRequired: 

365 continue 

366 assert attr in fields_dict, f"{attr!r} is missing in {fields_dict} {typ_}" 

367 

368 

369def _evaluate_forward_ref(ref: ForwardRef) -> object: 

370 if sys.version_info < (3, 14): 

371 return ref._evaluate( 

372 globals(), locals(), recursive_guard=frozenset(), type_params=None 

373 ) 

374 else: 

375 return typing.evaluate_forward_ref(ref) 

376 

377 

378def _get_type_arg(cls: type, name: str) -> object: 

379 for base in getattr(cls, "__orig_bases__", ()): 

380 origin = get_origin(base) 

381 if origin is None: 

382 continue 

383 

384 params = getattr(origin, "__type_params__", ()) 

385 args = get_args(base) 

386 

387 for param, arg in zip(params, args): 

388 if param.__name__ == name: 

389 return arg 

390 

391 raise KeyError(f"No type argument named {name!r} on {cls.__name__}")