Best Python code snippet using locust
test_cog.py
Source:test_cog.py  
1# Futures2# Built-in/Generic Imports3import asyncio4# Libs5import discord.ext.test as dpytest6import mock7import pytest_ordering as pytest8import pytest9import discord10from discord.ext import commands11from sqlalchemy import select, and_12# Own modules13import koalabot14from koala.db import session_manager15from koala.cogs import twitch_alert16from koala.cogs.twitch_alert import cog17from koala.cogs.twitch_alert.models import UserInTwitchAlert18from koala.colours import KOALA_GREEN19from tests.tests_utils.last_ctx_cog import LastCtxCog20# Constants21DB_PATH = "Koala.db"22# Variables23@pytest.mark.asyncio24async def test_setup():25    with mock.patch.object(discord.ext.commands.bot.Bot, 'add_cog') as mock1:26        cog.setup(koalabot.bot)27    mock1.assert_called()28@pytest.fixture29async def twitch_cog(bot: discord.ext.commands.Bot):30    """ setup any state specific to the execution of the given module."""31    twitch_cog = cog.TwitchAlert(bot)32    bot.add_cog(twitch_cog)33    await dpytest.empty_queue()34    dpytest.configure(bot)35    return twitch_cog36@mock.patch("koalabot.check_guild_has_ext", mock.MagicMock(return_value=True))37def test_twitch_is_enabled_true(twitch_cog):38    assert cog.twitch_is_enabled(None)39@mock.patch("koalabot.is_dm_channel", mock.MagicMock(return_value=True))40def test_twitch_is_enabled_dm():41    assert not cog.twitch_is_enabled(None)42@mock.patch("koalabot.is_dm_channel", mock.MagicMock(return_value=False))43@mock.patch("koalabot.is_dpytest", False)44@pytest.mark.asyncio45async def test_twitch_is_enabled_false(twitch_cog: cog.TwitchAlert):46    last_ctx_cog = LastCtxCog(bot=twitch_cog.bot)47    twitch_cog.bot.add_cog(last_ctx_cog)48    await dpytest.message(koalabot.COMMAND_PREFIX + "store_ctx", channel=-1)49    ctx: commands.Context = last_ctx_cog.get_last_ctx()50    assert not cog.twitch_is_enabled(ctx)51# @mock.patch("koala.utils.random_id", mock.MagicMock(return_value=7357))52@pytest.mark.asyncio(order=1)53async def test_edit_default_message_default_from_none(twitch_cog):54    this_channel = dpytest.get_config().channels[0]55    assert_embed = discord.Embed(title="Default Message Edited",56                                 description=f"Guild: {dpytest.get_config().guilds[0].id}\n"57                                             f"Channel: {this_channel.id}\n"58                                             f"Default Message: {twitch_alert.utils.DEFAULT_MESSAGE}")59    await dpytest.message(koalabot.COMMAND_PREFIX + f"twitch editMsg {this_channel.id}")60    assert dpytest.verify().message().embed(embed=assert_embed)61# @mock.patch("koala.utils.random_id", mock.MagicMock(return_value=7357))62@pytest.mark.asyncio(order=2)63async def test_edit_default_message_existing(twitch_cog):64    this_channel = dpytest.get_config().channels[0]65    assert_embed = discord.Embed(title="Default Message Edited",66                                 description=f"Guild: {dpytest.get_config().guilds[0].id}\n"67                                             f"Channel: {this_channel.id}\n"68                                             "Default Message: {user} is bad")69    await dpytest.message(koalabot.COMMAND_PREFIX + "twitch editMsg " + str(this_channel.id) + " {user} is bad")70    assert dpytest.verify().message().embed(embed=assert_embed)71@pytest.mark.asyncio(order=3)72async def test_add_user_to_twitch_alert(twitch_cog):73    assert_embed = discord.Embed(title="Added User to Twitch Alert",74                                 description=f"Channel: {dpytest.get_config().channels[0].id}\n"75                                             f"User: monstercat\n"76                                             f"Message: {twitch_alert.utils.DEFAULT_MESSAGE}",77                                 colour=KOALA_GREEN)78    await dpytest.message(79        f"{koalabot.COMMAND_PREFIX}twitch add monstercat {dpytest.get_config().channels[0].id}")80    assert dpytest.verify().message().embed(embed=assert_embed)81@pytest.mark.asyncio(order=3)82async def test_add_user_to_twitch_alert_wrong_guild(twitch_cog: twitch_alert.cog.TwitchAlert):83    guild = dpytest.backend.make_guild(name="TestGuild")84    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)85    dpytest.get_config().guilds.append(guild)86    dpytest.get_config().channels.append(channel)87    member = await dpytest.member_join(1, name="TestUser", discrim=1)88    await dpytest.member_join(1, dpytest.get_config().client.user)89    with pytest.raises(discord.ext.commands.errors.ChannelNotFound,90                       match=f"Channel \"{dpytest.get_config().guilds[0].channels[0].id}\" not found."):91        await dpytest.message(92        f"{koalabot.COMMAND_PREFIX}twitch add monstercat {dpytest.get_config().guilds[0].channels[0].id}",93        channel=-1, member=member)94@pytest.mark.asyncio(order=3)95async def test_add_user_to_twitch_alert_custom_message(twitch_cog: twitch_alert.cog.TwitchAlert):96    test_custom_message = "We be live gamers!"97    guild = dpytest.backend.make_guild(name="TestGuild")98    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)99    dpytest.get_config().guilds.append(guild)100    dpytest.get_config().channels.append(channel)101    member = await dpytest.member_join(-1, name="TestUser", discrim=1)102    await dpytest.member_join(-1, dpytest.get_config().client.user)103    assert_embed = discord.Embed(title="Added User to Twitch Alert",104                                 description=f"Channel: {channel.id}\n"105                                             f"User: monstercat\n"106                                             f"Message: {test_custom_message}",107                                 colour=KOALA_GREEN)108    await dpytest.message(109        f"{koalabot.COMMAND_PREFIX}twitch add monstercat {channel.id} {test_custom_message}", channel=-1,110        member=member)111    assert dpytest.verify().message().embed(embed=assert_embed)112    sql_check_updated_server = select(UserInTwitchAlert.custom_message).where(113        and_(UserInTwitchAlert.twitch_username == 'monstercat', UserInTwitchAlert.channel_id == channel.id))114    with session_manager() as session:115        result = session.execute(sql_check_updated_server).one()116    assert result.custom_message == test_custom_message117@pytest.mark.asyncio()118async def test_remove_user_from_twitch_alert_with_message(twitch_cog: twitch_alert.cog.TwitchAlert):119    test_custom_message = "We be live gamers!"120    # Creates guild and channels and adds user and bot121    guild = dpytest.backend.make_guild(name="TestGuild")122    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)123    dpytest.get_config().guilds.append(guild)124    dpytest.get_config().channels.append(channel)125    member = await dpytest.member_join(-1, name="TestUser", discrim=1)126    await dpytest.member_join(-1, dpytest.get_config().client.user)127    # Creates Twitch Alert128    await dpytest.message(129        f"{koalabot.COMMAND_PREFIX}twitch add monstercat {channel.id} {test_custom_message}", channel=-1,130        member=member)131    sql_check_updated_server = select(UserInTwitchAlert.custom_message).where(and_(UserInTwitchAlert.twitch_username == 'monstercat', UserInTwitchAlert.channel_id == channel.id))132    with session_manager() as session:133        result_before = session.execute(sql_check_updated_server).one()134        assert result_before.custom_message == test_custom_message135        await dpytest.empty_queue()136        # Removes Twitch Alert137        await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch remove monstercat {channel.id}", channel=-1,138                              member=member)139        new_embed = discord.Embed(title="Removed User from Twitch Alert", colour=KOALA_GREEN,140                                  description=f"Channel: {channel.id}\n"141                                              f"User: monstercat")142        assert dpytest.verify().message().embed(new_embed)143        result_after = session.execute(sql_check_updated_server).one_or_none()144        assert result_after is None145@pytest.mark.asyncio(order=3)146async def test_remove_user_from_twitch_alert_wrong_guild(twitch_cog):147    guild = dpytest.backend.make_guild(name="TestGuild")148    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)149    dpytest.get_config().guilds.append(guild)150    dpytest.get_config().channels.append(channel)151    member = await dpytest.member_join(1, name="TestUser", discrim=1)152    await dpytest.member_join(1, dpytest.get_config().client.user)153    with pytest.raises(discord.ext.commands.errors.ChannelNotFound,154                       match=f"Channel \"{dpytest.get_config().channels[0].id}\" not found."):155        await dpytest.message(156        f"{koalabot.COMMAND_PREFIX}twitch remove monstercat {dpytest.get_config().channels[0].id}",157        channel=-1, member=member)158@pytest.mark.asyncio()159async def test_add_team_to_twitch_alert(twitch_cog):160    # Creates guild and channels and adds user and bot161    guild = dpytest.backend.make_guild(name="TestGuild")162    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)163    dpytest.get_config().guilds.append(guild)164    dpytest.get_config().channels.append(channel)165    member = await dpytest.member_join(-1, name="TestUser", discrim=1)166    await dpytest.member_join(-1, dpytest.get_config().client.user)167    assert_embed = discord.Embed(title="Added Team to Twitch Alert",168                                 description=f"Channel: {channel.id}\n"169                                             f"Team: faze\n"170                                             f"Message: {twitch_alert.utils.DEFAULT_MESSAGE}",171                                 colour=KOALA_GREEN)172    # Creates Twitch Alert173    await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch addTeam faze {channel.id}", channel=-1,174                          member=member)175    assert dpytest.verify().message().embed(assert_embed)176@pytest.mark.asyncio()177async def test_add_team_to_twitch_alert_with_message(twitch_cog):178    # Creates guild and channels and adds user and bot179    guild = dpytest.backend.make_guild(name="TestGuild")180    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)181    dpytest.get_config().guilds.append(guild)182    dpytest.get_config().channels.append(channel)183    member = await dpytest.member_join(-1, name="TestUser", discrim=1)184    await dpytest.member_join(-1, dpytest.get_config().client.user)185    assert_embed = discord.Embed(title="Added Team to Twitch Alert",186                                 description=f"Channel: {channel.id}\n"187                                             f"Team: faze\n"188                                             f"Message: wooo message",189                                 colour=KOALA_GREEN)190    # Creates Twitch Alert191    await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch addTeam faze {channel.id} wooo message",192                          channel=-1, member=member)193    assert dpytest.verify().message().embed(assert_embed)194@pytest.mark.asyncio()195async def test_add_team_to_twitch_alert_wrong_guild(twitch_cog):196    # Creates guild and channels and adds user and bot197    guild = dpytest.backend.make_guild(name="TestGuild")198    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)199    dpytest.get_config().guilds.append(guild)200    dpytest.get_config().channels.append(channel)201    member = await dpytest.member_join(-1, name="TestUser", discrim=1)202    await dpytest.member_join(-1, dpytest.get_config().client.user)203    # Creates Twitch Alert204    with pytest.raises(discord.ext.commands.errors.ChannelNotFound,205                       match=f"Channel \"{dpytest.get_config().channels[0].id}\" not found."):206        await dpytest.message(207        f"{koalabot.COMMAND_PREFIX}twitch addTeam faze {dpytest.get_config().channels[0].id}",208        channel=-1, member=member)209@pytest.mark.asyncio()210async def test_remove_team_from_twitch_alert_with_message(twitch_cog):211    test_custom_message = "We be live gamers!"212    # Creates guild and channels and adds user and bot213    guild = dpytest.backend.make_guild(name="TestGuild")214    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)215    dpytest.get_config().guilds.append(guild)216    dpytest.get_config().channels.append(channel)217    member = await dpytest.member_join(-1, name="TestUser", discrim=1)218    await dpytest.member_join(-1, dpytest.get_config().client.user)219    # Creates Twitch Alert220    await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch addTeam faze {channel.id} {test_custom_message}",221                          channel=-1, member=member)222    await dpytest.empty_queue()223    # Removes Twitch Alert224    await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch removeTeam faze {channel.id}", channel=-1,225                          member=member)226    new_embed = discord.Embed(title="Removed Team from Twitch Alert", colour=KOALA_GREEN,227                              description=f"Channel: {channel.id}\n"228                                          f"Team: faze")229    assert dpytest.verify().message().embed(new_embed)230    pass231@pytest.mark.asyncio(order=3)232async def test_remove_team_from_twitch_alert_wrong_guild(twitch_cog):233    guild = dpytest.backend.make_guild(name="TestGuild")234    channel = dpytest.backend.make_text_channel(name="TestChannel", guild=guild)235    dpytest.get_config().guilds.append(guild)236    dpytest.get_config().channels.append(channel)237    member = await dpytest.member_join(1, name="TestUser", discrim=1)238    await dpytest.member_join(1, dpytest.get_config().client.user)239    with pytest.raises(discord.ext.commands.errors.ChannelNotFound,240                       match=f"Channel \"{dpytest.get_config().channels[0].id}\" not found."):241        await dpytest.message(242        f"{koalabot.COMMAND_PREFIX}twitch addTeam faze {dpytest.get_config().channels[0].id}",243        channel=-1, member=member)244@pytest.mark.asyncio()245@pytest.mark.first246async def test_on_ready(twitch_cog: twitch_alert.cog.TwitchAlert):247    with mock.patch.object(twitch_alert.cog.TwitchAlert, 'start_loops') as mock1:248        await twitch_cog.on_ready()249    mock1.assert_called_with()250@mock.patch("koala.utils.random_id", mock.MagicMock(return_value=7363))251@mock.patch("cogs.twitch_alert.TwitchAPIHandler.get_streams_data",252            mock.MagicMock(return_value={'id': '3215560150671170227', 'user_id': '27446517',253                                         "user_name": "Monstercat", 'game_id': "26936", 'type': 'live',254                                         'title': 'Music 24/7'}))255@pytest.mark.skip(reason="Issues with testing inside asyncio event loop, not implemented")256@pytest.mark.asyncio257async def test_loop_check_live(twitch_cog: twitch_alert.cog.TwitchAlert):258    this_channel = dpytest.get_config().channels[0]259    expected_embed = discord.Embed(colour=koalabot.KOALA_GREEN,260                                   title="<:twitch:734024383957434489>  Monstercat is now streaming!",261                                   description="https://twitch.tv/monstercat")262    expected_embed.add_field(name="Stream Title", value="Non Stop Music - Monstercat Radio :notes:")263    expected_embed.add_field(name="Playing", value="Music & Performing Arts")264    expected_embed.set_thumbnail(url="https://static-cdn.jtvnw.net/jtv_user_pictures/"265                                     "monstercat-profile_image-3e109d75f8413319-300x300.jpeg")266    await dpytest.message(f"{koalabot.COMMAND_PREFIX}twitch add monstercat 7363")267    await dpytest.empty_queue()268    twitch_cog.start_loop()269    await asyncio.sleep(10)270    assert dpytest.verify().message().embed(expected_embed)271@pytest.mark.skip(reason="Issues with testing inside asyncio event loop, not implemented")272@pytest.mark.asyncio273async def test_loop_check_team_live(twitch_cog):...test.py
Source:test.py  
1import unittest2from calculate import calculate3class UnitTests(unittest.TestCase):4    def test_custom_message(self):5        self.assertEqual(calculate(6            operation='add',7            message='You just added',8            first=2,9            second=410        ), "You just added 6")11    def test_default_message(self):12        self.assertEqual(calculate(13            operation='divide',14            first=3.5,15            second=516        ), "The result is 0.7")17    def test_int_trunc(self):18        self.assertEqual(calculate(...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
