Skip to content

Fix CliRunner TypeError with pathlib.Path arguments#3284

Closed
elazar wants to merge 7 commits intopallets:mainfrom
elazar:fix-pathlib-clirunner-args
Closed

Fix CliRunner TypeError with pathlib.Path arguments#3284
elazar wants to merge 7 commits intopallets:mainfrom
elazar:fix-pathlib-clirunner-args

Conversation

@elazar
Copy link

@elazar elazar commented Mar 25, 2026

Summary

• Fixes TypeError: object of type 'PosixPath' has no len() when passing pathlib.Path objects to CliRunner.invoke()
• Implements automatic Path-to-string conversion using Python's __fspath__ protocol
• Preserves backward compatibility and core parser behavior

Background

When pathlib.Path objects are passed to CliRunner.invoke(), Click's argument parser crashes because it calls len() on the Path object without type checking. This issue was reported in #1324 but remained unresolved with a cryptic error message that doesn't guide users to the solution.

Changes

Core Fix (src/click/testing.py):

  • Added automatic conversion of path-like objects to strings in CliRunner.invoke()
  • Uses Python's standard __fspath__ protocol for path-like object detection
  • Only affects the testing layer, preserving production parser behavior

Test Coverage (tests/test_testing.py):

  • Added comprehensive test suite with 4 test functions
  • Tests various Path object types (absolute, relative, current/parent directories)
  • Verifies backward compatibility with existing string arguments
  • Confirms core parser behavior remains unchanged

Related Issues

Fixes #1324

elazar and others added 7 commits March 25, 2026 11:48
- Add automatic Path-to-string conversion in CliRunner.invoke()
- Resolves 'object of type PosixPath has no len()' error
- Uses __fspath__ protocol for path-like object detection
- Maintains backward compatibility with existing string arguments
- Add comprehensive test coverage for pathlib integration

Fixes pallets#1324
Apply automatic formatting fixes from ruff:
- Convert single quotes to double quotes for consistency
- Reformat list comprehension to single line
- Fix import order and spacing
- Add blank lines after docstrings per style guide
The TypeError message differs between CPython and PyPy:
- CPython: "object of type 'PosixPath' has no len()"
- PyPy: "'PosixPath' has no length"

Update regex to match both variants.
- Use str(test_path) in assertions to handle platform-specific path separators
- Update error message regex to match both PosixPath and WindowsPath
- Handle different error message formats across Python implementations
@davidism davidism closed this Mar 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Passing an instance of Pathlib.Path to CliRunner.invoke() gets a TypeError

2 participants