Debian Codegraph @

tests/base_backend_test.py

raw ◀ ▶
1 Debian patch touch this file
1 # coding=utf-8
2 import logging
3 import os # noqa
4 import re # noqa
5 import sys
6 from collections import OrderedDict
7 from os.path import sep
8 from pathlib import Path
9 from queue import Empty, Queue # noqa
10 from tempfile import mkdtemp
11
12 import pytest
13
14 from errbot import arg_botcmd, botcmd, re_botcmd, templating # noqa
15 from errbot.backend_plugin_manager import BackendPluginManager
16 from errbot.backends.base import ONLINE, Identifier, Message, Room
17 from errbot.backends.test import (
18 ShallowConfig,
19 TestOccupant,
20 TestPerson,
21 TestRoom,
22 TestRoomAcl,
23 )
24 from errbot.bootstrap import CORE_STORAGE, bot_config_defaults
25 from errbot.core import ErrBot
26 from errbot.core_plugins.acls import ACLS
27 from errbot.plugin_manager import BotPluginManager
28 from errbot.rendering import text
29 from errbot.repo_manager import BotRepoManager
30 from errbot.storage.base import StoragePluginBase
31 from errbot.utils import PLUGINS_SUBDIR
32
33 LONG_TEXT_STRING = (
34 "This is a relatively long line of output, but I am repeated multiple times.\n"
35 )
36
37 logging.basicConfig(level=logging.DEBUG)
38
39 SIMPLE_JSON_PLUGINS_INDEX = """
40 {"errbotio/err-helloworld":
41 {"HelloWorld":
42 {"path": "/helloWorld.plug",
43 "documentation": "let's say hello!",
44 "avatar_url": "https://avatars.githubusercontent.com/u/15802630?v=3",
45 "name": "HelloWorld",
46 "python": "2+",
47 "repo": "https://github.com/errbotio/err-helloworld"
48 }
49 }
50 }
51 """
52
53
54 class DummyBackend(ErrBot):
55 def change_presence(self, status: str = ONLINE, message: str = "") -> None:
56 pass
57
58 def prefix_groupchat_reply(self, message: Message, identifier: Identifier):
59 pass
60
61 def query_room(self, room: str) -> Room:
62 pass
63
64 def __init__(self, extra_config=None):
65 self.outgoing_message_queue = Queue()
66 if extra_config is None:
67 extra_config = {}
68 # make up a config.
69 tempdir = mkdtemp()
70 # reset the config every time
71 sys.modules.pop("errbot.config-template", None)
72 __import__("errbot.config-template")
73 config = ShallowConfig()
74 config.__dict__.update(sys.modules["errbot.config-template"].__dict__)
75 bot_config_defaults(config)
76
77 # It injects itself as a plugin. Changed the name to be sure we distinguish it.
78 self.name = "DummyBackendRealName"
79
80 config.BOT_DATA_DIR = tempdir
81 config.BOT_LOG_FILE = tempdir + sep + "log.txt"
82 config.BOT_PLUGIN_INDEXES = tempdir + sep + "repos.json"
83 config.BOT_EXTRA_PLUGIN_DIR = []
84 config.BOT_LOG_LEVEL = logging.DEBUG
85 config.BOT_IDENTITY = {"username": "err@localhost"}
86 config.BOT_ASYNC = False
87 config.BOT_PREFIX = "!"
88 config.CHATROOM_FN = "blah"
89
90 # Writeout the made up repos file
91 with open(config.BOT_PLUGIN_INDEXES, "w") as index_file:
92 index_file.write(SIMPLE_JSON_PLUGINS_INDEX)
93
94 for key in extra_config:
95 setattr(config, key, extra_config[key])
96 super().__init__(config)
97 self.bot_identifier = self.build_identifier("err")
98 self.md = text() # We just want simple text for testing purposes
99
100 # setup a memory based storage
101 spm = BackendPluginManager(
102 config, "errbot.storage", "Memory", StoragePluginBase, CORE_STORAGE
103 )
104 storage_plugin = spm.load_plugin()
105
106 # setup the plugin_manager just internally
107 botplugins_dir = os.path.join(config.BOT_DATA_DIR, PLUGINS_SUBDIR)
108 if not os.path.exists(botplugins_dir):
109 os.makedirs(botplugins_dir, mode=0o755)
110
111 # get it back from where we publish it.
112 repo_index_paths = (
113 os.path.join(
114 os.path.dirname(__file__), "..", "docs", "_extra", "repos.json"
115 ),
116 )
117 repo_manager = BotRepoManager(storage_plugin, botplugins_dir, repo_index_paths)
118 self.attach_storage_plugin(storage_plugin)
119 self.attach_repo_manager(repo_manager)
120 self.attach_plugin_manager(
121 BotPluginManager(
122 storage_plugin,
123 config.BOT_EXTRA_PLUGIN_DIR,
124 config.AUTOINSTALL_DEPS,
125 getattr(config, "CORE_PLUGINS", None),
126 lambda name, clazz: clazz(self, name),
127 getattr(config, "PLUGINS_CALLBACK_ORDER", (None,)),
128 )
129 )
130 self.inject_commands_from(self)
131 self.inject_command_filters_from(ACLS(self))
132
133 def build_identifier(self, text_representation):
134 return TestPerson(text_representation)
135
136 def build_reply(self, msg, text=None, private=False, threaded=False):
137 reply = self.build_message(text)
138 reply.frm = self.bot_identifier
139 reply.to = msg.frm
140 if threaded:
141 reply.parent = msg
142 return reply
143
144 def send_message(self, msg):
145 msg._body = self.md.convert(msg.body)
146 self.outgoing_message_queue.put(msg)
147
148 def pop_message(self, timeout=3, block=True):
149 return self.outgoing_message_queue.get(timeout=timeout, block=block)
150
151 @botcmd
152 def command(self, msg, args):
153 return "Regular command"
154
155 @botcmd(admin_only=True)
156 def admin_command(self, msg, args):
157 return "Admin command"
158
159 @re_botcmd(pattern=r"^regex command with prefix$", prefixed=True)
160 def regex_command_with_prefix(self, msg, match):
161 return "Regex command"
162
163 @re_botcmd(pattern=r"^regex command without prefix$", prefixed=False)
164 def regex_command_without_prefix(self, msg, match):
165 return "Regex command"
166
167 @re_botcmd(
168 pattern=r"regex command with capture group: (?P<capture>.*)", prefixed=False
169 )
170 def regex_command_with_capture_group(self, msg, match):
171 return match.group("capture")
172
173 @re_botcmd(pattern=r"matched by two commands")
174 def double_regex_command_one(self, msg, match):
175 return "one"
176
177 @re_botcmd(pattern=r"matched by two commands", flags=re.IGNORECASE)
178 def double_regex_command_two(self, msg, match):
179 return "two"
180
181 @re_botcmd(pattern=r"match_here", matchall=True)
182 def regex_command_with_matchall(self, msg, matches):
183 return len(matches)
184
185 @botcmd
186 def return_args_as_str(self, msg, args):
187 return "".join(args)
188
189 @botcmd(template="args_as_md")
190 def return_args_as_md(self, msg, args):
191 return {"args": args}
192
193 @botcmd
194 def send_args_as_md(self, msg, args):
195 self.send_templated(msg.frm, "args_as_md", {"args": args})
196
197 @botcmd
198 def raises_exception(self, msg, args):
199 raise Exception("Kaboom!")
200
201 @botcmd
202 def yield_args_as_str(self, msg, args):
203 for arg in args:
204 yield arg
205
206 @botcmd(template="args_as_md")
207 def yield_args_as_md(self, msg, args):
208 for arg in args:
209 yield {"args": [arg]}
210
211 @botcmd
212 def yields_str_then_raises_exception(self, msg, args):
213 yield "foobar"
214 raise Exception("Kaboom!")
215
216 @botcmd
217 def return_long_output(self, msg, args):
218 return LONG_TEXT_STRING * 3
219
220 @botcmd
221 def yield_long_output(self, msg, args):
222 for i in range(2):
223 yield LONG_TEXT_STRING * 3
224
225 ##
226 # arg_botcmd test commands
227 ##
228
229 @arg_botcmd("--first-name", dest="first_name")
230 @arg_botcmd("--last-name", dest="last_name")
231 def yields_first_name_last_name(self, msg, first_name=None, last_name=None):
232 yield "%s %s" % (first_name, last_name)
233
234 @arg_botcmd("--first-name", dest="first_name")
235 @arg_botcmd("--last-name", dest="last_name")
236 def returns_first_name_last_name(self, msg, first_name=None, last_name=None):
237 return "%s %s" % (first_name, last_name)
238
239 @arg_botcmd("--first-name", dest="first_name")
240 @arg_botcmd("--last-name", dest="last_name", unpack_args=False)
241 def returns_first_name_last_name_without_unpacking(self, msg, args):
242 return "%s %s" % (args.first_name, args.last_name)
243
244 @arg_botcmd("value", type=str)
245 @arg_botcmd("--count", dest="count", type=int)
246 def returns_value_repeated_count_times(self, msg, value=None, count=None):
247 # str * int gives a repeated string
248 return value * count
249
250 @property
251 def mode(self):
252 return "Dummy"
253
254 @property
255 def rooms(self):
256 return []
257
258
259 @pytest.fixture
•260 def dummy_backend(request):
261 def on_finish():
262 backend.flow_executor._pool.close()
263 backend.flow_executor._pool.join()
264
265 backend = DummyBackend()
266 request.addfinalizer(on_finish)
267 return backend
268
269
270 def test_buildreply(dummy_backend):
271 m = dummy_backend.build_message("Content")
272 m.frm = dummy_backend.build_identifier("user")
273 m.to = dummy_backend.build_identifier("somewhere")
274 resp = dummy_backend.build_reply(m, "Response")
275
276 assert str(resp.to) == "user"
277 assert str(resp.frm) == "err"
278 assert str(resp.body) == "Response"
279 assert resp.parent is None
280
281
282 def test_buildreply_with_parent(dummy_backend):
283 m = dummy_backend.build_message("Content")
284 m.frm = dummy_backend.build_identifier("user")
285 m.to = dummy_backend.build_identifier("somewhere")
286 resp = dummy_backend.build_reply(m, "Response", threaded=True)
287
288 assert resp.parent is not None
289
290
291 def test_all_command_private():
292 dummy_backend = DummyBackend(extra_config={"DIVERT_TO_PRIVATE": ("ALL_COMMANDS",)})
293 m = dummy_backend.build_message("Content")
294 m.frm = dummy_backend.build_identifier("user")
295 m.to = dummy_backend.build_identifier("somewhere")
296 resp = dummy_backend.build_reply(m, "Response", threaded=True)
297 assert "ALL_COMMANDS" in dummy_backend.bot_config.DIVERT_TO_PRIVATE
298 assert resp is not None
299
300
301 def test_bot_admins_unique_string():
302 dummy = DummyBackend(extra_config={"BOT_ADMINS": "err@localhost"})
303 assert dummy.bot_config.BOT_ADMINS == ("err@localhost",)
304
305
306 @pytest.fixture
307 def dummy_execute_and_send():
308 dummy = DummyBackend()
309 example_message = dummy.build_message("some_message")
310 example_message.frm = dummy.build_identifier("noterr")
311 example_message.to = dummy.build_identifier("err")
312
313 assets_path = os.path.join(os.path.dirname(__file__), "assets")
314 templating.template_path.append(
315 str(templating.make_templates_path(Path(assets_path)))
316 )
317 templating.env = templating.Environment(
318 loader=templating.FileSystemLoader(templating.template_path)
319 )
320 return dummy, example_message
321
322
323 def test_commands_can_return_string(dummy_execute_and_send):
324 dummy, m = dummy_execute_and_send
325
326 dummy._execute_and_send(
327 cmd="return_args_as_str",
328 args=["foo", "bar"],
329 match=None,
330 msg=m,
331 template_name=dummy.return_args_as_str._err_command_template,
332 )
333 assert "foobar" == dummy.pop_message().body
334
335
336 def test_commands_can_return_md(dummy_execute_and_send):
337 dummy, m = dummy_execute_and_send
338 dummy._execute_and_send(
339 cmd="return_args_as_md",
340 args=["foo", "bar"],
341 match=None,
342 msg=m,
343 template_name=dummy.return_args_as_md._err_command_template,
344 )
345 response = dummy.pop_message()
346 assert "foobar" == response.body
347
348
349 def test_commands_can_send_templated(dummy_execute_and_send):
350 dummy, m = dummy_execute_and_send
351 dummy._execute_and_send(
352 cmd="send_args_as_md",
353 args=["foo", "bar"],
354 match=None,
355 msg=m,
356 template_name=dummy.return_args_as_md._err_command_template,
357 )
358 response = dummy.pop_message()
359 assert "foobar" == response.body
360
361
362 def test_exception_is_caught_and_shows_error_message(dummy_execute_and_send):
363 dummy, m = dummy_execute_and_send
364 dummy._execute_and_send(
365 cmd="raises_exception",
366 args=[],
367 match=None,
368 msg=m,
369 template_name=dummy.raises_exception._err_command_template,
370 )
371 assert dummy.MSG_ERROR_OCCURRED in dummy.pop_message().body
372
373 dummy._execute_and_send(
374 cmd="yields_str_then_raises_exception",
375 args=[],
376 match=None,
377 msg=m,
378 template_name=dummy.yields_str_then_raises_exception._err_command_template,
379 )
380 assert "foobar" == dummy.pop_message().body
381 assert dummy.MSG_ERROR_OCCURRED in dummy.pop_message().body
382
383
384 def test_commands_can_yield_strings(dummy_execute_and_send):
385 dummy, m = dummy_execute_and_send
386 dummy._execute_and_send(
387 cmd="yield_args_as_str",
388 args=["foo", "bar"],
389 match=None,
390 msg=m,
391 template_name=dummy.yield_args_as_str._err_command_template,
392 )
393 assert "foo" == dummy.pop_message().body
394 assert "bar" == dummy.pop_message().body
395
396
397 def test_commands_can_yield_md(dummy_execute_and_send):
398 dummy, m = dummy_execute_and_send
399 dummy._execute_and_send(
400 cmd="yield_args_as_md",
401 args=["foo", "bar"],
402 match=None,
403 msg=m,
404 template_name=dummy.yield_args_as_md._err_command_template,
405 )
406 assert "foo" == dummy.pop_message().body
407 assert "bar" == dummy.pop_message().body
408
409
410 def test_output_longer_than_max_msg_size_is_split_into_multiple_msgs_when_returned(
411 dummy_execute_and_send,
412 ):
413 dummy, m = dummy_execute_and_send
414 dummy.bot_config.MESSAGE_SIZE_LIMIT = len(LONG_TEXT_STRING)
415
416 dummy._execute_and_send(
417 cmd="return_long_output",
418 args=["foo", "bar"],
419 match=None,
420 msg=m,
421 template_name=dummy.return_long_output._err_command_template,
422 )
423 for i in range(
424 3
425 ): # return_long_output outputs a string that's 3x longer than the size limit
426 assert LONG_TEXT_STRING.strip() == dummy.pop_message().body
427
428 with pytest.raises(Empty):
429 dummy.pop_message(block=False)
430
431
432 def test_output_longer_than_max_msg_size_is_split_into_multiple_msgs_when_yielded(
433 dummy_execute_and_send,
434 ):
435 dummy, m = dummy_execute_and_send
436 dummy.bot_config.MESSAGE_SIZE_LIMIT = len(LONG_TEXT_STRING)
437
438 dummy._execute_and_send(
439 cmd="yield_long_output",
440 args=["foo", "bar"],
441 match=None,
442 msg=m,
443 template_name=dummy.yield_long_output._err_command_template,
444 )
445 for i in range(
446 6
447 ): # yields_long_output yields 2 strings that are 3x longer than the size limit
448 assert LONG_TEXT_STRING.strip() == dummy.pop_message().body
449 with pytest.raises(Empty):
450 dummy.pop_message(block=False)
451
452
453 def makemessage(dummy, message, from_=None, to=None):
454 if not from_:
455 from_ = dummy.build_identifier("noterr")
456 if not to:
457 to = dummy.build_identifier("noterr")
458 m = dummy.build_message(message)
459 m.frm = from_
460 m.to = to
461 return m
462
463
464 def test_inject_skips_methods_without_botcmd_decorator(dummy_backend):
465 assert "build_message" not in dummy_backend.commands
466
467
468 def test_inject_and_remove_botcmd(dummy_backend):
469 assert "command" in dummy_backend.commands
470 dummy_backend.remove_commands_from(dummy_backend)
471 assert len(dummy_backend.commands) == 0
472
473
474 def test_inject_and_remove_re_botcmd(dummy_backend):
475 assert "regex_command_with_prefix" in dummy_backend.re_commands
476 dummy_backend.remove_commands_from(dummy_backend)
477 assert len(dummy_backend.re_commands) == 0
478
479
480 def test_callback_message(dummy_backend):
481 dummy_backend.callback_message(
482 makemessage(dummy_backend, "!return_args_as_str one two")
483 )
484 assert "one two" == dummy_backend.pop_message().body
485
486
487 def test_callback_message_with_prefix_optional():
488 dummy = DummyBackend({"BOT_PREFIX_OPTIONAL_ON_CHAT": True})
489 m = makemessage(dummy, "return_args_as_str one two")
490 dummy.callback_message(m)
491 assert "one two" == dummy.pop_message().body
492
493 # Groupchat should still require the prefix
494 m.frm = TestOccupant("someone", "room")
495 room = TestRoom("room", bot=dummy)
496 m.to = room
497 dummy.callback_message(m)
498
499 with pytest.raises(Empty):
500 dummy.pop_message(block=False)
501
502 m = makemessage(
503 dummy,
504 "!return_args_as_str one two",
505 from_=TestOccupant("someone", "room"),
506 to=room,
507 )
508 dummy.callback_message(m)
509 assert "one two" == dummy.pop_message().body
510
511
512 def test_callback_message_with_bot_alt_prefixes():
513 dummy = DummyBackend(
514 {"BOT_ALT_PREFIXES": ("Err",), "BOT_ALT_PREFIX_SEPARATORS": (",", ";")}
515 )
516 dummy.callback_message(makemessage(dummy, "Err return_args_as_str one two"))
517 assert "one two" == dummy.pop_message().body
518 dummy.callback_message(makemessage(dummy, "Err, return_args_as_str one two"))
519 assert "one two" == dummy.pop_message().body
520
521
522 def test_callback_message_with_re_botcmd(dummy_backend):
523 dummy_backend.callback_message(
524 makemessage(dummy_backend, "!regex command with prefix")
525 )
526 assert "Regex command" == dummy_backend.pop_message().body
527 dummy_backend.callback_message(
528 makemessage(dummy_backend, "regex command without prefix")
529 )
530 assert "Regex command" == dummy_backend.pop_message().body
531 dummy_backend.callback_message(
532 makemessage(dummy_backend, "!regex command with capture group: Captured text")
533 )
534 assert "Captured text" == dummy_backend.pop_message().body
535 dummy_backend.callback_message(
536 makemessage(dummy_backend, "regex command with capture group: Captured text")
537 )
538 assert "Captured text" == dummy_backend.pop_message().body
539 dummy_backend.callback_message(
540 makemessage(
541 dummy_backend,
542 "This command also allows extra text in front - regex "
543 "command with capture group: Captured text",
544 )
545 )
546 assert "Captured text" == dummy_backend.pop_message().body
547
548
549 def test_callback_message_with_re_botcmd_and_alt_prefixes():
550 dummy_backend = DummyBackend(
551 {"BOT_ALT_PREFIXES": ("Err",), "BOT_ALT_PREFIX_SEPARATORS": (",", ";")}
552 )
553 dummy_backend.callback_message(
554 makemessage(dummy_backend, "!regex command with prefix")
555 )
556 assert "Regex command" == dummy_backend.pop_message().body
557 dummy_backend.callback_message(
558 makemessage(dummy_backend, "Err regex command with prefix")
559 )
560 assert "Regex command" == dummy_backend.pop_message().body
561 dummy_backend.callback_message(
562 makemessage(dummy_backend, "Err, regex command with prefix")
563 )
564 assert "Regex command" == dummy_backend.pop_message().body
565 dummy_backend.callback_message(
566 makemessage(dummy_backend, "regex command without prefix")
567 )
568 assert "Regex command" == dummy_backend.pop_message().body
569 dummy_backend.callback_message(
570 makemessage(dummy_backend, "!regex command with capture group: Captured text")
571 )
572 assert "Captured text" == dummy_backend.pop_message().body
573 dummy_backend.callback_message(
574 makemessage(dummy_backend, "regex command with capture group: Captured text")
575 )
576 assert "Captured text" == dummy_backend.pop_message().body
577 dummy_backend.callback_message(
578 makemessage(
579 dummy_backend,
580 "This command also allows extra text in front - "
581 "regex command with capture group: Captured text",
582 )
583 )
584 assert "Captured text" == dummy_backend.pop_message().body
585 dummy_backend.callback_message(
586 makemessage(
587 dummy_backend, "Err, regex command with capture group: Captured text"
588 )
589 )
590 assert "Captured text" == dummy_backend.pop_message().body
591 dummy_backend.callback_message(
592 makemessage(
593 dummy_backend,
594 "Err This command also allows extra text in front - "
595 "regex command with capture group: Captured text",
596 )
597 )
598 assert "Captured text" == dummy_backend.pop_message().body
599 dummy_backend.callback_message(makemessage(dummy_backend, "!match_here"))
600 assert "1" == dummy_backend.pop_message().body
601 dummy_backend.callback_message(
602 makemessage(dummy_backend, "!match_here match_here match_here")
603 )
604 assert "3" == dummy_backend.pop_message().body
605
606
607 def test_regex_commands_can_overlap(dummy_backend):
608 dummy_backend.callback_message(
609 makemessage(dummy_backend, "!matched by two commands")
610 )
611 response = (dummy_backend.pop_message().body, dummy_backend.pop_message().body)
612 assert response == ("one", "two") or response == ("two", "one")
613
614
615 def test_regex_commands_allow_passing_re_flags(dummy_backend):
616 dummy_backend.callback_message(
617 makemessage(dummy_backend, "!MaTcHeD By TwO cOmMaNdS")
618 )
619 assert "two" == dummy_backend.pop_message().body
620 with pytest.raises(Empty):
621 dummy_backend.pop_message(timeout=1)
622
623
624 def test_arg_botcmd_returns_first_name_last_name(dummy_backend):
625 dummy_backend.callback_message(
626 makemessage(
627 dummy_backend,
628 "!returns_first_name_last_name --first-name=Err --last-name=Bot",
629 )
630 )
631 assert "Err Bot"
632
633
634 def test_arg_botcmd_returns_with_escaping(dummy_backend):
635 first_name = 'Err\\"'
636 last_name = "Bot"
637 dummy_backend.callback_message(
638 makemessage(
639 dummy_backend,
640 "!returns_first_name_last_name --first-name=%s --last-name=%s"
641 % (first_name, last_name),
642 )
643 )
644 assert 'Err" Bot' == dummy_backend.pop_message().body
645
646
647 def test_arg_botcmd_returns_with_incorrect_escaping(dummy_backend):
648 first_name = 'Err"'
649 last_name = "Bot"
650 dummy_backend.callback_message(
651 makemessage(
652 dummy_backend,
653 "!returns_first_name_last_name --first-name=%s --last-name=%s"
654 % (first_name, last_name),
655 )
656 )
657 assert (
658 "I couldn't parse this command; No closing quotation"
659 in dummy_backend.pop_message().body
660 )
661
662
663 def test_arg_botcmd_yields_first_name_last_name(dummy_backend):
664 dummy_backend.callback_message(
665 makemessage(
666 dummy_backend,
667 "!yields_first_name_last_name --first-name=Err --last-name=Bot",
668 )
669 )
670 assert "Err Bot" == dummy_backend.pop_message().body
671
672
673 def test_arg_botcmd_returns_value_repeated_count_times(dummy_backend):
674 dummy_backend.callback_message(
675 makemessage(dummy_backend, "!returns_value_repeated_count_times Foo --count 5")
676 )
677 assert "FooFooFooFooFoo" == dummy_backend.pop_message().body
678
679
680 def test_arg_botcmd_doesnt_raise_systemerror(dummy_backend):
681 dummy_backend.callback_message(
682 makemessage(dummy_backend, "!returns_first_name_last_name --invalid-parameter")
683 )
684
685
686 def test_arg_botcdm_returns_errors_as_chat(dummy_backend):
687 dummy_backend.callback_message(
688 makemessage(dummy_backend, "!returns_first_name_last_name --invalid-parameter")
689 )
690 assert (
691 "I couldn't parse the arguments; unrecognized arguments: --invalid-parameter"
692 in dummy_backend.pop_message().body
693 )
694
695
696 def test_arg_botcmd_returns_help_message_as_chat(dummy_backend):
697 dummy_backend.callback_message(
698 makemessage(dummy_backend, "!returns_first_name_last_name --help")
699 )
700 assert (
701 "usage: returns_first_name_last_name [-h] [--last-name LAST_NAME]"
702 in dummy_backend.pop_message().body
703 )
704
705
706 def test_arg_botcmd_undoes_fancy_unicode_dash_conversion(dummy_backend):
707 dummy_backend.callback_message(
708 makemessage(
709 dummy_backend,
710 "!returns_first_name_last_name —first-name=Err —last-name=Bot",
711 )
712 )
713 assert "Err Bot" == dummy_backend.pop_message().body
714
715
716 def test_arg_botcmd_without_argument_unpacking(dummy_backend):
717 dummy_backend.callback_message(
718 makemessage(
719 dummy_backend,
720 "!returns_first_name_last_name_without_unpacking --first-name=Err --last-name=Bot",
721 )
722 )
723 assert "Err Bot" == dummy_backend.pop_message().body
724
725
726 def test_access_controls(dummy_backend):
727 testroom = TestRoom("room", bot=dummy_backend)
728 tests = [
729 # BOT_ADMINS scenarios
730 dict(
731 message=makemessage(dummy_backend, "!admin_command"),
732 bot_admins=("noterr",),
733 expected_response="Admin command",
734 ),
735 dict(
736 message=makemessage(dummy_backend, "!admin_command"),
737 bot_admins=(),
738 expected_response="This command requires bot-admin privileges",
739 ),
740 dict(
741 message=makemessage(dummy_backend, "!admin_command"),
742 bot_admins=("*err",),
743 expected_response="Admin command",
744 ),
745 # admin_only commands SHOULD be private-message only by default
746 dict(
747 message=makemessage(
748 dummy_backend,
749 "!admin_command",
750 from_=TestOccupant("noterr", room=testroom),
751 to=testroom,
752 ),
753 bot_admins=("noterr",),
754 expected_response="This command may only be issued through a direct message",
755 ),
756 # But MAY be sent via groupchat IF 'allowmuc' is specifically set to True.
757 dict(
758 message=makemessage(
759 dummy_backend,
760 "!admin_command",
761 from_=TestOccupant("noterr", room=testroom),
762 to=testroom,
763 ),
764 bot_admins=("noterr",),
765 acl={"admin_command": {"allowmuc": True}},
766 expected_response="Admin command",
767 ),
768 # ACCESS_CONTROLS scenarios WITHOUT wildcards (<4.0 format)
769 dict(
770 message=makemessage(dummy_backend, "!command"),
771 expected_response="Regular command",
772 ),
773 dict(
774 message=makemessage(dummy_backend, "!regex command with prefix"),
775 expected_response="Regex command",
776 ),
777 dict(
778 message=makemessage(dummy_backend, "!command"),
779 acl_default={"allowmuc": False, "allowprivate": False},
780 expected_response="You're not allowed to access this command via private message to me",
781 ),
782 dict(
783 message=makemessage(dummy_backend, "regex command without prefix"),
784 acl_default={"allowmuc": False, "allowprivate": False},
785 expected_response="You're not allowed to access this command via private message to me",
786 ),
787 dict(
788 message=makemessage(dummy_backend, "!command"),
789 acl_default={"allowmuc": True, "allowprivate": False},
790 expected_response="You're not allowed to access this command via private message to me",
791 ),
792 dict(
793 message=makemessage(dummy_backend, "!command"),
794 acl_default={"allowmuc": False, "allowprivate": True},
795 expected_response="Regular command",
796 ),
797 dict(
798 message=makemessage(dummy_backend, "!command"),
799 acl={"command": {"allowprivate": False}},
800 acl_default={"allowmuc": False, "allowprivate": True},
801 expected_response="You're not allowed to access this command via private message to me",
802 ),
803 dict(
804 message=makemessage(dummy_backend, "!command"),
805 acl={"command": {"allowmuc": True}},
806 acl_default={"allowmuc": True, "allowprivate": False},
807 expected_response="You're not allowed to access this command via private message to me",
808 ),
809 dict(
810 message=makemessage(dummy_backend, "!command"),
811 acl={"command": {"allowprivate": True}},
812 acl_default={"allowmuc": False, "allowprivate": False},
813 expected_response="Regular command",
814 ),
815 dict(
816 message=makemessage(
817 dummy_backend,
818 "!command",
819 from_=TestOccupant("someone", "room"),
820 to=TestRoom("room", bot=dummy_backend),
821 ),
822 acl={"command": {"allowrooms": ("room",)}},
823 expected_response="Regular command",
824 ),
825 dict(
826 message=makemessage(
827 dummy_backend,
828 "!command",
829 from_=TestOccupant("someone", "room"),
830 to=TestRoomAcl("room", bot=dummy_backend),
831 ),
832 acl={"command": {"allowrooms": ("room",)}},
833 expected_response="Regular command",
834 ),
835 dict(
836 message=makemessage(
837 dummy_backend,
838 "!command",
839 from_=TestOccupant("someone", "room_1"),
840 to=TestRoom("room1", bot=dummy_backend),
841 ),
842 acl={"command": {"allowrooms": ("room_*",)}},
843 expected_response="Regular command",
844 ),
845 dict(
846 message=makemessage(
847 dummy_backend,
848 "!command",
849 from_=TestOccupant("someone", "room"),
850 to=TestRoom("room", bot=dummy_backend),
851 ),
852 acl={"command": {"allowrooms": ("anotherroom@localhost",)}},
853 expected_response="You're not allowed to access this command from this room",
854 ),
855 dict(
856 message=makemessage(
857 dummy_backend,
858 "!command",
859 from_=TestOccupant("someone", "room"),
860 to=TestRoomAcl("room", bot=dummy_backend),
861 ),
862 acl={"command": {"allowrooms": ("anotherroom@localhost",)}},
863 expected_response="You're not allowed to access this command from this room",
864 ),
865 dict(
866 message=makemessage(
867 dummy_backend,
868 "!command",
869 from_=TestOccupant("someone", "room"),
870 to=TestRoom("room", bot=dummy_backend),
871 ),
872 acl={"command": {"denyrooms": ("room",)}},
873 expected_response="You're not allowed to access this command from this room",
874 ),
875 dict(
876 message=makemessage(
877 dummy_backend,
878 "!command",
879 from_=TestOccupant("someone", "room"),
880 to=TestRoom("room", bot=dummy_backend),
881 ),
882 acl={"command": {"denyrooms": ("*",)}},
883 expected_response="You're not allowed to access this command from this room",
884 ),
885 dict(
886 message=makemessage(
887 dummy_backend,
888 "!command",
889 from_=TestOccupant("someone", "room"),
890 to=TestRoom("room", bot=dummy_backend),
891 ),
892 acl={"command": {"denyrooms": ("anotherroom",)}},
893 expected_response="Regular command",
894 ),
895 dict(
896 message=makemessage(dummy_backend, "!command"),
897 acl={"command": {"allowusers": ("noterr",)}},
898 expected_response="Regular command",
899 ),
900 dict(
901 message=makemessage(dummy_backend, "!command"),
902 acl={"command": {"allowusers": "noterr"}}, # simple string instead of tuple
903 expected_response="Regular command",
904 ),
905 dict(
906 message=makemessage(dummy_backend, "!command"),
907 acl={"command": {"allowusers": ("err",)}},
908 expected_response="You're not allowed to access this command from this user",
909 ),
910 dict(
911 message=makemessage(dummy_backend, "!command"),
912 acl={"command": {"allowusers": ("*err",)}},
913 expected_response="Regular command",
914 ),
915 dict(
916 message=makemessage(dummy_backend, "!command"),
917 acl={"command": {"denyusers": ("err",)}},
918 expected_response="Regular command",
919 ),
920 dict(
921 message=makemessage(dummy_backend, "!command"),
922 acl={"command": {"denyusers": ("noterr",)}},
923 expected_response="You're not allowed to access this command from this user",
924 ),
925 dict(
926 message=makemessage(dummy_backend, "!command"),
927 acl={"command": {"denyusers": "noterr"}}, # simple string instead of tuple
928 expected_response="You're not allowed to access this command from this user",
929 ),
930 dict(
931 message=makemessage(dummy_backend, "!command"),
932 acl={"command": {"denyusers": ("*err",)}},
933 expected_response="You're not allowed to access this command from this user",
934 ),
935 dict(
936 message=makemessage(dummy_backend, "!command echo"),
937 acl={"command": {"allowargs": ("echo",)}},
938 expected_response="Regular command",
939 ),
940 dict(
941 message=makemessage(dummy_backend, "!command notallowed"),
942 acl={"command": {"allowargs": ("echo",)}},
943 expected_response="You're not allowed to access this command using the provided arguments",
944 ),
945 dict(
946 message=makemessage(dummy_backend, "!command echodeny"),
947 acl={"command": {"denyargs": ("echodeny",)}},
948 expected_response="You're not allowed to access this command using the provided arguments",
949 ),
950 dict(
951 message=makemessage(dummy_backend, "!command echo"),
952 acl={"command": {"denyargs": ("echodeny",)}},
953 expected_response="Regular command",
954 ),
955 # ACCESS_CONTROLS scenarios WITH wildcards (>=4.0 format)
956 dict(
957 message=makemessage(dummy_backend, "!command"),
958 acl={"DummyBackendRealName:command": {"denyusers": ("noterr",)}},
959 expected_response="You're not allowed to access this command from this user",
960 ),
961 dict(
962 message=makemessage(dummy_backend, "!command"),
963 acl={"*:command": {"denyusers": ("noterr",)}},
964 expected_response="You're not allowed to access this command from this user",
965 ),
966 dict(
967 message=makemessage(dummy_backend, "!command"),
968 acl={"DummyBackendRealName:*": {"denyusers": ("noterr",)}},
969 expected_response="You're not allowed to access this command from this user",
970 ),
971 dict(
972 message=makemessage(dummy_backend, "!command echo"),
973 acl={"command": {"allowargs": ("ec*",)}},
974 expected_response="Regular command",
975 ),
976 dict(
977 message=makemessage(dummy_backend, "!command notallowed"),
978 acl={"command": {"allowargs": ("e*",)}},
979 expected_response="You're not allowed to access this command using the provided arguments",
980 ),
981 dict(
982 message=makemessage(dummy_backend, "!command denied"),
983 acl={"command": {"denyargs": ("den*",)}},
984 expected_response="You're not allowed to access this command using the provided arguments",
985 ),
986 # Overlapping globs should use first match
987 dict(
988 message=makemessage(dummy_backend, "!command"),
989 acl=OrderedDict(
990 [
991 ("DummyBackendRealName:*", {"denyusers": ("noterr",)}),
992 ("DummyBackendRealName:command", {"denyusers": ()}),
993 ]
994 ),
995 expected_response="You're not allowed to access this command from this user",
996 ),
997 # ACCESS_CONTROLS with numeric username as in telegram
998 dict(
999 message=makemessage(
1000 dummy_backend, "!command", from_=dummy_backend.build_identifier(1234)
1001 ),
1002 acl={"command": {"allowusers": (1234,)}},
1003 expected_response="Regular command",
1004 ),
1005 ]
1006
1007 for test in tests:
1008 dummy_backend.bot_config.ACCESS_CONTROLS_DEFAULT = test.get("acl_default", {})
1009 dummy_backend.bot_config.ACCESS_CONTROLS = test.get("acl", {})
1010 dummy_backend.bot_config.BOT_ADMINS = test.get("bot_admins", ())
1011 logger = logging.getLogger(__name__)
1012 logger.info(f"** message: {test['message'].body}")
1013 logger.info(f"** bot_admins: {dummy_backend.bot_config.BOT_ADMINS}")
1014 logger.info(f"** acl: {dummy_backend.bot_config.ACCESS_CONTROLS}")
1015 logger.info(
1016 "** acl_default: {!r}".format(
1017 dummy_backend.bot_config.ACCESS_CONTROLS_DEFAULT
1018 )
1019 )
1020 dummy_backend.callback_message(test["message"])
1021 assert test["expected_response"] == dummy_backend.pop_message().body