Skip to content

Commit 7e2c2c5

Browse files
committed
Fix client tests
1 parent 262e5c3 commit 7e2c2c5

File tree

2 files changed

+51
-36
lines changed

2 files changed

+51
-36
lines changed

cloudbot/bot.py

Lines changed: 47 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,11 @@
1818
from cloudbot import clients
1919
from cloudbot.client import Client
2020
from cloudbot.config import Config
21-
from cloudbot.event import Event, CommandEvent, RegexEvent, EventType
21+
from cloudbot.event import CommandEvent, Event, EventType, RegexEvent
2222
from cloudbot.hook import Action
2323
from cloudbot.plugin import PluginManager
24-
from cloudbot.reloader import PluginReloader, ConfigReloader
25-
from cloudbot.util import database, formatting, async_util
24+
from cloudbot.reloader import ConfigReloader, PluginReloader
25+
from cloudbot.util import async_util, database, formatting
2626
from cloudbot.util.mapping import KeyFoldDict
2727

2828
logger = logging.getLogger("cloudbot")
@@ -58,28 +58,34 @@ def clean_name(n):
5858
:type n: str
5959
:rtype: str
6060
"""
61-
return re.sub('[^A-Za-z0-9_]+', '', n.replace(" ", "_"))
61+
return re.sub("[^A-Za-z0-9_]+", "", n.replace(" ", "_"))
6262

6363

6464
def get_cmd_regex(event):
6565
conn = event.conn
6666
is_pm = event.chan.lower() == event.nick.lower()
67-
command_prefix = re.escape(conn.config.get('command_prefix', '.'))
67+
command_prefix = re.escape(conn.config.get("command_prefix", "."))
6868
conn_nick = re.escape(event.conn.nick)
6969
cmd_re = re.compile(
7070
r"""
7171
^
7272
# Prefix or nick
7373
(?:
74-
(?P<prefix>[""" + command_prefix + r"""])""" + ('?' if is_pm else '') + r"""
74+
(?P<prefix>["""
75+
+ command_prefix
76+
+ r"""])"""
77+
+ ("?" if is_pm else "")
78+
+ r"""
7579
|
76-
""" + conn_nick + r"""[,;:]+\s+
80+
"""
81+
+ conn_nick
82+
+ r"""[,;:]+\s+
7783
)
7884
(?P<command>\w+) # Command
7985
(?:$|\s+)
8086
(?P<text>.*) # Text
8187
""",
82-
re.IGNORECASE | re.VERBOSE
88+
re.IGNORECASE | re.VERBOSE,
8389
)
8490
return cmd_re
8591

@@ -126,7 +132,7 @@ def __init__(self, loop=asyncio.get_event_loop()):
126132
self.memory = collections.defaultdict()
127133

128134
# declare and create data folder
129-
self.data_dir = os.path.abspath('data')
135+
self.data_dir = os.path.abspath("data")
130136
if not os.path.exists(self.data_dir):
131137
logger.debug("Data folder not found, creating.")
132138
os.mkdir(self.data_dir)
@@ -141,11 +147,14 @@ def __init__(self, loop=asyncio.get_event_loop()):
141147
self.config_reloading_enabled = reloading_conf.get("config_reloading", True)
142148

143149
# this doesn't REALLY need to be here but it's nice
144-
self.user_agent = self.config.get('user_agent', 'CloudBot/3.0 - CloudBot Refresh '
145-
'<https://github.com/CloudBotIRC/CloudBot/>')
150+
self.user_agent = self.config.get(
151+
"user_agent",
152+
"CloudBot/3.0 - CloudBot Refresh "
153+
"<https://github.com/CloudBotIRC/CloudBot/>",
154+
)
146155

147156
# setup db
148-
db_path = self.config.get('database', 'sqlite:///cloudbot.db')
157+
db_path = self.config.get("database", "sqlite:///cloudbot.db")
149158
self.db_engine = create_engine(db_path)
150159
self.db_factory = sessionmaker(bind=self.db_engine)
151160
self.db_session = scoped_session(self.db_factory)
@@ -201,15 +210,14 @@ def register_client(self, name, cls):
201210

202211
def create_connections(self):
203212
""" Create a BotConnection for all the networks defined in the config """
204-
for config in self.config['connections']:
213+
for config in self.config["connections"]:
205214
# strip all spaces and capitalization from the connection name
206-
name = clean_name(config['name'])
207-
nick = config['nick']
215+
name = clean_name(config["name"])
216+
nick = config["nick"]
208217
_type = config.get("type", "irc")
209218

210219
self.connections[name] = self.get_client(_type)(
211-
self, _type, name, nick, config=config,
212-
channels=config['channels']
220+
self, _type, name, nick, config=config, channels=config["channels"]
213221
)
214222
logger.debug("[%s] Created connection.", name)
215223

@@ -283,7 +291,9 @@ async def _init_routine(self):
283291
conn.active = True
284292

285293
# Connect to servers
286-
await asyncio.gather(*[conn.try_connect() for conn in self.connections.values()], loop=self.loop)
294+
await asyncio.gather(
295+
*[conn.try_connect() for conn in self.connections.values()], loop=self.loop
296+
)
287297
logger.debug("Connections created.")
288298

289299
# Run a manual garbage collection cycle, to clean up any unused objects created during initialization
@@ -294,7 +304,7 @@ def load_clients(self):
294304
Load all clients from the "clients" directory
295305
"""
296306
scanner = Scanner(bot=self)
297-
scanner.scan(clients, categories=['cloudbot.client'])
307+
scanner.scan(clients, categories=["cloudbot.client"])
298308

299309
def process(self, event):
300310
"""
@@ -348,12 +358,16 @@ def add_hook(hook, _event):
348358
cmd_match = get_cmd_regex(event).match(event.content)
349359

350360
if cmd_match:
351-
command_prefix = event.conn.config.get('command_prefix', '.')
352-
prefix = cmd_match.group('prefix') or command_prefix[0]
353-
command = cmd_match.group('command').lower()
354-
text = cmd_match.group('text').strip()
361+
command_prefix = event.conn.config.get("command_prefix", ".")
362+
prefix = cmd_match.group("prefix") or command_prefix[0]
363+
command = cmd_match.group("command").lower()
364+
text = cmd_match.group("text").strip()
355365
cmd_event = partial(
356-
CommandEvent, text=text, triggered_command=command, base_event=event, cmd_prefix=prefix
366+
CommandEvent,
367+
text=text,
368+
triggered_command=command,
369+
base_event=event,
370+
cmd_prefix=prefix,
357371
)
358372
if command in self.plugin_manager.commands:
359373
command_hook = self.plugin_manager.commands[command]
@@ -373,7 +387,9 @@ def add_hook(hook, _event):
373387
command_event = cmd_event(hook=command_hook)
374388
add_hook(command_hook, command_event)
375389
else:
376-
commands = sorted(command for command, plugin in potential_matches)
390+
commands = sorted(
391+
command for command, plugin in potential_matches
392+
)
377393
txt_list = formatting.get_text_list(commands)
378394
event.notice("Possible matches: {}".format(txt_list))
379395

@@ -390,12 +406,16 @@ def add_hook(hook, _event):
390406
regex_match = regex.search(event.content)
391407
if regex_match:
392408
regex_matched = True
393-
regex_event = RegexEvent(hook=regex_hook, match=regex_match, base_event=event)
409+
regex_event = RegexEvent(
410+
hook=regex_hook, match=regex_match, base_event=event
411+
)
394412
if not add_hook(regex_hook, regex_event):
395413
# The hook has an action of Action.HALT* so stop adding new tasks
396414
break
397415

398416
tasks.sort(key=lambda t: t[0].priority)
399417

400418
for _hook, _event in tasks:
401-
async_util.wrap_future(self.plugin_manager.launch(_hook, _event))
419+
async_util.wrap_future(
420+
self.plugin_manager.launch(_hook, _event), loop=self.loop
421+
)

tests/core_tests/irc_client_test.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import asyncio
2-
from asyncio import Task
32
from unittest.mock import MagicMock
43

54
from cloudbot.clients.irc import _IrcProtocol
@@ -11,13 +10,11 @@ def _filter_event(self, event):
1110
return {k: v for k, v in dict(event).items() if not callable(v)}
1211

1312
def test_data_received(self):
14-
conn, out, proto = self.make_proto()
13+
_, out, proto = self.make_proto()
1514
proto.data_received(
1615
b":server.host COMMAND this is :a command\r\n:server.host PRIVMSG me :hi\r\n"
1716
)
1817

19-
conn.loop.run_until_complete(asyncio.gather(*Task.all_tasks(conn.loop)))
20-
2118
assert out == [
2219
{
2320
"chan": None,
@@ -62,24 +59,22 @@ def test_data_received(self):
6259
def make_proto(self):
6360
conn = MagicMock()
6461
conn.nick = "me"
65-
conn.loop = asyncio.get_event_loop_policy().new_event_loop()
62+
conn.loop = conn.bot.loop = asyncio.get_event_loop_policy().new_event_loop()
6663
out = []
6764

68-
async def func(e):
65+
def func(e):
6966
out.append(self._filter_event(e))
7067

7168
conn.bot.process = func
7269
proto = _IrcProtocol(conn)
7370
return conn, out, proto
7471

7572
def test_broken_line_doesnt_interrupt(self):
76-
conn, out, proto = self.make_proto()
73+
_, out, proto = self.make_proto()
7774
proto.data_received(
7875
b":server.host COMMAND this is :a command\r\nPRIVMSG\r\n:server.host PRIVMSG me :hi\r\n"
7976
)
8077

81-
conn.loop.run_until_complete(asyncio.gather(*Task.all_tasks(conn.loop)))
82-
8378
assert out == [
8479
{
8580
"chan": None,

0 commit comments

Comments
 (0)