test_legacypath.py
Overview
`test_legacypath.py` is a test suite designed to verify backward compatibility, functionality, and integration of legacy path handling features within the `pytest` testing framework. It specifically tests components related to legacy path objects (`py.path`), temporary directory factories, fixture requests, and configuration handling for path-related options. The file ensures that legacy interfaces (such as `tmpdir` and `testdir`) behave as expected alongside newer APIs (`tmp_path`), and that configuration options involving filesystem paths are correctly parsed and overridden.
The tests use `pytest` fixtures and helper classes (`Testdir`, `TempdirFactory`, `TopRequest`) from `pytest`'s internal legacy path support modules to validate these behaviors in different contexts, including session-scoped fixtures and command-line configuration.
Detailed Explanations
Functions
test_item_fspath(pytester: pytest.Pytester) -> None
**Purpose:** Tests that generated test items have consistent file system path attributes (`fspath` and `path`) and that these attributes remain stable when re-generated from an item's node id.
**Parameters:**
pytester: Apytest.Pytesterfixture used to create and run test files in isolation.
**Returns:**
None
**Usage Example:**
def test_example(pytester):
pytester.makepyfile("def test_func(): pass")
items, _ = pytester.inline_genitems()
assert items[0].fspath is not None
**Details:**
Uses
pytester.inline_genitems()to generate test items.Asserts that the first item has expected attributes and that regenerating items by
nodeidyields an equivalent item.
test_testdir_testtmproot(testdir: Testdir) -> None
**Purpose:** Verifies that the `test_tmproot` attribute on the `Testdir` fixture is a `py.path` directory object, ensuring backward compatibility.
**Parameters:**
testdir: A legacyTestdirfixture providing a temporary test directory.
**Returns:**
None
**Details:**
Uses
check(dir=1)ontest_tmprootto confirm it is a directory.
test_testdir_makefile_dot_prefixes_extension_silently(testdir: Testdir) -> None
**Purpose:** Tests that creating a file with an extension prefixed by a dot results in a filename including that dot, which preserves legacy behavior.
**Parameters:**
testdir: Legacy test directory fixture.
**Returns:**
None
**Details:**
Calls
makefile("foo.bar", "")and asserts the resulting filename includes.foo.bar.
test_testdir_makefile_ext_none_raises_type_error(testdir: Testdir) -> None
**Purpose:** Ensures calling `makefile` with `None` as the extension raises a `TypeError`.
**Parameters:**
testdir: Legacy test directory fixture.
**Returns:**
None
test_testdir_makefile_ext_empty_string_makes_file(testdir: Testdir) -> None
**Purpose:** Confirms that calling `makefile` with an empty string extension creates a file successfully.
**Parameters:**
testdir: Legacy test directory fixture.
**Returns:**
None
attempt_symlink_to(path: str, to_path: str) -> None
**Purpose:** Attempts to create a symbolic link from `path` to `to_path`. If the platform or permissions do not support symlinks (e.g., Windows without admin rights), the test is skipped.
**Parameters:**
path: The symlink path to create.to_path: The target path the symlink points to.
**Returns:**
None
**Details:**
Uses
pathlib.Path.symlink_to.Catches
OSErrorto skip tests gracefully if symlinks are not allowed.
test_tmpdir_factory(tmpdir_factory: TempdirFactory, tmp_path_factory: pytest.TempPathFactory) -> None
**Purpose:** Validates that `tmpdir_factory` and `tmp_path_factory` share the same base temporary directory and that `tmpdir_factory.mktemp()` creates a directory.
**Parameters:**
tmpdir_factory: Legacy temporary directory factory.tmp_path_factory: Newerpathlib.Path-based temporary directory factory.
**Returns:**
None
test_tmpdir_equals_tmp_path(tmpdir: LEGACY_PATH, tmp_path: Path) -> None
**Purpose:** Asserts that the legacy `tmpdir` and `tmp_path` fixtures point to the same filesystem path.
**Parameters:**
tmpdir: Legacy temporary directory path (typepy.path).tmp_path: Modernpathlib.Pathtemporary directory.
**Returns:**
None
test_tmpdir_always_is_realpath(pytester: pytest.Pytester) -> None
**Purpose:** Ensures that the `tmpdir` fixture always resolves to the real path (no symlinks).
**Parameters:**
pytester:pytesttest runner helper.
**Returns:**
None
**Details:**
Creates a symlink to a directory.
Runs a test using
tmpdirunder the symlinked directory.Asserts that
os.path.realpathmatches thetmpdirpath, verifying realpath resolution.
test_cache_makedir(cache: pytest.Cache) -> None
**Purpose:** Tests that the `cache.makedir()` method creates a directory and that the directory can be removed.
**Parameters:**
cache:pytest.Cachefixture.
**Returns:**
None
test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None
**Purpose:** Verifies that the `TopRequest` fixture request correctly exposes module path attributes.
**Parameters:**
pytester:pytesttest runner helper.
**Returns:**
None
**Details:**
Creates a module collection.
Generates test items.
Creates a
TopRequestand checks it has correctpathandfspathattributes.
Class: TestFixtureRequestSessionScoped
Tests session-scoped fixture requests for correct attribute availability.
Fixture: session_request(self, request)
**Scope:** Session
**Purpose:** Provides a session-scoped `request` fixture for tests.
Method: test_session_scoped_unavailable_attributes(self, session_request)
**Purpose:** Verifies that accessing `.fspath` on a session-scoped fixture request raises `AttributeError`, as expected.
Parameterized Test: test_addini_paths(pytester: pytest.Pytester, config_type: str) -> None
**Purpose:** Tests that `pytest_addoption` can add ini options of type `pathlist` and that those paths are correctly parsed from both `pytest.ini` and `pyproject.toml`.
**Parameters:**
pytester:pytesttest runner helper.config_type: Either"ini"or"pyproject"specifying the configuration format.
**Returns:**
None
**Details:**
Defines ini options with a
pathlisttype.Creates config files accordingly.
Asserts that paths are parsed as path objects relative to the config file.
Verifies error on unknown ini keys.
Function: test_override_ini_paths(pytester: pytest.Pytester) -> None
**Purpose:** Tests that ini options of type `pathlist` can be overridden via the command line using `--override-ini`.
**Parameters:**
pytester:pytesttest runner helper.
**Returns:**
None
**Details:**
Defines a pathlist ini option.
Overrides the option on the command line.
Checks that the overridden paths are correctly passed to the test.
Function: test_inifile_from_cmdline_main_hook(pytester: pytest.Pytester) -> None
**Purpose:** Ensures that the `Config.inifile` attribute is available during the `pytest_cmdline_main` hook, confirming access to the ini file path at early pytest lifecycle stages.
**Parameters:**
pytester:pytesttest runner helper.
**Returns:**
None
Important Implementation Details
The file uses
pytest's internal legacy path fixtures (Testdir,TempdirFactory,TopRequest) to test old APIs still supported for backward compatibility.It compares legacy
py.pathobjects (tmpdir,test_tmproot) against newerpathlib.Pathequivalents (tmp_path,tmp_path_factory) ensuring smooth coexistence.Symlink creation is wrapped with exception handling and test skipping to maintain cross-platform compatibility.
The configuration tests validate the correct parsing and override behavior of path-related ini options, supporting both
pytest.iniandpyproject.toml.Session-scoped fixture requests are tested for expected attribute availability constraints.
Uses
pytesterfixture extensively for creating temporary test files, configs, and running sub-processes isolated from the main test run.
Interactions with Other System Components
pytest Core:
Tests path-related features and fixtures within pytest’s framework, ensuring legacy and new APIs interoperate correctly.pytest Configuration System:
Validates how path-type ini options are parsed, accessed, and overridden.Filesystem and OS:
Interacts with the filesystem for temporary directories, file creation, and symbolic links, abstracting differences between platforms.Legacy Path Support Modules (
_pytest.legacypath):
Uses legacy path fixtures and helpers to mimic older pytest behaviors.Cache System:
Tests directory creation functionalities in the pytest cache.
Visual Diagram
classDiagram
class TestFixtureRequestSessionScoped {
+session_request(request) : fixture
+test_session_scoped_unavailable_attributes(session_request)
}
class pytester {
+makepyfile()
+inline_genitems()
+mkdir()
+makeconftest()
+makeini()
+makepyprojecttoml()
+runpytest()
+runpytest_subprocess()
+getmodulecol()
+genitems()
}
class Testdir {
+test_tmproot: py.path.local
+makefile(ext: str, content: str) : py.path.local
}
class TempdirFactory {
+getbasetemp() : py.path.local
+mktemp(name: str) : py.path.local
}
class pytest.Cache {
+makedir(name: str) : py.path.local
}
test_legacypath.py ..> pytester : uses
test_legacypath.py ..> Testdir : uses
test_legacypath.py ..> TempdirFactory : uses
test_legacypath.py ..> pytest.Cache : uses
test_legacypath.py ..> TestFixtureRequestSessionScoped : defines
Summary
`test_legacypath.py` serves as a comprehensive backward compatibility and integration test suite for legacy path-related features and fixtures in pytest. It ensures that legacy `py.path`-based interfaces coexist correctly with newer `pathlib.Path` APIs, that configuration options involving filesystem paths are properly handled, and that session-scoped fixtures behave as expected. This file plays a critical role in validating the stability and correctness of pytest’s filesystem and configuration subsystems across versions.