Back to Repositories

Testing Directory Command Correction Implementation in TheFuck

This test suite validates the directory handling functionality in the ‘cat_dir’ rule of TheFuck command-line tool. It ensures proper behavior when users accidentally try to use ‘cat’ command on directories instead of files.

Test Coverage Overview

The test suite provides comprehensive coverage of the cat_dir rule functionality.

Key areas tested include:
  • Directory path validation scenarios
  • Command matching for directory inputs
  • Command correction from ‘cat’ to ‘ls’
  • Various directory path formats (relative, absolute)
Edge cases cover invalid commands and non-directory inputs.

Implementation Analysis

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

Key patterns include:
  • Fixture-based mocking of directory checks
  • Parametrized test cases for different command formats
  • Command object usage for input/output validation
  • Separation of matching and command generation logic

Technical Details

Testing infrastructure includes:
  • pytest framework for test organization
  • pytest-mock for directory validation mocking
  • Custom Command type for command representation
  • Modular test structure with separate match and command generation tests

Best Practices Demonstrated

The test suite exemplifies several testing best practices.

Notable aspects include:
  • Clear separation of test cases
  • Effective use of fixtures for dependency injection
  • Comprehensive positive and negative test scenarios
  • Consistent test naming and organization
  • Mock usage for filesystem operations

nvbn/thefuck

tests/rules/test_cat_dir.py

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


@pytest.fixture
def isdir(mocker):
    return mocker.patch('thefuck.rules.cat_dir'
                        '.os.path.isdir')


@pytest.mark.parametrize('command', [
    Command('cat foo', 'cat: foo: Is a directory
'),
    Command('cat /foo/bar/', 'cat: /foo/bar/: Is a directory
'),
    Command('cat cat/', 'cat: cat/: Is a directory
'),
])
def test_match(command, isdir):
    isdir.return_value = True
    assert match(command)


@pytest.mark.parametrize('command', [
    Command('cat foo', 'foo bar baz'),
    Command('cat foo bar', 'foo bar baz'),
    Command('notcat foo bar', 'some output'),
])
def test_not_match(command, isdir):
    isdir.return_value = False
    assert not match(command)


@pytest.mark.parametrize('command, new_command', [
    (Command('cat foo', 'cat: foo: Is a directory
'), 'ls foo'),
    (Command('cat /foo/bar/', 'cat: /foo/bar/: Is a directory
'), 'ls /foo/bar/'),
    (Command('cat cat', 'cat: cat: Is a directory
'), 'ls cat'),
])
def test_get_new_command(command, new_command):
    isdir.return_value = True
    assert get_new_command(command) == new_command