Skip to content

Commit

Permalink
test(8ball): Refactor to allow testing of choice logic
Browse files Browse the repository at this point in the history
We parametrise the class with a source of randomness so it can be fixed with a seed in the tests
  • Loading branch information
mrwilson committed Jul 27, 2024
1 parent 230240a commit 5837123
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 12 deletions.
27 changes: 15 additions & 12 deletions cogs/commands/eightball.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import random
import shlex
import string
from typing import List
from random import Random
from shlex import split
from typing import List, Optional

from discord.ext import commands
from discord.ext.commands import Bot, Context, clean_content
Expand All @@ -16,20 +15,24 @@


class EightBall(commands.Cog):
def __init__(self, bot: Bot, options: List[string]):
def __init__(self, bot: Bot, random: Random, options: List[str]):
self.bot = bot
self.random = random
self.options = options

def execute(self, author: str, args: List[str]) -> Optional[str]:
if len(args) == 1:
return f"You must pose the Magic 8-ball a dilemma {author}!"
else:
return f"{author}: {(self.random.choice(self.options))}"

@commands.hybrid_command(name="8ball", help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)
async def execute(self, ctx: Context, *, args: str = ""):
async def eight_ball(self, ctx: Context, *, args: str = ""):
args = await clean_content().convert(ctx, args)
args = shlex.split(args)
display_name = get_name_string(ctx.message)

if len(args) == 1:
await ctx.send(f"You must pose the Magic 8-ball a dilemma {display_name}!")
else:
await ctx.send(f"{display_name}: {(random.choice(self.options))}")
if response := self.execute(display_name, split(args)):
await ctx.send(response)


async def setup(bot: Bot):
Expand Down Expand Up @@ -59,4 +62,4 @@ async def setup(bot: Bot):
"Very doubtful",
]

await bot.add_cog(EightBall(bot, options))
await bot.add_cog(EightBall(bot, Random(), options))
25 changes: 25 additions & 0 deletions tests/test_eightball.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from random import Random

from discord import Intents
from discord.ext.commands import Bot

from cogs.commands.eightball import EightBall


def test_eightball_no_question():
eightball = EightBall(Bot("/", intents=Intents()), Random(1), [])

assert (
eightball.execute("test", [])
== "You must pose the Magic 8-ball a dilemma test!"
)


def test_eightball_question_with_fixed_randomness():
eightball = EightBall(
Bot("/", intents=Intents()), Random(1), ["Yes", "No", "Maybe"]
)

answers = [eightball.execute("test", []) for i in range(0, 7)]

assert answers == ["Yes", "Maybe", "Yes", "No", "Yes", "No", "No"]

0 comments on commit 5837123

Please sign in to comment.