def test_behaviors_say_hi(bot): """Tests say_hi method by simply calling it. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') plugin = Behaviors(bot) plugin.say_hi(mask, channel) assert bot.privmsg.called_once_with(channel, 'mybot: Hey there!')
def test_karma(bot): """Tests karma command. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {} expected = 'python (5), java (-10)' plugin = Commands(bot) asyncio.get_event_loop().run_until_complete( plugin.karma(mask, channel, args)) assert bot.privmsg.called_once_with(channel, expected)
def test_slackers(bot): """Tests slackers command. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {} expected = 'somebody_else (100), somebody (10)' plugin = Commands(bot) asyncio.get_event_loop().run_until_complete( plugin.slackers(mask, channel, args)) assert bot.privmsg.called_once_with(channel, expected)
def wrap(): response = yield from self.lastfm.now_playing_response( IrcString('bar!id@host'), {'<user>': None}) assert response == ( 'bar was just playing “M83 – Kim & Jessie” (♥) (5 plays) ' '(3m00s ago) (electronic, indie, electropop, electro, ' 'catchy).')
def test_cebolate(bot): """Tests the cebolate command. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<message>': ['CORRECT', 'answer']} plugin = Commands(bot) async def test(): response = await plugin.cebolate(mask, channel, args) assert response == 'COLLECT answel' asyncio.get_event_loop().run_until_complete(test())
def test_behaviors_handle_message_raising_exception(mock_handle_url, bot): """Tests handle_message method simulating an URL read from channel and raising an exception. Args: mock_handle_url: Fakes Behaviors.handle_url method. bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') data = 'https://github.com/meleca/mr-roboto' mock_handle_url.side_effect = ValueError() plugin = Behaviors(bot) asyncio.get_event_loop().run_until_complete( plugin.handle_message(mask=mask, target=channel, data=data)) assert bot.privmsg.called_once_with(channel, 'Booom shakalaka')
def wrap(): response = yield from self.lastfm.now_playing_response( IrcString('bar!id@host'), {'<user>': None}) assert response == ( 'bar was just playing “M83 – Kim & Jessie” (♥) (5 plays) ' '(3m00s ago) (dream pop, ambient music, dance and ' 'electronica, electronic).')
def topic_cmd(self, mask, target, args): """ Set the channel topic, prefixing the weekend progressbar. You need to be an operator to use this. %%topic <topic>... """ nick = IrcString(mask).nick self.log.info("Topic command: {mask}, {target}, {args}".format( mask=mask, target=target, args=args)) # Someone set the topic. Check if they are permitted to do so. if nick in self.context.channels[target].modes["@"]: if self.context.nick in self.context.channels[target].modes["@"]: self.set_weekend_topic(target, " ".join(args["<topic>"])) self.log.info("Topic command succeeded") else: self.context.privmsg( nick, "I can't set a topic unless I have '+o' mode on {}.". format(target)) self.log.info("Topic command refused (no op)") else: self.context.privmsg( nick, "Get a '+o' on {} first to use the !topic command.".format( target))
def wrap(): response = yield from self.lastfm.now_playing_response( IrcString('bar!id@host'), {'<user>': None}) yield from asyncio.sleep(0.01) assert response == ('bar is not currently playing anything ' '(last seen 1 day ago).') assert not mock.called, "Shouldn't call get_info if not recent"
def test_greeting_raising_exception(bot): """Tests the greeting command when error occur. Args: bot: Fake instance of an Irc3Bot. """ bot.dataset['greetings'].upsert.side_effect = ValueError() mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<nick>': 'nickname', '<message>': 'Hello there.'} plugin = Commands(bot) async def test(): response = await plugin.greeting(mask, channel, args) assert response == 'Sorry, looks like something went wrong :(' asyncio.get_event_loop().run_until_complete(test())
def setUp(self): mask = IrcString('nick!user@host') @asyncio.coroutine def id_func(): return mask self.user = User(mask, ['#foo'], id_func, MockDb())
def test_urls(mock_or_, date, keyword, expected, bot): """Tests the urls command. Args: mock_or_: Fakes sqlalchemy.sql.or_ function. date: An ISO date or special keyword. keyword: A list of keywords to be used for filtering. expected: Expected response. bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<date>': date, '<keyword>': keyword} expected = 'Invalid date' if date == '2018-02-31' else expected plugin = Commands(bot) asyncio.get_event_loop().run_until_complete( plugin.urls(mask, channel, args)) assert bot.privmsg.called_once_with(channel, expected)
def test_about(bot): """Tests about command. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {} expected = ( f'Hi there, my name is {bot.nick} and I am an IRC bot ' 'written in Python. If you wanna know more about me take ' 'a look at my Github page https://github.com/meleca/mr-roboto/. ' f'Currently running v{bot.version}') plugin = Commands(bot) asyncio.get_event_loop().run_until_complete( plugin.about(mask, channel, args)) assert bot.privmsg.called_once_with(channel, expected)
def test_ircstring(self): s = IrcString('nick') self.assertTrue(s.is_nick) self.assertEqual(s.nick, 'nick') self.assertEqual(s.host, None) s = IrcString('nick!user@host') self.assertTrue(s.is_user) self.assertTrue(s.is_nick) self.assertEqual(s.nick, 'nick') self.assertEqual(s.host, 'user@host') s = IrcString('#chan') self.assertTrue(s.is_channel) s = IrcString('&chan') self.assertTrue(s.is_channel) s = IrcString('*') self.assertTrue(s.is_server)
def test_excuse(mock_session_get, bot): """Tests the excuse command. Args: mock_session_get: Fakes aiohttp.ClientSession.get method. bot: Fake instance of an Irc3Bot. """ data = 'The user must not know how to use it' request = asynctest.Mock(text=asynctest.CoroutineMock(side_effect=[data])) mock_session_get.return_value.__aenter__.return_value = request mask = IrcString('[email protected]') channel = IrcString('#meleca') plugin = Commands(bot) async def test(): response = await plugin.excuse(mask, channel, None) assert response == data asyncio.get_event_loop().run_until_complete(test())
def test_behaviors_handle_message(mock_handle_url, mock_slack_meter, mock_karma, bot): """Tests handle_message method simulating an URL read from channel. Args: mock_handle_url: Fakes Behaviors.handle_url method. mock_slack_meter: Fakes Behaviors.slack_meter method. bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') data = 'https://github.com/meleca/mr-roboto' plugin = Behaviors(bot) asyncio.get_event_loop().run_until_complete( plugin.handle_message(mask=mask, target=channel, data=data)) assert mock_handle_url.called_once_with(channel, data.encode('utf-8')) assert mock_slack_meter.called_once_with(channel=channel, nick=mask.nick, message=data) assert not mock_karma.called
def on_topic_changed(self, channel=None, data=None, mask=None, **kw): """ The topic has changed. """ nick = IrcString(mask).nick # who set the topic? if nick == self.context.nick: # don't change the topic that we just set return self.set_weekend_topic(channel, data)
def test_behaviors_karma(bot): """Tests karma method. Args: bot: Fake instance of an Irc3Bot. """ channel = IrcString('#meleca') entity = b'python++' plugin = Behaviors(bot) asyncio.get_event_loop().run_until_complete(plugin.karma(channel, entity)) assert bot.dataset['karma'].upsert.called_once assert bot.privmsg.called_once_with(channel, 'python (6)')
def wrap(): self.bot.dispatch(':bar!id@foo PRIVMSG #chan :!np') yield from asyncio.sleep(0.1) self.assertSent([ 'PRIVMSG #chan :bar is not currently playing ' 'anything (last seen 3 days, 2 minutes ago).' ]) response = yield from self.lastfm.now_playing_response( IrcString('bar!id@hosta'), {'<user>': None}) assert response == ('bar is not currently playing anything ' '(last seen 3 days, 2 minutes ago).') assert not mock.called, "Shouldn't call get_info if not recent"
def test_horoscope(mock_session_get, sign, expected, bot): """Tests the horoscope command. Args: mock_session_get: Fakes aiohttp.ClientSession.get method. sign: A zodiac sign. expected: The expected response. bot: Fake instance of an Irc3Bot. """ data = {'horoscope': expected} request = asynctest.Mock(json=asynctest.CoroutineMock(side_effect=[data])) mock_session_get.return_value.__aenter__.return_value = request mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<sign>': sign} plugin = Commands(bot) async def test(): response = await plugin.horoscope(mask, channel, args) assert response == expected asyncio.get_event_loop().run_until_complete(test())
def test_behaviors_slack_meter(bot): """Tests slack_meter method. Args: bot: Fake instance of an Irc3Bot. """ channel = IrcString('#meleca') nick = 'somebody' msg = 'Do you think I talk too much?' plugin = Behaviors(bot) asyncio.get_event_loop().run_until_complete( plugin.slack_meter(channel, nick, msg)) assert bot.dataset['slackers'].upsert.called_once
def test_joke(mock_session_get, subject, joke, expected, bot): """Tests the joke command. Args: mock_session_get: Fakes aiohttp.ClientSession.get method. subject: A joke subject. joke: Fake joke service response. expected: The expected response. bot: Fake instance of an Irc3Bot. """ request = asynctest.Mock(json=asynctest.CoroutineMock(side_effect=[joke])) mock_session_get.return_value.__aenter__.return_value = request mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<subject>': subject} plugin = Commands(bot) async def test(): response = await plugin.joke(mask, channel, args) assert response == expected asyncio.get_event_loop().run_until_complete(test())
def admin_answer(self, mask, target, data, **kwargs): if 'https://pastebin.com' in data: self.bot.privmsg( target, '{}: Please use dpaste.de for all your paste bin needs'.format( IrcString(mask).nick)) elif 'there are 2 hard things in computer science' in data.lower(): self.bot.privmsg( target, '{}: Cache invalidation, naming things and off by 1 errors'. format(IrcString(mask).nick)) elif data.startswith('FunkyBot:'): message = re.sub(r'^FunkyBot: *', '', data) doc_match = re.search(r'^doc +(\w+)', message) if doc_match: if re.search(r'^[A-Z_]+$', doc_match[1]): self.bot.privmsg( target, 'https://docs.djangoproject.com/en/stable/ref/settings/#{}' .format(slugify(doc_match[1])), ) elif re.search(r'admin.*\?', message, re.IGNORECASE): self.bot.privmsg( target, '{}: {}'.format( IrcString(mask).nick, random.choice(admin_quotes)), ) elif 'What are the 3 rules of optimisation?' in message: self.bot.privmsg( target, '{}: 1. Don\'t! 2. Not yet! 3. Profile!'.format( IrcString(mask).nick), )
def test_greeting(bot): """Tests the greeting command. Args: bot: Fake instance of an Irc3Bot. """ mask = IrcString('[email protected]') channel = IrcString('#meleca') args = {'<nick>': 'nickname', '<message>': 'Hello there.'} data = { 'channel': channel.replace('#', ''), 'nick': args.get('<nick>'), 'options': '\n'.join(['Hey there!', 'Hello there.']) } rule = ['channel', 'nick'] plugin = Commands(bot) async def test(): response = await plugin.greeting(mask, channel, args) assert bot.dataset['greetings'].upsert.called_once_with(data, rule) assert response == 'Okie dokie' asyncio.get_event_loop().run_until_complete(test())
def is_admin(self, mask, target): target = self.bot.casefold(target) if not isinstance(mask, IrcString): mask = IrcString(mask) # we consider halfop/op and above admins prefixes = self.bot.config['server_config'].get('PREFIX', '(ov)@+') prefixes = prefixes.split(')')[1] admin_prefix_index = prefixes.index('%') if '%' in prefixes else prefixes.index('@') admin_prefixes = prefixes[:admin_prefix_index + 1] for prefix in admin_prefixes: if mask.nick in self.bot.channels[target].modes[prefix]: return True return False
def on_who(self, channel=None, nick=None, username=None, host=None, server=None, **kwargs): """Process a WHO reply since it could contain new information. Should only be processed for channels we are currently in! """ if channel not in self.channels: self.log.debug( "Got WHO for channel I'm not in: {chan}".format(chan=channel)) return self.log.debug("Got WHO for %s: %s (%s)", channel, nick, host) if nick not in self.active_users: mask = IrcString('{}!{}@{}'.format(nick, username, host)) self.active_users[nick] = self.create_user(mask, [channel]) else: self.active_users[nick].join(channel)
def test_behaviors_handle_url(mock_session_get, header, data, message, bot): """Tests handle_url method simulating all expected types of valid and invalid entries. Args: mock_session_get: Fakes aiohttp.ClientSession.get method. header: An fake HTTP request response header. data: An fake HTTP request response content. message: The expected bot's response. bot: Fake instance of an Irc3Bot. """ channel = IrcString('#meleca') url = b'https://github.com/meleca/mr-roboto' request = mock.Mock(headers={'CONTENT-TYPE': header}, charset='utf-8', read=asynctest.CoroutineMock(side_effect=[data])) mock_session_get.return_value.__aenter__.return_value = request plugin = Behaviors(bot) asyncio.get_event_loop().run_until_complete(plugin.handle_url( channel, url)) assert bot.privmsg.called_once_with(channel, message) assert bot.dataset['url_history'].upsert.called_once
def my420(self): self.bot.privmsg(self.announce_to, choice(['Oh!', 'Ooo!', 'Whoops!', 'Hmm? Ah..'])) self.bot.loop.call_later( 7, self.bot.privmsg, self.announce_to, "\x01ACTION gets " + choice([ 'up.', 'up to get something.', 'something.', 'ready.', 'excited.' ]) + "\x01") if choice(['a', 'b', 'c', 'd']) == 'c': self.bot.loop.call_later(32, self.bot.privmsg, self.announce_to, "!getin") self.bot.loop.call_later(37, self.bot.privmsg, self.announce_to, "Oh yeah, that's me...") self.bot.loop.call_later(40, self.getin, IrcString(self.bot.nick + '!user@host'), self.announce_to, [], True) self.bot.loop.call_later(( 5 * 61 ) + 1, self.bot.privmsg, self.announce_to, "\x01ACTION " + choice([ 'hits it!', 'tokes.', 'knocks the bong over! :(', 'gets faded...', 'shrieks "ACHE SHAW" at the top of their lungs and hits the bong like a madperson!' ]) + "\x01")
def _is_a_channel(channel): return IrcString(channel).is_channel
def who(self, channel=None, nick=None, user=None, host=None, **kw): self.channels[channel].add(nick.lower()) mask = IrcString(nick + '!' + user + '@' + host) self.nicks[nick.lower()] = mask