Back to Repositories

Testing Directory Creation Command Correction in TheFuck

This test suite validates the behavior of the ‘cp_create_destination’ rule in TheFuck, which handles file copy/move operations when destination directories don’t exist. The tests ensure proper command correction by automatically creating missing directories.

Test Coverage Overview

The test suite provides comprehensive coverage of directory creation scenarios for cp and mv commands.

Key functionality tested includes:
  • Command matching for missing directory errors
  • Automatic directory creation with mkdir -p
  • Handling of nested directory paths
  • Error message pattern recognition

Implementation Analysis

The testing approach uses pytest’s parametrize decorator to efficiently test multiple input scenarios with minimal code duplication.

Implementation patterns include:
  • Separate test cases for matching and non-matching scenarios
  • Command object usage for input/output handling
  • Structured command transformation validation

Technical Details

Testing tools and configuration:
  • pytest framework for test organization
  • Command class from thefuck.types for command representation
  • Parametrized test cases for multiple scenarios
  • Direct assertion testing for boolean matches
  • String comparison for command transformation verification

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Python.

Notable practices include:
  • Clear separation of positive and negative test cases
  • Comprehensive edge case coverage
  • Efficient test parameterization
  • Consistent test method naming
  • Focused test scope per function

nvbn/thefuck

tests/rules/test_cp_create_destination.py

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


@pytest.mark.parametrize(
    "script, output",
    [("cp", "cp: directory foo does not exist
"), ("mv", "No such file or directory")],
)
def test_match(script, output):
    assert match(Command(script, output))


@pytest.mark.parametrize(
    "script, output", [("cp", ""), ("mv", ""), ("ls", "No such file or directory")]
)
def test_not_match(script, output):
    assert not match(Command(script, output))


@pytest.mark.parametrize(
    "script, output, new_command",
    [
        ("cp foo bar/", "cp: directory foo does not exist
", "mkdir -p bar/ && cp foo bar/"),
        ("mv foo bar/", "No such file or directory", "mkdir -p bar/ && mv foo bar/"),
        ("cp foo bar/baz/", "cp: directory foo does not exist
", "mkdir -p bar/baz/ && cp foo bar/baz/"),
    ],
)
def test_get_new_command(script, output, new_command):
    assert get_new_command(Command(script, output)) == new_command