Skip to content

Commit

Permalink
Add more tests for worker/mqtt.py
Browse files Browse the repository at this point in the history
  • Loading branch information
DasSkelett committed Aug 28, 2022
1 parent c3dcb6b commit 80a963f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion wgkex/worker/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import re
import socket
import threading
from typing import Optional, Dict, Any, Union
from typing import Optional, Any

import paho.mqtt.client as mqtt

Expand Down
42 changes: 42 additions & 0 deletions wgkex/worker/mqtt_test.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
"""Unit tests for mqtt.py"""
import socket
import threading
import unittest
from time import sleep

import mock
import paho.mqtt.client

from wgkex.common.mqtt import TOPIC_CONNECTED_PEERS
from wgkex.worker import mqtt


Expand Down Expand Up @@ -88,6 +93,43 @@ def test_on_message_wireguard_fails_no_domain(self, config_mock, link_mock):
with self.assertRaises(ValueError):
mqtt.on_message_wireguard(None, None, mqtt_msg)

@mock.patch.object(mqtt, "get_config")
@mock.patch.object(mqtt, "get_connected_peers_count")
def test_publish_metrics_loop_success(self, conn_peers_mock, config_mock):
config_mock.return_value = _get_config_mock()
conn_peers_mock.return_value = 20
mqtt_client = mock.MagicMock(spec=paho.mqtt.client.Client)

ee = threading.Event()
thread = threading.Thread(
target=mqtt.publish_metrics_loop,
args=(ee, mqtt_client, "_ffmuc_domain.one"),
)
thread.start()

i = 0
while i < 20 and not mqtt_client.publish.called:
i += 1
sleep(0.1)

conn_peers_mock.assert_called_with("wg-domain.one")
mqtt_client.publish.assert_called_with(
TOPIC_CONNECTED_PEERS.format(
domain="_ffmuc_domain.one", worker=socket.gethostname()
),
20,
retain=True,
)

ee.set()

i = 0
while i < 20 and thread.is_alive():
i += 1
sleep(0.1)

self.assertFalse(thread.is_alive())


if __name__ == "__main__":
unittest.main()

0 comments on commit 80a963f

Please sign in to comment.