paper-dynasty-discord/tests/players_refactor/README.md
2025-08-17 08:46:55 -05:00

7.6 KiB

Players Refactor Test Suite

This directory contains comprehensive tests for the refactored players.py modules in the Paper Dynasty Discord bot.

Overview

The original players.py file (1,713 lines) has been refactored into 6 focused modules, each with corresponding test files:

Module Test File Purpose Commands Tested
player_lookup.py test_player_lookup.py Player card display and lookup player, update-player, card-id, player-id, random
team_management.py test_team_management.py Team info and management team, branding-pd, pullroster, ai-teams
paperdex.py test_paperdex.py Collection tracking paperdex cardset, paperdex team
standings_records.py test_standings_records.py Standings and records record, standings
gauntlet.py test_gauntlet.py Gauntlet game mode gauntlet status, gauntlet start, gauntlet reset
utility_commands.py test_utility_commands.py Utility and admin commands build_list, in, out, fuck, chaos, sba

Test Structure

Fixtures and Mocks (conftest.py)

  • Mock Discord Objects: Bot, interactions, members, guilds, channels
  • Sample Data: Player data, team data, API responses, gauntlet data
  • API Mocking: db_get, db_post, db_patch, helper functions
  • Permission Mocking: Role checks, channel checks

Test Categories

Each test file includes:

  1. Initialization Tests: Verify cog setup
  2. Command Success Tests: Happy path scenarios
  3. Error Handling Tests: API failures, missing data, invalid input
  4. Permission Tests: Role and channel restrictions
  5. Edge Case Tests: Boundary conditions, malformed data
  6. Integration Tests: Multi-step command flows
  7. Utility Tests: Helper functions and formatting

Running Tests

Prerequisites

  • Docker socket configured: unix:///home/cal/.docker/desktop/docker.sock
  • PostgreSQL test containers available
  • All dependencies installed: pip install -r requirements.txt

Basic Usage

# Run all players refactor tests
pytest tests/players_refactor/

# Run specific module tests
pytest tests/players_refactor/test_player_lookup.py
pytest tests/players_refactor/test_team_management.py

# Run with verbose output
pytest -v tests/players_refactor/

# Run with coverage reporting
pytest --cov=cogs.players tests/players_refactor/

# Run specific test methods
pytest tests/players_refactor/test_player_lookup.py::TestPlayerLookup::test_player_command_success

# Run tests matching pattern
pytest -k "test_gauntlet" tests/players_refactor/

Performance Testing

# Run only fast tests (skip slow database tests)
pytest -m "not slow" tests/players_refactor/

# Run slow tests only
pytest -m "slow" tests/players_refactor/

# Show test duration
pytest --durations=10 tests/players_refactor/

Debugging

# Run with pdb on failures
pytest --pdb tests/players_refactor/

# Show print statements
pytest -s tests/players_refactor/

# Stop on first failure
pytest -x tests/players_refactor/

Test Data and Factories

Database Fixtures

Tests use the existing session_fixture from tests/factory.py which provides:

  • PostgreSQL test containers
  • Sample teams, players, cards
  • Game data and lineups
  • Position ratings and scouting data

Mock Data Factories

Each test file includes fixtures for:

  • API responses (players, teams, standings, gauntlet data)
  • Discord objects (interactions, members, roles)
  • Complex nested data structures

Example Test Data

sample_team_data = {
    'id': 31,
    'abbrev': 'TST',
    'sname': 'Test Team',
    'gmid': 123456789,
    'wallet': 1000,
    'team_value': 5000
}

sample_player_data = {
    'player_id': 123,
    'p_name': 'Test Player',
    'cost': 100,
    'position': 'CF',
    'cardset': {'id': 1, 'name': '2024 Season'}
}

Mocking Strategy

API Calls

All external API calls are mocked to avoid:

  • Network dependencies
  • Rate limiting
  • Data inconsistency
  • Slow test execution

Discord API

Discord interactions are fully mocked:

  • Slash command interactions
  • Role management
  • Message sending
  • Permission checking

Helper Functions

Common helper functions are mocked with realistic return values:

  • Fuzzy search results
  • Team lookups
  • Channel validation
  • Embed creation

Error Testing

API Failures

  • Network timeouts
  • HTTP errors
  • Invalid responses
  • Missing data

Discord Errors

  • Permission denied
  • Role not found
  • Channel restrictions
  • User not found

Input Validation

  • Invalid parameters
  • Missing required fields
  • Malformed data
  • Edge case values

Coverage Goals

Target coverage for each module:

  • Command Functions: 100% - All command paths tested
  • Helper Functions: 90% - Core logic covered
  • Error Handling: 95% - Exception paths tested
  • Permission Checks: 100% - Security critical

Common Patterns

Command Testing Pattern

@patch('api_calls.db_get')
@patch('helpers.get_team_by_owner')
async def test_command_success(self, mock_get_team, mock_db_get, 
                              cog, mock_interaction, sample_data):
    # Setup mocks
    mock_get_team.return_value = sample_data
    mock_db_get.return_value = {'success': True}
    
    # Execute command
    await cog.command(mock_interaction)
    
    # Assert behavior
    mock_interaction.response.defer.assert_called_once()
    mock_interaction.followup.send.assert_called_once()

Error Testing Pattern

async def test_command_error(self, mock_interaction):
    # Setup error condition
    with patch('api_calls.db_get') as mock_db:
        mock_db.return_value = None
        
        # Execute and assert error handling
        await cog.command(mock_interaction)
        mock_interaction.followup.send.assert_called_with('Error message')

Integration with CI/CD

These tests are designed to work with:

  • GitHub Actions
  • Docker-based CI environments
  • Automated test reporting
  • Coverage analysis tools

Maintenance

Adding New Tests

  1. Follow existing naming conventions
  2. Use appropriate fixtures and mocks
  3. Include success and failure cases
  4. Test edge cases and permissions
  5. Update documentation

Updating Existing Tests

  1. Maintain backward compatibility
  2. Update mock data as needed
  3. Keep tests focused and atomic
  4. Ensure proper cleanup

Best Practices

  • One test per scenario
  • Clear, descriptive test names
  • Minimal setup in each test
  • Use parametrized tests for variations
  • Mock external dependencies
  • Assert specific behaviors, not just "no errors"

Troubleshooting

Common Issues

Docker Socket Errors

# Fix Docker socket permissions
export DOCKER_HOST=unix:///home/cal/.docker/desktop/docker.sock

Import Errors

# Ensure modules exist (tests are designed to handle missing imports)
# Check PYTHONPATH includes project root
export PYTHONPATH=/mnt/NV2/Development/paper-dynasty/discord-app:$PYTHONPATH

Database Connection Issues

# Verify PostgreSQL container access
docker ps | grep postgres

Slow Test Performance

# Run without database fixtures
pytest -m "not slow" tests/players_refactor/

Getting Help

For issues with the test suite:

  1. Check test output and error messages
  2. Verify mock setup and data
  3. Ensure proper imports and dependencies
  4. Review existing test patterns
  5. Check Discord.py and pytest documentation

Future Enhancements

Planned improvements:

  • Performance benchmarking
  • Integration with actual Discord test bot
  • Load testing for concurrent commands
  • Enhanced error message validation
  • Automated test data generation
  • Visual test coverage reports