Ejemplo n.º 1
0
    async def test_trigger_at_mj(self):
        """Unit tests for IA.trigger_at_mj function."""
        # async def trigger_at_mj(message)
        trigger_at_mj = IA.trigger_at_mj

        # no mention
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oo", role_mentions=[])
        rep = await trigger_at_mj(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # other role mention
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx,
                                       "oo",
                                       role_mentions=[config.Role.joueur_mort])
        rep = await trigger_at_mj(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # @MJ mention
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx,
                                       "oo",
                                       role_mentions=[config.Role.mj])
        rep = await trigger_at_mj(message)
        self.assertIs(rep, True)
        ctx.assert_sent("ils sont en route")
Ejemplo n.º 2
0
    async def test_process_IA(self, *patches):
        """Unit tests for IA.process_IA function."""
        # async def process_IA(message, debug=False)
        process_IA = IA.process_IA
        # patches = reverse order of triggers

        # test if none triggered except default, then mot_unique, then...
        for i in range(len(patches)):
            # made reaction = patch[i]
            for ii, patch in enumerate(patches):
                if ii <= i:  # i and lower priority: return True
                    patch.return_value = True
                else:  # higher priority: return False
                    patch.return_value = False

            ctx = mock_discord.get_ctx(None)
            message = mock_discord.message(ctx, "")
            rep = await process_IA(message)
            for ii, patch in enumerate(patches):
                if ii >= i:  # i and higher priority: called
                    patch.assert_called_once()
                    self.assertEqual(patch.call_args.args[0], message)
                else:  # lower priority: not called
                    patch.assert_not_called()
                patch.reset_mock()
Ejemplo n.º 3
0
    async def test_trigger_a_ou_b(self):
        """Unit tests for IA.trigger_a_ou_b function."""
        # async def trigger_a_ou_b(message)
        trigger_a_ou_b = IA.trigger_a_ou_b

        samples = {
            "": False,
            "bla bla": False,
            "boozabaka": False,
            "booza ou baka": "Baka.",
            "a v à @ ou b. !??,!;;!": "B.",
            "a v à @ ou b. !??,!;;!a": "B. !??,!;;!a.",
        }

        # all samples
        for sample, result in samples.items():
            ctx = mock_discord.get_ctx(None)
            message = mock_discord.message(ctx, sample)
            rep = await trigger_a_ou_b(message)
            if result is False:
                self.assertIs(rep, False)
                ctx.assert_sent()
            else:
                self.assertIs(rep, True)
                ctx.assert_sent(result)
Ejemplo n.º 4
0
    async def test_trigger_mot_unique(self):
        """Unit tests for IA.trigger_mot_unique function."""
        # async def trigger_mot_unique(message)
        trigger_mot_unique = IA.trigger_mot_unique

        samples = {
            "": False,
            "bla bla": False,
            "boozabaka": "Boozabaka ?",
            "booza-baka": "Booza-baka ?",
            "@!!!": "@!!! ?",
            "http://oui": False,
        }

        # all samples
        for sample, result in samples.items():
            ctx = mock_discord.get_ctx(None)
            message = mock_discord.message(ctx, sample)
            rep = await trigger_mot_unique(message)
            if result is False:
                self.assertIs(rep, False)
                ctx.assert_sent()
            else:
                self.assertIs(rep, True)
                ctx.assert_sent(result)
Ejemplo n.º 5
0
    async def test_trigger_di(self):
        """Unit tests for IA.trigger_di function."""
        # async def trigger_di(message)
        trigger_di = IA.trigger_di
        diprefs = ["di", "dy", "dis ", "dit ", "dis-", "dit-"]
        criprefs = ["cri", "cry", "kri", "kry"]

        samples = {
            "": False,
            "boozabaka": False,
            **{f"{pref}kaboom": "kaboom"
               for pref in diprefs},
            **{f"{pref}kaé@@m": "KAÉ@@M"
               for pref in criprefs},
            **{f"aa{pref}ka{pref}oh": f"ka{pref}oh"
               for pref in diprefs},
        }

        # all samples
        for sample, result in samples.items():
            ctx = mock_discord.get_ctx(None)
            message = mock_discord.message(ctx, sample)
            rep = await trigger_di(message)
            if result is False:
                self.assertIs(rep, False)
                ctx.assert_sent()
            else:
                self.assertIs(rep, True)
                ctx.assert_sent(result)
Ejemplo n.º 6
0
    async def test_trigger_roles(self):
        """Unit tests for IA.trigger_roles function."""
        # async def trigger_roles(message, sensi=0.8)
        trigger_roles = IA.trigger_roles
        mock_bdd.add_campsroles(10, 10)

        # nothing
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "ooooo")
        rep = await trigger_roles(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # one exact role found
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "Role3")
        role3 = bdd.Role.query.get("role3")
        role3.prefixe = "PREF@x"
        role3.description_courte = "D€$k00rt"
        role3.description_longue = "D€$k_longue"
        role3.camp = bdd.Camp.query.get("camp3")
        rep = await trigger_roles(message)
        self.assertIs(rep, True)
        ctx.assert_sent(
            ["Role3", "PREF@x", "D€$k00rt", "D€$k_longue", "Camp3"])

        # high sensi
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "Rol")
        rep = await trigger_roles(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # low sensi - more roles found
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "Rol")
        rep = await trigger_roles(message, sensi=0.5)
        self.assertIs(rep, True)
        ctx.assert_sent("Role")  # one selected
Ejemplo n.º 7
0
    async def test_trigger_gif(self, ft_patch):
        """Unit tests for IA.trigger_gif function."""
        # async def trigger_gif(message)
        trigger_gif = IA.trigger_gif
        config.bot.in_fals = [12, 13]

        # not in FALS
        ctx = mock_discord.get_ctx(None)
        ctx.channel.id = 2
        message = mock_discord.message(ctx, "booza")
        rep = await trigger_gif(message)
        self.assertIs(rep, False)
        ft_patch.assert_not_called()
        ctx.assert_sent()

        # in FALS, return None
        ctx = mock_discord.get_ctx(None)
        ctx.channel.id = 12
        message = mock_discord.message(ctx, "booza")
        ft_patch.return_value = None
        rep = await trigger_gif(message)
        self.assertIs(rep, False)
        ft_patch.assert_called_once_with("booza")
        ctx.assert_sent()
        ft_patch.reset_mock()

        # in FALS, return a gif
        ctx = mock_discord.get_ctx(None)
        ctx.channel.id = 12
        message = mock_discord.message(ctx, "booza")
        ft_patch.return_value = "gif://cgénial"
        rep = await trigger_gif(message)
        self.assertIs(rep, True)
        ft_patch.assert_called_once_with("booza")
        ctx.assert_sent("gif://cgénial")
        ft_patch.reset_mock()

        config.bot.in_fals = []
Ejemplo n.º 8
0
    async def test_default(self):
        """Unit tests for IA.default function."""
        # async def default(message)
        default = IA.default

        samples = {
            "": False,
            "bla bla": False,
            "boozabaka": False,
            "booza ou baka": "Baka.",
            "a v à @ ou b. !??,!;;!": "B.",
            "a v à @ ou b. !??,!;;!a": "B. !??,!;;!a.",
        }

        # all samples
        for sample, result in samples.items():
            ctx = mock_discord.get_ctx(None)
            message = mock_discord.message(ctx, sample)
            rep = await default(message)
            self.assertIs(rep, True)
Ejemplo n.º 9
0
    async def test_addIA(self, bs_patch):
        """Unit tests for !addIA command."""
        # async def addIA(self, ctx, *, triggers=None)
        addIA = self.cog.addIA

        # no triggers, simple gave
        ctx = mock_discord.get_ctx(addIA)
        bs_patch.return_value = "s€quenZ"
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "trigzz"))):
            await ctx.invoke()
        bs_patch.assert_called_once_with(ctx)
        ctx.assert_sent("déclencheurs", "trigzz", "s€quenZ", "ajoutée en base")
        trig = bdd.Trigger.query.one()
        reac = bdd.Reaction.query.one()
        self.assertEqual(trig.trigger, "trigzz")
        self.assertEqual(trig.reaction, reac)
        self.assertEqual(reac.reponse, "s€quenZ")
        bdd.Trigger.delete(trig, reac)
        bs_patch.reset_mock()

        # complex triggers
        triggers = "trigger\n\nTR1; trégèrçù; trÉgÈrÇÙ   ;;  ❤\nah!"
        formated_trgz = ["trigger", "tr1", "tregercu", "tregercu", "❤", "ah!"]
        ctx = mock_discord.get_ctx(addIA, triggers=triggers)
        bs_patch.return_value = "s€quenZ"
        await ctx.invoke()
        bs_patch.assert_called_once_with(ctx)
        ctx.assert_sent(formated_trgz, "s€quenZ", "ajoutée en base")
        trigs = bdd.Trigger.query.all()
        reac = bdd.Reaction.query.one()
        self.assertEqual(len(trigs), 5)
        self.assertEqual({trig.trigger for trig in trigs}, set(formated_trgz))
        self.assertEqual([trig.reaction for trig in trigs], [reac] * 5)
        self.assertEqual(reac.reponse, "s€quenZ")
        bs_patch.reset_mock()
Ejemplo n.º 10
0
    async def test_send(self):
        """Unit tests for !send command."""
        # async def send(self, ctx, cible, *, message)
        send = self.cog.send
        mock_bdd.add_campsroles(10, 10)
        joueurs = [
            bdd.Joueur(discord_id=1,
                       chan_id_=11,
                       nom="Joueur1",
                       statut=bdd.Statut.vivant,
                       _role_slug="role1",
                       votant_village=True,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=2,
                       chan_id_=21,
                       nom="Joueur2",
                       chambre="ch2",
                       statut=bdd.Statut.vivant,
                       votant_village=True,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=3,
                       chan_id_=31,
                       nom="Joueur3",
                       statut=bdd.Statut.mort,
                       _role_slug="role3",
                       _camp_slug="camp3",
                       votant_village=True,
                       votant_loups=False,
                       role_actif=True),
            bdd.Joueur(discord_id=4,
                       chan_id_=41,
                       nom="Joueur4",
                       chambre="ch 4",
                       statut=bdd.Statut.mort,
                       votant_village=False,
                       votant_loups=False,
                       role_actif=True),
            bdd.Joueur(discord_id=5,
                       chan_id_=51,
                       nom="Joueur 5",
                       statut=bdd.Statut.MV,
                       _camp_slug="camp3",
                       votant_village=False,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=6,
                       chan_id_=61,
                       nom="Joueur6",
                       statut=bdd.Statut.immortel,
                       _role_slug="role3",
                       votant_village=False,
                       votant_loups=True,
                       role_actif=False),
        ]
        bdd.Joueur.add(*joueurs)

        # cible = "all"
        ctx = mock_discord.get_ctx(send, "all", message="ouizz")
        with mock_discord.mock_members_and_chans(*joueurs):
            chans = [joueur.private_chan for joueur in joueurs]
            await ctx.invoke()
        ctx.assert_sent("6 trouvé", "Fini")
        for chan in chans:
            chan.send.assert_called_once_with("ouizz")

        # cible = "vivants"
        ctx = mock_discord.get_ctx(send, "vivants", message="nonkk")
        with mock_discord.mock_members_and_chans(*joueurs):
            chans = [joueur.private_chan for joueur in joueurs]
            await ctx.invoke()
        ctx.assert_sent("3 trouvé", "Fini")
        for i, chan in enumerate(chans):
            if i in [0, 1, 4]:
                chan.send.assert_called_once_with("nonkk")
            else:
                chan.send.assert_not_called()

        # cible = "morts"
        ctx = mock_discord.get_ctx(send, "morts", message="bzzk.!")
        with mock_discord.mock_members_and_chans(*joueurs):
            chans = [joueur.private_chan for joueur in joueurs]
            await ctx.invoke()
        ctx.assert_sent("2 trouvé", "Fini")
        for i, chan in enumerate(chans):
            if i in [2, 3]:
                chan.send.assert_called_once_with("bzzk.!")
            else:
                chan.send.assert_not_called()

        # cible = bat crit
        ctx = mock_discord.get_ctx(send, "biz=oui", message="hmm")
        with self.assertRaises(discord.ext.commands.UserInputError) as cm:
            await ctx.invoke()
        self.assertIn("critère 'biz' incorrect", cm.exception.args[0])

        # cible = all crits
        crits = {
            "discord_id=3": [2],
            "chan_id_=21": [1],
            "nom=Joueur4": [3],
            "nom=Joueur 5": [4],
            "chambre=ch2": [1],
            "chambre=ch 4": [3],
            "statut=vivant": [0, 1],
            "statut=mort": [2, 3],
            "statut=MV": [4],
            "statut=immortel": [5],
            "role=role1": [0],
            "role=role3": [2, 5],
            "camp=camp3": [2, 4],
            "votant_village=True": [0, 1, 2],
            "votant_village=1": [0, 1, 2],
            "votant_village=faux": [3, 4, 5],
            "votant_loups=vrai": [5],
            "votant_loups=0": [0, 1, 2, 3, 4],
            "role_actif=True": [2, 3],
            "role_actif=False": [0, 1, 4, 5],
        }
        for crit, ijs in crits.items():
            ctx = mock_discord.get_ctx(send, crit, message="bakka")
            with mock_discord.mock_members_and_chans(*joueurs):
                chans = [joueur.private_chan for joueur in joueurs]
                await ctx.invoke()
            ctx.assert_sent(f"{len(ijs)} trouvé", "Fini")
            for i, chan in enumerate(chans):
                if i in ijs:
                    chan.send.assert_called_once_with("bakka")
                else:
                    chan.send.assert_not_called()

        # cible = non-existing joueur, correct
        ctx = mock_discord.get_ctx(send, "gouzigouzi", message="oui")
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "krr")),
            ("wait_for_message_here", mock_discord.message(ctx, "Joueur2")),
        ):
            with mock_discord.mock_members_and_chans(*joueurs):
                chans = [joueur.private_chan for joueur in joueurs]
                await ctx.invoke()
        ctx.assert_sent("Aucune entrée trouvée", "Aucune entrée trouvée",
                        "1 trouvé", "Fini")
        for i, chan in enumerate(chans):
            if i == 1:
                chan.send.assert_called_once_with("oui")
            else:
                chan.send.assert_not_called()

        # cible = existing joueur, correct
        ctx = mock_discord.get_ctx(send, "Joueur 5", message="oui")
        with mock_discord.mock_members_and_chans(*joueurs):
            chans = [joueur.private_chan for joueur in joueurs]
            await ctx.invoke()
        ctx.assert_sent("1 trouvé", "Fini")
        for i, chan in enumerate(chans):
            if i == 4:
                chan.send.assert_called_once_with("oui")
            else:
                chan.send.assert_not_called()

        # cible = all, test eval
        ctx = mock_discord.get_ctx(
            send,
            "all",
            message="Salut {member.mention}, tu t'appelles {joueur.role}, rôle "
            "{joueur.role.nom}, camp {joueur.camp.nom}, chan {chan.name}")
        with mock_discord.mock_members_and_chans(*joueurs):
            members = [joueur.member for joueur in joueurs]
            chans = [joueur.private_chan for joueur in joueurs]
            await ctx.invoke()
        ctx.assert_sent("6 trouvé", "Fini")
        for joueur, chan, member in zip(joueurs, chans, members):
            chan.send.assert_called_once_with(
                f"Salut {member.mention}, tu t'appelles {joueur.role}, rôle "
                f"{joueur.role.nom}, camp {joueur.camp.nom}, chan {chan.name}")
Ejemplo n.º 11
0
    async def test_annoncemort(self, as_patch):
        """Unit tests for !annoncemort command."""
        # async def annoncemort(self, ctx, *, victime=None)
        annoncemort = self.cog.annoncemort
        mock_bdd.add_campsroles(10, 10)
        joueurs = [
            bdd.Joueur(discord_id=1,
                       chan_id_=11,
                       nom="Joueur1",
                       statut=bdd.Statut.vivant,
                       _role_slug="role1"),
            bdd.Joueur(discord_id=2,
                       chan_id_=21,
                       nom="Joueur2",
                       chambre="ch2",
                       statut=bdd.Statut.vivant),
            bdd.Joueur(discord_id=3,
                       chan_id_=31,
                       nom="Joueur3",
                       statut=bdd.Statut.mort,
                       _role_slug="role3",
                       _camp_slug="camp3"),
            bdd.Joueur(discord_id=4,
                       chan_id_=41,
                       nom="Joueur4",
                       chambre="ch 4",
                       statut=bdd.Statut.mort),
            bdd.Joueur(discord_id=5,
                       chan_id_=51,
                       nom="Joueur5",
                       statut=bdd.Statut.MV,
                       _role_slug="role5"),
            bdd.Joueur(discord_id=6,
                       chan_id_=61,
                       nom="Joueur6",
                       statut=bdd.Statut.immortel,
                       _role_slug="role3"),
        ]
        bdd.Joueur.add(*joueurs)

        # victime = None, correct "Joueur3", role ok, abort
        ctx = mock_discord.get_ctx(annoncemort)
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "bzz")),
            ("wait_for_message_here", mock_discord.message(ctx, "Joueur3")),
            ("yes_no", True),  # rôle à afficher
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", False),  # abort
        ):
            await ctx.invoke(cog=self.cog)
        ctx.assert_sent("Qui", "Aucune entrée trouvée", "Rôle à afficher",
                        "Contexte", "Ça part", "Mission aborted")
        as_patch.assert_not_called()

        # victime = "Joueur3", role ok, proceed
        ctx = mock_discord.get_ctx(annoncemort, victime="Joueur3")
        with mock_discord.interact(
            ("yes_no", True),  # rôle à afficher
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", True),  # proceed
        ):
            await ctx.invoke(cog=self.cog)
        ctx.assert_sent("Rôle à afficher", "Contexte", "Ça part",
                        "c'est parti")
        as_patch.assert_called_once()
        self.assertIn("quelque chose", as_patch.call_args.args[0])
        embed = as_patch.call_args.kwargs["embed"]
        self.assertIn("Joueur3", embed.title)
        self.assertIn("Role3", embed.title)
        self.assertIn("oui", embed.description)
        self.assertEqual(discord.Embed.Empty, embed.thumbnail.url)
        # standard role: no emoji
        as_patch.reset_mock()

        # victime = "Joueur3", role ok, proceed + emoji
        ctx = mock_discord.get_ctx(annoncemort, victime="Joueur3")
        emoji3 = mock.NonCallableMock(discord.Emoji)
        emoji3.configure_mock(name="emoji3", url="bzooop")
        _emojis = config.guild.emojis
        config.guild.emojis = [emoji3]
        with mock_discord.interact(
            ("yes_no", True),  # rôle à afficher
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", True),  # proceed
        ):
            await ctx.invoke(cog=self.cog)
        config.guild.emojis = _emojis
        ctx.assert_sent("Rôle à afficher", "Contexte", "Ça part",
                        "c'est parti")
        as_patch.assert_called_once()
        self.assertIn("quelque chose", as_patch.call_args.args[0])
        embed = as_patch.call_args.kwargs["embed"]
        self.assertIn("Joueur3", embed.title)
        self.assertIn("Role3", embed.title)
        self.assertIn("oui", embed.description)
        self.assertEqual("bzooop", embed.thumbnail.url)
        as_patch.reset_mock()

        # victime = "Joueur5" (MV), role ok no MV, proceed
        ctx = mock_discord.get_ctx(annoncemort, victime="Joueur5")
        with mock_discord.interact(
            ("yes_no", True),  # rôle à afficher
            ("yes_no", False),  # afficher la MVance
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", True),  # proceed
        ):
            await ctx.invoke(cog=self.cog)
        ctx.assert_sent("Rôle à afficher", "Annoncer la mort-vivance",
                        "Contexte", "Ça part", "c'est parti")
        as_patch.assert_called_once()
        self.assertIn("quelque chose", as_patch.call_args.args[0])
        embed = as_patch.call_args.kwargs["embed"]
        self.assertIn("Joueur5", embed.title)
        self.assertIn("Role5", embed.title)
        self.assertNotIn("Mort-Vivant", embed.title)
        self.assertIn("oui", embed.description)
        as_patch.reset_mock()

        # victime = "Joueur5" (MV), role ok no MV, proceed
        ctx = mock_discord.get_ctx(annoncemort, victime="Joueur5")
        with mock_discord.interact(
            ("yes_no", True),  # rôle à afficher
            ("yes_no", True),  # afficher la MVance
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", True),  # proceed
        ):
            await ctx.invoke(cog=self.cog)
        ctx.assert_sent("Rôle à afficher", "Annoncer la mort-vivance",
                        "Contexte", "Ça part", "c'est parti")
        as_patch.assert_called_once()
        self.assertIn("quelque chose", as_patch.call_args.args[0])
        embed = as_patch.call_args.kwargs["embed"]
        self.assertIn("Joueur5", embed.title)
        self.assertIn("Role5", embed.title)
        self.assertIn("Mort-Vivant", embed.title)
        self.assertIn("oui", embed.description)
        as_patch.reset_mock()

        role_village = bdd.Role(slug="")

        # victime = "Joueur3", role not ok usoab, proceed
        ctx = mock_discord.get_ctx(annoncemort, victime="Joueur3")
        with mock_discord.interact(
            ("yes_no", False),  # rôle à afficher
            ("wait_for_message_here", mock_discord.message(ctx, "RolZZZ")),
            ("wait_for_react_clic",
             mock.NonCallableMock(discord.Emoji, url="bzooop")),
            ("wait_for_message_here", mock_discord.message(ctx, "oui")),
            ("yes_no", True),  # proceed
        ):
            await ctx.invoke(cog=self.cog)
        ctx.assert_sent("Rôle à afficher", "Rôle à afficher", "Camp",
                        "Contexte", "Ça part", "c'est parti")
        as_patch.assert_called_once()
        self.assertIn("quelque chose", as_patch.call_args.args[0])
        embed = as_patch.call_args.kwargs["embed"]
        self.assertIn("Joueur3", embed.title)
        self.assertIn("RolZZZ", embed.title)
        self.assertIn("oui", embed.description)
        self.assertEqual("bzooop", embed.thumbnail.url)
        as_patch.reset_mock()
Ejemplo n.º 12
0
    async def test_addhere(self):
        """Unit tests for !addhere command."""
        # async def addhere(self, ctx, *joueurs)
        addhere = self.cog.addhere

        mock_bdd.add_campsroles(10, 10)
        joueurs = [
            bdd.Joueur(discord_id=1,
                       chan_id_=11,
                       nom="Joueur1",
                       statut=bdd.Statut.vivant,
                       _role_slug="role1",
                       votant_village=True,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=2,
                       chan_id_=21,
                       nom="Joueur2",
                       chambre="ch2",
                       statut=bdd.Statut.vivant,
                       votant_village=True,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=3,
                       chan_id_=31,
                       nom="Joueur3",
                       statut=bdd.Statut.mort,
                       _role_slug="role3",
                       _camp_slug="camp3",
                       votant_village=True,
                       votant_loups=False,
                       role_actif=True),
            bdd.Joueur(discord_id=4,
                       chan_id_=41,
                       nom="Joueur4",
                       chambre="ch 4",
                       statut=bdd.Statut.mort,
                       votant_village=False,
                       votant_loups=False,
                       role_actif=True),
            bdd.Joueur(discord_id=5,
                       chan_id_=51,
                       nom="Joueur 5",
                       statut=bdd.Statut.MV,
                       _camp_slug="camp3",
                       votant_village=False,
                       votant_loups=False,
                       role_actif=False),
            bdd.Joueur(discord_id=6,
                       chan_id_=61,
                       nom="Joueur6",
                       statut=bdd.Statut.immortel,
                       _role_slug="role3",
                       votant_village=False,
                       votant_loups=True,
                       role_actif=False),
        ]
        bdd.Joueur.add(*joueurs)

        # cible = bat filtre
        ctx = mock_discord.get_ctx(addhere, "biz=oui")
        with self.assertRaises(discord.ext.commands.UserInputError) as cm:
            await ctx.invoke()
        self.assertIn("critère 'biz' incorrect", cm.exception.args[0])

        # cible = all filtres
        crits = {
            "discord_id=3": [2],
            "chan_id_=21": [1],
            "nom=Joueur4": [3],
            "nom=Joueur 5": [4],
            "chambre=ch2": [1],
            "chambre=ch 4": [3],
            "statut=vivant": [0, 1],
            "statut=mort": [2, 3],
            "statut=MV": [4],
            "statut=immortel": [5],
            "role=role1": [0],
            "role=role3": [2, 5],
            "camp=camp3": [2, 4],
            "votant_village=True": [0, 1, 2],
            "votant_village=1": [0, 1, 2],
            "votant_village=faux": [3, 4, 5],
            "votant_loups=vrai": [5],
            "votant_loups=0": [0, 1, 2, 3, 4],
            "role_actif=True": [2, 3],
            "role_actif=False": [0, 1, 4, 5],
        }
        for crit, ijs in crits.items():
            ctx = mock_discord.get_ctx(addhere, crit)
            with mock_discord.mock_members_and_chans(*joueurs):
                members = [joueur.member for joueur in joueurs]
                with mock_discord.interact(("yes_no", False)):
                    await ctx.invoke()
            ctx.assert_sent(*[joueurs[ij].nom for ij in ijs], "Fini")
            self.assertEqual(ctx.channel.set_permissions.call_count, len(ijs))
            ctx.channel.set_permissions.assert_has_calls([
                mock.call(member, read_messages=True, send_messages=True)
                for ij, member in enumerate(members) if ij in ijs
            ])
            ctx.channel.purge.assert_not_called()

        # cible = non-existing joueur, correct
        ctx = mock_discord.get_ctx(addhere, "gouzigouzi")
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "krr")),
            ("wait_for_message_here", mock_discord.message(ctx, "Joueur2")),
            ("yes_no", False),
        ):
            with mock_discord.mock_members_and_chans(*joueurs):
                members = [joueur.member for joueur in joueurs]
                await ctx.invoke()
        ctx.assert_sent("Aucune entrée trouvée", "Aucune entrée trouvée",
                        "Joueur2", "Fini")
        ctx.channel.set_permissions.assert_called_once_with(members[1],
                                                            read_messages=True,
                                                            send_messages=True)
        ctx.channel.purge.assert_not_called()

        # cible = existing joueur
        ctx = mock_discord.get_ctx(addhere, "Joueur 5")
        with mock_discord.mock_members_and_chans(*joueurs):
            members = [joueur.member for joueur in joueurs]
            with mock_discord.interact(("yes_no", False)):
                await ctx.invoke()
        ctx.assert_sent("Joueur 5", "Fini")
        ctx.channel.set_permissions.assert_called_once_with(members[4],
                                                            read_messages=True,
                                                            send_messages=True)
        ctx.channel.purge.assert_not_called()

        # cible = several joueurs, correct some
        ctx = mock_discord.get_ctx(addhere, "Joueur2", "kwdzz", "Joueur 5")
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "krr")),
            ("wait_for_message_here", mock_discord.message(ctx, "Joueur4")),
            ("yes_no", False),
        ):
            with mock_discord.mock_members_and_chans(*joueurs):
                members = [joueur.member for joueur in joueurs]
                await ctx.invoke()
        ctx.assert_sent("Aucune entrée trouvée", "Aucune entrée trouvée",
                        "Joueur2", "Joueur4", "Joueur 5", "Fini")
        self.assertEqual(ctx.channel.set_permissions.call_count, 3)
        ctx.channel.set_permissions.assert_has_calls([
            mock.call(members[1], read_messages=True, send_messages=True),
            mock.call(members[3], read_messages=True, send_messages=True),
            mock.call(members[4], read_messages=True, send_messages=True),
        ])
        ctx.channel.purge.assert_not_called()

        # cible = existing joueur, purge
        ctx = mock_discord.get_ctx(addhere, "Joueur 5")
        with mock_discord.mock_members_and_chans(*joueurs):
            members = [joueur.member for joueur in joueurs]
            with mock_discord.interact(("yes_no", True)):
                await ctx.invoke()
        ctx.assert_sent("Joueur 5", "Fini")
        ctx.channel.set_permissions.assert_called_once_with(members[4],
                                                            read_messages=True,
                                                            send_messages=True)
        ctx.channel.purge.assert_called_once()
Ejemplo n.º 13
0
    async def test_modifIA(self, bs_patch):
        """Unit tests for !modifIA command."""
        # async def modifIA(self, ctx, *, trigger=None)
        modifIA = self.cog.modifIA

        reac = bdd.Reaction(reponse="s€quenZ")
        triggers = [
            bdd.Trigger(trigger="trigz1", reaction=reac),
            bdd.Trigger(trigger="tr1gZ2", reaction=reac),
            bdd.Trigger(trigger="tr!Gz3", reaction=reac),
        ]
        bdd.Reaction.add(reac, *triggers)

        # nothing found
        ctx = mock_discord.get_ctx(modifIA)
        bs_patch.return_value = "s€quenZ"
        with mock_discord.interact(
            ("wait_for_message_here", mock_discord.message(ctx, "ooooo"))):
            await ctx.invoke()
        ctx.assert_sent("déclencheur", "Rien trouvé")
        bs_patch.assert_not_called()

        # modif triggers
        ctx = mock_discord.get_ctx(modifIA, trigger="trigz")
        with mock_discord.interact(
            ("wait_for_react_clic", 1),  # modif triggers
            ("wait_for_react_clic", "ahbon"),  # trigger 4
            ("wait_for_react_clic", "3"),  # delete trigger 3
            ("wait_for_react_clic", "0"),  # end
        ):
            await ctx.invoke()
        ctx.assert_sent(
            ["trigz1", "tr1gZ2", "tr!Gz3", "s€quenZ"],
            "Modifier",
            ["Supprimer", "ajouter", "trigz1", "tr1gZ2", "tr!Gz3"],
            ["Supprimer", "ajouter", "trigz1", "tr1gZ2", "tr!Gz3", "ahbon"],
            ["Supprimer", "ajouter", "trigz1", "tr1gZ2", "ahbon"],
            "Fini",
        )
        self.assertEqual(bdd.Reaction.query.one(), reac)
        self.assertEqual({trig.trigger
                          for trig in reac.triggers},
                         {"trigz1", "tr1gZ2", "ahbon"})
        self.assertEqual(reac.reponse, "s€quenZ")
        bs_patch.assert_not_called()

        # delete all triggers
        ctx = mock_discord.get_ctx(modifIA, trigger="trigz")
        with mock_discord.interact(
            ("wait_for_react_clic", 1),  # modif triggers
            ("wait_for_react_clic", "3"),  # delete trigger 3
            ("wait_for_react_clic", "1"),  # delete trigger 1
            ("wait_for_react_clic", "1"),  # delete trigger 1
            ("wait_for_react_clic", "0"),  # end
        ):
            await ctx.invoke()
        ctx.assert_sent(
            ["trigz1", "tr1gZ2", "ahbon", "s€quenZ"],
            "Modifier",
            ["Supprimer", "ajouter", "trigz1", "tr1gZ2", "ahbon"],
            ["Supprimer", "ajouter", "trigz1", "tr1gZ2"],
            ["Supprimer", "ajouter", "tr1gZ2"],
            ["Supprimer", "ajouter"],
            "suppression",
        )
        self.assertEqual(len(bdd.Reaction.query.all()), 0)
        self.assertEqual(len(bdd.Trigger.query.all()), 0)
        bs_patch.assert_not_called()

        # modif sequence (simple)
        reac = bdd.Reaction(reponse="s€quenZ")
        triggers = [
            bdd.Trigger(trigger="trigz1", reaction=reac),
            bdd.Trigger(trigger="tr1gZ2", reaction=reac),
            bdd.Trigger(trigger="tr!Gz3", reaction=reac),
        ]
        bdd.Reaction.add(reac, *triggers)

        ctx = mock_discord.get_ctx(modifIA, trigger="trigz")
        bs_patch.return_value = "new_s€qu€nZ"
        with mock_discord.interact(
            ("wait_for_react_clic", 2),  # modif sequence
        ):
            await ctx.invoke()
        ctx.assert_sent(
            ["trigz1", "tr1gZ2", "tr!Gz3", "s€quenZ"],
            "Modifier",
            "Fini",
        )
        self.assertEqual(bdd.Reaction.query.one(), reac)
        self.assertEqual({trig.trigger
                          for trig in reac.triggers},
                         {"trigz1", "tr1gZ2", "tr!Gz3"})
        self.assertEqual(reac.reponse, "new_s€qu€nZ")
        bs_patch.assert_called_once_with(ctx)
        bs_patch.reset_mock()

        # modif sequence (complex)
        reac.reponse = f"s€quenZ{IA.MARK_THEN}oui"
        reac.update()

        ctx = mock_discord.get_ctx(modifIA, trigger="trigz")
        bs_patch.return_value = "new_s€qu€nZ"
        with mock_discord.interact(
            ("wait_for_react_clic", 2),  # modif sequence
        ):
            await ctx.invoke()
        ctx.assert_sent(
            ["trigz1", "tr1gZ2", "tr!Gz3", "s€quenZ"],
            "Modifier",
            "modifiée rapidement",
            "Fini",
        )
        self.assertEqual(bdd.Reaction.query.one(), reac)
        self.assertEqual({trig.trigger
                          for trig in reac.triggers},
                         {"trigz1", "tr1gZ2", "tr!Gz3"})
        self.assertEqual(reac.reponse, "new_s€qu€nZ")
        bs_patch.assert_called_once_with(ctx)
        bs_patch.reset_mock()

        # delete sequence
        ctx = mock_discord.get_ctx(modifIA, trigger="trigz")
        with mock_discord.interact(
            ("wait_for_react_clic", 0),  # dekete sequence
        ):
            await ctx.invoke()
        ctx.assert_sent(
            ["trigz1", "tr1gZ2", "tr!Gz3", "new_s€qu€nZ"],
            "Modifier",
            "Fini",
        )
        self.assertEqual(len(bdd.Reaction.query.all()), 0)
        self.assertEqual(len(bdd.Trigger.query.all()), 0)
        bs_patch.assert_not_called()
Ejemplo n.º 14
0
    async def test_trigger_sub_reactions(self, tr_patch):
        """Unit tests for IA.trigger_sub_reactions function."""
        # async def trigger_sub_reactions(message, sensi=0.9, debug=False)
        trigger_sub_reactions = IA.trigger_sub_reactions

        # empty message
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "")
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, False)
        tr_patch.assert_not_called()
        ctx.assert_sent()

        # one word
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "boo")
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, False)
        tr_patch.assert_not_called()
        ctx.assert_sent()

        # <= 4-length words
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "boo a baaz tok paaf")
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, False)
        tr_patch.assert_not_called()
        ctx.assert_sent()

        # one > 4-length word, return False
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "boo a baazA tok paaf")
        tr_patch.return_value = False
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, False)
        tr_patch.assert_called_once_with(message,
                                         chain="baazA",
                                         sensi=0.9,
                                         debug=False)
        ctx.assert_sent()
        tr_patch.reset_mock()

        # one > 4-length word, return True (and debug True)
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "boo a baazA tok paaf")
        tr_patch.return_value = True
        rep = await trigger_sub_reactions(message, debug=True)
        self.assertIs(rep, True)
        tr_patch.assert_called_once_with(message,
                                         chain="baazA",
                                         sensi=0.9,
                                         debug=True)
        ctx.assert_sent()
        tr_patch.reset_mock()

        # several > 4-length words, all False
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(
            ctx, "book@! a baazA tok pa "
            "frooookpoozpzpzpzppa")
        tr_patch.side_effect = [False, False, False]
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, False)
        self.assertEqual(tr_patch.call_args_list, [
            mock.call(
                message, chain="frooookpoozpzpzpzppa", sensi=0.9, debug=False),
            mock.call(message, chain="book@!", sensi=0.9, debug=False),
            mock.call(message, chain="baazA", sensi=0.9, debug=False),
        ])
        ctx.assert_sent()
        tr_patch.reset_mock()

        # several > 4-length words, second True
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(
            ctx, "book@! a baazA tok pa "
            "frooookpoozpzpzpzppa")
        tr_patch.side_effect = [False, True]
        rep = await trigger_sub_reactions(message)
        self.assertIs(rep, True)
        self.assertEqual(tr_patch.call_args_list, [
            mock.call(
                message, chain="frooookpoozpzpzpzppa", sensi=0.9, debug=False),
            mock.call(message, chain="book@!", sensi=0.9, debug=False),
        ])
        ctx.assert_sent()
        tr_patch.reset_mock()
Ejemplo n.º 15
0
    async def test_trigger_reactions(self):
        """Unit tests for IA.trigger_reactions function."""
        # async def trigger_reactions(message, chain=None, sensi=0.7,
        #                             debug=False)
        trigger_reactions = IA.trigger_reactions

        # no reactions
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "ooooo")
        rep = await trigger_reactions(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # no matching reactions
        reac = bdd.Reaction(reponse="non")
        bdd.Trigger(trigger="oui", reaction=reac).add(reac)
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "ooo")
        rep = await trigger_reactions(message)
        self.assertIs(rep, False)
        ctx.assert_sent()

        # lower sensi -> matching
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "ooo")
        rep = await trigger_reactions(message, sensi=0.3)
        self.assertIs(rep, True)
        ctx.assert_sent("non")

        # command
        reac.reponse = f"{IA.MARK_CMD}commandz"
        reac.update()
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oui")
        with mock.patch("lgrez.config.bot.process_commands") as pc_patch:
            rep = await trigger_reactions(message)
        self.assertIs(rep, True)
        self.assertEqual(message.content, "!commandz")
        ctx.assert_sent()
        pc_patch.assert_called_once_with(message)

        # command - other prefix
        reac.reponse = f"{IA.MARK_CMD}commandz"
        reac.update()
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oui")
        config.bot.command_prefix = "PREFix"
        with mock.patch("lgrez.config.bot.process_commands") as pc_patch:
            rep = await trigger_reactions(message)
        config.bot.command_prefix = "!"
        self.assertIs(rep, True)
        self.assertEqual(message.content, "PREFixcommandz")
        ctx.assert_sent()
        pc_patch.assert_called_once_with(message)

        # react
        reac.reponse = f"{IA.MARK_REACT}bon."
        reac.update()
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oui")
        rep = await trigger_reactions(message)
        self.assertIs(rep, True)
        ctx.assert_sent()
        message.add_reaction.assert_called_once_with("bon.")

        # several commands / reactions / texts
        reac.reponse = (f"mezzage{IA.MARK_THEN}{IA.MARK_REACT}bon."
                        f"{IA.MARK_THEN}{IA.MARK_CMD}ouizz"
                        f"{IA.MARK_THEN}aha!{IA.MARK_THEN}{IA.MARK_REACT}krr")
        reac.update()
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oui")
        with mock.patch("lgrez.config.bot.process_commands") as pc_patch:
            rep = await trigger_reactions(message)
        self.assertIs(rep, True)
        ctx.assert_sent("mezzage", "aha!")
        self.assertEqual(
            message.add_reaction.mock_calls,
            [mock.call("bon."), mock.call("krr")])
        self.assertEqual(message.content, "!ouizz")
        pc_patch.assert_called_once_with(message)

        # OR
        reac.reponse = (f"a{IA.MARK_OR}b")
        reac.update()
        ctx = mock_discord.get_ctx(None)
        message = mock_discord.message(ctx, "oui")
        na = 0
        nb = 0
        for i in range(1000):
            await trigger_reactions(message)
            sent = ctx.send.call_args.args[0]
            if sent == "a":
                na += 1
            elif sent == "b":
                nb += 1
            else:
                raise AssertionError("Sent something else!")
        self.assertGreater(na, 400)
        self.assertGreater(nb, 400)