Testing tools

Fixtures with py.test

Pytest plugin for Sopel.

New in version 7.0.

sopel.tests.pytest_plugin.botfactory()

Fixture to get a Bot factory.

Returns

a factory to create a mocked bot instance

Return type

sopel.tests.factories.BotFactory

This is very useful in unit tests:

def test_bot(configfactory, botfactory):
    settings = configfactory('... skip for clarity ...')
    bot = botfactory(settings) # no plugins loaded
    # ... do something with the bot

def test_bot_loaded(configfactory, botfactory):
    settings = configfactory('... skip for clarity ...')
    bot = botfactory.preloaded(settings, ['myplugin'])
    # now the bot has `coretasks` and `myplugin` loaded
sopel.tests.pytest_plugin.configfactory(tmpdir)

Fixture to get a config factory.

Returns

a factory to create test settings

Return type

sopel.tests.factories.ConfigFactory

The factory will be automatically configured with a tmpdir object.

sopel.tests.pytest_plugin.ircfactory()

Fixture to get an IRC factory.

Returns

a factory to create mock IRC servers

Return type

sopel.tests.factories.IRCFactory

For example, a plugin command could be tested with this:

from sopel.tests import rawlist

def test_mycommand(configfactory, botfactory, ircfactory, userfactory):
    settings = configfactory('... skip for clarity ...')
    bot = botfactory(settings, ['myplugin'])
    irc = ircfactory(bot)
    user = userfactory('User')

    irc.say(user, '#test', '.mycommand'))

    assert bot.backend.message_sent == rawlist(
        'PRIVMSG #test :My plugin replied this.'
    )
sopel.tests.pytest_plugin.triggerfactory()

Fixture to get a trigger factory.

Returns

a factory to create triggers

Return type

sopel.tests.factories.TriggerFactory

sopel.tests.pytest_plugin.userfactory()

Fixture to get a user factory.

Returns

a factory to create mock users

Return type

sopel.tests.factories.UserFactory

def test_mycommand(userfactory):
    user = userfactory('User')

    assert user.nick == 'User'
    assert user.user == 'user'
    assert user.host == 'example.com'
    assert user.prefix == 'User!user@example.com'

Factories

Test factories: they create objects for testing purposes.

New in version 7.0.

class sopel.tests.factories.BotFactory

Factory to create bot.

See also

The botfactory() fixture can be used to instantiate this factory.

preloaded(settings, preloads=None)

Create a bot and preload its plugins.

Parameters
  • settings (sopel.config.Config) – Sopel’s configuration for testing purposes

  • preloads (list) – list of plugins to preload, setup, and register

Returns

a test instance of the bot

Return type

sopel.bot.Sopel

This will instantiate a Sopel object, replace its backend with a MockIRCBackend, and then preload plugins. This will automatically load the coretasks plugin, and every other plugin from preloads:

factory = BotFactory()
bot = factory.with_autoloads(settings, ['emoticons', 'remind'])

Note

This will automatically setup plugins: be careful with plugins that require access to external services on setup.

You may also need to manually call shutdown routines for the loaded plugins.

class sopel.tests.factories.ConfigFactory(tmpdir)

Factory to create settings.

See also

The configfactory() fixture can be used to instantiate this factory.

class sopel.tests.factories.IRCFactory

Factory to create mock IRC server.

See also

The ircfactory() fixture can be used to create this factory.

class sopel.tests.factories.TriggerFactory

Factory to create trigger.

See also

The triggerfactory() fixture can be used to instantiate this factory.

class sopel.tests.factories.UserFactory

Factory to create mock user.

See also

The userfactory() fixture can be used to create this factory.

Mocks

Test mocks: they fake objects for testing.

New in version 7.0.

class sopel.tests.mocks.MockIRCBackend(*args, **kwargs)

Fake IRC connection backend for testing purpose.

This backend doesn’t require an actual connection. Instead, it stores every message sent in the message_sent list.

message_sent = None

List of raw messages sent by the bot.

send(data)

Store data into message_sent.

class sopel.tests.mocks.MockIRCServer(bot)

Fake IRC Server that can send messages to a test bot.

Parameters

bot (sopel.bot.Sopel) – test bot instance to send messages to

This mock object helps developers when they want to simulate an IRC server sending messages to the bot.

The IRCFactory factory can be used to create such mock object, either directly or by using py.test and the ircfactory() fixture.

channel_joined(channel, users=None)

Send events as if the bot just joined a channel.

Parameters
  • channel (str) – channel to send message for

  • users (list) – list (or tuple) of nicknames that will be present in the RPL_NAMREPLY event

This will send 2 messages to the bot:

  • a RPL_NAMREPLY event (353), giving information about users present in channel

  • a RPL_ENDOFNAMES event (366) for completion

Use this to emulate when the bot joins a channel, and the server replies with the list of connected users:

factory.channel_joined('#test', ['Owner', '@ChanServ'])

In this example, the bot will know that there are 2 other users present in #test: “Owner” (a regular user) and “ChanServ” (which is a channel operator). Note that the bot itself will be added to the list of users automatically, and you should not pass it in the users parameter.

This is particulary useful to populate the bot’s memory of who is in a channel.

Note

To add a user to a channel after using this method, you should use the join() method.

property chanserv

ChanServ’s message prefix.

join(user, channel)

Send a channel JOIN event from user.

Parameters
  • user (MockUser) – factory for the user who joins the channel

  • channel (str) – channel the user joined

This will send a JOIN message as if user just joined the channel:

factory.join(MockUser('NewUser'), '#test')

See also

This function is a shortcut to call the bot with the result from the user factory’s join() method.

mode_set(channel, flags, users)

Send a MODE event for a channel

Parameters
  • channel (str) – channel receiving the MODE event

  • flags (str) – MODE flags set

  • users (list) – users getting the MODE flags

This will send a MODE message as if ChanServ added/removed channel modes for a set of users. This method assumes the flags parameter follows the IRC specification for MODE:

factory.mode_set('#test', '+vo-v', ['UserV', UserOP', 'UserAnon'])
pm(user, text)

Send a PRIVMSG to the bot by a user.

Parameters
  • user (MockUser) – factory for the user object who sends a message

  • text (str) – content of the message sent to the bot

This will send a PRIVMSG message as forwarded by the server for a user sending it to the bot:

factory.pm(MockUser('NewUser'), 'A private word.')

See also

This function is a shortcut to call the bot with the result from the user factory’s privmsg() method, using the bot’s nick as recipient.

say(user, channel, text)

Send a PRIVMSG to channel by user.

Parameters
  • user (MockUser) – factory for the user who sends a message to channel

  • channel (str) – recipient of the user’s PRIVMSG

  • text (str) – content of the message sent to the channel

This will send a PRIVMSG message as if user sent it to the channel, and the server forwarded it to its clients:

factory.say(MockUser('NewUser'), '#test', '.shrug')

See also

This function is a shortcut to call the bot with the result from the user’s privmsg() method.

class sopel.tests.mocks.MockUser(nick=None, user=None, host=None)

Fake user that can generate messages to send to a bot.

Parameters
  • nick (str) – nickname

  • user (str) – IRC username

  • host (str) – user’s host

The UserFactory factory can be used to create such mock object, either directly or by using py.test and the userfactory() fixture.

join(channel)

Generate a JOIN command forwarded by the server for the user.

Parameters

channel (str) – channel the user joined

Returns

the JOIN command the server sends to its clients present in the same channel when the user joins it.

Return type

str

property prefix

User’s hostmask as seen by other users on the server.

When the server forwards a User’s command, it uses this prefix.

privmsg(recipient, text)

Generate a PRIVMSG command forwarded by a server for the user.

Parameters
  • recipient (str) – a channel name or the bot’s nick

  • text (str) – content of the message

Returns

a PRIVMSG command forwarded by the server as if it originated from the user’s hostmask

Return type

str

Old testing tools

This module has classes and functions that can help in writing tests.

Note

This module formerly contained mock classes for bot, bot wrapper, and config objects. Those are deprecated, and will be removed in Sopel 8.0. New code should use the new mocks, factories, and pytest_plugin added in Sopel 7.0.

class sopel.test_tools.MockConfig
define_section(name, cls_)

Define the available settings in a section.

Parameters
  • name (str) – name of the new section

  • cls_ (subclass of StaticSection) – class defining the settings within the section

  • validate (bool) – whether to validate the section’s values (optional; defaults to True)

Raises

ValueError – if the section name has been defined already with a different cls_

If validate is True, the section’s values will be validated, and an exception (usually ValueError or AttributeError) raised if they are invalid. This is desirable in a plugin’s setup() function, for example, but might not be in the configure() function.

class sopel.test_tools.MockSopelWrapper(*args, **kwargs)
sopel.test_tools.get_example_test(tested_func, msg, results, privmsg, admin, owner, repeat, use_regexp, ignore=[])

Get a function that calls tested_func with fake wrapper and trigger.

Parameters
  • tested_func (callable) – a Sopel callable that accepts a SopelWrapper and a Trigger

  • msg (str) – message that is supposed to trigger the command

  • results (list) – expected output from the callable

  • privmsg (bool) – if True, make the message appear to have arrived in a private message to the bot; otherwise make it appear to have come from a channel

  • admin (bool) – make the message appear to have come from an admin

  • owner (bool) – make the message appear to have come from an owner

  • repeat (int) – how many times to repeat the test; useful for tests that return random stuff

  • use_regexp (bool) – pass True if results are in regexp format

  • ignore (list) – strings to ignore

Returns

a test function for tested_func

Return type

function

sopel.test_tools.insert_into_module(func, module_name, base_name, prefix)

Add a function into a module.