Back to Repositories

Testing Sudo Command Correction Logic in TheFuck

This test suite validates the sudo rule functionality in TheFuck project, focusing on permission-related command corrections. It verifies the automatic prepending of sudo commands when permission errors are encountered during command execution.

Test Coverage Overview

The test suite provides comprehensive coverage of permission-denied scenarios and sudo command transformations.

Key areas tested include:
  • Various permission denied error messages and patterns
  • Command transformation logic for different shell operations
  • Root privilege requirement detection
  • Complex command handling with pipes and redirections

Implementation Analysis

The testing approach uses pytest’s parametrize feature to efficiently test multiple input scenarios against expected outputs.

Notable patterns include:
  • Parametrized test cases for error message matching
  • Command transformation verification for shell operations
  • Separate positive and negative test cases
  • Shell command escaping validation

Technical Details

Testing infrastructure includes:
  • Pytest framework for test organization
  • Command object mocking
  • String pattern matching
  • Shell command parsing and transformation
  • Error message validation

Best Practices Demonstrated

The test suite exemplifies several testing best practices:

  • Comprehensive error message coverage
  • Clear test case organization
  • Efficient test parameterization
  • Edge case handling for complex shell commands
  • Separate positive and negative test scenarios

nvbn/thefuck

tests/rules/test_sudo.py

            
import pytest
from thefuck.rules.sudo import match, get_new_command
from thefuck.types import Command


@pytest.mark.parametrize('output', [
    'Permission denied',
    'permission denied',
    "npm ERR! Error: EACCES, unlink",
    'requested operation requires superuser privilege',
    'need to be root',
    'need root',
    'shutdown: NOT super-user',
    'Error: This command has to be run with superuser privileges (under the root user on most systems).',
    'updatedb: can not open a temporary file for `/var/lib/mlocate/mlocate.db',
    'must be root',
    'You don\'t have access to the history DB.',
    "error: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/ipaddr.py'"])
def test_match(output):
    assert match(Command('', output))


def test_not_match():
    assert not match(Command('', ''))
    assert not match(Command('sudo ls', 'Permission denied'))


@pytest.mark.parametrize('before, after', [
    ('ls', 'sudo ls'),
    ('echo a > b', 'sudo sh -c "echo a > b"'),
    ('echo "a" >> b', 'sudo sh -c "echo \\"a\\" >> b"'),
    ('mkdir && touch a', 'sudo sh -c "mkdir && touch a"')])
def test_get_new_command(before, after):
    assert get_new_command(Command(before, '')) == after