Debian Codegraph @

debian/patches/dgit-changes

raw
1 From:
2 Subject: Debian changes
3
4 The Debian packaging of amqtt is maintained in git, using a workflow
5 similar to the one described in dgit-maint-merge(7).
6 The Debian delta is represented by this one combined patch; there isn't a
7 patch queue that can be represented as a quilt series.
8
9 A detailed breakdown of the changes is available from their canonical
10 representation -- git commits in the packaging repository.
11 For example, to see the changes made by the Debian maintainer in the first
12 upload of upstream version 1.2.3, you could use:
13
14 % git clone https://git.dgit.debian.org/amqtt
15 % cd amqtt
16 % git log --oneline 1.2.3..debian/1.2.3-1 -- . ':!debian'
17
18 (If you have dgit, use `dgit clone amqtt`, rather than plain `git clone`.)
19
20 We don't use debian/source/options single-debian-patch because it has bugs.
21 Therefore, NMUs etc. may nevertheless have made additional patches.
22
23 ---
24
25 diff --git a/amqtt/client.py b/amqtt/client.py
26 index 6a7ff99..05203b1 100644
27 --- a/amqtt/client.py
28 +++ b/amqtt/client.py
29 @@ -497,6 +497,7 @@ class MQTTClient:
30 self.session.broker_uri,
31 subprotocols=[websockets.Subprotocol("mqtt")],
32 additional_headers=self.additional_headers,
33 + proxy=None,
34 **kwargs,
35 ), timeout=connection_timeout)
36
37 diff --git a/amqtt/contrib/auth_db/topic_mgr_cli.py b/amqtt/contrib/auth_db/topic_mgr_cli.py
38 index deaf719..7199fc8 100644
39 --- a/amqtt/contrib/auth_db/topic_mgr_cli.py
40 +++ b/amqtt/contrib/auth_db/topic_mgr_cli.py
41 @@ -13,13 +13,13 @@ from amqtt.errors import MQTTError
42
43 logging.basicConfig(level=logging.INFO, format="%(message)s")
44 logger = logging.getLogger(__name__)
45 -topic_app = typer.Typer(no_args_is_help=True)
46 +topic_app = typer.Typer(invoke_without_command=True)
47
48
49 @topic_app.callback()
50 def main(
51 ctx: typer.Context,
52 - db_type: Annotated[DBType, typer.Option("--db", "-d", help="db type", count=False)],
53 + db_type: Annotated[DBType | None, typer.Option("--db", "-d", help="db type", count=False)] = None,
54 db_username: Annotated[str, typer.Option("--username", "-u", help="db username", show_default=False)] = "",
55 db_port: Annotated[int, typer.Option("--port", "-p", help="database port (defaults to db type)", show_default=False)] = 0,
56 db_host: Annotated[str, typer.Option("--host", "-h", help="database host")] = "localhost",
57 @@ -33,6 +33,12 @@ def main(
58 If you need to create users programmatically, see `amqtt.contrib.auth_db.managers.TopicManager` which provides
59 the underlying functionality to this command line interface.
60 """
61 + if ctx.invoked_subcommand is None:
62 + typer.echo(ctx.get_help())
63 + raise typer.Exit(code=2)
64 + if db_type is None:
65 + raise typer.BadParameter("--db is required")
66 +
67 if db_type == DBType.SQLITE and ctx.invoked_subcommand == "sync" and not Path(db_filename).exists():
68 pass
69 elif db_type == DBType.SQLITE and not Path(db_filename).exists():
70 diff --git a/amqtt/contrib/auth_db/user_mgr_cli.py b/amqtt/contrib/auth_db/user_mgr_cli.py
71 index d881653..ceee8db 100644
72 --- a/amqtt/contrib/auth_db/user_mgr_cli.py
73 +++ b/amqtt/contrib/auth_db/user_mgr_cli.py
74 @@ -11,13 +11,13 @@ from amqtt.errors import MQTTError
75
76 logging.basicConfig(level=logging.INFO, format="%(message)s")
77 logger = logging.getLogger(__name__)
78 -user_app = typer.Typer(no_args_is_help=True)
79 +user_app = typer.Typer(invoke_without_command=True)
80
81
82 @user_app.callback()
83 def main(
84 ctx: typer.Context,
85 - db_type: Annotated[DBType, typer.Option(..., "--db", "-d", help="db type", show_default=False)],
86 + db_type: Annotated[DBType | None, typer.Option("--db", "-d", help="db type", show_default=False)] = None,
87 db_username: Annotated[str, typer.Option("--username", "-u", help="db username", show_default=False)] = "",
88 db_port: Annotated[int, typer.Option("--port", "-p", help="database port (defaults to db type)", show_default=False)] = 0,
89 db_host: Annotated[str, typer.Option("--host", "-h", help="database host")] = "localhost",
90 @@ -36,6 +36,12 @@ def main(
91 <p>Use NIST or other password guidelines when calling functions that set or update passwords.</p>
92 </details>
93 """
94 + if ctx.invoked_subcommand is None:
95 + typer.echo(ctx.get_help())
96 + raise typer.Exit(code=2)
97 + if db_type is None:
98 + raise typer.BadParameter("--db is required")
99 +
100 if db_type == DBType.SQLITE and ctx.invoked_subcommand == "sync" and not Path(db_filename).exists():
101 pass
102 elif db_type == DBType.SQLITE and not Path(db_filename).exists():
103 diff --git a/amqtt/contrib/cert.py b/amqtt/contrib/cert.py
104 index e355105..8a3d202 100644
105 --- a/amqtt/contrib/cert.py
106 +++ b/amqtt/contrib/cert.py
107 @@ -96,7 +96,7 @@ def generate_root_creds(country: str, state: str, locality: str,
108 # generate private key for the server
109 ca_key = rsa.generate_private_key(
110 public_exponent=65537,
111 - key_size=4096,
112 + key_size=2048,
113 )
114 # Create certificate subject and issuer (self-signed)
115 subject = issuer = x509.Name([
116 diff --git a/samples/broker_acl.py b/samples/broker_acl.py
117 index 9fd4cbc..6e710d5 100644
118 --- a/samples/broker_acl.py
119 +++ b/samples/broker_acl.py
120 @@ -1,5 +1,6 @@
121 import asyncio
122 import logging
123 +import os
124 from pathlib import Path
125
126 from amqtt.broker import Broker
127 @@ -14,10 +15,10 @@ config = {
128 "listeners": {
129 "default": {
130 "type": "tcp",
131 - "bind": "0.0.0.0:1883",
132 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_BROKER_PORT', '1883')}",
133 },
134 "ws-mqtt": {
135 - "bind": "127.0.0.1:8080",
136 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_WS_PORT', '8080')}",
137 "type": "ws",
138 "max_connections": 10,
139 },
140 diff --git a/samples/broker_simple.py b/samples/broker_simple.py
141 index 40f1c5b..fc9b819 100644
142 --- a/samples/broker_simple.py
143 +++ b/samples/broker_simple.py
144 @@ -1,6 +1,7 @@
145 import asyncio
146 from asyncio import CancelledError
147 import logging
148 +import os
149
150 from amqtt.broker import Broker
151
152 @@ -13,7 +14,9 @@ logging.basicConfig(level=logging.INFO, format=formatter)
153
154
155 async def run_server() -> None:
156 - broker = Broker()
157 + port = os.environ.get("AMQTT_BROKER_PORT")
158 + config = {"listeners": {"default": {"type": "tcp", "bind": f"127.0.0.1:{port}"}}} if port else None
159 + broker = Broker(config)
160 try:
161 await broker.start()
162 while True:
163 diff --git a/samples/broker_start.py b/samples/broker_start.py
164 index e0c9231..7829661 100644
165 --- a/samples/broker_start.py
166 +++ b/samples/broker_start.py
167 @@ -1,5 +1,6 @@
168 import asyncio
169 import logging
170 +import os
171 from pathlib import Path
172
173 from amqtt.broker import Broker
174 @@ -14,10 +15,10 @@ config = {
175 "listeners": {
176 "default": {
177 "type": "tcp",
178 - "bind": "0.0.0.0:1883",
179 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_BROKER_PORT', '1883')}",
180 },
181 "ws-mqtt": {
182 - "bind": "127.0.0.1:8080",
183 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_WS_PORT', '8080')}",
184 "type": "ws",
185 "max_connections": 10,
186 },
187 diff --git a/samples/broker_taboo.py b/samples/broker_taboo.py
188 index 19cfbd1..3a34a55 100644
189 --- a/samples/broker_taboo.py
190 +++ b/samples/broker_taboo.py
191 @@ -1,5 +1,6 @@
192 import asyncio
193 import logging
194 +import os
195 from pathlib import Path
196
197 from amqtt.broker import Broker
198 @@ -14,10 +15,10 @@ config = {
199 "listeners": {
200 "default": {
201 "type": "tcp",
202 - "bind": "0.0.0.0:1883",
203 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_BROKER_PORT', '1883')}",
204 },
205 "ws-mqtt": {
206 - "bind": "127.0.0.1:8080",
207 + "bind": f"127.0.0.1:{os.environ.get('AMQTT_WS_PORT', '8080')}",
208 "type": "ws",
209 "max_connections": 10,
210 },
211 diff --git a/samples/client_keepalive.py b/samples/client_keepalive.py
212 index 5de40c5..5c72182 100644
213 --- a/samples/client_keepalive.py
214 +++ b/samples/client_keepalive.py
215 @@ -1,6 +1,7 @@
216 import asyncio
217 from asyncio import CancelledError
218 import logging
219 +import os
220
221 from amqtt.client import MQTTClient
222
223 @@ -19,7 +20,7 @@ async def main() -> None:
224 client = MQTTClient(config=config)
225
226 try:
227 - await client.connect("mqtt://localhost:1883/")
228 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtt://localhost:1883/"))
229 logger.info("client connected")
230 await asyncio.sleep(7)
231 except CancelledError:
232 diff --git a/samples/client_publish.py b/samples/client_publish.py
233 index 83ee5d9..c97a100 100644
234 --- a/samples/client_publish.py
235 +++ b/samples/client_publish.py
236 @@ -1,5 +1,6 @@
237 import asyncio
238 import logging
239 +import os
240
241 from amqtt.client import ConnectError, MQTTClient
242 from amqtt.mqtt.constants import QOS_1, QOS_2
243 @@ -22,7 +23,7 @@ config = {
244
245 async def test_coro1() -> None:
246 client = MQTTClient()
247 - await client.connect("mqtt://localhost:1883/")
248 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtt://localhost:1883/"))
249 tasks = [
250 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_0")),
251 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=QOS_1)),
252 @@ -36,7 +37,7 @@ async def test_coro1() -> None:
253 async def test_coro2() -> None:
254 try:
255 client = MQTTClient(config={"auto_reconnect": False, "connection_timeout": 1})
256 - await client.connect("mqtt://localhost:1884/")
257 + await client.connect(os.environ.get("AMQTT_CLIENT_FAIL_URL", "mqtt://localhost:1884/"))
258 await client.publish("a/b", b"TEST MESSAGE WITH QOS_0", qos=0x00)
259 await client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=0x01)
260 await client.publish("a/b", b"TEST MESSAGE WITH QOS_2", qos=0x02)
261 diff --git a/samples/client_publish_acl.py b/samples/client_publish_acl.py
262 index 99a4cd3..47de4f2 100644
263 --- a/samples/client_publish_acl.py
264 +++ b/samples/client_publish_acl.py
265 @@ -1,5 +1,6 @@
266 import asyncio
267 import logging
268 +import os
269
270 from amqtt.client import ConnectError, MQTTClient
271 from amqtt.mqtt.constants import QOS_1
272 @@ -15,7 +16,7 @@ logger = logging.getLogger(__name__)
273 async def test_coro() -> None:
274 try:
275 client = MQTTClient()
276 - await client.connect("mqtt://0.0.0.0:1883")
277 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtt://0.0.0.0:1883"))
278 await client.publish("data/classified", b"TOP SECRET", qos=QOS_1)
279 await client.publish("data/memes", b"REAL FUN", qos=QOS_1)
280 await client.publish("repositories/amqtt/master", b"NEW STABLE RELEASE", qos=QOS_1)
281 diff --git a/samples/client_publish_ssl.py b/samples/client_publish_ssl.py
282 index a0ae79b..7a1f1ce 100644
283 --- a/samples/client_publish_ssl.py
284 +++ b/samples/client_publish_ssl.py
285 @@ -1,6 +1,7 @@
286 import argparse
287 import asyncio
288 import logging
289 +import os
290
291 from amqtt.client import MQTTClient
292 from amqtt.mqtt.constants import QOS_1, QOS_2
293 @@ -42,7 +43,7 @@ async def test_coro(certfile: str) -> None:
294 config["certfile"] = certfile
295 client = MQTTClient(config=config)
296
297 - await client.connect("mqtts://localhost:8883")
298 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtts://localhost:8883"))
299 tasks = [
300 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_0")),
301 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=QOS_1)),
302 diff --git a/samples/client_publish_ws.py b/samples/client_publish_ws.py
303 index e02c73e..97998f0 100644
304 --- a/samples/client_publish_ws.py
305 +++ b/samples/client_publish_ws.py
306 @@ -1,5 +1,6 @@
307 import asyncio
308 import logging
309 +import os
310
311 from amqtt.client import MQTTClient
312 from amqtt.mqtt.constants import QOS_1, QOS_2
313 @@ -22,7 +23,7 @@ client = MQTTClient(config=config)
314
315
316 async def test_coro() -> None:
317 - await client.connect("ws://localhost:8080/")
318 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "ws://localhost:8080/"))
319 tasks = [
320 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_0")),
321 asyncio.ensure_future(client.publish("a/b", b"TEST MESSAGE WITH QOS_1", qos=QOS_1)),
322 diff --git a/samples/client_subscribe.py b/samples/client_subscribe.py
323 index c0f4982..3658da5 100644
324 --- a/samples/client_subscribe.py
325 +++ b/samples/client_subscribe.py
326 @@ -1,5 +1,6 @@
327 import asyncio
328 import logging
329 +import os
330
331 from amqtt.client import ClientError, MQTTClient
332 from amqtt.mqtt.constants import QOS_1, QOS_2
333 @@ -13,7 +14,7 @@ logger = logging.getLogger(__name__)
334
335 async def uptime_coro() -> None:
336 client = MQTTClient(config={"auto_reconnect": False})
337 - await client.connect("mqtt://localhost:1883")
338 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtt://localhost:1883"))
339
340 await client.subscribe(
341 [
342 diff --git a/samples/client_subscribe_acl.py b/samples/client_subscribe_acl.py
343 index e5c1399..9345aa2 100644
344 --- a/samples/client_subscribe_acl.py
345 +++ b/samples/client_subscribe_acl.py
346 @@ -1,5 +1,6 @@
347 import asyncio
348 import logging
349 +import os
350
351 from amqtt.client import ClientError, MQTTClient
352 from amqtt.mqtt.constants import QOS_1
353 @@ -15,7 +16,7 @@ logger = logging.getLogger(__name__)
354
355 async def uptime_coro() -> None:
356 client = MQTTClient()
357 - await client.connect("mqtt://test:[email protected]:1883")
358 + await client.connect(os.environ.get("AMQTT_CLIENT_URL", "mqtt://test:[email protected]:1883"))
359
360 result = await client.subscribe(
361 [
362 @@ -42,13 +43,7 @@ async def uptime_coro() -> None:
363 def __main__():
364 formatter = "[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s"
365 logging.basicConfig(level=logging.INFO, format=formatter)
366 -
367 - loop = asyncio.new_event_loop()
368 - asyncio.set_event_loop(loop)
369 - loop.run_until_complete(uptime_coro())
370 -
371 -
372 -
373 + asyncio.run(uptime_coro())
374
375 if __name__ == "__main__":
376 __main__()
377 diff --git a/samples/http_server_integration.py b/samples/http_server_integration.py
378 index cc80e3d..2b2c85a 100644
379 --- a/samples/http_server_integration.py
380 +++ b/samples/http_server_integration.py
381 @@ -1,6 +1,7 @@
382 import asyncio
383 import io
384 import logging
385 +import os
386 import ssl
387
388 import aiohttp
389 @@ -137,7 +138,6 @@ def main():
390 # create an `aiohttp` server
391 lp = asyncio.new_event_loop()
392 asyncio.set_event_loop(lp)
393 -
394 app = web.Application()
395 app.add_routes(
396 [
397 @@ -150,7 +150,7 @@ def main():
398
399 # make sure that both `aiohttp` server and `amqtt` broker run in the same loop
400 # so the server can hand off the connection to the broker (prevents attached-to-a-different-loop `RuntimeError`)
401 - web.run_app(app, loop=lp)
402 + web.run_app(app, host="127.0.0.1", port=int(os.environ.get("AMQTT_HTTP_PORT", "8080")), loop=lp)
403
404
405 async def run_broker(_app):
406 @@ -160,7 +160,10 @@ async def run_broker(_app):
407 # standard TCP connection as well as an externalized-listener
408 cfg = BrokerConfig(
409 listeners={
410 - "default":ListenerConfig(type=ListenerType.TCP, bind="127.0.0.1:1883"),
411 + "default":ListenerConfig(
412 + type=ListenerType.TCP,
413 + bind=f"127.0.0.1:{os.environ.get('AMQTT_BROKER_PORT', '1883')}",
414 + ),
415 MQTT_LISTENER_NAME: ListenerConfig(type=ListenerType.EXTERNAL),
416 }
417 )
418 diff --git a/tests/test_samples.py b/tests/test_samples.py
419 index 8fcde3d..10ebe74 100644
420 --- a/tests/test_samples.py
421 +++ b/tests/test_samples.py
422 @@ -1,8 +1,10 @@
423 import ast
424 import asyncio
425 import logging
426 +import os
427 import multiprocessing
428 import signal
429 +import socket
430 import subprocess
431 import sys
432
433 @@ -24,6 +26,28 @@ from samples.broker_dollar_topics import config as broker_dollar_topics_config
434
435 logger = logging.getLogger(__name__)
436
437 +def unused_tcp_port() -> int:
438 + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
439 + sock.bind(("127.0.0.1", 0))
440 + return sock.getsockname()[1]
441 +
442 +
443 +def listener_port(broker: Broker, listener_name: str = "default") -> int:
444 + return broker._servers[listener_name].instance.sockets[0].getsockname()[1]
445 +
446 +
447 +def sample_env(url: str) -> dict[str, str]:
448 + return {**os.environ, "AMQTT_CLIENT_URL": url}
449 +
450 +
451 +def sample_broker_env() -> dict[str, str]:
452 + return {
453 + **os.environ,
454 + "AMQTT_BROKER_PORT": str(unused_tcp_port()),
455 + "AMQTT_WS_PORT": str(unused_tcp_port()),
456 + }
457 +
458 +
459 SAMPLES_DIR = Path(__file__).parent.parent / "samples"
460 IGNORED_SAMPLE_FILES = frozenset()
461
462 @@ -73,7 +97,12 @@ def test_all_sample_files_are_accounted_for():
463 @pytest.mark.sample("broker_acl.py")
464 async def test_broker_acl():
465 broker_acl_script = Path(__file__).parent.parent / "samples/broker_acl.py"
466 - process = subprocess.Popen([sys.executable, broker_acl_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
467 + process = subprocess.Popen(
468 + [sys.executable, broker_acl_script],
469 + stdout=subprocess.PIPE,
470 + stderr=subprocess.PIPE,
471 + env=sample_broker_env(),
472 + )
473 # Send the interrupt signal
474 await asyncio.sleep(2)
475 process.send_signal(signal.SIGINT)
476 @@ -103,7 +132,12 @@ async def test_broker_custom_plugin():
477 @pytest.mark.sample("broker_simple.py")
478 async def test_broker_simple():
479 broker_simple_script = Path(__file__).parent.parent / "samples/broker_simple.py"
480 - process = subprocess.Popen([sys.executable, broker_simple_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
481 + process = subprocess.Popen(
482 + [sys.executable, broker_simple_script],
483 + stdout=subprocess.PIPE,
484 + stderr=subprocess.PIPE,
485 + env=sample_broker_env(),
486 + )
487 await asyncio.sleep(2)
488
489 # Send the interrupt signal
490 @@ -120,7 +154,12 @@ async def test_broker_simple():
491 @pytest.mark.sample("broker_start.py")
492 async def test_broker_start():
493 broker_start_script = Path(__file__).parent.parent / "samples/broker_start.py"
494 - process = subprocess.Popen([sys.executable, broker_start_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
495 + process = subprocess.Popen(
496 + [sys.executable, broker_start_script],
497 + stdout=subprocess.PIPE,
498 + stderr=subprocess.PIPE,
499 + env=sample_broker_env(),
500 + )
501 await asyncio.sleep(2)
502
503 # Send the interrupt signal to stop broker
504 @@ -136,7 +175,12 @@ async def test_broker_start():
505 @pytest.mark.sample("broker_taboo.py")
506 async def test_broker_taboo():
507 broker_taboo_script = Path(__file__).parent.parent / "samples/broker_taboo.py"
508 - process = subprocess.Popen([sys.executable, broker_taboo_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
509 + process = subprocess.Popen(
510 + [sys.executable, broker_taboo_script],
511 + stdout=subprocess.PIPE,
512 + stderr=subprocess.PIPE,
513 + env=sample_broker_env(),
514 + )
515 await asyncio.sleep(2)
516
517 # Send the interrupt signal to stop broker
518 @@ -151,13 +195,17 @@ async def test_broker_taboo():
519 @pytest.mark.asyncio
520 @pytest.mark.sample("client_keepalive.py")
521 async def test_client_keepalive():
522 -
523 - broker = Broker()
524 + broker = Broker({"listeners": {"default": {"type": "tcp", "bind": "127.0.0.1:0"}}})
525 await broker.start()
526 await asyncio.sleep(2)
527
528 keep_alive_script = Path(__file__).parent.parent / "samples/client_keepalive.py"
529 - process = subprocess.Popen([sys.executable, keep_alive_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
530 + process = subprocess.Popen(
531 + [sys.executable, keep_alive_script],
532 + stdout=subprocess.PIPE,
533 + stderr=subprocess.PIPE,
534 + env=sample_env(f"mqtt://127.0.0.1:{listener_port(broker)}/"),
535 + )
536 await asyncio.sleep(1)
537
538 stdout, stderr = await asyncio.to_thread(process.communicate)
539 @@ -170,12 +218,17 @@ async def test_client_keepalive():
540 @pytest.mark.asyncio
541 @pytest.mark.sample("client_publish.py")
542 async def test_client_publish():
543 - broker = Broker()
544 + broker = Broker({"listeners": {"default": {"type": "tcp", "bind": "127.0.0.1:0"}}})
545 await broker.start()
546 await asyncio.sleep(2)
547
548 client_publish = Path(__file__).parent.parent / "samples/client_publish.py"
549 - process = subprocess.Popen([sys.executable, client_publish], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
550 + process = subprocess.Popen(
551 + [sys.executable, client_publish],
552 + stdout=subprocess.PIPE,
553 + stderr=subprocess.PIPE,
554 + env=sample_env(f"mqtt://127.0.0.1:{listener_port(broker)}/"),
555 + )
556 await asyncio.sleep(2)
557
558 stdout, stderr = process.communicate()
559 @@ -192,16 +245,16 @@ def broker_ssl_config(rsa_keys):
560 "listeners": {
561 "default": {
562 "type": "tcp",
563 - "bind": "0.0.0.0:8883",
564 + "bind": "127.0.0.1:0",
565 "ssl": True,
566 "certfile": certfile,
567 "keyfile": keyfile,
568 }
569 },
570 - "auth": {
571 - "allow-anonymous": True,
572 - "plugins": ["auth_anonymous"]
573 - }
574 + "plugins": {
575 + "amqtt.plugins.authentication.AnonymousAuthPlugin": {"allow_anonymous": True},
576 + "amqtt.plugins.sys.broker.BrokerSysPlugin": {"sys_interval": 0},
577 + },
578 }
579
580 @pytest.mark.asyncio
581 @@ -216,7 +269,12 @@ async def test_client_publish_ssl(broker_ssl_config, rsa_keys):
582 await asyncio.sleep(2)
583 # run the sample
584 client_publish_ssl_script = Path(__file__).parent.parent / "samples/client_publish_ssl.py"
585 - process = subprocess.Popen([sys.executable, client_publish_ssl_script, '--cert', certfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
586 + process = subprocess.Popen(
587 + [sys.executable, client_publish_ssl_script, '--cert', certfile],
588 + stdout=subprocess.PIPE,
589 + stderr=subprocess.PIPE,
590 + env=sample_env(f"mqtts://localhost:{listener_port(broker)}"),
591 + )
592 await asyncio.sleep(2)
593 stdout, stderr = process.communicate()
594
595 @@ -230,12 +288,17 @@ async def test_client_publish_ssl(broker_ssl_config, rsa_keys):
596 @pytest.mark.sample("client_publish_acl.py")
597 async def test_client_publish_acl():
598
599 - broker = Broker()
600 + broker = Broker({"listeners": {"default": {"type": "tcp", "bind": "127.0.0.1:0"}}})
601 await broker.start()
602 await asyncio.sleep(2)
603
604 broker_simple_script = Path(__file__).parent.parent / "samples/client_publish_acl.py"
605 - process = subprocess.Popen([sys.executable, broker_simple_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
606 + process = subprocess.Popen(
607 + [sys.executable, broker_simple_script],
608 + stdout=subprocess.PIPE,
609 + stderr=subprocess.PIPE,
610 + env=sample_env(f"mqtt://127.0.0.1:{listener_port(broker)}"),
611 + )
612 # Send the interrupt signal
613 await asyncio.sleep(2)
614
615 @@ -250,13 +313,13 @@ broker_ws_config = {
616 "listeners": {
617 "default": {
618 "type": "ws",
619 - "bind": "0.0.0.0:8080",
620 + "bind": "127.0.0.1:0",
621 }
622 },
623 - "auth": {
624 - "allow-anonymous": True,
625 - "plugins": ["auth_anonymous"]
626 - }
627 + "plugins": {
628 + "amqtt.plugins.authentication.AnonymousAuthPlugin": {"allow_anonymous": True},
629 + "amqtt.plugins.sys.broker.BrokerSysPlugin": {"sys_interval": 0},
630 + },
631 }
632
633 @pytest.mark.asyncio
634 @@ -269,21 +332,27 @@ async def test_client_publish_ws():
635 # run the sample
636
637 client_publish_ssl_script = Path(__file__).parent.parent / "samples/client_publish_ws.py"
638 - process = subprocess.Popen([sys.executable, client_publish_ssl_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
639 - await asyncio.sleep(2)
640 - stdout, stderr = process.communicate()
641 -
642 - assert "ERROR" not in stderr.decode("utf-8")
643 - assert "Exception" not in stderr.decode("utf-8")
644 -
645 - await broker.shutdown()
646 + try:
647 + process = await asyncio.create_subprocess_exec(
648 + sys.executable,
649 + client_publish_ssl_script,
650 + stdout=asyncio.subprocess.PIPE,
651 + stderr=asyncio.subprocess.PIPE,
652 + env=sample_env(f"ws://127.0.0.1:{listener_port(broker)}/"),
653 + )
654 + stdout, stderr = await process.communicate()
655 +
656 + assert "ERROR" not in stderr.decode("utf-8")
657 + assert "Exception" not in stderr.decode("utf-8")
658 + finally:
659 + await broker.shutdown()
660
661
662 broker_std_config = {
663 "listeners": {
664 "default": {
665 "type": "tcp",
666 - "bind": "0.0.0.0:1883",
667 + "bind": "127.0.0.1:0",
668 }
669 },
670 'sys_interval':2,
671 @@ -310,7 +379,8 @@ async def test_client_subscribe():
672 sys.executable,
673 str(client_subscribe_script),
674 stdout=asyncio.subprocess.PIPE,
675 - stderr=asyncio.subprocess.PIPE
676 + stderr=asyncio.subprocess.PIPE,
677 + env=sample_env(f"mqtt://127.0.0.1:{listener_port(broker)}"),
678 )
679
680 stdout, stderr = await process.communicate()
681 @@ -326,11 +396,18 @@ async def test_client_subscribe():
682 @pytest.mark.asyncio
683 @pytest.mark.sample("client_subscribe_acl.py")
684 async def test_client_subscribe_plugin_acl():
685 + broker_acl_config["listeners"]["default"]["bind"] = "127.0.0.1:0"
686 + broker_acl_config["listeners"]["ws-mqtt"]["bind"] = "127.0.0.1:0"
687 broker = Broker(config=broker_acl_config)
688 await broker.start()
689
690 broker_simple_script = Path(__file__).parent.parent / "samples/client_subscribe_acl.py"
691 - process = subprocess.Popen([sys.executable, broker_simple_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
692 + process = subprocess.Popen(
693 + [sys.executable, broker_simple_script],
694 + stdout=subprocess.PIPE,
695 + stderr=subprocess.PIPE,
696 + env=sample_env(f"mqtt://test:[email protected]:{listener_port(broker)}"),
697 + )
698 # Send the interrupt signal
699 await asyncio.sleep(2)
700 process.send_signal(signal.SIGINT)
701 @@ -346,11 +423,18 @@ async def test_client_subscribe_plugin_acl():
702 @pytest.mark.asyncio
703 @pytest.mark.sample("client_subscribe_acl.py")
704 async def test_client_subscribe_plugin_taboo():
705 + broker_taboo_config["listeners"]["default"]["bind"] = "127.0.0.1:0"
706 + broker_taboo_config["listeners"]["ws-mqtt"]["bind"] = "127.0.0.1:0"
707 broker = Broker(config=broker_taboo_config)
708 await broker.start()
709
710 broker_simple_script = Path(__file__).parent.parent / "samples/client_subscribe_acl.py"
711 - process = subprocess.Popen([sys.executable, broker_simple_script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
712 + process = subprocess.Popen(
713 + [sys.executable, broker_simple_script],
714 + stdout=subprocess.PIPE,
715 + stderr=subprocess.PIPE,
716 + env=sample_env(f"mqtt://test:[email protected]:{listener_port(broker)}"),
717 + )
718 # Send the interrupt signal
719 await asyncio.sleep(2)
720 process.send_signal(signal.SIGINT)
721 @@ -364,14 +448,18 @@ async def test_client_subscribe_plugin_taboo():
722
723
724 @pytest.fixture
725 -def external_http_server():
726 +def external_http_server(monkeypatch):
727 + http_port = unused_tcp_port()
728 + broker_port = unused_tcp_port()
729 + monkeypatch.setenv("AMQTT_HTTP_PORT", str(http_port))
730 + monkeypatch.setenv("AMQTT_BROKER_PORT", str(broker_port))
731 # Force "spawn" so the child starts a fresh interpreter with no event loop.
732 # On Linux the default start method is "fork", which would inherit the running
733 # pytest-asyncio event loop and break `web.run_app` inside the sample's main().
734 ctx = multiprocessing.get_context("spawn")
735 p = ctx.Process(target=http_server_main)
736 p.start()
737 - yield p
738 + yield http_port
739 p.terminate()
740 p.join()
741
742 @@ -397,7 +485,7 @@ async def test_external_http_server(external_http_server):
743
744 await _wait_for_port("127.0.0.1", 8080)
745 client = MQTTClient(config={'auto_reconnect': False})
746 - await client.connect("ws://127.0.0.1:8080/mqtt")
747 + await client.connect(f"ws://127.0.0.1:{external_http_server}/mqtt")
748 assert client.session is not None
749 await client.publish("my/topic", b'test message')
750 await client.disconnect()
751 diff --git a/tests/test_session_monitor.py b/tests/test_session_monitor.py
752 index 438f2fd..536758c 100644
753 --- a/tests/test_session_monitor.py
754 +++ b/tests/test_session_monitor.py
755 @@ -9,6 +9,9 @@ from amqtt.contexts import BrokerConfig, ListenerConfig, ConnectionConfig, Clien
756
757 logger = logging.getLogger(__name__)
758
759 +def listener_port(broker: Broker, listener_name: str = "default") -> int:
760 + return broker._servers[listener_name].instance.sockets[0].getsockname()[1]
761 +
762 @pytest.fixture
763 def session_broker_config():
764 return BrokerConfig(
765 @@ -37,16 +40,18 @@ def session_broker_config():
766 async def test_clear_session_expiration(caplog, session_broker_config, username, clean_session, session_count, expiration):
767 caplog.set_level(logging.DEBUG)
768
769 + session_broker_config.listeners["default"].bind = "127.0.0.1:0"
770 session_broker_config.session_expiry_interval = expiration
771 session_broker_config.plugins = {'amqtt.plugins.authentication.AnonymousAuthPlugin': {'allow_anonymous': username == ""}}
772
773 broker = Broker(config=session_broker_config)
774 await broker.start()
775 + port = listener_port(broker)
776 await asyncio.sleep(0.1)
777 assert len(broker._sessions) < 1
778
779 c = MQTTClient(config=ClientConfig(cleansession=clean_session, auto_reconnect=False))
780 - await c.connect(f'mqtt://{username}127.0.0.1:1883')
781 + await c.connect(f'mqtt://{username}127.0.0.1:{port}')
782 await asyncio.sleep(0.1)
783 assert len(broker._sessions) == 1, "client should be connected"
784 await asyncio.sleep(0.1)