Skip to content

Commit

Permalink
test: increase coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
natelandau committed Nov 8, 2023
1 parent 3000d43 commit 675b8cf
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 41 deletions.
54 changes: 27 additions & 27 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
aiofiles = "^23.2.1"
arrow = "^1.3.0"
beanie = "^1.23.1"
boto3 = "^1.28.78"
boto3 = "^1.28.80"
inflect = "^7.0.0"
loguru = "^0.7.2"
numpy = "^1.26.1"
Expand All @@ -45,7 +45,7 @@
pytest-xdist = "^3.3.1"

[tool.poetry.group.dev.dependencies]
black = "^23.10.1"
black = "^23.11.0"
commitizen = "^3.12.0"
coverage = "^7.3.2"
mypy = "^1.6.1"
Expand Down Expand Up @@ -98,7 +98,6 @@
omit = [
"src/valentina/__version__.py",
"src/valentina/bot.py",
"src/valentina/character/*",
"src/valentina/cogs/*",
"src/valentina/main.py",
"src/valentina/views/*",
Expand Down
7 changes: 0 additions & 7 deletions src/valentina/models/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,13 +385,6 @@ async def on_connect(self) -> None:
# Initialize the mongodb database
await init_database()

# TODO: BEGIN one-time migration code (remove after first run)
from valentina.utils.migrate_to_mongo import Migrate # noqa: PLC0415

migrate = Migrate(config=CONFIG)
await migrate.do_migration()
# TODO: END: Remove one-time migration code

# Connect to discord
if not self.connected:
logger.info(f"Logged in as {self.user.name} ({self.user.id})")
Expand Down
6 changes: 3 additions & 3 deletions src/valentina/utils/autocomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -557,7 +557,7 @@ async def select_trait_category(ctx: discord.AutocompleteContext) -> list[Option
return [
OptionChoice(category.name.title(), category.name)
for category in TraitCategory
if category.name.lower().startswith(ctx.options["category"].lower())
if category.name.startswith(ctx.options["category"].upper())
][:MAX_OPTION_LIST_SIZE]


Expand All @@ -574,7 +574,7 @@ async def select_vampire_clan(ctx: discord.AutocompleteContext) -> list[OptionCh
list[str]: A list of vampire clan names for the autocomplete list.
"""
return [
OptionChoice(c.name, c.name)
OptionChoice(c.name.title(), c.name)
for c in VampireClan
if c.value.name.lower().startswith(ctx.options["vampire_clan"].lower())
if c.name.startswith(ctx.options["vampire_clan"].upper())
][:MAX_OPTION_LIST_SIZE]
4 changes: 4 additions & 0 deletions src/valentina/utils/database.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Database utilities for Valentina."""

from beanie import init_beanie
from loguru import logger
from motor.motor_asyncio import AsyncIOMotorClient

from valentina.constants import CONFIG
Expand All @@ -23,6 +24,7 @@ async def init_database(client=None, database=None) -> None: # type: ignore [no
client (AsyncIOMotorClient, optional): The database client. Defaults to None.
database (AsyncIOMotorClient, optional): The database. Defaults to None.
"""
logger.debug("DB: Initializing...")
# Create Motor client
if not client:
client = AsyncIOMotorClient(f"{CONFIG['VALENTINA_MONGO_URI']}", tz_aware=True)
Expand All @@ -43,3 +45,5 @@ async def init_database(client=None, database=None) -> None: # type: ignore [no
RollProbability,
],
)

logger.info("DB: Initialized")
20 changes: 19 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ async def _init_database(request):


### Mock discord.py objects ###
@pytest.fixture()
def mock_interaction1(mocker, mock_guild1, mock_member):
"""A mock of a discord.Interaction object."""
mock_interaction = mocker.MagicMock()
mock_interaction.id = 1
mock_interaction.guild = mock_guild1
mock_interaction.author = mock_member

mock_interaction.__class__ = discord.Interaction

return mock_interaction


@pytest.fixture()
def mock_member(mocker):
"""A mock of a discord.Member object."""
Expand Down Expand Up @@ -119,15 +132,20 @@ def mock_guild2(mocker):


@pytest.fixture()
def mock_ctx1(mocker, mock_member, mock_guild1):
def mock_ctx1(mocker, mock_member, mock_guild1, mock_interaction1):
"""Create a mock context object with user 1."""
# Mock the ctx.bot object
mock_bot = mocker.MagicMock()
mock_bot.user_svc.update_or_add = MagicMock(return_value=mock_member)
mock_bot.__class__ = commands.Bot

mock_options = mocker.MagicMock()
mock_options.__class__ = dict
mock_options = {}

# Mock the ctx object
mock_ctx = mocker.MagicMock()
mock_ctx.interaction = mock_interaction1
mock_ctx.author = mock_member
mock_ctx.bot = mock_bot
mock_ctx.guild = mock_guild1
Expand Down
118 changes: 118 additions & 0 deletions tests/test_autocomplete.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# type: ignore
"""Test the autocomplete functions."""

import discord
import pytest
from discord.commands import OptionChoice
from rich import print

from valentina.models import Campaign
from valentina.utils import autocomplete

from .factories import *


@pytest.mark.drop_db()
async def test_select_campaign(campaign_factory, mock_ctx1):
"""Test the select_campaign function."""
# GIVEN a campaign in the database
campaign = campaign_factory.build(name="mock_campaign", guild=mock_ctx1.interaction.guild.id)
await campaign.insert()

mock_ctx1.options = {"campaign": "mock_campaign"}

# WHEN calling select_campaign
result = await autocomplete.select_campaign(mock_ctx1)

# THEN the campaign is returned
assert len(result) == 1
assert result[0].name == "mock_campaign"
assert result[0].value == str(campaign.id)


@pytest.mark.no_db()
async def test_select_vampire_clan(mock_ctx1):
"""Test the select_vampire_clan function."""
# GIVEN a mock context
mock_ctx1.options = {"vampire_clan": "Ventrue"}

# WHEN calling select_vampire_clan
result = await autocomplete.select_vampire_clan(mock_ctx1)

# THEN the clan is returned
assert len(result) == 1
assert result[0].name == "Ventrue"
assert result[0].value == "VENTRUE"

# GIVEN a mock context
mock_ctx1.options = {"vampire_clan": "some_thing"}

# WHEN calling select_vampire_clan
result = await autocomplete.select_vampire_clan(mock_ctx1)

# THEN the clan is returned
assert len(result) == 0


@pytest.mark.no_db()
async def test_select_trait_category(mock_ctx1):
"""Test the select_trait_category function."""
# GIVEN a mock context
mock_ctx1.options = {"category": "physical"}

# WHEN calling select_trait_category
result = await autocomplete.select_trait_category(mock_ctx1)

# THEN the category is returned
assert len(result) == 1
assert result[0].name == "Physical"
assert result[0].value == "PHYSICAL"

# GIVEN a mock context
mock_ctx1.options = {"category": "some_thing"}

# WHEN calling select_trait_category
result = await autocomplete.select_trait_category(mock_ctx1)

# THEN the category is returned
assert len(result) == 0


@pytest.mark.drop_db()
async def test_select_storyteller_character(mock_ctx1, character_factory):
"""Test the select_storyteller_character function."""
# GIVEN two characters in the database and a mock_ context
character1 = character_factory.build(
name_first="character1",
name_last="character1",
guild=mock_ctx1.interaction.guild.id,
type_storyteller=True,
type_player=False,
type_chargen=False,
is_alive=True,
traits=[],
)

character2 = character_factory.build(
name_first="character2",
name_last="character2",
guild=mock_ctx1.interaction.guild.id,
type_storyteller=False,
type_player=True,
type_chargen=False,
is_alive=True,
traits=[],
)

await character1.insert()
await character2.insert()

mock_ctx1.value = "char"

# WHEN calling select_storyteller_character
result = await autocomplete.select_storyteller_character(mock_ctx1)

# THEN the storyteller character is returned
assert len(result) == 1
assert result[0].name == "character1 character1"
assert result[0].value == str(character1.id)

0 comments on commit 675b8cf

Please sign in to comment.