diff --git a/slack_sdk/oauth/installation_store/sqlite3/__init__.py b/slack_sdk/oauth/installation_store/sqlite3/__init__.py index 7a68e24a0..e4181c101 100644 --- a/slack_sdk/oauth/installation_store/sqlite3/__init__.py +++ b/slack_sdk/oauth/installation_store/sqlite3/__init__.py @@ -1,5 +1,6 @@ import logging import sqlite3 +from contextlib import closing from logging import Logger from sqlite3 import Connection from typing import Optional @@ -33,7 +34,7 @@ def logger(self) -> Logger: def init(self): try: - with sqlite3.connect(database=self.database) as conn: + with closing(sqlite3.connect(database=self.database)) as conn: cur = conn.execute("select count(1) from slack_installations;") row_num = cur.fetchone()[0] self.logger.debug(f"{row_num} installations are stored in {self.database}") @@ -47,7 +48,7 @@ def connect(self) -> Connection: return sqlite3.connect(database=self.database) def create_tables(self): - with sqlite3.connect(database=self.database) as conn: + with closing(sqlite3.connect(database=self.database)) as conn: conn.execute(""" create table slack_installations ( id integer primary key autoincrement, @@ -124,7 +125,7 @@ async def async_save_bot(self, bot: Bot): return self.save_bot(bot) def save(self, installation: Installation): - with self.connect() as conn: + with closing(self.connect()) as conn: conn.execute( """ insert into slack_installations ( @@ -220,7 +221,7 @@ def save_bot(self, bot: Bot): self.logger.debug("Skipped saving a new row because of the absence of bot token in it") return - with self.connect() as conn: + with closing(self.connect()) as conn: conn.execute( """ insert into slack_bots ( @@ -297,7 +298,7 @@ def find_bot( team_id = "" try: - with self.connect() as conn: + with closing(self.connect()) as conn: cur = conn.execute( """ select @@ -384,7 +385,7 @@ def find_installation( team_id = "" try: - with self.connect() as conn: + with closing(self.connect()) as conn: row = None columns = """ app_id, @@ -541,7 +542,7 @@ async def async_delete_bot(self, *, enterprise_id: Optional[str], team_id: Optio def delete_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str]) -> None: try: - with self.connect() as conn: + with closing(self.connect()) as conn: conn.execute( """ delete @@ -581,7 +582,7 @@ def delete_installation( user_id: Optional[str] = None, ) -> None: try: - with self.connect() as conn: + with closing(self.connect()) as conn: if user_id is None: conn.execute( """ diff --git a/slack_sdk/oauth/state_store/sqlite3/__init__.py b/slack_sdk/oauth/state_store/sqlite3/__init__.py index 3a18c4682..2c58591e4 100644 --- a/slack_sdk/oauth/state_store/sqlite3/__init__.py +++ b/slack_sdk/oauth/state_store/sqlite3/__init__.py @@ -1,6 +1,7 @@ import logging import sqlite3 import time +from contextlib import closing from logging import Logger from sqlite3 import Connection from uuid import uuid4 @@ -30,7 +31,7 @@ def logger(self) -> Logger: def init(self): try: - with sqlite3.connect(database=self.database) as conn: + with closing(sqlite3.connect(database=self.database)) as conn: cur = conn.execute("select count(1) from oauth_states;") row_num = cur.fetchone()[0] self.logger.debug(f"{row_num} oauth states are stored in {self.database}") @@ -44,7 +45,7 @@ def connect(self) -> Connection: return sqlite3.connect(database=self.database) def create_tables(self): - with sqlite3.connect(database=self.database) as conn: + with closing(sqlite3.connect(database=self.database)) as conn: conn.execute(""" create table oauth_states ( id integer primary key autoincrement, @@ -63,7 +64,7 @@ async def async_consume(self, state: str) -> bool: def issue(self, *args, **kwargs) -> str: state: str = str(uuid4()) - with self.connect() as conn: + with closing(self.connect()) as conn: parameters = [ state, time.time() + self.expiration_seconds, @@ -75,7 +76,7 @@ def issue(self, *args, **kwargs) -> str: def consume(self, state: str) -> bool: try: - with self.connect() as conn: + with closing(self.connect()) as conn: cur = conn.execute( "select id, state from oauth_states where state = ? and expire_at > ?;", [state, time.time()], diff --git a/tests/helpers.py b/tests/helpers.py index 776aa49c2..38c968eeb 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -2,7 +2,9 @@ import copy import os import sys -from typing import Any +from contextlib import contextmanager +from typing import Any, Iterator, List +from unittest.mock import patch def async_test(coro): @@ -43,3 +45,17 @@ def create_copy(original: Any) -> Any: return copy.copy(original) else: return copy.deepcopy(original) + + +@contextmanager +def record_return_values(module: Any, name: str) -> Iterator[List[Any]]: + real = getattr(module, name) + values: List[Any] = [] + + def record(*args, **kwargs): + value = real(*args, **kwargs) + values.append(value) + return value + + with patch.object(module, name, side_effect=record): + yield values diff --git a/tests/slack_sdk/oauth/installation_store/test_sqlite3.py b/tests/slack_sdk/oauth/installation_store/test_sqlite3.py index a44104a49..547da12e0 100644 --- a/tests/slack_sdk/oauth/installation_store/test_sqlite3.py +++ b/tests/slack_sdk/oauth/installation_store/test_sqlite3.py @@ -1,10 +1,11 @@ import logging +import sqlite3 import tempfile import unittest from slack_sdk.oauth.installation_store import Installation from slack_sdk.oauth.installation_store.sqlite3 import SQLite3InstallationStore -from tests.helpers import async_test +from tests.helpers import async_test, record_return_values class TestSQLite3(unittest.TestCase): @@ -403,3 +404,29 @@ def test_lookup_failure_logs_the_traceback_when_debug_is_enabled(self): self.assertEqual([record.levelno for record in logs.records], [logging.ERROR]) self.assertIsNotNone(logs.records[0].exc_info) + + def test_closes_every_connection(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + store = SQLite3InstallationStore(database=f"{directory.name}/test.db", client_id="111.222") + + with record_return_values(sqlite3, "connect") as connections: + store.save( + Installation( + app_id="A111", + team_id="T111", + user_id="U111", + bot_id="B111", + bot_token="xoxb-111", + bot_user_id="U222", + ) + ) + store.find_bot(enterprise_id=None, team_id="T111") + store.find_installation(enterprise_id=None, team_id="T111") + store.delete_bot(enterprise_id=None, team_id="T111") + store.delete_installation(enterprise_id=None, team_id="T111") + + self.assertGreater(len(connections), 0) + for connection in connections: + with self.assertRaises(sqlite3.ProgrammingError): + connection.execute("select 1") diff --git a/tests/slack_sdk/oauth/state_store/test_sqlite3.py b/tests/slack_sdk/oauth/state_store/test_sqlite3.py index 7a34dd704..42a45a9ff 100644 --- a/tests/slack_sdk/oauth/state_store/test_sqlite3.py +++ b/tests/slack_sdk/oauth/state_store/test_sqlite3.py @@ -1,6 +1,9 @@ +import sqlite3 +import tempfile import unittest from slack_sdk.oauth.state_store.sqlite3 import SQLite3OAuthStateStore +from tests.helpers import record_return_values class TestSQLite3(unittest.TestCase): @@ -27,3 +30,16 @@ def test_issue_and_consume(self): self.assertTrue(result) result = store.consume(state) self.assertFalse(result) + + def test_closes_every_connection(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + store = SQLite3OAuthStateStore(database=f"{directory.name}/test.db", expiration_seconds=10) + + with record_return_values(sqlite3, "connect") as connections: + store.consume(store.issue()) + + self.assertGreater(len(connections), 0) + for connection in connections: + with self.assertRaises(sqlite3.ProgrammingError): + connection.execute("select 1")