Skip to content

Commit 492dbf5

Browse files
authored
Merge pull request #678 from TotallyNotRobots/regex-chans-coverage
Add coverage of regex_chans db access
2 parents e08663a + 85474e7 commit 492dbf5

File tree

2 files changed

+828
-60
lines changed

2 files changed

+828
-60
lines changed

plugins/core/regex_chans.py

Lines changed: 80 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
import logging
2-
from typing import Dict, Tuple
2+
from typing import TYPE_CHECKING, Dict, Optional, Tuple
33

44
from sqlalchemy import Column, String, Table, UniqueConstraint
55

66
from cloudbot import hook
77
from cloudbot.util import database
88

9+
if TYPE_CHECKING:
10+
from cloudbot.bot import CloudBot
11+
from cloudbot.client import Client
12+
from cloudbot.event import Event
13+
from cloudbot.plugin_hooks import Hook
14+
915
table = Table(
1016
"regex_chans",
1117
database.metadata,
@@ -15,11 +21,14 @@
1521
UniqueConstraint("connection", "channel"),
1622
)
1723

24+
ENABLED = "ENABLED"
25+
DISABLED = "DISABLED"
26+
1827
# Default value.
1928
# If True, all channels without a setting will have regex enabled
2029
# If False, all channels without a setting will have regex disabled
2130
default_enabled = True
22-
status_cache: Dict[Tuple[str, str], str] = {}
31+
status_cache: Dict[Tuple[str, str], bool] = {}
2332
logger = logging.getLogger("cloudbot")
2433

2534

@@ -30,27 +39,44 @@ def load_cache(db):
3039
conn = row["connection"]
3140
chan = row["channel"]
3241
status = row["status"]
33-
new_cache[(conn, chan)] = status
42+
if status == ENABLED:
43+
value = True
44+
elif status == DISABLED:
45+
value = False
46+
else:
47+
# Unknown values just use the default (existing behavior)
48+
logger.warning(
49+
"[regex_chans] Unknown status: %s, falling back to default",
50+
tuple(row),
51+
)
52+
continue
53+
54+
new_cache[(conn, chan)] = value
3455

3556
status_cache.clear()
3657
status_cache.update(new_cache)
3758

3859

39-
def set_status(db, conn, chan, status):
60+
def set_status(db, conn, chan, status: bool):
61+
status_value = ENABLED if status else DISABLED
4062
if (conn, chan) in status_cache:
4163
# if we have a set value, update
4264
db.execute(
4365
table.update()
44-
.values(status=status)
66+
.values(status=status_value)
4567
.where(table.c.connection == conn)
4668
.where(table.c.channel == chan)
4769
)
4870
else:
4971
# otherwise, insert
5072
db.execute(
51-
table.insert().values(connection=conn, channel=chan, status=status)
73+
table.insert().values(
74+
connection=conn, channel=chan, status=status_value
75+
)
5276
)
77+
5378
db.commit()
79+
load_cache(db)
5480

5581

5682
def delete_status(db, conn, chan):
@@ -59,27 +85,59 @@ def delete_status(db, conn, chan):
5985
.where(table.c.connection == conn)
6086
.where(table.c.channel == chan)
6187
)
88+
6289
db.commit()
90+
load_cache(db)
91+
92+
93+
def get_status(conn: "Client", chan: str) -> bool:
94+
return status_cache.get((conn.name, chan), default_enabled)
95+
96+
97+
def parse_args(text: str, chan: str) -> str:
98+
text = text.strip().lower()
99+
if not text:
100+
channel = chan
101+
elif text.startswith("#"):
102+
channel = text
103+
else:
104+
channel = f"#{text}"
105+
106+
return channel
107+
108+
109+
def change_status(db, event, status):
110+
channel = parse_args(event.text, event.chan)
111+
action = "Enabling" if status else "Disabling"
112+
event.message(
113+
"{} regex matching (youtube, etc) (issued by {})".format(
114+
action, event.nick
115+
),
116+
target=channel,
117+
)
118+
119+
event.notice(f"{action} regex matching (youtube, etc) in channel {channel}")
120+
set_status(db, event.conn.name, channel, status)
63121

64122

65123
@hook.sieve()
66-
def sieve_regex(bot, event, _hook):
124+
def sieve_regex(
125+
bot: "CloudBot", event: "Event", _hook: "Hook"
126+
) -> Optional["Event"]:
67127
if (
68128
_hook.type == "regex"
69129
and event.chan.startswith("#")
70130
and _hook.plugin.title != "factoids"
71131
):
72-
status = status_cache.get((event.conn.name, event.chan))
73-
if status != "ENABLED" and (
74-
status == "DISABLED" or not default_enabled
75-
):
132+
if not get_status(event.conn, event.chan):
76133
logger.info(
77134
"[%s] Denying %s from %s",
78135
event.conn.name,
79136
_hook.function_name,
80137
event.chan,
81138
)
82139
return None
140+
83141
logger.info(
84142
"[%s] Allowing %s to %s",
85143
event.conn.name,
@@ -90,29 +148,6 @@ def sieve_regex(bot, event, _hook):
90148
return event
91149

92150

93-
def change_status(db, event, status):
94-
text = event.text.strip().lower()
95-
if not text:
96-
channel = event.chan
97-
elif text.startswith("#"):
98-
channel = text
99-
else:
100-
channel = f"#{text}"
101-
102-
action = "Enabling" if status else "Disabling"
103-
event.message(
104-
"{} regex matching (youtube, etc) (issued by {})".format(
105-
action, event.nick
106-
),
107-
target=channel,
108-
)
109-
event.notice(f"{action} regex matching (youtube, etc) in channel {channel}")
110-
set_status(
111-
db, event.conn.name, channel, "ENABLED" if status else "DISABLED"
112-
)
113-
load_cache(db)
114-
115-
116151
@hook.command(autohelp=False, permissions=["botcontrol"])
117152
def enableregex(db, event):
118153
"""[chan] - Enable regex hooks in [chan] (default: current channel)"""
@@ -128,54 +163,39 @@ def disableregex(db, event):
128163
@hook.command(autohelp=False, permissions=["botcontrol"])
129164
def resetregex(text, db, conn, chan, nick, message, notice):
130165
"""[chan] - Reset regex hook status in [chan] (default: current channel)"""
131-
text = text.strip().lower()
132-
if not text:
133-
channel = chan
134-
elif text.startswith("#"):
135-
channel = text
136-
else:
137-
channel = f"#{text}"
138-
166+
channel = parse_args(text, chan)
139167
message(
140168
"Resetting regex matching setting (youtube, etc) (issued by {})".format(
141169
nick
142170
),
143171
target=channel,
144172
)
173+
145174
notice(
146175
"Resetting regex matching setting (youtube, etc) in channel {}".format(
147176
channel
148177
)
149178
)
179+
150180
delete_status(db, conn.name, channel)
151-
load_cache(db)
152181

153182

154183
@hook.command(autohelp=False, permissions=["botcontrol"])
155-
def regexstatus(text, conn, chan):
184+
def regexstatus(text: str, conn: "Client", chan: str) -> str:
156185
"""[chan] - Get status of regex hooks in [chan] (default: current channel)"""
157-
text = text.strip().lower()
158-
if not text:
159-
channel = chan
160-
elif text.startswith("#"):
161-
channel = text
162-
else:
163-
channel = f"#{text}"
164-
status = status_cache.get((conn.name, chan))
165-
if status is None:
166-
if default_enabled:
167-
status = "ENABLED"
168-
else:
169-
status = "DISABLED"
170-
return f"Regex status for {channel}: {status}"
186+
channel = parse_args(text, chan)
187+
status = get_status(conn, channel)
188+
return f"Regex status for {channel}: {ENABLED if status else DISABLED}"
171189

172190

173191
@hook.command(autohelp=False, permissions=["botcontrol"])
174-
def listregex(conn):
192+
def listregex(conn: "Client") -> str:
175193
"""- List non-default regex statuses for channels"""
176194
values = []
177195
for (conn_name, chan), status in status_cache.items():
178196
if conn_name != conn.name:
179197
continue
180-
values.append(f"{chan}: {status}")
198+
199+
values.append(f"{chan}: {ENABLED if status else DISABLED}")
200+
181201
return ", ".join(values)

0 commit comments

Comments
 (0)