Back to Repositories

Testing Script Existence Detection Rules in TheFuck Command-Line Tool

This test suite validates the functionality of the ‘has_exists_script’ rule in TheFuck project, which handles cases where commands exist as scripts in the current directory but aren’t properly invoked with ‘./’.

Test Coverage Overview

The test suite provides comprehensive coverage for the script existence checking functionality.

Key areas tested include:
  • Command not found scenarios with existing scripts
  • Command not found scenarios with non-existing scripts
  • Command variations with arguments (–help)
  • Empty output handling

Implementation Analysis

The testing approach utilizes Python’s mock library to simulate file system behaviors, specifically patching os.path.exists.

Testing patterns include:
  • Context manager usage for mock implementation
  • Multiple assertion scenarios within single test functions
  • Positive and negative test cases

Technical Details

Testing tools and configuration:
  • Python mock library for path existence simulation
  • Command type from thefuck.types for input structuring
  • Pytest as the testing framework
  • Patch decorator for mock implementation

Best Practices Demonstrated

The test suite demonstrates several testing best practices in Python.

Notable practices include:
  • Isolation of system dependencies through mocking
  • Clear test function naming and organization
  • Comprehensive positive and negative test cases
  • Efficient test case grouping within functions

nvbn/thefuck

tests/rules/test_has_exists_script.py

            
from mock import patch
from thefuck.rules.has_exists_script import match, get_new_command
from thefuck.types import Command


def test_match():
    with patch('os.path.exists', return_value=True):
        assert match(Command('main', 'main: command not found'))
        assert match(Command('main --help',
                             'main: command not found'))
        assert not match(Command('main', ''))

    with patch('os.path.exists', return_value=False):
        assert not match(Command('main', 'main: command not found'))


def test_get_new_command():
    assert get_new_command(Command('main --help', '')) == './main --help'