|
13 | 13 | from serial import EIGHTBITS, PARITY_NONE, STOPBITS_ONE |
14 | 14 |
|
15 | 15 | import pyplumio.connection |
16 | | -from pyplumio.connection import Connection, SerialConnection, TcpConnection |
| 16 | +from pyplumio.connection import ( |
| 17 | + RECONNECT_AFTER_SECONDS, |
| 18 | + Connection, |
| 19 | + SerialConnection, |
| 20 | + TcpConnection, |
| 21 | +) |
17 | 22 | from pyplumio.devices.ecomax import EcoMAX |
18 | 23 | from pyplumio.exceptions import ConnectionFailedError |
19 | 24 | from pyplumio.protocol import AsyncProtocol, DummyProtocol, Protocol |
@@ -115,33 +120,43 @@ async def test_connect(self, mock_open_connection, mock_protocol) -> None: |
115 | 120 | await connection.close() |
116 | 121 | mock_protocol.shutdown.assert_called_once() |
117 | 122 |
|
118 | | - @pytest.mark.parametrize( |
119 | | - ("reconnect_on_failure", "expected_log"), |
120 | | - [ |
121 | | - (True, "Can't connect to the device"), |
122 | | - (False, None), |
123 | | - ], |
| 123 | + @pytest.mark.parametrize("reconnect_on_failure", [True, False]) |
| 124 | + @patch.object( |
| 125 | + DummyConnection, |
| 126 | + "_open_connection", |
| 127 | + side_effect=(OSError, (AsyncMock(), AsyncMock), None), |
124 | 128 | ) |
125 | | - @patch.object(DummyConnection, "_open_connection", side_effect=(OSError, None)) |
| 129 | + @patch("pyplumio.protocol.AsyncProtocol.connection_established") |
126 | 130 | async def test_reconnect( |
127 | 131 | self, |
| 132 | + mock_connection_established, |
128 | 133 | mock_open_connection, |
129 | 134 | caplog, |
130 | 135 | reconnect_on_failure: bool, |
131 | | - expected_log: str | None, |
132 | 136 | ) -> None: |
133 | 137 | """Test reconnect logic.""" |
134 | 138 | connection = DummyConnection(reconnect_on_failure=reconnect_on_failure) |
135 | 139 | if reconnect_on_failure: |
136 | 140 | with caplog.at_level(logging.ERROR): |
137 | 141 | await connection.connect() |
| 142 | + assert "Unable to connect to the device." in caplog.text |
| 143 | + assert ( |
| 144 | + f"Will attempt to reconnect every {RECONNECT_AFTER_SECONDS} seconds" |
| 145 | + in caplog.text |
| 146 | + ) |
| 147 | + |
| 148 | + with caplog.at_level(logging.INFO): |
| 149 | + await connection.connect() |
| 150 | + assert "Connection to device restored after 1 retries" in caplog.text |
| 151 | + mock_connection_established.assert_called_once() |
| 152 | + |
| 153 | + assert mock_open_connection.await_count == 2 |
138 | 154 |
|
139 | | - assert expected_log in caplog.text |
140 | 155 | else: |
141 | 156 | with pytest.raises(ConnectionFailedError): |
142 | 157 | await connection.connect() |
143 | 158 |
|
144 | | - mock_open_connection.assert_awaited_once() |
| 159 | + mock_open_connection.assert_awaited_once() |
145 | 160 |
|
146 | 161 | @patch.object(DummyConnection, "close") |
147 | 162 | @patch.object(DummyConnection, "connect") |
|
0 commit comments