test_collection.py


Overview

[test_collection.py](/projects/286/67495) is a comprehensive test suite for verifying the collection mechanisms and related behaviors of the `pytest` testing framework. The file primarily focuses on ensuring that pytest correctly discovers, collects, and manages test items (functions, classes, modules) from the filesystem, Python packages, and custom plugins. It tests core pytest collection features such as:

This file uses the `pytest` testing framework itself and the `pytester` plugin extensively to simulate test environments, create test files dynamically, run pytest commands, and assert expected behaviors.


Detailed Entity Descriptions

Function: ensure_file(file_path: Path) -> Path

**Purpose:** Ensure that a file exists at the specified path, creating parent directories if necessary.

**Parameters:**

**Returns:**

**Usage Example:**

file = ensure_file(Path("/tmp/some/dir/file.txt"))
# file now exists on the filesystem

Class: TestCollector

Test cases related to basic collection principles and pytest node hierarchy.

Methods:


Class: TestCollectFS

Tests related to filesystem-based collection, including ignoring certain directories, virtual environment detection, and honoring collection-related config.

Key Methods:


Class: TestCollectPluginHookRelay

Tests proper relay of the `pytest_collect_file` hook for plugin-defined collection.


Class: TestPrunetraceback

Tests related to error reporting and traceback pruning during collection.


Class: TestCustomConftests

Test scenarios involving custom collection behaviors configured via `conftest.py`.


Class: TestSession

Tests on `pytest.main.Session` collection protocol and item reporting.


Class: TestNodeKeywords

Tests related to keyword handling on collected nodes (used for test selection with `-k`).


Class: TestCollectDirectoryHook

Tests involving the `pytest_collect_directory` hook for custom directory collection.


Other Notable Functions and Tests


Important Implementation Details


Interaction with Other System Components


Usage Examples

The tests themselves serve as usage examples for pytest collection behaviors. For instance, to test that a class with `__test__ = False` is skipped:

def test_can_skip_class_with_test_attr(pytester: Pytester) -> None:
    pytester.makepyfile(
        """
        class TestFoo(object):
            __test__ = False
            def __init__(self):
                pass
            def test_foo():
                assert True
        """
    )
    result = pytester.runpytest()
    result.stdout.fnmatch_lines(["collected 0 items", "*no tests ran in*"])

Or to create a custom file collector via a plugin:

def test_pytest_collect_file(self, pytester: Pytester) -> None:
    wascalled = []

    class Plugin:
        def pytest_collect_file(self, file_path: Path) -> None:
            if not file_path.name.startswith("."):
                wascalled.append(file_path)

    pytester.makefile(".abc", "xyz")
    pytest.main(pytester.path, plugins=[Plugin()])
    assert len(wascalled) == 1
    assert wascalled[0].suffix == ".abc"

Visual Diagram: Class Structure Overview

The key class defined in this file is `TestCollector`, which is a test class containing multiple test methods for collection behavior. There are also several other test classes grouping related tests. Below is a simplified Mermaid class diagram summarizing the main test classes and their key methods or responsibilities:

classDiagram
    class TestCollector {
        +test_collect_versus_item()
        +test_check_equality(pytester)
        +test_getparent_and_accessors(pytester)
        +test_getcustomfile_roundtrip(pytester)
        +test_can_skip_class_with_test_attr(pytester)
    }

    class TestCollectFS {
        +test_ignored_certain_directories(pytester)
        +test_ignored_virtualenvs(pytester, env_path)
        +test_custom_norecursedirs(pytester)
        +test_testpaths_ini(pytester, monkeypatch)
        +test_missing_permissions_on_unselected_directory_doesnt_crash(pytester)
    }

    class TestPrunetraceback {
        +test_custom_repr_failure(pytester)
        +test_collection_error_traceback_is_clean(pytester)
    }

    class TestSession {
        +test_collect_topdir(pytester)
        +test_collect_protocol_single_function(pytester)
        +test_collect_protocol_method(pytester)
        +test_collect_custom_nodes_multi_id(pytester)
        +test_collect_parametrized_order(pytester)
    }

    class TestNodeKeywords {
        +test_no_under(pytester)
        +test_keyword_matching_is_case_insensitive_by_default(pytester)
        +test_duplicates_handled_correctly(pytester)
        +test_unpacked_marks_added_to_keywords(pytester)
    }

    class TestCustomConftests {
        +test_ignore_collect_path(pytester)
        +test_collectignore_exclude_on_option(pytester)
        +test_pytest_fs_collect_hooks_are_seen(pytester)
    }

    %% Relation: All test classes inherit from object (implied)
    TestCollector <|-- object
    TestCollectFS <|-- object
    TestPrunetraceback <|-- object
    TestSession <|-- object
    TestNodeKeywords <|-- object
    TestCustomConftests <|-- object

Summary

The [test_collection.py](/projects/286/67495) file is an extensive pytest test module that validates the correctness and robustness of pytest's test collection subsystem. It covers a broad spectrum of scenarios from basic node relationships to complex plugin and filesystem interactions, ensuring pytest's core functionality remains reliable and configurable under various conditions.


End of Documentation for test_collection.py