Skip to content

Commit dc5ebc7

Browse files
committed
Handle exceptions when closing DB connection
When using JayDeBeApi, closing the connection can cause the following exception to be raised: jpype._core.JVMNotRunning: Java Virtual Machine is not running Since we're closing the connection anyway, it seems like the best behavior is to log the exception and continue on. Fixes #71
1 parent 62747de commit dc5ebc7

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

src/itoolkit/transport/database.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
import logging
3+
24
from .base import XmlServiceTransport
35

46
__all__ = [
@@ -81,4 +83,12 @@ def _call(self, tk):
8183
return "".join(row[0] for row in cursor.fetchall()).rstrip('\0')
8284

8385
def _close(self):
84-
self.conn.close()
86+
try:
87+
self.conn.close()
88+
except RuntimeError:
89+
# JayDeBeApi can fail to close a connection with
90+
# jpype._core.JVMNotRunning: Java Virtual Machine is not running
91+
#
92+
# Doesn't seem to be anything reasonable to do but log the
93+
# exception and continue.
94+
logging.exception("Unexpected exception closing database connection")

tests/conftest.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,13 @@ def database_execute():
6767
return mock_database(use_callproc=False)
6868

6969

70+
@pytest.fixture
71+
def database_close_exception():
72+
conn = mock_database(use_callproc=True)
73+
conn.close.side_effect = RuntimeError
74+
return conn
75+
76+
7077
@pytest.fixture
7178
def database():
7279
return mock_database(use_callproc=True)

tests/test_unit_transport_database.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,21 @@ def test_database_transport_call_raises_when_closed(database_execute):
7171
with pytest.raises(TransportClosedException):
7272
tk = iToolKit()
7373
out = transport.call(tk)
74+
75+
76+
def test_database_transport_logs_exception_on_close(database_close_exception, caplog, capsys):
77+
schema = 'MYSCHEMA'
78+
transport = DatabaseTransport(database_close_exception, schema=schema)
79+
80+
tk = iToolKit()
81+
out = transport.call(tk)
82+
83+
with capsys.disabled():
84+
transport.close()
85+
86+
assert len(caplog.records) == 1
87+
l = caplog.records[0]
88+
assert l.levelname == "ERROR"
89+
assert 'Unexpected exception' in l.message
90+
91+
caplog.clear()

0 commit comments

Comments
 (0)