pytest-dev/pytest · error · UsageError

{optname} must be a directory, given: {path}

Error message

{optname} must be a directory, given: {path}

What it means

The directory_arg function is an argparse type validator for pytest CLI options (e.g., --rootdir, -o with certain args) that must receive a directory path. If the path does not exist or is a file rather than a directory, pytest raises UsageError. This ensures pytest operates on an existing directory.

Source

Thrown at src/_pytest/config/__init__.py:308

def filename_arg(path: str, optname: str) -> str:
    """Argparse type validator for filename arguments.

    :path: Path of filename.
    :optname: Name of the option.
    """
    if os.path.isdir(path):
        raise UsageError(f"{optname} must be a filename, given: {path}")
    return path


def directory_arg(path: str, optname: str) -> str:
    """Argparse type validator for directory arguments.

    :path: Path of directory.
    :optname: Name of the option.
    """
    if not os.path.isdir(path):
        raise UsageError(f"{optname} must be a directory, given: {path}")
    return path


# Plugins that cannot be disabled via "-p no:X" currently.
essential_plugins = (
    "mark",
    "main",
    "runner",
    "fixtures",
    "helpconfig",  # Provides -p.
)

default_plugins = (
    *essential_plugins,
    "python",
    "terminal",
    "debugging",
    "unittest",

View on GitHub (pinned to 98b357f69e)

Solutions

  1. Create the directory first if it does not exist (mkdir -p <path>).
  2. Correct the path to point at an existing directory, not a file.
  3. Use an absolute path to avoid cwd-relative resolution ambiguity.

Example fix

# before
pytest --rootdir ./conftest.py

# after
pytest --rootdir ./tests
Defensive patterns

Strategy: validation

Validate before calling

import os

def ensure_is_directory(path: str, optname: str) -> str:
    if not os.path.isdir(path):
        raise FileNotFoundError(f"{optname} must be a directory, but '{path}' is not a directory")
    return path

Prevention

When it happens

Trigger: Passing a nonexistent path or a file path to an option that expects a directory (wired through directory_arg). os.path.isdir(path) returns False, triggering the error.

Common situations: Typo in the directory name, pointing at a path that hasn't been created yet, or pointing at a file (e.g., conftest.py) instead of its parent directory.

Related errors


AI-assisted analysis of pytest-dev/pytest@98b357f69e (2026-08-04). Data as JSON: /data/errors/4048d65d101874bb.json. Report an issue: GitHub.