Skip to content
17 changes: 9 additions & 8 deletions slack_sdk/oauth/installation_store/sqlite3/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging
import sqlite3
from contextlib import closing
from logging import Logger
from sqlite3 import Connection
from typing import Optional
Expand Down Expand Up @@ -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}")
Expand All @@ -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,
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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 (
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
"""
Expand Down
9 changes: 5 additions & 4 deletions slack_sdk/oauth/state_store/sqlite3/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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}")
Expand All @@ -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,
Expand All @@ -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,
Expand All @@ -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()],
Expand Down
18 changes: 17 additions & 1 deletion tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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]]:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

praise: Keeping each connection alive is the clever bit here, since without it garbage collection closes them and the test would pass on main too.

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
29 changes: 28 additions & 1 deletion tests/slack_sdk/oauth/installation_store/test_sqlite3.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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")
16 changes: 16 additions & 0 deletions tests/slack_sdk/oauth/state_store/test_sqlite3.py
Original file line number Diff line number Diff line change
@@ -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):
Expand All @@ -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")