Skip to content

Commit 46b0e4a

Browse files
committed
Fix: Ensure that connection is closed when using context manager
When using the context manager on the Gmp class which determines the supported GMP version ensure that the opened connection is closed when leaving the context. Fixes #659
1 parent 73435e7 commit 46b0e4a

2 files changed

Lines changed: 30 additions & 4 deletions

File tree

gvm/protocols/gmp.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
"""
2020
Module for communication with gvmd
2121
"""
22-
from typing import Any, Optional, Callable, Union
22+
from types import TracebackType
23+
from typing import Any, Optional, Callable, Union, Type
2324

2425
from gvm.errors import GvmError
2526

@@ -114,8 +115,17 @@ def determine_supported_gmp(self) -> SUPPORTED_GMP_VERSIONS:
114115
return gmp_class(self._connection, transform=self._gmp_transform)
115116

116117
def __enter__(self):
117-
gmp = self.determine_supported_gmp()
118+
self._gmp = self.determine_supported_gmp()
118119

119-
gmp.connect()
120+
self._gmp.connect()
120121

121-
return gmp
122+
return self._gmp
123+
124+
def __exit__(
125+
self,
126+
exc_type: Optional[Type[BaseException]],
127+
exc_value: Optional[BaseException],
128+
traceback: Optional[TracebackType],
129+
) -> Any:
130+
self._gmp.disconnect()
131+
self._gmp = None

tests/protocols/gmp/test_context_manager.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
# along with this program. If not, see <http://www.gnu.org/licenses/>.
1818

1919
import unittest
20+
from unittest.mock import MagicMock, patch
2021

2122
from tests.protocols import GmpTestCase
2223

@@ -115,6 +116,21 @@ def test_invalid_response(self):
115116
with self.gmp:
116117
pass
117118

119+
@patch("gvm.protocols.gmp.Gmpv214")
120+
def test_connect_disconnect(self, gmp_mock: MagicMock):
121+
self.connection.read.return_value(
122+
'<get_version_response status="200" status_text="OK">'
123+
'<version>21.04</version>'
124+
'</get_version_response>'
125+
)
126+
127+
with self.gmp:
128+
gmp_mock.assert_called_once()
129+
130+
mock_instance = gmp_mock.return_value
131+
mock_instance.connect.assert_called_once()
132+
mock_instance.disconnect.assert_called_once()
133+
118134

119135
if __name__ == '__main__':
120136
unittest.main()

0 commit comments

Comments
 (0)